From 1c037655b217dc5346166dc24df83f5efc3e8deb Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:51:43 -0700 Subject: [PATCH] telephony: match LXST 0.6.0 signalling, profiles, and call modes --- CHANGELOG.md | 22 + README.md | 1 + api/snapshots/lxst-core.txt | 34 +- api/snapshots/lxst-embedded.txt | 30 +- api/snapshots/lxst-telephony.txt | 29 +- api/stability.json | 12 +- crates/lxst-core/src/lib.rs | 4 +- crates/lxst-core/src/opus.rs | 83 +- crates/lxst-core/src/raw.rs | 94 +- crates/lxst-core/src/shared/actions.rs | 6 +- crates/lxst-core/src/shared/call_types.rs | 6 +- crates/lxst-core/src/shared/profile.rs | 53 ++ crates/lxst-core/src/shared/telephony.rs | 142 ++- crates/lxst-core/src/shared/wire_types.rs | 14 +- crates/lxst-core/src/telephony.rs | 165 +++- crates/lxst-embedded/src/lib.rs | 2 +- crates/lxst-embedded/src/session.rs | 58 +- crates/lxst-embedded/tests/session.rs | 99 ++- crates/lxst-embedded/tests/wire.rs | 20 +- crates/lxst-telephony/Cargo.toml | 1 + crates/lxst-telephony/src/lib.rs | 558 +++++++----- crates/lxst-telephony/src/media.rs | 109 ++- crates/lxst-telephony/src/tests.rs | 831 ++++++++++++++---- .../tests/fixtures/lxst_060_media.json | 68 ++ .../tests/fixtures/lxst_media_fixtures.py | 78 ++ .../tests/python_telephone_helper.rs | 8 +- .../tests/python_telephone_live_interop.rs | 386 +++++++- tools/common/lxst_reference.py | 10 +- tools/interop/lxst_telephone_helper.py | 38 +- tools/reference/lxst_reference_lock.json | 30 +- 30 files changed, 2398 insertions(+), 593 deletions(-) create mode 100644 crates/lxst-telephony/tests/fixtures/lxst_060_media.json create mode 100644 crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e5219ba..7823fcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## Unreleased +Parity with Python LXST 0.6.0. Several experimental APIs change. + +- Call modes: full and half duplex are signalled with the profile when the + callee rings, can be switched during a call, and squelch transmit in half + duplex. `TelephonyControl::Call` takes a `mode`. +- The callee is established as soon as it answers. The answer retry and its + timeout are removed (`retry_answer`, `answer_retry_interval`, + `answer_timeout`). +- Outgoing calls end unless the callee rings within `connect_timeout` + (5 seconds by default), and the 70 second wait runs from the call request, + path discovery included. +- The line is busy while an outgoing call discovers its path. +- A call to a peer with a known path sends no path request. +- The first announce follows 5 seconds after start; the startup announce burst + is off by default. +- Received audio is decoded by the codec of each frame, and a bad frame is + skipped instead of dropping its packet. +- `Profile::buffer_frames` gives the receive buffer depth of each profile. +- Raw float128 samples use IEEE binary128. +- `lxst-embedded` sessions use the 60, 70, and 5 second ring, wait, and + connect times. + ## 0.3.1 - 2026-11-08 - Telephony wakes on Link events instead of polling, polls once a second when diff --git a/README.md b/README.md index aa26c3d..989d9ac 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,7 @@ control_tx .send(TelephonyControl::Call { remote_identity, profile: Some(Profile::QualityMedium), + mode: None, discovery_timeout: Duration::from_secs(8), }) .await?; diff --git a/api/snapshots/lxst-core.txt b/api/snapshots/lxst-core.txt index 5695aed..5e7e207 100644 --- a/api/snapshots/lxst-core.txt +++ b/api/snapshots/lxst-core.txt @@ -6,6 +6,18 @@ impl lxst_core::AudioCodec pub const fn lxst_core::AudioCodec::channels(self) -> u8 pub const fn lxst_core::AudioCodec::codec_kind(self) -> lxst_core::CodecKind pub const fn lxst_core::AudioCodec::sample_rate_hz(self) -> u32 +#[repr(u8)] pub enum lxst_core::CallMode +pub lxst_core::CallMode::FullDuplex = 1 +pub lxst_core::CallMode::HalfDuplex = 2 +impl lxst_core::CallMode +pub const lxst_core::CallMode::AVAILABLE: [Self; 2] +pub const lxst_core::CallMode::DEFAULT: Self +pub const fn lxst_core::CallMode::abbreviation(self) -> &'static str +pub const fn lxst_core::CallMode::from_wire(u8) -> core::option::Option +pub const fn lxst_core::CallMode::name(self) -> &'static str +pub const fn lxst_core::CallMode::wire_value(self) -> u8 +impl core::convert::From for lxst_core::Signal +pub fn lxst_core::Signal::from(lxst_core::CallMode) -> Self pub enum lxst_core::CallRole pub lxst_core::CallRole::Incoming pub lxst_core::CallRole::Outgoing @@ -147,6 +159,7 @@ pub const lxst_core::Profile::DEFAULT: Self pub const lxst_core::Profile::ORDER: [Self; 8] pub const fn lxst_core::Profile::abbreviation(self) -> &'static str pub const fn lxst_core::Profile::audio_codec(self) -> lxst_core::AudioCodec +pub const fn lxst_core::Profile::buffer_frames(self) -> u8 pub const fn lxst_core::Profile::channels(self) -> u8 pub const fn lxst_core::Profile::frame_time_ms(self) -> u16 pub const fn lxst_core::Profile::from_wire(u32) -> core::option::Option @@ -169,12 +182,15 @@ pub const fn lxst_core::RawBitDepth::bytes_per_sample(self) -> usize pub const fn lxst_core::RawBitDepth::from_header_bits(u8) -> core::result::Result pub const fn lxst_core::RawBitDepth::numpy_dtype(self) -> &'static str pub enum lxst_core::Signal +pub lxst_core::Signal::PreferredMode(u8) pub lxst_core::Signal::PreferredProfile(lxst_core::Profile) pub lxst_core::Signal::Raw(u32) pub lxst_core::Signal::Status(lxst_core::SignallingStatus) impl lxst_core::Signal pub const fn lxst_core::Signal::from_wire(u32) -> Self pub const fn lxst_core::Signal::wire_value(self) -> u32 +impl core::convert::From for lxst_core::Signal +pub fn lxst_core::Signal::from(lxst_core::CallMode) -> Self impl core::convert::From for lxst_core::Signal pub fn lxst_core::Signal::from(lxst_core::Profile) -> Self impl core::convert::From for lxst_core::Signal @@ -217,10 +233,13 @@ pub lxst_core::TelephonyAction::OpenAudioPipelines pub lxst_core::TelephonyAction::PrepareDialingPipelines pub lxst_core::TelephonyAction::ResetDialingPipelines pub lxst_core::TelephonyAction::RingIncomingCall +pub lxst_core::TelephonyAction::SelectMode(lxst_core::CallMode) pub lxst_core::TelephonyAction::SelectProfile(lxst_core::Profile) pub lxst_core::TelephonyAction::SendSignal(lxst_core::Signal) +pub lxst_core::TelephonyAction::SendSignalPair(lxst_core::Signal, lxst_core::Signal) pub lxst_core::TelephonyAction::StartAudioPipelines pub lxst_core::TelephonyAction::StartDialTone +pub lxst_core::TelephonyAction::SwitchMode(lxst_core::CallMode) pub lxst_core::TelephonyAction::SwitchProfile(lxst_core::Profile) pub lxst_core::TelephonyAction::TeardownLink pub lxst_core::TelephonyAction::Terminate(core::option::Option) @@ -301,6 +320,12 @@ pub const fn lxst_core::OpusMonoDecoder::channels(&self) -> u8 pub fn lxst_core::OpusMonoDecoder::decode_packet(&mut self, &[u8]) -> core::result::Result pub fn lxst_core::OpusMonoDecoder::new() -> core::result::Result pub const fn lxst_core::OpusMonoDecoder::sample_rate_hz(&self) -> u32 +pub struct lxst_core::OpusPacketDecoder +impl lxst_core::OpusPacketDecoder +pub const fn lxst_core::OpusPacketDecoder::channels(&self) -> u8 +pub fn lxst_core::OpusPacketDecoder::decode_packet(&mut self, &[u8]) -> core::result::Result +pub fn lxst_core::OpusPacketDecoder::new(u32, u8) -> core::result::Result +pub const fn lxst_core::OpusPacketDecoder::sample_rate_hz(&self) -> u32 pub struct lxst_core::RawAudioFrame pub lxst_core::RawAudioFrame::channels: u8 pub lxst_core::RawAudioFrame::samples: alloc::vec::Vec @@ -308,9 +333,11 @@ impl lxst_core::RawAudioFrame pub fn lxst_core::RawAudioFrame::from_frame(&lxst_core::Frame) -> core::result::Result pub fn lxst_core::RawAudioFrame::from_payload(&[u8]) -> core::result::Result pub fn lxst_core::RawAudioFrame::new(u8, impl core::convert::Into>) -> core::result::Result +pub fn lxst_core::RawAudioFrame::resampled(&self, u32, u32) -> Self pub fn lxst_core::RawAudioFrame::sample_frames(&self) -> usize pub fn lxst_core::RawAudioFrame::to_frame(&self, lxst_core::RawBitDepth) -> core::result::Result pub fn lxst_core::RawAudioFrame::to_payload(&self, lxst_core::RawBitDepth) -> core::result::Result, lxst_core::Error> +pub fn lxst_core::RawAudioFrame::with_channels(self, u8) -> core::result::Result pub struct lxst_core::RawFrameCollector impl lxst_core::RawFrameCollector pub fn lxst_core::RawFrameCollector::frames(&self) -> &[lxst_core::RawAudioFrame] @@ -338,16 +365,21 @@ impl lxst_core::TelephonyCall pub fn lxst_core::TelephonyCall::answer(&mut self) -> alloc::vec::Vec pub const fn lxst_core::TelephonyCall::answered(&self) -> bool pub fn lxst_core::TelephonyCall::caller_identified(&mut self, bool, bool) -> alloc::vec::Vec +pub fn lxst_core::TelephonyCall::disable_remote_mode_follow(&mut self) pub fn lxst_core::TelephonyCall::hangup(&mut self, bool) -> alloc::vec::Vec pub fn lxst_core::TelephonyCall::incoming() -> Self pub fn lxst_core::TelephonyCall::incoming_link_established(bool) -> alloc::vec::Vec +pub const fn lxst_core::TelephonyCall::mode(&self) -> core::option::Option pub fn lxst_core::TelephonyCall::outgoing(core::option::Option) -> Self +pub fn lxst_core::TelephonyCall::outgoing_with_mode(core::option::Option, core::option::Option) -> Self pub const fn lxst_core::TelephonyCall::profile(&self) -> core::option::Option pub fn lxst_core::TelephonyCall::receive_signal(&mut self, lxst_core::Signal) -> alloc::vec::Vec -pub fn lxst_core::TelephonyCall::retry_answer(&self) -> alloc::vec::Vec pub const fn lxst_core::TelephonyCall::role(&self) -> lxst_core::CallRole +pub fn lxst_core::TelephonyCall::set_transmit_squelched(&mut self, bool) pub const fn lxst_core::TelephonyCall::status(&self) -> lxst_core::SignallingStatus +pub fn lxst_core::TelephonyCall::switch_mode(&mut self, lxst_core::CallMode) -> alloc::vec::Vec pub fn lxst_core::TelephonyCall::switch_profile(&mut self, lxst_core::Profile) -> alloc::vec::Vec +pub const fn lxst_core::TelephonyCall::transmit_squelched(&self) -> bool pub const lxst_core::APP_NAME: &str pub const lxst_core::FIELD_FRAMES: u8 pub const lxst_core::FIELD_SIGNALLING: u8 diff --git a/api/snapshots/lxst-embedded.txt b/api/snapshots/lxst-embedded.txt index 3849139..38f8833 100644 --- a/api/snapshots/lxst-embedded.txt +++ b/api/snapshots/lxst-embedded.txt @@ -33,12 +33,15 @@ pub lxst_embedded::wire::Error::Truncated pub lxst_embedded::wire::Error::UnknownCodec(u8) pub lxst_embedded::wire::Error::UnknownCodec2Mode(u8) pub enum lxst_embedded::wire::Signal +pub lxst_embedded::wire::Signal::PreferredMode(u8) pub lxst_embedded::wire::Signal::PreferredProfile(lxst_embedded::Profile) pub lxst_embedded::wire::Signal::Raw(u32) pub lxst_embedded::wire::Signal::Status(lxst_embedded::SignallingStatus) impl lxst_embedded::wire::Signal pub const fn lxst_embedded::wire::Signal::from_wire(u32) -> Self pub const fn lxst_embedded::wire::Signal::wire_value(self) -> u32 +impl core::convert::From for lxst_embedded::wire::Signal +pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self impl core::convert::From for lxst_embedded::wire::Signal pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self impl core::convert::From for lxst_embedded::wire::Signal @@ -63,6 +66,18 @@ impl lxst_embedded::AudioCodec pub const fn lxst_embedded::AudioCodec::channels(self) -> u8 pub const fn lxst_embedded::AudioCodec::codec_kind(self) -> lxst_embedded::wire::CodecKind pub const fn lxst_embedded::AudioCodec::sample_rate_hz(self) -> u32 +#[repr(u8)] pub enum lxst_embedded::CallMode +pub lxst_embedded::CallMode::FullDuplex = 1 +pub lxst_embedded::CallMode::HalfDuplex = 2 +impl lxst_embedded::CallMode +pub const lxst_embedded::CallMode::AVAILABLE: [Self; 2] +pub const lxst_embedded::CallMode::DEFAULT: Self +pub const fn lxst_embedded::CallMode::abbreviation(self) -> &'static str +pub const fn lxst_embedded::CallMode::from_wire(u8) -> core::option::Option +pub const fn lxst_embedded::CallMode::name(self) -> &'static str +pub const fn lxst_embedded::CallMode::wire_value(self) -> u8 +impl core::convert::From for lxst_embedded::wire::Signal +pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self pub enum lxst_embedded::CallRole pub lxst_embedded::CallRole::Incoming pub lxst_embedded::CallRole::Outgoing @@ -159,6 +174,7 @@ pub const lxst_embedded::Profile::DEFAULT: Self pub const lxst_embedded::Profile::ORDER: [Self; 8] pub const fn lxst_embedded::Profile::abbreviation(self) -> &'static str pub const fn lxst_embedded::Profile::audio_codec(self) -> lxst_embedded::AudioCodec +pub const fn lxst_embedded::Profile::buffer_frames(self) -> u8 pub const fn lxst_embedded::Profile::channels(self) -> u8 pub const fn lxst_embedded::Profile::frame_time_ms(self) -> u16 pub const fn lxst_embedded::Profile::from_wire(u32) -> core::option::Option @@ -176,12 +192,15 @@ pub lxst_embedded::QueueError::Expired pub lxst_embedded::QueueError::OutputCapacity pub lxst_embedded::QueueError::PayloadTooLarge pub enum lxst_embedded::Signal +pub lxst_embedded::Signal::PreferredMode(u8) pub lxst_embedded::Signal::PreferredProfile(lxst_embedded::Profile) pub lxst_embedded::Signal::Raw(u32) pub lxst_embedded::Signal::Status(lxst_embedded::SignallingStatus) impl lxst_embedded::wire::Signal pub const fn lxst_embedded::wire::Signal::from_wire(u32) -> Self pub const fn lxst_embedded::wire::Signal::wire_value(self) -> u32 +impl core::convert::From for lxst_embedded::wire::Signal +pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self impl core::convert::From for lxst_embedded::wire::Signal pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self impl core::convert::From for lxst_embedded::wire::Signal @@ -208,10 +227,13 @@ pub lxst_embedded::TelephonyAction::OpenAudioPipelines pub lxst_embedded::TelephonyAction::PrepareDialingPipelines pub lxst_embedded::TelephonyAction::ResetDialingPipelines pub lxst_embedded::TelephonyAction::RingIncomingCall +pub lxst_embedded::TelephonyAction::SelectMode(lxst_embedded::CallMode) pub lxst_embedded::TelephonyAction::SelectProfile(lxst_embedded::Profile) pub lxst_embedded::TelephonyAction::SendSignal(lxst_embedded::wire::Signal) +pub lxst_embedded::TelephonyAction::SendSignalPair(lxst_embedded::wire::Signal, lxst_embedded::wire::Signal) pub lxst_embedded::TelephonyAction::StartAudioPipelines pub lxst_embedded::TelephonyAction::StartDialTone +pub lxst_embedded::TelephonyAction::SwitchMode(lxst_embedded::CallMode) pub lxst_embedded::TelephonyAction::SwitchProfile(lxst_embedded::Profile) pub lxst_embedded::TelephonyAction::TeardownLink pub lxst_embedded::TelephonyAction::Terminate(core::option::Option) @@ -223,16 +245,21 @@ impl lxst_embedded::CallState pub fn lxst_embedded::CallState::answer(&mut self) -> lxst_embedded::Actions pub const fn lxst_embedded::CallState::answered(&self) -> bool pub fn lxst_embedded::CallState::caller_identified(&mut self, bool, bool) -> lxst_embedded::Actions +pub fn lxst_embedded::CallState::disable_remote_mode_follow(&mut self) pub fn lxst_embedded::CallState::hangup(&mut self, bool) -> lxst_embedded::Actions pub fn lxst_embedded::CallState::incoming() -> Self pub fn lxst_embedded::CallState::incoming_link_established(bool) -> lxst_embedded::Actions +pub const fn lxst_embedded::CallState::mode(&self) -> core::option::Option pub fn lxst_embedded::CallState::outgoing(core::option::Option) -> Self +pub fn lxst_embedded::CallState::outgoing_with_mode(core::option::Option, core::option::Option) -> Self pub const fn lxst_embedded::CallState::profile(&self) -> core::option::Option pub fn lxst_embedded::CallState::receive_signal(&mut self, lxst_embedded::wire::Signal) -> lxst_embedded::Actions -pub fn lxst_embedded::CallState::retry_answer(&self) -> lxst_embedded::Actions pub const fn lxst_embedded::CallState::role(&self) -> lxst_embedded::CallRole +pub fn lxst_embedded::CallState::set_transmit_squelched(&mut self, bool) pub const fn lxst_embedded::CallState::status(&self) -> lxst_embedded::SignallingStatus +pub fn lxst_embedded::CallState::switch_mode(&mut self, lxst_embedded::CallMode) -> lxst_embedded::Actions pub fn lxst_embedded::CallState::switch_profile(&mut self, lxst_embedded::Profile) -> lxst_embedded::Actions +pub const fn lxst_embedded::CallState::transmit_squelched(&self) -> bool pub struct lxst_embedded::Codec2PacketCodec impl lxst_embedded::Codec2PacketCodec pub fn lxst_embedded::Codec2PacketCodec::decode_into(&mut self, &[u8], &mut [i16]) -> core::result::Result::Error>> @@ -272,6 +299,7 @@ pub fn lxst_embedded::Session::end(&mut self, lxst_embedded::EndReason) -> lxst_ pub const fn lxst_embedded::Session::ended(&self) -> core::option::Option pub fn lxst_embedded::Session::link_established(&mut self) -> lxst_embedded::Events pub fn lxst_embedded::Session::media_ready(&self) -> bool +pub const fn lxst_embedded::Session::mode(&self) -> core::option::Option pub fn lxst_embedded::Session::new(lxst_embedded::CallRole, lxst_embedded::SessionConfig, u64) -> core::result::Result pub fn lxst_embedded::Session::peer_verified(&mut self, u64) -> lxst_embedded::Events pub fn lxst_embedded::Session::playback_allowed(&self) -> bool diff --git a/api/snapshots/lxst-telephony.txt b/api/snapshots/lxst-telephony.txt index 607ac7c..42eccf7 100644 --- a/api/snapshots/lxst-telephony.txt +++ b/api/snapshots/lxst-telephony.txt @@ -66,18 +66,27 @@ pub lxst_telephony::TelephonyCommand::ResetDialingPipelines::link_id: lxst_telep pub lxst_telephony::TelephonyCommand::RingIncomingCall pub lxst_telephony::TelephonyCommand::RingIncomingCall::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::RingIncomingCall::remote_identity: lxst_telephony::IdentityHash +pub lxst_telephony::TelephonyCommand::SelectMode +pub lxst_telephony::TelephonyCommand::SelectMode::link_id: lxst_telephony::LinkId +pub lxst_telephony::TelephonyCommand::SelectMode::mode: lxst_core::profile::CallMode pub lxst_telephony::TelephonyCommand::SelectProfile pub lxst_telephony::TelephonyCommand::SelectProfile::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::SelectProfile::profile: lxst_core::profile::Profile pub lxst_telephony::TelephonyCommand::SendSignal pub lxst_telephony::TelephonyCommand::SendSignal::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::SendSignal::signal: lxst_core::wire::Signal +pub lxst_telephony::TelephonyCommand::SendSignalPair +pub lxst_telephony::TelephonyCommand::SendSignalPair::link_id: lxst_telephony::LinkId +pub lxst_telephony::TelephonyCommand::SendSignalPair::signals: [lxst_core::wire::Signal; 2] pub lxst_telephony::TelephonyCommand::StartAudioPipelines pub lxst_telephony::TelephonyCommand::StartAudioPipelines::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::StartDialTone pub lxst_telephony::TelephonyCommand::StartDialTone::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::StopAudioPipelines pub lxst_telephony::TelephonyCommand::StopAudioPipelines::link_id: lxst_telephony::LinkId +pub lxst_telephony::TelephonyCommand::SwitchMode +pub lxst_telephony::TelephonyCommand::SwitchMode::link_id: lxst_telephony::LinkId +pub lxst_telephony::TelephonyCommand::SwitchMode::mode: lxst_core::profile::CallMode pub lxst_telephony::TelephonyCommand::SwitchProfile pub lxst_telephony::TelephonyCommand::SwitchProfile::link_id: lxst_telephony::LinkId pub lxst_telephony::TelephonyCommand::SwitchProfile::profile: lxst_core::profile::Profile @@ -99,8 +108,10 @@ pub lxst_telephony::TelephonyControl::Answer::expected_link_id: lxst_telephony:: pub lxst_telephony::TelephonyControl::Answer::reply: tokio::sync::oneshot::Sender> pub lxst_telephony::TelephonyControl::Call pub lxst_telephony::TelephonyControl::Call::discovery_timeout: core::time::Duration +pub lxst_telephony::TelephonyControl::Call::mode: core::option::Option pub lxst_telephony::TelephonyControl::Call::profile: core::option::Option pub lxst_telephony::TelephonyControl::Call::remote_identity: lxst_telephony::IdentityHash +pub lxst_telephony::TelephonyControl::DisableRemoteModeFollow pub lxst_telephony::TelephonyControl::Hangup pub lxst_telephony::TelephonyControl::Hangup::ring_timeout: bool pub lxst_telephony::TelephonyControl::SendAudioFrames @@ -115,6 +126,7 @@ pub lxst_telephony::TelephonyControl::SendRawFrames::frames: alloc::vec::Vec pub lxst_telephony::TelephonyControl::StartAudioStream @@ -131,6 +143,8 @@ pub lxst_telephony::TelephonyControl::StopAudioReceiveStream pub lxst_telephony::TelephonyControl::StopAudioStream pub lxst_telephony::TelephonyControl::StopOpusReceiveStream pub lxst_telephony::TelephonyControl::StopOpusStream +pub lxst_telephony::TelephonyControl::SwitchMode +pub lxst_telephony::TelephonyControl::SwitchMode::mode: lxst_core::profile::CallMode pub lxst_telephony::TelephonyControl::SwitchProfile pub lxst_telephony::TelephonyControl::SwitchProfile::profile: lxst_core::profile::Profile pub enum lxst_telephony::TelephonyLinkEvent @@ -228,10 +242,12 @@ pub lxst_telephony::ActiveCall::remote_identity: lxst_telephony::IdentityHash pub struct lxst_telephony::ActiveCallSnapshot pub lxst_telephony::ActiveCallSnapshot::answered: bool pub lxst_telephony::ActiveCallSnapshot::link_id: lxst_telephony::LinkId +pub lxst_telephony::ActiveCallSnapshot::mode: core::option::Option pub lxst_telephony::ActiveCallSnapshot::profile: core::option::Option pub lxst_telephony::ActiveCallSnapshot::remote_identity: lxst_telephony::IdentityHash pub lxst_telephony::ActiveCallSnapshot::role: lxst_core::telephony::CallRole pub lxst_telephony::ActiveCallSnapshot::status: lxst_core::profile::SignallingStatus +pub lxst_telephony::ActiveCallSnapshot::transmit_squelched: bool pub struct lxst_telephony::AudioTransmitGate impl lxst_telephony::AudioTransmitGate pub fn lxst_telephony::AudioTransmitGate::allows(&self) -> bool @@ -265,6 +281,7 @@ impl lxst_telephony::TelephonyRnsEndpoint pub fn lxst_telephony::TelephonyRnsEndpoint::announce(&self) -> core::result::Result<(), lxst_telephony::Error> pub fn lxst_telephony::TelephonyRnsEndpoint::await_path_to_identity(&self, lxst_telephony::IdentityHash, core::time::Duration) -> impl core::future::future::Future> + core::marker::Send + 'static pub async fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, core::option::Option, core::time::Duration) -> core::result::Result +pub fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link_with_mode(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, [u8; 64], core::option::Option, core::option::Option, u8) -> core::result::Result pub fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link_with_remote_pubkey(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, [u8; 64], core::option::Option, u8) -> core::result::Result pub fn lxst_telephony::TelephonyRnsEndpoint::deregister_destination(&self) -> core::result::Result<(), lxst_telephony::Error> pub fn lxst_telephony::TelephonyRnsEndpoint::deregister_link_destination(&self, lxst_telephony::LinkId) -> core::result::Result<(), lxst_telephony::Error> @@ -293,6 +310,8 @@ pub const fn lxst_telephony::TelephonyRuntimeCore::access_policy(&self) -> &lxst pub fn lxst_telephony::TelephonyRuntimeCore::active_call(&self) -> core::option::Option<&lxst_telephony::ActiveCall> pub fn lxst_telephony::TelephonyRuntimeCore::answer_active(&mut self, lxst_telephony::LinkId) -> core::result::Result, lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::caller_identified(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash) -> core::result::Result, lxst_telephony::Error> +pub const fn lxst_telephony::TelephonyRuntimeCore::dialling(&self) -> bool +pub fn lxst_telephony::TelephonyRuntimeCore::disable_remote_mode_follow(&mut self) -> core::result::Result<(), lxst_telephony::Error> pub const fn lxst_telephony::TelephonyRuntimeCore::external_busy(&self) -> bool pub fn lxst_telephony::TelephonyRuntimeCore::hangup_active(&mut self, bool) -> core::result::Result, lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::incoming_link_established(&mut self, lxst_telephony::LinkId) -> alloc::vec::Vec @@ -303,10 +322,13 @@ pub fn lxst_telephony::TelephonyRuntimeCore::outgoing_link_established(&mut self pub fn lxst_telephony::TelephonyRuntimeCore::pending_link_count(&self) -> usize pub fn lxst_telephony::TelephonyRuntimeCore::receive_signal(&mut self, lxst_telephony::LinkId, lxst_core::wire::Signal) -> core::result::Result, lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::set_access_policy(&mut self, lxst_telephony::CallerAccessPolicy) +pub fn lxst_telephony::TelephonyRuntimeCore::set_active_transmit_squelched(&mut self, bool) -> core::result::Result<(), lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::set_external_busy(&mut self, bool) pub fn lxst_telephony::TelephonyRuntimeCore::shutdown(&mut self) -> alloc::vec::Vec pub fn lxst_telephony::TelephonyRuntimeCore::snapshot(&self) -> lxst_telephony::TelephonyRuntimeSnapshot pub fn lxst_telephony::TelephonyRuntimeCore::start_outgoing_call(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash, core::option::Option) -> core::result::Result<(), lxst_telephony::Error> +pub fn lxst_telephony::TelephonyRuntimeCore::start_outgoing_call_with_mode(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash, core::option::Option, core::option::Option) -> core::result::Result<(), lxst_telephony::Error> +pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_mode(&mut self, lxst_core::profile::CallMode) -> core::result::Result, lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_profile(&mut self, lxst_core::profile::Profile) -> core::result::Result, lxst_telephony::Error> pub fn lxst_telephony::TelephonyRuntimeCore::with_access_policy(lxst_telephony::CallerAccessPolicy) -> Self pub struct lxst_telephony::TelephonyRuntimeSnapshot @@ -328,8 +350,7 @@ pub fn lxst_telephony::TelephonyServiceChannelConfig::default() -> Self pub struct lxst_telephony::TelephonyServiceConfig pub lxst_telephony::TelephonyServiceConfig::announce_interval: core::option::Option pub lxst_telephony::TelephonyServiceConfig::announce_on_start: bool -pub lxst_telephony::TelephonyServiceConfig::answer_retry_interval: core::option::Option -pub lxst_telephony::TelephonyServiceConfig::answer_timeout: core::option::Option +pub lxst_telephony::TelephonyServiceConfig::connect_timeout: core::option::Option pub lxst_telephony::TelephonyServiceConfig::incoming_ring_timeout: core::option::Option pub lxst_telephony::TelephonyServiceConfig::media_frames_per_tick: usize pub lxst_telephony::TelephonyServiceConfig::outgoing_call_timeout: core::option::Option @@ -348,8 +369,12 @@ pub lxst_telephony::TelephonyStep::inbound: core::option::Option) -> Self pub const lxst_telephony::TELEPHONY_ANNOUNCE_INTERVAL: core::time::Duration +pub const lxst_telephony::TELEPHONY_CONNECT_TIME: core::time::Duration +pub const lxst_telephony::TELEPHONY_JOB_INTERVAL: core::time::Duration +pub const lxst_telephony::TELEPHONY_RING_TIME: core::time::Duration pub const lxst_telephony::TELEPHONY_STARTUP_ANNOUNCE_RETRIES: u8 pub const lxst_telephony::TELEPHONY_STARTUP_ANNOUNCE_RETRY_INTERVAL: core::time::Duration +pub const lxst_telephony::TELEPHONY_WAIT_TIME: core::time::Duration pub fn lxst_telephony::execute_command_with_link(&tokio::sync::mpsc::bounded::Sender, &[u8; 64], &rns_identity::identity::Identity, &mut rns_link::link::Link, &lxst_telephony::TelephonyCommand) -> core::result::Result pub async fn lxst_telephony::request_answer(&tokio::sync::mpsc::bounded::Sender, lxst_telephony::LinkId) -> core::result::Result pub fn lxst_telephony::signalling_packet(lxst_core::wire::Signal) -> lxst_core::wire::LxstPacket diff --git a/api/stability.json b/api/stability.json index bc7a278..966e68b 100644 --- a/api/stability.json +++ b/api/stability.json @@ -33,8 +33,8 @@ "tier": "experimental", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxst-embedded.txt", - "itemCount": 299, - "sha256": "7cfa734581040e35c4b817422376e4e99c9f7d447181d9e3a9e1dac0912b9295" + "itemCount": 327, + "sha256": "072f231f31bce55c2aa0b5466988b3e62af42f66cc5e30b8f7c2572b1eef0d8d" }, { "name": "lxst-core", @@ -42,8 +42,8 @@ "tier": "experimental", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxst-core.txt", - "itemCount": 364, - "sha256": "2c272021cc340af7f779d944bebb336ae1804938239a8ead3cbf11a8074022e4" + "itemCount": 396, + "sha256": "a55ad460bfe1c4a2d689ed94dda09ff2625d9c3aee05285bf1cbd792f6d72f1e" }, { "name": "lxst-rns", @@ -60,8 +60,8 @@ "tier": "experimental", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxst-telephony.txt", - "itemCount": 360, - "sha256": "c9b9784a9b09bb41a9beffb29b62085b21f2b22cb8b7d18ef53ea9f673d77698" + "itemCount": 385, + "sha256": "1e7083b6302801c0d7f2417ff182e4dc559e1bf5a1ebde8638efaae26af62a24" } ], "newPackages": [ diff --git a/crates/lxst-core/src/lib.rs b/crates/lxst-core/src/lib.rs index 25beb41..8c35d54 100644 --- a/crates/lxst-core/src/lib.rs +++ b/crates/lxst-core/src/lib.rs @@ -21,10 +21,10 @@ mod wire; pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError}; pub use opus::{ OPUS_ENCODED_FRAME_MAX_BYTES, OPUS_ENCODED_PACKET_MAX_BYTES, OPUS_MONO_DECODE_SAMPLE_RATE_HZ, - OpusCodecError, OpusDecoderState, OpusEncoderState, OpusMonoDecoder, + OpusCodecError, OpusDecoderState, OpusEncoderState, OpusMonoDecoder, OpusPacketDecoder, opus_packet_duration_samples_48k, }; -pub use profile::{AudioCodec, OpusApplication, OpusProfile, Profile, SignallingStatus}; +pub use profile::{AudioCodec, CallMode, OpusApplication, OpusProfile, Profile, SignallingStatus}; pub use raw::RawAudioFrame; pub use stream::{ DropPolicy, FramePacketizer, FrameStreamEvent, FrameStreamState, JitterBuffer, JitterPush, diff --git a/crates/lxst-core/src/opus.rs b/crates/lxst-core/src/opus.rs index f79f38f..03f0953 100644 --- a/crates/lxst-core/src/opus.rs +++ b/crates/lxst-core/src/opus.rs @@ -404,6 +404,87 @@ impl OpusMonoDecoder { } } +/// Decodes any legal Opus packet (2.5 to 120 ms, mono or stereo) to a fixed sample rate +/// and channel count, as Python's libopus decoder does whatever the local profile is. +pub struct OpusPacketDecoder { + sample_rate_hz: u32, + channels: u8, + decoders: [Option; 2], +} + +impl OpusPacketDecoder { + pub fn new(sample_rate_hz: u32, channels: u8) -> Result { + if !matches!(sample_rate_hz, 8_000 | 12_000 | 16_000 | 24_000 | 48_000) { + return Err(OpusCodecError::UnsupportedFrameDuration { + sample_rate_hz, + sample_frames: 0, + }); + } + if !matches!(channels, 1 | 2) { + return Err(OpusCodecError::ChannelMismatch { + expected: 2, + actual: channels, + }); + } + Ok(Self { + sample_rate_hz, + channels, + decoders: [None, None], + }) + } + + pub const fn sample_rate_hz(&self) -> u32 { + self.sample_rate_hz + } + + pub const fn channels(&self) -> u8 { + self.channels + } + + pub fn decode_packet(&mut self, packet: &[u8]) -> Result { + let inspected = inspect_opus_packet(packet)?; + let packet_channels = usize::from(inspected.channels); + let samples_per_frame = + inspected.samples_per_frame_48k * self.sample_rate_hz as usize / 48_000; + let slot = &mut self.decoders[packet_channels - 1]; + if slot.is_none() { + *slot = Some( + OpusDecoder::new(self.sample_rate_hz as i32, packet_channels) + .map_err(|err| OpusCodecError::Codec(err.to_string()))?, + ); + } + let decoder = slot.as_mut().expect("decoder exists after creation"); + + let mut samples = + Vec::with_capacity(samples_per_frame * inspected.frames.len() * packet_channels); + let direct_toc = inspected.toc & !0x03; + for payload in inspected.frames { + let mut direct_packet = Vec::with_capacity(payload.len() + 1); + direct_packet.push(direct_toc); + direct_packet.extend_from_slice(payload); + + let output_start = samples.len(); + samples.resize(output_start + samples_per_frame * packet_channels, 0.0); + let decoded = decoder + .decode( + &direct_packet, + samples_per_frame, + &mut samples[output_start..], + ) + .map_err(|err| OpusCodecError::Codec(err.to_string()))?; + if decoded != samples_per_frame { + return Err(OpusCodecError::DecodedPacketDurationMismatch { + expected: samples_per_frame, + actual: decoded, + }); + } + } + + let frame = RawAudioFrame::new(inspected.channels, samples)?; + Ok(frame.with_channels(self.channels)?) + } +} + /// Returns a supported packet's total duration in samples at the Opus 48 kHz clock. /// /// The packet is structurally inspected using the framing rules from RFC 6716. Every legal @@ -683,7 +764,7 @@ fn supports_direct_frame(sample_rate_hz: u32, sample_frames: usize) -> bool { sample_frames != 0 && (sample_rate_hz as usize).is_multiple_of(sample_frames) } -fn resample_interleaved_linear( +pub(crate) fn resample_interleaved_linear( input: &[f32], input_frames: usize, output_frames: usize, diff --git a/crates/lxst-core/src/raw.rs b/crates/lxst-core/src/raw.rs index 3427a7e..0e14398 100644 --- a/crates/lxst-core/src/raw.rs +++ b/crates/lxst-core/src/raw.rs @@ -46,6 +46,46 @@ impl RawAudioFrame { }) } + /// Convert to `channels`: mono is duplicated, extra channels are averaged to mono, + /// otherwise the leading channels are kept and the last one repeated. + pub fn with_channels(self, channels: u8) -> Result { + if channels == self.channels { + return Ok(self); + } + let source = usize::from(self.channels); + let target = usize::from(channels); + let mut samples = Vec::with_capacity(self.sample_frames() * target); + for frame in self.samples.chunks_exact(source) { + if target == 1 { + samples.push(frame.iter().sum::() / source as f32); + } else { + for channel in 0..target { + samples.push(frame[channel.min(source - 1)]); + } + } + } + Self::new(channels, samples) + } + + /// Linearly resample from `input_rate_hz` to `output_rate_hz`. + pub fn resampled(&self, input_rate_hz: u32, output_rate_hz: u32) -> Self { + if input_rate_hz == output_rate_hz || input_rate_hz == 0 { + return self.clone(); + } + let input_frames = self.sample_frames(); + let output_frames = + (input_frames as u64 * u64::from(output_rate_hz) / u64::from(input_rate_hz)) as usize; + Self { + channels: self.channels, + samples: crate::opus::resample_interleaved_linear( + &self.samples, + input_frames, + output_frames, + usize::from(self.channels), + ), + } + } + pub fn to_payload(&self, bit_depth: RawBitDepth) -> Result, Error> { validate_sample_count(self.channels, self.samples.len())?; let header = RawFrameHeader::new(self.channels, bit_depth)?; @@ -92,7 +132,7 @@ fn decode_samples(bytes: &[u8], bit_depth: RawBitDepth) -> Result, Erro } RawBitDepth::Float128 => { for chunk in bytes.as_chunks::<16>().0 { - samples.push(decode_float128_lossy(chunk)); + samples.push(decode_float128(chunk)); } } } @@ -125,24 +165,50 @@ fn encode_samples(samples: &[f32], bit_depth: RawBitDepth, out: &mut Vec) { } } -fn decode_float128_lossy(bytes: &[u8]) -> f32 { - // Python/Numpy names this dtype "float128", but on common little-endian - // platforms it may be backed by an 80-bit extended value padded to 16 bytes. - // We preserve finite zero exactly and otherwise use the leading f64 lane as - // a conservative lossy fallback until a platform-specific long-double codec - // is introduced. - if bytes.iter().all(|byte| *byte == 0) { +// numpy float128 is IEEE binary128 on Linux aarch64; x86_64 pads an 80-bit value instead. +const BINARY128_EXPONENT_BIAS: i32 = 16_383; +const BINARY128_MANTISSA_BITS: u32 = 112; + +fn decode_float128(bytes: &[u8]) -> f32 { + let mut le = [0u8; 16]; + le.copy_from_slice(bytes); + let bits = u128::from_le_bytes(le); + let negative = bits >> 127 != 0; + let exponent = ((bits >> BINARY128_MANTISSA_BITS) & 0x7FFF) as i32; + let mantissa = bits & ((1u128 << BINARY128_MANTISSA_BITS) - 1); + let magnitude = if exponent == 0x7FFF { + if mantissa == 0 { + f64::INFINITY + } else { + f64::NAN + } + } else if exponent == 0 { + // Subnormal binary128 values are far below the f32 range. 0.0 } else { - f64::from_le_bytes([ - bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], - ]) as f32 - } + let fraction = (mantissa >> (BINARY128_MANTISSA_BITS - 52)) as f64 / (1u64 << 52) as f64; + (1.0 + fraction) * 2f64.powi(exponent - BINARY128_EXPONENT_BIAS) + }; + (if negative { -magnitude } else { magnitude }) as f32 } fn encode_float128_from_f32(sample: f32, out: &mut Vec) { - out.extend_from_slice(&f64::from(sample).to_le_bytes()); - out.extend_from_slice(&[0u8; 8]); + let value = f64::from(sample); + let f64_bits = value.to_bits(); + let sign = u128::from(f64_bits >> 63) << 127; + let exponent = ((f64_bits >> 52) & 0x7FF) as i32; + let mantissa = u128::from(f64_bits & ((1u64 << 52) - 1)); + let bits = if value == 0.0 { + sign + } else if exponent == 0x7FF { + let nan_mantissa = if mantissa == 0 { 0 } else { 1u128 << 111 }; + sign | (0x7FFFu128 << BINARY128_MANTISSA_BITS) | nan_mantissa + } else { + // Every f32 widens to a normal f64. + let exponent = (exponent - 1023 + BINARY128_EXPONENT_BIAS) as u128; + sign | (exponent << BINARY128_MANTISSA_BITS) | (mantissa << (BINARY128_MANTISSA_BITS - 52)) + }; + out.extend_from_slice(&bits.to_le_bytes()); } #[cfg(test)] diff --git a/crates/lxst-core/src/shared/actions.rs b/crates/lxst-core/src/shared/actions.rs index a303aec..6aad575 100644 --- a/crates/lxst-core/src/shared/actions.rs +++ b/crates/lxst-core/src/shared/actions.rs @@ -1,16 +1,16 @@ use crate::Signal; use crate::TelephonyAction; -/// Every current transition emits at most four ordered actions. +/// Every current transition emits at most six ordered actions. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Actions { - items: [TelephonyAction; 4], + items: [TelephonyAction; 6], length: usize, } impl Actions { pub(crate) fn new() -> Self { Self { - items: [const { TelephonyAction::IgnoreSignal(Signal::Raw(0)) }; 4], + items: [const { TelephonyAction::IgnoreSignal(Signal::Raw(0)) }; 6], length: 0, } } diff --git a/crates/lxst-core/src/shared/call_types.rs b/crates/lxst-core/src/shared/call_types.rs index 4a18f0e..ccf9d85 100644 --- a/crates/lxst-core/src/shared/call_types.rs +++ b/crates/lxst-core/src/shared/call_types.rs @@ -1,4 +1,4 @@ -use crate::{Profile, Signal, SignallingStatus}; +use crate::{CallMode, Profile, Signal, SignallingStatus}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CallRole { @@ -9,6 +9,8 @@ pub enum CallRole { #[derive(Debug, Clone, PartialEq, Eq)] pub enum TelephonyAction { SendSignal(Signal), + /// Send both signals in one packet, as Python sends profile and mode on RINGING. + SendSignalPair(Signal, Signal), IdentifyLocalIdentity, SelectProfile(Profile), PrepareDialingPipelines, @@ -20,5 +22,7 @@ pub enum TelephonyAction { TeardownLink, RingIncomingCall, SwitchProfile(Profile), + SelectMode(CallMode), + SwitchMode(CallMode), IgnoreSignal(Signal), } diff --git a/crates/lxst-core/src/shared/profile.rs b/crates/lxst-core/src/shared/profile.rs index 72aaf1f..e433024 100644 --- a/crates/lxst-core/src/shared/profile.rs +++ b/crates/lxst-core/src/shared/profile.rs @@ -159,6 +159,21 @@ impl Profile { } } + /// Python `Profiles.get_buffer_frames`: its sink holds one frame more than this and + /// starts playback at `max(1, buffer_frames() - 2)` frames. + pub const fn buffer_frames(self) -> u8 { + match self { + Self::BandwidthUltraLow => 2, + Self::BandwidthVeryLow => 2, + Self::BandwidthLow => 2, + Self::QualityMedium => 5, + Self::QualityHigh => 5, + Self::QualityMax => 5, + Self::LatencyLow => 3, + Self::LatencyUltraLow => 2, + } + } + pub fn next(self) -> Self { let index = Self::ORDER .iter() @@ -168,6 +183,44 @@ impl Profile { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum CallMode { + FullDuplex = 0x01, + HalfDuplex = 0x02, +} + +impl CallMode { + pub const DEFAULT: Self = Self::FullDuplex; + pub const AVAILABLE: [Self; 2] = [Self::FullDuplex, Self::HalfDuplex]; + + pub const fn wire_value(self) -> u8 { + self as u8 + } + + pub const fn from_wire(value: u8) -> Option { + match value { + 0x01 => Some(Self::FullDuplex), + 0x02 => Some(Self::HalfDuplex), + _ => None, + } + } + + pub const fn name(self) -> &'static str { + match self { + Self::FullDuplex => "Full Duplex", + Self::HalfDuplex => "Half Duplex", + } + } + + pub const fn abbreviation(self) -> &'static str { + match self { + Self::FullDuplex => "FDX", + Self::HalfDuplex => "HDX", + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AudioCodec { Opus(OpusProfile), diff --git a/crates/lxst-core/src/shared/telephony.rs b/crates/lxst-core/src/shared/telephony.rs index 80f2295..2a08739 100644 --- a/crates/lxst-core/src/shared/telephony.rs +++ b/crates/lxst-core/src/shared/telephony.rs @@ -1,5 +1,5 @@ use crate::actions::Actions; -use crate::{CallRole, Profile, Signal, SignallingStatus, TelephonyAction}; +use crate::{CallMode, CallRole, Profile, Signal, SignallingStatus, TelephonyAction}; macro_rules! actions { ($($value:expr),* $(,)?) => { Actions::from_array([$($value),*]) }; @@ -10,16 +10,27 @@ pub struct CallState { role: CallRole, status: SignallingStatus, profile: Option, + /// Raw mode value; Python stores unknown modes without acting on them. + mode: Option, answered: bool, + transmit_squelched: bool, + remote_mode_follow_disabled: bool, } impl CallState { pub fn outgoing(profile: Option) -> Self { + Self::outgoing_with_mode(profile, None) + } + + pub fn outgoing_with_mode(profile: Option, mode: Option) -> Self { Self { role: CallRole::Outgoing, status: SignallingStatus::Calling, profile, + mode: mode.map(|mode| mode.wire_value()), answered: false, + transmit_squelched: false, + remote_mode_follow_disabled: false, } } @@ -28,7 +39,10 @@ impl CallState { role: CallRole::Incoming, status: SignallingStatus::Available, profile: None, + mode: None, answered: false, + transmit_squelched: false, + remote_mode_follow_disabled: false, } } @@ -48,6 +62,29 @@ impl CallState { self.answered } + /// Selected call mode, or `None` before selection or for an unknown remote mode. + pub const fn mode(&self) -> Option { + match self.mode { + Some(value) => CallMode::from_wire(value), + None => None, + } + } + + /// Whether outbound media frames are dropped, as Python's squelched Packetizer. + pub const fn transmit_squelched(&self) -> bool { + self.transmit_squelched + } + + /// Squelch or unsquelch transmit locally without signalling, as Python `squelch_transmit`. + pub fn set_transmit_squelched(&mut self, squelched: bool) { + self.transmit_squelched = squelched; + } + + /// Ignore later remote mode switches, as Python `disable_remote_mode_follow`. + pub fn disable_remote_mode_follow(&mut self) { + self.remote_mode_follow_disabled = true; + } + pub fn incoming_link_established(line_busy: bool) -> Actions { if line_busy { actions![ @@ -84,36 +121,15 @@ impl CallState { let mut actions = Actions::new(); self.answered = true; self.ensure_profile(&mut actions); + self.ensure_mode(&mut actions); + self.squelch_for_opened_pipelines(); self.push_status_signal(SignallingStatus::Connecting, &mut actions); actions.push(TelephonyAction::OpenAudioPipelines); - // Python LXST sends ESTABLISHED as the final half of the answer offer, - // then the outgoing peer echoes ESTABLISHED while opening its own - // pipelines. Keep the incoming call in CONNECTING until that remote - // echo is observed: local queue admission alone is not proof that the - // caller received the answer. - actions.push(TelephonyAction::SendSignal(Signal::from( - SignallingStatus::Established, - ))); + self.push_status_signal(SignallingStatus::Established, &mut actions); + actions.push(TelephonyAction::StartAudioPipelines); actions } - /// Return the answer offer again without reopening pipelines or changing state. - /// The caller controls retry timing and count. No actions are returned once - /// the incoming call leaves CONNECTING, including after an ESTABLISHED echo. - pub fn retry_answer(&self) -> Actions { - if self.role != CallRole::Incoming - || !self.answered - || self.status != SignallingStatus::Connecting - { - return Actions::new(); - } - - actions![ - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), - ] - } - pub fn receive_signal(&mut self, signal: Signal) -> Actions { if self.role == CallRole::Incoming && !self.answered && matches!(signal, Signal::Status(_)) { @@ -143,11 +159,13 @@ impl CallState { } let mut actions = Actions::new(); self.status = SignallingStatus::Ringing; - self.ensure_profile(&mut actions); + let profile = self.ensure_profile(&mut actions); + let mode = self.ensure_mode(&mut actions); actions.push(TelephonyAction::PrepareDialingPipelines); - if let Some(profile) = self.profile { - actions.push(TelephonyAction::SendSignal(Signal::from(profile))); - } + actions.push(TelephonyAction::SendSignalPair( + Signal::from(profile), + Signal::PreferredMode(mode), + )); actions.push(TelephonyAction::StartDialTone); actions } @@ -155,9 +173,8 @@ impl CallState { if self.role == CallRole::Outgoing && self.status.wire_value() >= SignallingStatus::Connecting.wire_value() { - // A delayed/retried CONNECTING must not regress an already - // established call. Re-echo ESTABLISHED so an incoming - // peer can recover if its first acknowledgement was lost. + // Python answers every CONNECTING with ESTABLISHED, and callees + // from rsLXST 0.3.1 and earlier resend CONNECTING until they see it. return actions![TelephonyAction::SendSignal(Signal::from( SignallingStatus::Established, ))]; @@ -166,6 +183,7 @@ impl CallState { return actions![TelephonyAction::IgnoreSignal(signal)]; } self.status = SignallingStatus::Connecting; + self.squelch_for_opened_pipelines(); let mut actions = actions![ TelephonyAction::ResetDialingPipelines, TelephonyAction::OpenAudioPipelines, @@ -198,10 +216,45 @@ impl CallState { actions![TelephonyAction::SelectProfile(profile)] } } + Signal::PreferredMode(mode) => { + if self.status == SignallingStatus::Established { + if self.remote_mode_follow_disabled || self.mode == Some(mode) { + return Actions::new(); + } + let Some(known) = CallMode::from_wire(mode) else { + return Actions::new(); + }; + self.mode = Some(mode); + self.apply_mode_squelch(known); + actions![TelephonyAction::SwitchMode(known)] + } else { + self.mode = Some(mode); + match CallMode::from_wire(mode) { + Some(known) => { + self.apply_mode_squelch(known); + actions![TelephonyAction::SelectMode(known)] + } + None => Actions::new(), + } + } + } Signal::Raw(_) => actions![TelephonyAction::IgnoreSignal(signal)], } } + /// Switch the mode of an established call and signal it, as Python `switch_mode`. + pub fn switch_mode(&mut self, mode: CallMode) -> Actions { + if self.status != SignallingStatus::Established || self.mode == Some(mode.wire_value()) { + return Actions::new(); + } + self.mode = Some(mode.wire_value()); + self.apply_mode_squelch(mode); + actions![ + TelephonyAction::SendSignal(Signal::from(mode)), + TelephonyAction::SwitchMode(mode), + ] + } + pub fn switch_profile(&mut self, profile: Profile) -> Actions { if self.profile == Some(profile) { return Actions::new(); @@ -236,10 +289,31 @@ impl CallState { actions } - fn ensure_profile(&mut self, actions: &mut Actions) { + fn ensure_profile(&mut self, actions: &mut Actions) -> Profile { let profile = self.profile.unwrap_or(Profile::DEFAULT); self.profile = Some(profile); actions.push(TelephonyAction::SelectProfile(profile)); + profile + } + + /// Python `__select_call_mode`: an unset mode becomes the default, an unknown one is kept. + fn ensure_mode(&mut self, actions: &mut Actions) -> u8 { + let mode = self.mode.unwrap_or(CallMode::DEFAULT.wire_value()); + self.mode = Some(mode); + if let Some(known) = CallMode::from_wire(mode) { + self.apply_mode_squelch(known); + actions.push(TelephonyAction::SelectMode(known)); + } + mode + } + + fn apply_mode_squelch(&mut self, mode: CallMode) { + self.transmit_squelched = mode == CallMode::HalfDuplex; + } + + /// Python builds a new Packetizer when pipelines open and squelches it only for half duplex. + fn squelch_for_opened_pipelines(&mut self) { + self.transmit_squelched = self.mode == Some(CallMode::HalfDuplex.wire_value()); } fn push_status_signal(&mut self, status: SignallingStatus, actions: &mut Actions) { diff --git a/crates/lxst-core/src/shared/wire_types.rs b/crates/lxst-core/src/shared/wire_types.rs index cee00fa..76fa5ad 100644 --- a/crates/lxst-core/src/shared/wire_types.rs +++ b/crates/lxst-core/src/shared/wire_types.rs @@ -1,6 +1,7 @@ // Shared directly with lxst-embedded. The enclosing wire module supplies its // own error type; wire identifiers and conversions have one implementation. -use crate::profile::{Profile, SignallingStatus}; +use crate::profile::{CallMode, Profile, SignallingStatus}; +const PREFERRED_MODE_BASE: u32 = 0xF0; const PREFERRED_PROFILE_BASE: u32 = 0xFF; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -36,6 +37,8 @@ impl CodecKind { pub enum Signal { Status(SignallingStatus), PreferredProfile(Profile), + /// Raw mode byte after `0xF0`; unknown modes are carried, not rejected. + PreferredMode(u8), Raw(u32), } @@ -44,6 +47,7 @@ impl Signal { match self { Self::Status(status) => status.wire_value(), Self::PreferredProfile(profile) => PREFERRED_PROFILE_BASE + profile.wire_value(), + Self::PreferredMode(mode) => PREFERRED_MODE_BASE + mode as u32, Self::Raw(value) => value, } } @@ -58,6 +62,8 @@ impl Signal { } else { Self::Raw(value) } + } else if value >= PREFERRED_MODE_BASE { + Self::PreferredMode((value - PREFERRED_MODE_BASE) as u8) } else { Self::Raw(value) } @@ -70,6 +76,12 @@ impl From for Signal { } } +impl From for Signal { + fn from(value: CallMode) -> Self { + Self::PreferredMode(value.wire_value()) + } +} + impl From for Signal { fn from(value: Profile) -> Self { Self::PreferredProfile(value) diff --git a/crates/lxst-core/src/telephony.rs b/crates/lxst-core/src/telephony.rs index 0e46c4e..e9d662d 100644 --- a/crates/lxst-core/src/telephony.rs +++ b/crates/lxst-core/src/telephony.rs @@ -12,6 +12,11 @@ impl TelephonyCall { state: CallState::outgoing(profile), } } + pub fn outgoing_with_mode(profile: Option, mode: Option) -> Self { + Self { + state: CallState::outgoing_with_mode(profile, mode), + } + } pub fn incoming() -> Self { Self { state: CallState::incoming(), @@ -29,6 +34,21 @@ impl TelephonyCall { pub const fn answered(&self) -> bool { self.state.answered() } + pub const fn mode(&self) -> Option { + self.state.mode() + } + pub const fn transmit_squelched(&self) -> bool { + self.state.transmit_squelched() + } + pub fn set_transmit_squelched(&mut self, squelched: bool) { + self.state.set_transmit_squelched(squelched); + } + pub fn disable_remote_mode_follow(&mut self) { + self.state.disable_remote_mode_follow(); + } + pub fn switch_mode(&mut self, mode: CallMode) -> Vec { + self.state.switch_mode(mode).as_slice().to_vec() + } pub fn incoming_link_established(line_busy: bool) -> Vec { CallState::incoming_link_established(line_busy) .as_slice() @@ -43,9 +63,6 @@ impl TelephonyCall { pub fn answer(&mut self) -> Vec { self.state.answer().as_slice().to_vec() } - pub fn retry_answer(&self) -> Vec { - self.state.retry_answer().as_slice().to_vec() - } pub fn receive_signal(&mut self, signal: Signal) -> Vec { self.state.receive_signal(signal).as_slice().to_vec() } @@ -93,22 +110,27 @@ mod tests { ); let answer = call.answer(); - assert_eq!(call.status(), SignallingStatus::Connecting); + assert_eq!(call.status(), SignallingStatus::Established); assert!(call.answered()); assert_eq!(call.profile(), Some(Profile::DEFAULT)); + assert_eq!(call.mode(), Some(CallMode::FullDuplex)); assert_eq!( answer, vec![ TelephonyAction::SelectProfile(Profile::DEFAULT), + TelephonyAction::SelectMode(CallMode::FullDuplex), TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), TelephonyAction::OpenAudioPipelines, TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), + TelephonyAction::StartAudioPipelines, ] ); assert_eq!( call.receive_signal(Signal::from(SignallingStatus::Established)), - vec![TelephonyAction::StartAudioPipelines] + vec![TelephonyAction::IgnoreSignal(Signal::from( + SignallingStatus::Established + ))] ); assert_eq!(call.status(), SignallingStatus::Established); } @@ -128,8 +150,12 @@ mod tests { ringing, vec![ TelephonyAction::SelectProfile(Profile::DEFAULT), + TelephonyAction::SelectMode(CallMode::FullDuplex), TelephonyAction::PrepareDialingPipelines, - TelephonyAction::SendSignal(Signal::from(Profile::DEFAULT)), + TelephonyAction::SendSignalPair( + Signal::from(Profile::DEFAULT), + Signal::from(CallMode::FullDuplex), + ), TelephonyAction::StartDialTone, ] ); @@ -150,29 +176,18 @@ mod tests { } #[test] - fn answer_retry_and_established_echo_are_bounded_idempotent_transitions() { + fn callee_is_established_on_answer_and_ignores_the_caller_echo() { let mut incoming = TelephonyCall::incoming(); incoming.caller_identified(false, true); incoming.answer(); - assert_eq!( - incoming.retry_answer(), - vec![ - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), - ] - ); - - assert_eq!( - incoming.receive_signal(Signal::from(SignallingStatus::Established)), - vec![TelephonyAction::StartAudioPipelines] - ); - assert!(incoming.retry_answer().is_empty()); + assert_eq!(incoming.status(), SignallingStatus::Established); assert_eq!( incoming.receive_signal(Signal::from(SignallingStatus::Established)), vec![TelephonyAction::IgnoreSignal(Signal::from( SignallingStatus::Established ))] ); + assert!(incoming.answer().is_empty()); let mut outgoing = TelephonyCall::outgoing(Some(Profile::DEFAULT)); outgoing.receive_signal(Signal::from(SignallingStatus::Available)); @@ -188,6 +203,116 @@ mod tests { assert_eq!(outgoing.status(), SignallingStatus::Established); } + #[test] + fn ringing_sends_profile_and_requested_mode_in_one_packet() { + let mut call = TelephonyCall::outgoing_with_mode( + Some(Profile::BandwidthLow), + Some(CallMode::HalfDuplex), + ); + call.receive_signal(Signal::from(SignallingStatus::Available)); + let ringing = call.receive_signal(Signal::from(SignallingStatus::Ringing)); + assert!(ringing.contains(&TelephonyAction::SendSignalPair( + Signal::from(Profile::BandwidthLow), + Signal::from(CallMode::HalfDuplex), + ))); + assert!(call.transmit_squelched()); + assert_eq!(Signal::from(CallMode::HalfDuplex).wire_value(), 0xF2); + } + + #[test] + fn mode_signal_before_answer_is_selected_but_status_is_ignored() { + let mut call = TelephonyCall::incoming(); + call.caller_identified(false, true); + assert_eq!( + call.receive_signal(Signal::from_wire(0xF2)), + vec![TelephonyAction::SelectMode(CallMode::HalfDuplex)] + ); + assert!(call.transmit_squelched()); + assert_eq!( + call.receive_signal(Signal::from(SignallingStatus::Connecting)), + vec![TelephonyAction::IgnoreSignal(Signal::from( + SignallingStatus::Connecting + ))] + ); + let answer = call.answer(); + assert!(answer.contains(&TelephonyAction::SelectMode(CallMode::HalfDuplex))); + assert!(call.transmit_squelched()); + } + + #[test] + fn unknown_mode_is_stored_without_squelch_change_or_error() { + let mut call = TelephonyCall::incoming(); + call.caller_identified(false, true); + assert!(call.receive_signal(Signal::from_wire(0xF3)).is_empty()); + assert_eq!(call.mode(), None); + assert!(!call.transmit_squelched()); + call.answer(); + assert!(!call.transmit_squelched()); + assert!(call.receive_signal(Signal::from_wire(0xF0)).is_empty()); + } + + #[test] + fn opening_pipelines_squelches_only_for_half_duplex() { + let mut callee = TelephonyCall::incoming(); + callee.caller_identified(false, true); + callee.receive_signal(Signal::from(CallMode::HalfDuplex)); + assert!(callee.receive_signal(Signal::from_wire(0xF5)).is_empty()); + assert!(callee.transmit_squelched()); + callee.answer(); + assert!(!callee.transmit_squelched()); + + let mut caller = TelephonyCall::outgoing(None); + caller.receive_signal(Signal::from(SignallingStatus::Available)); + caller.receive_signal(Signal::from(SignallingStatus::Ringing)); + caller.set_transmit_squelched(true); + caller.receive_signal(Signal::from(SignallingStatus::Connecting)); + assert!(!caller.transmit_squelched()); + + let mut half_duplex = TelephonyCall::outgoing_with_mode(None, Some(CallMode::HalfDuplex)); + half_duplex.receive_signal(Signal::from(SignallingStatus::Available)); + half_duplex.receive_signal(Signal::from(SignallingStatus::Ringing)); + half_duplex.receive_signal(Signal::from(SignallingStatus::Connecting)); + assert!(half_duplex.transmit_squelched()); + } + + #[test] + fn established_mode_switch_follows_remote_unless_disabled() { + let mut call = TelephonyCall::incoming(); + call.caller_identified(false, true); + call.answer(); + assert_eq!( + call.receive_signal(Signal::from(CallMode::HalfDuplex)), + vec![TelephonyAction::SwitchMode(CallMode::HalfDuplex)] + ); + assert!(call.transmit_squelched()); + assert!( + call.receive_signal(Signal::from(CallMode::HalfDuplex)) + .is_empty() + ); + call.disable_remote_mode_follow(); + assert!( + call.receive_signal(Signal::from(CallMode::FullDuplex)) + .is_empty() + ); + assert!(call.transmit_squelched()); + assert_eq!( + call.switch_mode(CallMode::FullDuplex), + vec![ + TelephonyAction::SendSignal(Signal::from(CallMode::FullDuplex)), + TelephonyAction::SwitchMode(CallMode::FullDuplex), + ] + ); + assert!(!call.transmit_squelched()); + assert!(call.switch_mode(CallMode::FullDuplex).is_empty()); + } + + #[test] + fn local_mode_switch_requires_established_call() { + let mut call = TelephonyCall::outgoing(None); + assert!(call.switch_mode(CallMode::HalfDuplex).is_empty()); + assert_eq!(call.mode(), None); + } + #[test] fn profile_signals_select_or_switch_profile_by_call_status() { let mut call = TelephonyCall::outgoing(None); diff --git a/crates/lxst-embedded/src/lib.rs b/crates/lxst-embedded/src/lib.rs index ade872e..6a3e351 100644 --- a/crates/lxst-embedded/src/lib.rs +++ b/crates/lxst-embedded/src/lib.rs @@ -17,7 +17,7 @@ pub use call_state::CallState; #[path = "../../lxst-core/src/shared/call_types.rs"] mod call_types; pub use call_types::{CallRole, TelephonyAction}; -pub use profile::{AudioCodec, OpusApplication, OpusProfile, Profile, SignallingStatus}; +pub use profile::{AudioCodec, CallMode, OpusApplication, OpusProfile, Profile, SignallingStatus}; pub use wire::{Codec2Mode, CodecKind, Signal}; #[path = "../../lxst-core/src/shared/codec2.rs"] diff --git a/crates/lxst-embedded/src/session.rs b/crates/lxst-embedded/src/session.rs index a5bac9a..a35fb5b 100644 --- a/crates/lxst-embedded/src/session.rs +++ b/crates/lxst-embedded/src/session.rs @@ -1,10 +1,17 @@ //! Local admission and microphone policy around the trusted call transitions. //! No extra wire extension, turn token or directional capability is invented. -use crate::{Actions, CallRole, CallState, Profile, Signal, SignallingStatus, TelephonyAction}; +use crate::{ + Actions, CallMode, CallRole, CallState, Profile, Signal, SignallingStatus, TelephonyAction, +}; +/// Local limit for an incoming link to identify its caller; Python has no counterpart. const SETUP_MS: u64 = 30_000; -const RING_MS: u64 = 90_000; -const ANSWER_MS: u64 = 10_000; +/// Python `Telephone.RING_TIME`. +const RING_MS: u64 = 60_000; +/// Python `Telephone.WAIT_TIME`, measured from the start of the outgoing call. +const WAIT_MS: u64 = 70_000; +/// Python `Telephone.CONNECT_TIME`: the callee must ring within this time of the call start. +const CONNECT_MS: u64 = 5_000; const PROFILE_MS: u64 = 5_000; pub const TALK_LIMIT_MS: u64 = 30_000; @@ -94,11 +101,10 @@ pub struct Session { audio_generation: u32, ended: Option, deadline: u64, + connect_deadline: Option, talk_started: u64, suggested: bool, profile_deadline: Option, - answer_retry: u64, - retries: u8, } impl Session { pub fn new(role: CallRole, config: SessionConfig, now_ms: u64) -> Result { @@ -123,12 +129,17 @@ impl Session { input_down: false, audio_generation: 1, ended: None, - deadline: now_ms.saturating_add(SETUP_MS), + deadline: now_ms.saturating_add(match role { + CallRole::Incoming => SETUP_MS, + CallRole::Outgoing => WAIT_MS, + }), + connect_deadline: match role { + CallRole::Incoming => None, + CallRole::Outgoing => Some(now_ms.saturating_add(CONNECT_MS)), + }, talk_started: 0, suggested: false, profile_deadline: None, - answer_retry: 0, - retries: 0, }) } pub const fn status(&self) -> SignallingStatus { @@ -137,6 +148,9 @@ impl Session { pub const fn profile(&self) -> Option { self.call.profile() } + pub const fn mode(&self) -> Option { + self.call.mode() + } pub const fn ended(&self) -> Option { self.ended } @@ -186,7 +200,7 @@ impl Session { } events } - pub fn answer(&mut self, now_ms: u64) -> Events { + pub fn answer(&mut self, _now_ms: u64) -> Events { let mut events = Events::new(); if self.ended.is_some() || !self.verified @@ -195,8 +209,6 @@ impl Session { { return events; } - self.deadline = now_ms.saturating_add(ANSWER_MS); - self.answer_retry = now_ms.saturating_add(1000); events.transitions(self.call.answer()); events } @@ -220,6 +232,7 @@ impl Session { return events; } self.profile_deadline = None; + self.suggested = false; if self.call.profile() != Some(profile) { self.stop_capture(&mut events); self.ready = false; @@ -273,11 +286,8 @@ impl Session { if !allowed { return events; } - if status == SignallingStatus::Ringing && current != status { - self.deadline = now_ms.saturating_add(RING_MS); - } - if status == SignallingStatus::Connecting && current == SignallingStatus::Ringing { - self.deadline = now_ms.saturating_add(ANSWER_MS); + if status == SignallingStatus::Ringing { + self.connect_deadline = None; } } events.transitions(self.call.receive_signal(signal)); @@ -352,20 +362,16 @@ impl Session { if self.status() != SignallingStatus::Established && now_ms >= self.deadline { return self.end(EndReason::Timeout); } + if self + .connect_deadline + .is_some_and(|deadline| now_ms >= deadline) + { + return self.end(EndReason::Timeout); + } if self.transmitting && now_ms.saturating_sub(self.talk_started) >= TALK_LIMIT_MS { self.stop_capture(&mut events); events.push(Event::FlushMedia); } - if self.call.role() == CallRole::Incoming - && self.call.answered() - && self.status() == SignallingStatus::Connecting - && now_ms >= self.answer_retry - && self.retries < 3 - { - self.retries += 1; - self.answer_retry = now_ms.saturating_add(1000); - events.transitions(self.call.retry_answer()); - } events } pub fn end(&mut self, reason: EndReason) -> Events { diff --git a/crates/lxst-embedded/tests/session.rs b/crates/lxst-embedded/tests/session.rs index 9b62c78..c8b54a6 100644 --- a/crates/lxst-embedded/tests/session.rs +++ b/crates/lxst-embedded/tests/session.rs @@ -1,6 +1,6 @@ use lxst_embedded::{ - CallRole, CallState, EndReason, Event, Profile, ProfileSet, Session, SessionConfig, Signal, - SignallingStatus as Status, TelephonyAction as Action, + CallMode, CallRole, CallState, EndReason, Event, Profile, ProfileSet, Session, SessionConfig, + Signal, SignallingStatus as Status, TelephonyAction as Action, }; #[test] @@ -24,14 +24,22 @@ fn crossed_profile_offers_converge_before_media_without_an_echo_loop() { for event in receiver.peer_verified(1).as_slice() { if let Event::Transition(Action::SendSignal(signal)) = event { for action in caller.receive_signal(*signal).as_slice() { - if let Action::SendSignal(signal) = action { - in_flight.push(*signal); + match action { + Action::SendSignal(signal) => in_flight.push(*signal), + Action::SendSignalPair(first, second) => { + in_flight.push(*first); + in_flight.push(*second); + } + _ => {} } } } } assert_eq!(caller.profile(), Some(preferred)); - assert_eq!(in_flight, vec![Signal::from(offered)]); + assert_eq!( + in_flight, + vec![Signal::from(offered), Signal::from(CallMode::FullDuplex)] + ); for signal in in_flight { for event in receiver.receive_signal(signal, 2).as_slice() { if let Event::Transition(Action::SendSignal(signal)) = event { @@ -200,26 +208,35 @@ fn unsupported_profile_has_one_bounded_offer_then_closes() { session.receive_signal(Profile::QualityHigh.into(), 20); session.receive_signal(Profile::BandwidthVeryLow.into(), 21); assert!(session.media_ready()); - session.receive_signal(Profile::QualityHigh.into(), 22); + let events = session.receive_signal(Profile::QualityHigh.into(), 22); + assert_eq!(session.ended(), None); + assert!( + events + .as_slice() + .contains(&Event::Transition(Action::SendSignal( + Profile::BandwidthVeryLow.into() + ))) + ); + session.receive_signal(Profile::QualityMax.into(), 23); assert_eq!(session.ended(), Some(EndReason::ProfileUnsupported)); } #[test] -fn retries_are_bounded_and_one_direction_devices_work() { +fn answer_establishes_without_retries_and_one_direction_devices_work() { let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap(); session.link_established(); session.peer_verified(1); - session.answer(2); - for n in 1..=3 { - let events = session.tick(2 + n * 1000); - assert_eq!(events.as_slice().len(), 2); - assert_eq!( - events.as_slice()[1], - Event::Transition(Action::SendSignal(Status::Established.into())) - ); + let answer = session.answer(2); + let sent = answer + .as_slice() + .iter() + .filter(|event| matches!(event, Event::Transition(Action::SendSignal(_)))) + .count(); + assert_eq!(sent, 2); + assert_eq!(session.status(), Status::Established); + for n in 1..=20 { + assert!(session.tick(2 + n * 1000).as_slice().is_empty()); } - assert!(session.tick(4002).as_slice().is_empty()); - session.tick(10002); - assert_eq!(session.ended(), Some(EndReason::Timeout)); + assert_eq!(session.ended(), None); for (capture, playback) in [(true, false), (false, true)] { let mut cfg = config(); cfg.capture = capture; @@ -304,3 +321,49 @@ fn authenticated_matching_media_confirms_standard_profile_fallback_without_echo( ringing.tick(5100); assert_eq!(ringing.ended(), Some(EndReason::ProfileUnsupported)); } + +#[test] +fn incoming_ring_times_out_after_python_ring_time() { + let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(0); + session.tick(59_999); + assert_eq!(session.ended(), None); + session.tick(60_000); + assert_eq!(session.ended(), Some(EndReason::Timeout)); +} + +#[test] +fn outgoing_call_ends_when_callee_does_not_ring_within_connect_time() { + let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(1); + session.receive_signal(Status::Available.into(), 100); + session.tick(4_999); + assert_eq!(session.ended(), None); + session.tick(5_000); + assert_eq!(session.ended(), Some(EndReason::Timeout)); +} + +#[test] +fn outgoing_wait_time_runs_from_call_start_once_ringing() { + let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(1); + session.receive_signal(Status::Available.into(), 100); + session.receive_signal(Status::Ringing.into(), 4_000); + session.tick(69_999); + assert_eq!(session.ended(), None); + session.tick(70_000); + assert_eq!(session.ended(), Some(EndReason::Timeout)); +} + +#[test] +fn preferred_mode_signal_is_recorded_by_the_session() { + let mut session = Session::new(CallRole::Incoming, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(1); + session.receive_signal(Signal::from_wire(0xF2), 2); + assert_eq!(session.mode(), Some(CallMode::HalfDuplex)); + assert_eq!(session.ended(), None); +} diff --git a/crates/lxst-embedded/tests/wire.rs b/crates/lxst-embedded/tests/wire.rs index 9be8e8f..0648390 100644 --- a/crates/lxst-embedded/tests/wire.rs +++ b/crates/lxst-embedded/tests/wire.rs @@ -123,7 +123,22 @@ fn shared_transitions_retain_full_rust_actions() { use lxst_embedded::{CallState, SignallingStatus}; let mut embedded = CallState::outgoing(Some(Profile::BandwidthVeryLow)); let mut host = lxst_core::TelephonyCall::outgoing(Some(lxst_core::Profile::BandwidthVeryLow)); - for signal in [3, 4, 5, 6, 5, 6, 0x11f, 0x12f, 0, 1, u32::MAX] { + for signal in [ + 3, + 4, + 5, + 6, + 5, + 6, + 0x11f, + 0x12f, + 0xf1, + 0xf2, + 0xf3, + 0, + 1, + u32::MAX, + ] { let a = embedded.receive_signal(Signal::from_wire(signal)); let b = host.receive_signal(lxst_core::Signal::from_wire(signal)); assert_eq!(format!("{:?}", a.as_slice()), format!("{b:?}")); @@ -132,13 +147,12 @@ fn shared_transitions_retain_full_rust_actions() { // Explore combinations including adversarial order to prove the shared // fixed action bound; session policy separately restricts allowed ordering. for first in 0..512 { - for second in [0, 3, 4, 5, 6, 0x11f, 0x12f, 0x13f] { + for second in [0, 3, 4, 5, 6, 0x11f, 0x12f, 0x13f, 0xf1, 0xf2] { let mut call = CallState::incoming(); call.caller_identified(false, true); call.receive_signal(Signal::from_wire(first)); call.answer(); call.receive_signal(Signal::from_wire(second)); - call.retry_answer(); call.hangup(false); assert_eq!(call.status(), SignallingStatus::Available); } diff --git a/crates/lxst-telephony/Cargo.toml b/crates/lxst-telephony/Cargo.toml index 8d817e6..0639362 100644 --- a/crates/lxst-telephony/Cargo.toml +++ b/crates/lxst-telephony/Cargo.toml @@ -21,6 +21,7 @@ thiserror.workspace = true tokio.workspace = true [dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } hex.workspace = true rns-interface.workspace = true serial_test.workspace = true diff --git a/crates/lxst-telephony/src/lib.rs b/crates/lxst-telephony/src/lib.rs index acbc8f8..ac18e7a 100644 --- a/crates/lxst-telephony/src/lib.rs +++ b/crates/lxst-telephony/src/lib.rs @@ -9,7 +9,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use bytes::Bytes; use lxst_core::{ - CallRole, CodecKind, Frame, FrameStreamEvent, LxstPacket, OpusCodecError, Profile, + CallMode, CallRole, CodecKind, Frame, FrameStreamEvent, LxstPacket, OpusCodecError, Profile, RawAudioFrame, RawBitDepth, Signal, SignallingStatus, TELEPHONY_DESTINATION_NAME, TelephonyAction, TelephonyCall, }; @@ -42,7 +42,7 @@ use tokio::time::{Duration, Instant, timeout}; mod capture_gate; mod media; pub use capture_gate::AudioTransmitGate; -use media::{AudioDecoder, AudioEncoder}; +use media::{AudioEncoder, ReceiveDecoder}; pub type LinkId = [u8; 16]; pub type IdentityHash = [u8; 16]; @@ -50,6 +50,14 @@ pub type IdentityHash = [u8; 16]; pub const TELEPHONY_ANNOUNCE_INTERVAL: Duration = Duration::from_secs(60 * 60 * 3); pub const TELEPHONY_STARTUP_ANNOUNCE_RETRY_INTERVAL: Duration = Duration::from_secs(5); pub const TELEPHONY_STARTUP_ANNOUNCE_RETRIES: u8 = 6; +/// Python `Telephone.JOB_INTERVAL`: the first periodic announce follows one job tick. +pub const TELEPHONY_JOB_INTERVAL: Duration = Duration::from_secs(5); +/// Python `Telephone.CONNECT_TIME`. +pub const TELEPHONY_CONNECT_TIME: Duration = Duration::from_secs(5); +/// Python `Telephone.WAIT_TIME`. +pub const TELEPHONY_WAIT_TIME: Duration = Duration::from_secs(70); +/// Python `Telephone.RING_TIME`. +pub const TELEPHONY_RING_TIME: Duration = Duration::from_secs(60); /// Housekeeping cadence with no call activity; link events still wake the service at once. const TELEPHONY_IDLE_POLL_INTERVAL: Duration = Duration::from_secs(1); @@ -161,6 +169,11 @@ pub enum TelephonyCommand { link_id: LinkId, signal: Signal, }, + /// Two signals in one LXST packet. + SendSignalPair { + link_id: LinkId, + signals: [Signal; 2], + }, IdentifyLocalIdentity { link_id: LinkId, }, @@ -172,6 +185,14 @@ pub enum TelephonyCommand { link_id: LinkId, profile: Profile, }, + SelectMode { + link_id: LinkId, + mode: CallMode, + }, + SwitchMode { + link_id: LinkId, + mode: CallMode, + }, PrepareDialingPipelines { link_id: LinkId, }, @@ -227,9 +248,12 @@ impl TelephonyCommand { pub const fn link_id(&self) -> LinkId { match self { Self::SendSignal { link_id, .. } + | Self::SendSignalPair { link_id, .. } | Self::IdentifyLocalIdentity { link_id } | Self::SelectProfile { link_id, .. } | Self::SwitchProfile { link_id, .. } + | Self::SelectMode { link_id, .. } + | Self::SwitchMode { link_id, .. } | Self::PrepareDialingPipelines { link_id } | Self::ResetDialingPipelines { link_id } | Self::OpenAudioPipelines { link_id } @@ -251,7 +275,11 @@ impl TelephonyCommand { } pub fn to_lxst_packet(&self) -> Option { - self.signal().map(signalling_packet) + match self { + Self::SendSignal { signal, .. } => Some(signalling_packet(*signal)), + Self::SendSignalPair { signals, .. } => Some(LxstPacket::signalling(*signals)), + _ => None, + } } } @@ -314,7 +342,9 @@ pub struct ActiveCallSnapshot { pub role: CallRole, pub status: SignallingStatus, pub profile: Option, + pub mode: Option, pub answered: bool, + pub transmit_squelched: bool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -328,6 +358,7 @@ pub struct TelephonyRuntimeSnapshot { pub struct TelephonyRuntimeCore { access: CallerAccessPolicy, external_busy: bool, + dialling: bool, pending_links: HashSet, ingress: HashMap, active_call: Option, @@ -361,8 +392,17 @@ impl TelephonyRuntimeCore { self.external_busy = busy; } + /// Python `Telephone.busy`: a call in setup, including path discovery, makes the line busy. pub fn line_busy(&self) -> bool { - self.external_busy || self.active_call.is_some() + self.external_busy || self.dialling || self.active_call.is_some() + } + + pub const fn dialling(&self) -> bool { + self.dialling + } + + fn set_dialling(&mut self, dialling: bool) { + self.dialling = dialling; } pub fn active_call(&self) -> Option<&ActiveCall> { @@ -383,7 +423,9 @@ impl TelephonyRuntimeCore { role: active.call.role(), status: active.call.status(), profile: active.call.profile(), + mode: active.call.mode(), answered: active.call.answered(), + transmit_squelched: active.call.transmit_squelched(), }), } } @@ -433,6 +475,16 @@ impl TelephonyRuntimeCore { link_id: LinkId, remote_identity: IdentityHash, profile: Option, + ) -> Result<(), Error> { + self.start_outgoing_call_with_mode(link_id, remote_identity, profile, None) + } + + pub fn start_outgoing_call_with_mode( + &mut self, + link_id: LinkId, + remote_identity: IdentityHash, + profile: Option, + mode: Option, ) -> Result<(), Error> { if self.line_busy() { return Err(Error::LineBusy); @@ -442,7 +494,7 @@ impl TelephonyRuntimeCore { self.active_call = Some(ActiveCall { link_id, remote_identity, - call: TelephonyCall::outgoing(profile), + call: TelephonyCall::outgoing_with_mode(profile, mode), }); Ok(()) } @@ -475,27 +527,6 @@ impl TelephonyRuntimeCore { Ok(self.commands_from_actions(link_id, Some(remote_identity), actions)) } - fn retry_answer_active( - &self, - expected_link_id: LinkId, - ) -> Result, Error> { - let active = self.active_call.as_ref().ok_or(Error::NoActiveCall)?; - if active.link_id != expected_link_id { - return Err(Error::WrongActiveLink); - } - if active.call.role() != CallRole::Incoming - || !active.call.answered() - || active.call.status() != SignallingStatus::Connecting - { - return Err(Error::CallNotAnswerable); - } - Ok(self.commands_from_actions( - active.link_id, - Some(active.remote_identity), - active.call.retry_answer(), - )) - } - pub fn switch_active_profile( &mut self, profile: Profile, @@ -511,25 +542,34 @@ impl TelephonyRuntimeCore { Ok(self.commands_from_actions(link_id, Some(remote_identity), actions)) } - pub fn hangup_active(&mut self, ring_timeout: bool) -> Result, Error> { - self.terminate_active(ring_timeout, None) + /// Python `switch_mode`: only an established call changes mode and signals it. + pub fn switch_active_mode(&mut self, mode: CallMode) -> Result, Error> { + let active = self.active_call.as_mut().ok_or(Error::NoActiveCall)?; + if active.call.status() != SignallingStatus::Established { + return Err(Error::CallNotEstablished); + } + + let link_id = active.link_id; + let remote_identity = active.remote_identity; + let actions = active.call.switch_mode(mode); + Ok(self.commands_from_actions(link_id, Some(remote_identity), actions)) } - fn timeout_answer_active( - &mut self, - expected_link_id: LinkId, - ) -> Result, Error> { - let active = self.active_call.as_ref().ok_or(Error::NoActiveCall)?; - if active.link_id != expected_link_id { - return Err(Error::WrongActiveLink); - } - if active.call.role() != CallRole::Incoming - || !active.call.answered() - || active.call.status() != SignallingStatus::Connecting - { - return Err(Error::CallNotAnswerable); - } - self.terminate_active(false, Some(SignallingStatus::Connecting)) + /// Python `squelch_transmit`/`unsquelch_transmit`: local only, nothing is signalled. + pub fn set_active_transmit_squelched(&mut self, squelched: bool) -> Result<(), Error> { + let active = self.active_call.as_mut().ok_or(Error::NoActiveCall)?; + active.call.set_transmit_squelched(squelched); + Ok(()) + } + + pub fn disable_remote_mode_follow(&mut self) -> Result<(), Error> { + let active = self.active_call.as_mut().ok_or(Error::NoActiveCall)?; + active.call.disable_remote_mode_follow(); + Ok(()) + } + + pub fn hangup_active(&mut self, ring_timeout: bool) -> Result, Error> { + self.terminate_active(ring_timeout, None) } fn terminate_active( @@ -615,7 +655,18 @@ impl TelephonyRuntimeCore { let mut commands = Vec::new(); for signal in inbound.packet.signals.clone() { + // Python returns at the first signal below PREFERRED_MODE on an unanswered + // incoming call, which drops the rest of the packet. + let ends_packet = signal.wire_value() < Signal::PreferredMode(0).wire_value() + && self.active_call.as_ref().is_some_and(|active| { + active.link_id == link_id + && active.call.role() == CallRole::Incoming + && !active.call.answered() + }); commands.extend(self.receive_signal(link_id, signal)?); + if ends_packet { + break; + } } Ok(TelephonyStep { @@ -702,6 +753,18 @@ impl TelephonyRuntimeCore { TelephonyAction::SendSignal(signal) => { Some(TelephonyCommand::SendSignal { link_id, signal }) } + TelephonyAction::SendSignalPair(first, second) => { + Some(TelephonyCommand::SendSignalPair { + link_id, + signals: [first, second], + }) + } + TelephonyAction::SelectMode(mode) => { + Some(TelephonyCommand::SelectMode { link_id, mode }) + } + TelephonyAction::SwitchMode(mode) => { + Some(TelephonyCommand::SwitchMode { link_id, mode }) + } TelephonyAction::IdentifyLocalIdentity => { Some(TelephonyCommand::IdentifyLocalIdentity { link_id }) } @@ -746,6 +809,7 @@ pub enum TelephonyControl { Call { remote_identity: IdentityHash, profile: Option, + mode: Option, discovery_timeout: Duration, }, Answer { @@ -791,16 +855,23 @@ pub enum TelephonyControl { SwitchProfile { profile: Profile, }, + SwitchMode { + mode: CallMode, + }, + /// Drop outbound media frames without signalling, as Python `squelch_transmit`. + SquelchTransmit(bool), + DisableRemoteModeFollow, SetExternalBusy(bool), SetAccessPolicy(CallerAccessPolicy), Shutdown, } /// Submit an exact-link answer request and wait until the telephony service -/// has validated the active incoming call, atomically admitted its signalling -/// packets, and queued the authoritative CONNECTING snapshot for the event consumer. -/// This does not confirm peer receipt or an established call. There is no built-in -/// wait deadline; cancelling this future does not retract an already queued request. +/// has validated the active incoming call, atomically admitted its CONNECTING and +/// ESTABLISHED signalling packets, and queued the ESTABLISHED snapshot for the event +/// consumer. As in Python, there is no retry and no wait for the caller's echo. +/// There is no built-in wait deadline; cancelling this future does not retract an +/// already queued request. pub async fn request_answer( control_tx: &mpsc::Sender, expected_link_id: LinkId, @@ -935,6 +1006,7 @@ enum TelephonyInternalEvent { OutgoingDiscoveryCompleted { remote_identity: IdentityHash, profile: Option, + mode: Option, result: Result, }, } @@ -943,15 +1015,18 @@ enum TelephonyInternalEvent { struct OutgoingDiscoveryState { remote_identity: IdentityHash, profile: Option, + mode: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TelephonyServiceConfig { pub poll_interval: Duration, pub incoming_ring_timeout: Option, - pub answer_retry_interval: Option, - pub answer_timeout: Option, + /// Python `wait_time`, measured from the call request and including path discovery. pub outgoing_call_timeout: Option, + /// Python `establishment_timeout` (`set_connect_timeout`): hang up unless the + /// callee rings within this time of the call request. + pub connect_timeout: Option, pub media_frames_per_tick: usize, pub announce_on_start: bool, pub announce_interval: Option, @@ -963,15 +1038,14 @@ impl Default for TelephonyServiceConfig { fn default() -> Self { Self { poll_interval: Duration::from_millis(20), - incoming_ring_timeout: Some(Duration::from_secs(60)), - answer_retry_interval: Some(Duration::from_millis(750)), - answer_timeout: Some(Duration::from_secs(5)), - outgoing_call_timeout: Some(Duration::from_secs(70)), + incoming_ring_timeout: Some(TELEPHONY_RING_TIME), + outgoing_call_timeout: Some(TELEPHONY_WAIT_TIME), + connect_timeout: Some(TELEPHONY_CONNECT_TIME), media_frames_per_tick: 4, announce_on_start: true, announce_interval: Some(TELEPHONY_ANNOUNCE_INTERVAL), startup_announce_retry_interval: Some(TELEPHONY_STARTUP_ANNOUNCE_RETRY_INTERVAL), - startup_announce_retries: TELEPHONY_STARTUP_ANNOUNCE_RETRIES, + startup_announce_retries: 0, } } } @@ -1000,6 +1074,7 @@ pub struct TelephonyServiceParts { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TelephonyServiceTimeoutKind { IncomingRing, + OutgoingEstablishment, OutgoingCall, } @@ -1010,13 +1085,6 @@ struct TelephonyServiceTimeout { expires_at: Instant, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct TelephonyAnsweringState { - link_id: LinkId, - next_retry_at: Option, - expires_at: Option, -} - #[derive(Default)] struct TelephonyServiceMedia { opus_encoder: Option, @@ -1036,7 +1104,7 @@ struct ActiveOpusEncoder { struct ActiveOpusDecoder { link_id: LinkId, profile: Profile, - decoder: AudioDecoder, + decoder: ReceiveDecoder, } struct ActiveOpusTransmitStream { @@ -1153,11 +1221,7 @@ impl TelephonyServiceMedia { .encoder) } - fn opus_decoder_for( - &mut self, - link_id: LinkId, - profile: Profile, - ) -> Result<&mut AudioDecoder, Error> { + fn opus_decoder_for(&mut self, link_id: LinkId, profile: Profile) -> &mut ReceiveDecoder { let needs_new = self .opus_decoder .as_ref() @@ -1168,15 +1232,15 @@ impl TelephonyServiceMedia { self.opus_decoder = Some(ActiveOpusDecoder { link_id, profile, - decoder: AudioDecoder::new(profile)?, + decoder: ReceiveDecoder::new(profile), }); } - Ok(&mut self + &mut self .opus_decoder .as_mut() .expect("Opus decoder exists after creation") - .decoder) + .decoder } } @@ -1189,7 +1253,7 @@ pub struct TelephonyService { event_tx: mpsc::Sender, config: TelephonyServiceConfig, active_timeout: Option, - answering: Option, + outgoing_started_at: Option, next_announce_at: Option, startup_announce_retries_remaining: u8, outgoing_discovery: Option, @@ -1256,7 +1320,7 @@ impl TelephonyService { config: TelephonyServiceConfig, ) -> Self { let next_announce_at = if config.announce_on_start { - Some(Instant::now()) + Some(Instant::now() + TELEPHONY_JOB_INTERVAL) } else { config .announce_interval @@ -1279,7 +1343,7 @@ impl TelephonyService { event_tx, config, active_timeout: None, - answering: None, + outgoing_started_at: None, next_announce_at, startup_announce_retries_remaining, outgoing_discovery: None, @@ -1341,9 +1405,6 @@ impl TelephonyService { if !self.drive_ready().await { break; } - if !self.handle_due_answer_retry().await { - break; - } if !self.handle_due_timeout().await { break; } @@ -1374,7 +1435,6 @@ impl TelephonyService { core.active_call.is_some() || !core.pending_links.is_empty() || !core.ingress.is_empty() - || self.answering.is_some() || self.active_timeout.is_some() || self.outgoing_discovery.is_some() || media.opus_encoder.is_some() @@ -1430,7 +1490,7 @@ impl TelephonyService { let stream_events = self.media.clear_unless_established(None); let _ = emit_service_events(self.event_tx.clone(), stream_events).await; self.active_timeout = None; - self.answering = None; + self.outgoing_started_at = None; } fn deregister_destinations(&self) { @@ -1461,10 +1521,11 @@ impl TelephonyService { TelephonyControl::Call { remote_identity, profile, + mode, discovery_timeout, } => { return self - .start_outgoing_discovery(remote_identity, profile, discovery_timeout) + .start_outgoing_discovery(remote_identity, profile, mode, discovery_timeout) .await; } TelephonyControl::Answer { @@ -1489,14 +1550,22 @@ impl TelephonyService { } TelephonyControl::Hangup { ring_timeout } => { if let Some(discovery) = self.outgoing_discovery.take() { - return emit_service_event( + self.core.set_dialling(false); + self.outgoing_started_at = None; + if !emit_service_event( self.event_tx.clone(), TelephonyServiceEvent::OutgoingCallFailed { remote_identity: discovery.remote_identity, message: "cancelled".to_string(), }, ) - .await; + .await + { + return false; + } + if self.core.active_call().is_none() { + return emit_snapshot(self.event_tx.clone(), self.core.snapshot()).await; + } } let commands = self.core.hangup_active(ring_timeout); self.control_commands(commands).await @@ -1564,6 +1633,17 @@ impl TelephonyService { let commands = self.core.switch_active_profile(profile); self.control_commands(commands).await } + TelephonyControl::SwitchMode { mode } => { + let commands = self.core.switch_active_mode(mode); + self.control_commands(commands).await + } + TelephonyControl::SquelchTransmit(squelched) => { + if let Err(err) = self.core.set_active_transmit_squelched(squelched) { + return emit_service_error(self.event_tx.clone(), err).await; + } + return emit_snapshot(self.event_tx.clone(), self.core.snapshot()).await; + } + TelephonyControl::DisableRemoteModeFollow => self.core.disable_remote_mode_follow(), TelephonyControl::SetExternalBusy(busy) => { self.core.set_external_busy(busy); let stream_events = self.refresh_active_timeout(); @@ -1589,16 +1669,31 @@ impl TelephonyService { &mut self, remote_identity: IdentityHash, profile: Option, + mode: Option, discovery_timeout: Duration, ) -> bool { if self.core.line_busy() || self.outgoing_discovery.is_some() { return emit_service_error(self.event_tx.clone(), Error::LineBusy).await; } + let started_at = Instant::now(); + self.outgoing_started_at = Some(started_at); + self.core.set_dialling(true); self.outgoing_discovery = Some(OutgoingDiscoveryState { remote_identity, profile, + mode, }); + // Python bounds path discovery by wait_time from call(). + let wait_deadline = self + .config + .outgoing_call_timeout + .map(|timeout| started_at + timeout); + let stage_timeout = move || { + wait_deadline.map_or(discovery_timeout, |deadline| { + discovery_timeout.min(deadline.saturating_duration_since(Instant::now())) + }) + }; if !emit_service_event( self.event_tx.clone(), @@ -1616,13 +1711,13 @@ impl TelephonyService { let peer = discover_remote_telephony_peer_on_transport( transport_tx.clone(), remote_identity, - discovery_timeout, + stage_timeout(), ) .await?; await_path_on_transport( transport_tx.clone(), peer.destination_hash, - discovery_timeout, + stage_timeout(), ) .await?; let peer = refresh_peer_hops_from_transport(transport_tx, peer).await?; @@ -1634,6 +1729,7 @@ impl TelephonyService { .send(TelephonyInternalEvent::OutgoingDiscoveryCompleted { remote_identity, profile, + mode, result, }) .await; @@ -1647,23 +1743,27 @@ impl TelephonyService { TelephonyInternalEvent::OutgoingDiscoveryCompleted { remote_identity, profile, + mode, result, } => { let expected = OutgoingDiscoveryState { remote_identity, profile, + mode, }; if self.outgoing_discovery != Some(expected) { return true; } self.outgoing_discovery = None; + self.core.set_dialling(false); match result.and_then(|peer| { - self.endpoint.begin_outgoing_link_with_remote_pubkey( + self.endpoint.begin_outgoing_link_with_mode( &mut self.core, remote_identity, peer.public_key, profile, + mode, peer.hops, ) }) { @@ -1686,8 +1786,9 @@ impl TelephonyService { emit_snapshot(self.event_tx.clone(), self.core.snapshot()).await } Err(err) => { + self.outgoing_started_at = None; let message = err.to_string(); - emit_service_event( + if !emit_service_event( self.event_tx.clone(), TelephonyServiceEvent::OutgoingCallFailed { remote_identity, @@ -1695,6 +1796,10 @@ impl TelephonyService { }, ) .await + { + return false; + } + emit_snapshot(self.event_tx.clone(), self.core.snapshot()).await } } } @@ -1874,20 +1979,6 @@ impl TelephonyService { } }; - let now = Instant::now(); - self.answering = Some(TelephonyAnsweringState { - link_id: expected_link_id, - next_retry_at: self - .config - .answer_retry_interval - .filter(|interval| !interval.is_zero()) - .map(|interval| now + interval), - expires_at: self - .config - .answer_timeout - .filter(|duration| !duration.is_zero()) - .map(|duration| now + duration), - }); self.publish_commands(commands, effects).await?; let active = self @@ -1954,6 +2045,10 @@ impl TelephonyService { if active.call.status() != SignallingStatus::Established { return Err(Error::CallNotEstablished); } + // A squelched Python Packetizer drops frames silently. + if active.call.transmit_squelched() { + return Ok(()); + } let link_id = active.link_id; let frame_count = frames.len(); @@ -1990,6 +2085,9 @@ impl TelephonyService { requested: profile, }); } + if active.call.transmit_squelched() { + return Ok(()); + } let link_id = active.link_id; let gate = self @@ -2045,15 +2143,16 @@ impl TelephonyService { for step in steps { let service_events = service_events_from_commands(&step.step.commands); let media_received = media_received_event(&step.step); - let opus_received_events = match self.opus_received_events(&step.step) { - Ok(events) => events, - Err(err) => { - if !emit_service_error(self.event_tx.clone(), err).await { - return false; - } - Vec::new() + let (opus_received_events, decode_errors) = + match self.opus_received_events(&step.step) { + Ok(decoded) => decoded, + Err(err) => (Vec::new(), vec![err]), + }; + for err in decode_errors { + if !emit_service_error(self.event_tx.clone(), err).await { + return false; } - }; + } if !emit_service_event( self.event_tx.clone(), TelephonyServiceEvent::Drive(step), @@ -2097,12 +2196,14 @@ impl TelephonyService { } } + /// Decode each received frame on its own; a bad frame is reported and skipped. + #[allow(clippy::type_complexity)] fn opus_received_events( &mut self, step: &TelephonyStep, - ) -> Result, Error> { + ) -> Result<(Vec, Vec), Error> { let Some(inbound) = step.inbound.as_ref() else { - return Ok(Vec::new()); + return Ok((Vec::new(), Vec::new())); }; let opus_frames = inbound .frame_events @@ -2117,7 +2218,7 @@ impl TelephonyService { }) .collect::>(); if opus_frames.is_empty() { - return Ok(Vec::new()); + return Ok((Vec::new(), Vec::new())); } let active = self.core.active_call().ok_or(Error::NoActiveCall)?; @@ -2126,16 +2227,26 @@ impl TelephonyService { } let link_id = active.link_id; if active.call.status() != SignallingStatus::Established { - return Ok(Vec::new()); + return Ok((Vec::new(), Vec::new())); } let profile = active.call.profile().unwrap_or(Profile::DEFAULT); + let mut errors = Vec::new(); let decoded = { - let decoder = self.media.opus_decoder_for(active.link_id, profile)?; + let decoder = self.media.opus_decoder_for(active.link_id, profile); opus_frames .iter() - .map(|frame| decoder.decode_frame(frame)) - .collect::, _>>()? + .filter_map(|frame| match decoder.decode_frame(frame) { + Ok(frame) => Some(frame), + Err(err) => { + errors.push(err); + None + } + }) + .collect::>() }; + if decoded.is_empty() { + return Ok((Vec::new(), errors)); + } let receive_stream_events = self.deliver_opus_receive_stream(link_id, profile, &decoded); let mut events = Vec::with_capacity(1 + receive_stream_events.len()); @@ -2145,7 +2256,7 @@ impl TelephonyService { frames: decoded, }); events.extend(receive_stream_events); - Ok(events) + Ok((events, errors)) } fn deliver_opus_receive_stream( @@ -2200,37 +2311,65 @@ impl TelephonyService { fn refresh_active_timeout(&mut self) -> Vec { let snapshot = self.core.snapshot(); - if self.answering.is_some_and(|answering| { - !snapshot.active_call.as_ref().is_some_and(|active| { - active.link_id == answering.link_id - && active.role == CallRole::Incoming - && active.answered - && active.status == SignallingStatus::Connecting - }) - }) { - self.answering = None; - } let stream_events = self .media .clear_unless_established(snapshot.active_call.as_ref()); let Some(active) = snapshot.active_call else { self.active_timeout = None; + if self.outgoing_discovery.is_none() { + self.outgoing_started_at = None; + } return stream_events; }; + if active.role != CallRole::Outgoing { + self.outgoing_started_at = None; + } + let now = Instant::now(); + let started_at = match self.outgoing_started_at { + Some(started_at) => started_at, + None if active.role == CallRole::Outgoing => { + self.outgoing_started_at = Some(now); + now + } + None => now, + }; + // Python arms both outgoing watchers from call(); the establishment one ends + // the call while the callee is not yet RINGING. + let wait_deadline = self + .config + .outgoing_call_timeout + .map(|duration| started_at + duration); let desired = match (active.role, active.status) { (CallRole::Incoming, SignallingStatus::Ringing) => self .config .incoming_ring_timeout - .map(|duration| (TelephonyServiceTimeoutKind::IncomingRing, duration)), - (CallRole::Outgoing, status) if status != SignallingStatus::Established => self - .config - .outgoing_call_timeout - .map(|duration| (TelephonyServiceTimeoutKind::OutgoingCall, duration)), + .map(|duration| (TelephonyServiceTimeoutKind::IncomingRing, now + duration)), + (CallRole::Outgoing, status) + if status.wire_value() < SignallingStatus::Ringing.wire_value() => + { + let connect_deadline = self + .config + .connect_timeout + .map(|duration| started_at + duration); + match (connect_deadline, wait_deadline) { + (Some(connect), Some(wait)) if wait < connect => { + Some((TelephonyServiceTimeoutKind::OutgoingCall, wait)) + } + (Some(connect), _) => { + Some((TelephonyServiceTimeoutKind::OutgoingEstablishment, connect)) + } + (None, Some(wait)) => Some((TelephonyServiceTimeoutKind::OutgoingCall, wait)), + (None, None) => None, + } + } + (CallRole::Outgoing, status) if status != SignallingStatus::Established => { + wait_deadline.map(|wait| (TelephonyServiceTimeoutKind::OutgoingCall, wait)) + } _ => None, }; - let Some((kind, duration)) = desired else { + let Some((kind, expires_at)) = desired else { self.active_timeout = None; return stream_events; }; @@ -2245,103 +2384,11 @@ impl TelephonyService { self.active_timeout = Some(TelephonyServiceTimeout { link_id: active.link_id, kind, - expires_at: Instant::now() + duration, + expires_at, }); stream_events } - async fn handle_due_answer_retry(&mut self) -> bool { - let Some(answering) = self.answering else { - return true; - }; - let now = Instant::now(); - - if answering - .expires_at - .is_some_and(|expires_at| now >= expires_at) - { - return self.timeout_answering(answering.link_id).await; - } - let Some(next_retry_at) = answering.next_retry_at else { - return true; - }; - if now < next_retry_at { - return true; - } - - let commands = match self.core.retry_answer_active(answering.link_id) { - Ok(commands) => commands, - Err(_) => { - self.answering = None; - return true; - } - }; - let effects = match self.endpoint.execute_signalling_batch(&commands) { - Ok(effects) => Some(effects), - Err(Error::TransportFull) => None, - Err(error) => { - let _ = emit_service_event( - self.event_tx.clone(), - TelephonyServiceEvent::Error { - message: error.to_string(), - }, - ) - .await; - None - } - }; - - if let Some(answering) = self.answering.as_mut() { - answering.next_retry_at = self - .config - .answer_retry_interval - .filter(|interval| !interval.is_zero()) - .map(|interval| now + interval); - } - - if let Some(effects) = effects - && !emit_service_event( - self.event_tx.clone(), - TelephonyServiceEvent::Drive(TelephonyDriveStep { - step: TelephonyStep::commands(commands), - effects, - }), - ) - .await - { - return false; - } - true - } - - async fn timeout_answering(&mut self, link_id: LinkId) -> bool { - self.answering = None; - let commands = match self.core.timeout_answer_active(link_id) { - Ok(commands) => commands, - Err(_) => return true, - }; - let effect_count = commands.len(); - let (effects, endpoint_error) = match self.endpoint.execute_commands(&commands) { - Ok(effects) => (effects, None), - Err(error) => ( - vec![TelephonyCommandEffect::Noop; effect_count], - Some(error.to_string()), - ), - }; - - if self.publish_commands(commands, effects).await.is_err() { - return false; - } - if let Some(message) = endpoint_error { - return emit_service_event( - self.event_tx.clone(), - TelephonyServiceEvent::Error { message }, - ) - .await; - } - true - } - async fn handle_due_timeout(&mut self) -> bool { let Some(timeout_state) = self.active_timeout else { return true; @@ -2366,6 +2413,10 @@ impl TelephonyService { TelephonyServiceTimeoutKind::IncomingRing => { active.role == CallRole::Incoming && active.status == SignallingStatus::Ringing } + TelephonyServiceTimeoutKind::OutgoingEstablishment => { + active.role == CallRole::Outgoing + && active.status.wire_value() < SignallingStatus::Ringing.wire_value() + } TelephonyServiceTimeoutKind::OutgoingCall => { active.role == CallRole::Outgoing && active.status != SignallingStatus::Established } @@ -2792,12 +2843,31 @@ impl TelephonyRnsEndpoint { profile: Option, hops: u8, ) -> Result { - let destination_hash = telephony_destination_hash(&remote_identity); - self.request_path_to_identity(&remote_identity)?; + self.begin_outgoing_link_with_mode( + core, + remote_identity, + remote_public_key, + profile, + None, + hops, + ) + } + /// Open the call link without a path request; Python `call()` requests a path only + /// when none is known, which discovery has already done. + pub fn begin_outgoing_link_with_mode( + &mut self, + core: &mut TelephonyRuntimeCore, + remote_identity: IdentityHash, + remote_public_key: [u8; 64], + profile: Option, + mode: Option, + hops: u8, + ) -> Result { + let destination_hash = telephony_destination_hash(&remote_identity); let (link, request_data) = Link::new_initiator(destination_hash, hops.max(1)); let link_id = link.link_id; - core.start_outgoing_call(link_id, remote_identity, profile)?; + core.start_outgoing_call_with_mode(link_id, remote_identity, profile, mode)?; let (event_tx, event_rx) = mpsc::channel(128); try_send_transport( @@ -3105,6 +3175,7 @@ impl TelephonyRnsEndpoint { if !matches!( command, TelephonyCommand::SendSignal { .. } + | TelephonyCommand::SendSignalPair { .. } | TelephonyCommand::IdentifyLocalIdentity { .. } | TelephonyCommand::TeardownLink { .. } ) { @@ -3114,8 +3185,10 @@ impl TelephonyRnsEndpoint { let link_id = command.link_id(); if self.manager.get_link(&link_id).is_some() { return match command { - TelephonyCommand::SendSignal { signal, .. } => { - let payload = signalling_packet(*signal) + TelephonyCommand::SendSignal { .. } | TelephonyCommand::SendSignalPair { .. } => { + let payload = command + .to_lxst_packet() + .expect("signal command has a packet") .encode() .map_err(lxst_rns::Error::from)?; self.manager @@ -3206,7 +3279,7 @@ impl TelephonyRnsEndpoint { .collect() } - /// Queue an answer/retry signalling batch without publishing a prefix. + /// Queue an answer signalling batch without publishing a prefix. /// /// Answer correctness depends on CONNECTING and ESTABLISHED being admitted /// together. Reserve every transport slot before sending either packet so @@ -3218,14 +3291,15 @@ impl TelephonyRnsEndpoint { ) -> Result, Error> { let signal_commands = commands .iter() - .filter_map(|command| match command { - TelephonyCommand::SendSignal { link_id, signal } => Some((*link_id, *signal)), - _ => None, + .filter_map(|command| { + command + .to_lxst_packet() + .map(|packet| (command.link_id(), packet)) }) .collect::>(); let mut prepared = Vec::with_capacity(signal_commands.len()); - for (link_id, signal) in &signal_commands { + for (link_id, packet) in &signal_commands { let (link, role) = if let Some(link) = self.manager.get_link_mut(link_id) { (link, LinkEndpointRole::Responder) } else { @@ -3237,7 +3311,7 @@ impl TelephonyRnsEndpoint { LinkEndpointRole::Initiator, ) }; - let packet = prepare_lxst_link_packet_send(link, role, &signalling_packet(*signal))?; + let packet = prepare_lxst_link_packet_send(link, role, packet)?; prepared.push((*link_id, role, packet)); } @@ -3273,7 +3347,8 @@ impl TelephonyRnsEndpoint { Ok(commands .iter() .map(|command| match command { - TelephonyCommand::SendSignal { link_id, .. } => { + TelephonyCommand::SendSignal { link_id, .. } + | TelephonyCommand::SendSignalPair { link_id, .. } => { TelephonyCommandEffect::QueuedLinkPacket { link_id: *link_id, kind: QueuedLinkPacketKind::LxstData, @@ -3762,8 +3837,11 @@ fn prepare_command_with_link( command: &TelephonyCommand, ) -> Result<(TelephonyCommandEffect, Option), Error> { let (effect, prepared) = match command { - TelephonyCommand::SendSignal { link_id, signal } => { - let packet = signalling_packet(*signal); + TelephonyCommand::SendSignal { link_id, .. } + | TelephonyCommand::SendSignalPair { link_id, .. } => { + let packet = command + .to_lxst_packet() + .expect("signal command has a packet"); let prepared = prepare_lxst_link_packet_send(link, role, &packet)?; ( TelephonyCommandEffect::QueuedLinkPacket { @@ -3918,8 +3996,8 @@ async fn discover_remote_telephony_peer_on_transport( destination_hash, DestinationResolveOptions { timeout: discovery_timeout, - drop_existing_path: true, - refresh_cached_path: true, + drop_existing_path: false, + refresh_cached_path: false, }, ) .await diff --git a/crates/lxst-telephony/src/media.rs b/crates/lxst-telephony/src/media.rs index d574cd1..98b3806 100644 --- a/crates/lxst-telephony/src/media.rs +++ b/crates/lxst-telephony/src/media.rs @@ -3,8 +3,8 @@ use crate::Error; use lxst_codec2::{Codec, Mode}; use lxst_core::{ - AudioCodec, Codec2Backend, Codec2Mode, Codec2PacketCodec, CodecKind, Frame, OpusDecoderState, - OpusEncoderState, Profile, RawAudioFrame, + AudioCodec, Codec2Backend, Codec2Mode, Codec2PacketCodec, CodecKind, Frame, OpusEncoderState, + OpusPacketDecoder, Profile, RawAudioFrame, }; struct Native(Box); @@ -74,33 +74,11 @@ impl Codec2Audio { result?; Ok(Frame::new(CodecKind::Codec2, payload)) } - fn decode(&mut self, frame: &Frame) -> Result { - if frame.codec != CodecKind::Codec2 { - return Err(Error::Audio("unexpected media codec".into())); - } - self.codec - .decode_into(&frame.payload, &mut self.pcm) - .map_err(|e| Error::Audio(e.to_string()))?; - let samples = self - .pcm - .iter() - .map(|v| f32::from(*v) / 32768.0) - .collect::>(); - self.pcm.fill(0); - Ok(RawAudioFrame { - channels: 1, - samples, - }) - } } pub(crate) enum AudioEncoder { Opus(Box), Codec2(Codec2Audio), } -pub(crate) enum AudioDecoder { - Opus(Box), - Codec2(Codec2Audio), -} impl AudioEncoder { pub(crate) fn new(profile: Profile) -> Result { match profile.audio_codec() { @@ -115,17 +93,84 @@ impl AudioEncoder { } } } -impl AudioDecoder { - pub(crate) fn new(profile: Profile) -> Result { - match profile.audio_codec() { - AudioCodec::Opus(_) => Ok(Self::Opus(Box::new(OpusDecoderState::new(profile)?))), - AudioCodec::Codec2(_) => Ok(Self::Codec2(Codec2Audio::new(profile)?)), +const CODEC2_SAMPLE_RATE_HZ: u32 = 8_000; + +/// Follows the codec and Codec2 mode of each received frame, as Python `LinkSource` +/// does, and converts the output to the local profile's sample rate and channels. +pub(crate) struct ReceiveDecoder { + sample_rate_hz: u32, + channels: u8, + opus: Option, + codec2: Vec<(Codec2Mode, Box)>, +} + +impl ReceiveDecoder { + pub(crate) fn new(profile: Profile) -> Self { + Self { + sample_rate_hz: profile.sample_rate_hz(), + channels: profile.channels(), + opus: None, + codec2: Vec::new(), } } + pub(crate) fn decode_frame(&mut self, frame: &Frame) -> Result { - match self { - Self::Opus(codec) => Ok(codec.decode_frame(frame)?), - Self::Codec2(codec) => codec.decode(frame), + match frame.codec { + CodecKind::Opus => { + if self.opus.is_none() { + self.opus = Some(OpusPacketDecoder::new(self.sample_rate_hz, self.channels)?); + } + let decoder = self + .opus + .as_mut() + .expect("Opus decoder exists after creation"); + Ok(decoder.decode_packet(&frame.payload)?) + } + CodecKind::Codec2 => self.decode_codec2(&frame.payload), + other => Err(Error::Audio(format!("unexpected media codec {other:?}"))), } } + + fn decode_codec2(&mut self, payload: &[u8]) -> Result { + let (&header, bytes) = payload + .split_first() + .ok_or_else(|| Error::Audio("empty Codec2 frame".into()))?; + let wire_mode = + Codec2Mode::from_header(header).map_err(|error| Error::Audio(error.to_string()))?; + let mode = match wire_mode { + Codec2Mode::Mode700C => Mode::Rate700C, + Codec2Mode::Mode1600 => Mode::Rate1600, + Codec2Mode::Mode3200 => Mode::Rate3200, + other => { + return Err(Error::Audio(format!( + "unsupported native Codec2 mode {other:?}" + ))); + } + }; + let index = match self.codec2.iter().position(|(m, _)| *m == wire_mode) { + Some(index) => index, + None => { + let mut storage = Box::::new_uninit(); + Codec::initialise(&mut storage, mode); + // SAFETY: initialise completed in final storage above. + self.codec2 + .push((wire_mode, unsafe { storage.assume_init() })); + self.codec2.len() - 1 + } + }; + let codec = &mut self.codec2[index].1; + // Python decodes every whole native frame in the payload. + let mut pcm = vec![0i16; mode.samples()]; + let mut samples = Vec::with_capacity(bytes.len() / mode.bytes() * mode.samples()); + for chunk in bytes.chunks_exact(mode.bytes()) { + codec + .decode(chunk, &mut pcm) + .map_err(|_| Error::Audio("invalid native frame".into()))?; + samples.extend(pcm.iter().map(|v| f32::from(*v) / 32768.0)); + } + let mono = RawAudioFrame::new(1, samples).map_err(|e| Error::Audio(e.to_string()))?; + mono.resampled(CODEC2_SAMPLE_RATE_HZ, self.sample_rate_hz) + .with_channels(self.channels) + .map_err(|e| Error::Audio(e.to_string())) + } } diff --git a/crates/lxst-telephony/src/tests.rs b/crates/lxst-telephony/src/tests.rs index 2cbd04d..49aa8af 100644 --- a/crates/lxst-telephony/src/tests.rs +++ b/crates/lxst-telephony/src/tests.rs @@ -416,6 +416,10 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { link_id, profile: Profile::DEFAULT, }, + TelephonyCommand::SelectMode { + link_id, + mode: CallMode::FullDuplex, + }, TelephonyCommand::SendSignal { link_id, signal: Signal::from(SignallingStatus::Connecting), @@ -425,11 +429,12 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { link_id, signal: Signal::from(SignallingStatus::Established), }, + TelephonyCommand::StartAudioPipelines { link_id }, ] ); assert_eq!( core.active_call().unwrap().call.status(), - SignallingStatus::Connecting + SignallingStatus::Established ); assert_eq!( @@ -439,7 +444,10 @@ fn incoming_call_identify_answer_and_hangup_emit_python_ordered_commands() { ) .unwrap() .commands, - vec![TelephonyCommand::StartAudioPipelines { link_id }] + vec![TelephonyCommand::IgnoredSignal { + link_id, + signal: Signal::from(SignallingStatus::Established), + }] ); assert_eq!( core.active_call().unwrap().call.status(), @@ -482,7 +490,7 @@ fn answer_admission_is_scoped_to_the_exact_ringing_incoming_link() { )); assert_eq!( core.active_call().unwrap().call.status(), - SignallingStatus::Connecting + SignallingStatus::Established ); } @@ -504,7 +512,7 @@ async fn answer_control_acks_authoritative_connecting_after_atomic_admission() { let snapshot = result.await.unwrap().unwrap(); assert_eq!(snapshot.link_id, link_id); assert_eq!(snapshot.role, CallRole::Incoming); - assert_eq!(snapshot.status, SignallingStatus::Connecting); + assert_eq!(snapshot.status, SignallingStatus::Established); assert!(snapshot.answered); let mut signals = Vec::new(); @@ -530,21 +538,25 @@ async fn answer_control_acks_authoritative_connecting_after_atomic_admission() { Some(TelephonyServiceEvent::Snapshot(snapshot)) if snapshot.active_call.as_ref().is_some_and(|active| { active.link_id == link_id - && active.status == SignallingStatus::Connecting + && active.status == SignallingStatus::Established && active.answered }) )); } #[tokio::test] -async fn answered_service_starts_media_only_after_remote_established_echo() { +async fn answered_callee_is_established_and_ignores_the_caller_echo() { let (mut service, _receiver, link_id, mut transport_rx, mut event_rx) = ringing_incoming_service(8, 12, TelephonyServiceConfig::default()); let _destination_registration = transport_rx.try_recv().unwrap(); let answer = service.answer_exact(link_id).await.unwrap(); - assert_eq!(answer.status, SignallingStatus::Connecting); - assert!(service.answering.is_some()); - let _ = collect_ready_service_events(&mut event_rx); + assert_eq!(answer.status, SignallingStatus::Established); + let events = collect_ready_service_events(&mut event_rx); + assert!(events.iter().any(|event| matches!( + event, + TelephonyServiceEvent::Drive(TelephonyDriveStep { step, .. }) + if step.commands.contains(&TelephonyCommand::StartAudioPipelines { link_id }) + ))); let step = service .core @@ -555,31 +567,15 @@ async fn answered_service_starts_media_only_after_remote_established_echo() { .unwrap(); assert_eq!( step.commands, - vec![TelephonyCommand::StartAudioPipelines { link_id }] + vec![TelephonyCommand::IgnoredSignal { + link_id, + signal: Signal::from(SignallingStatus::Established), + }] + ); + assert_eq!( + service.core.snapshot().active_call.unwrap().status, + SignallingStatus::Established ); - let effects = service.endpoint.execute_commands(&step.commands).unwrap(); - service - .publish_commands(step.commands, effects) - .await - .unwrap(); - - assert!(service.answering.is_none()); - let active = service.core.snapshot().active_call.unwrap(); - assert_eq!(active.link_id, link_id); - assert_eq!(active.status, SignallingStatus::Established); - let events = collect_ready_service_events(&mut event_rx); - assert!(events.iter().any(|event| matches!( - event, - TelephonyServiceEvent::Drive(TelephonyDriveStep { step, .. }) - if step.commands == vec![TelephonyCommand::StartAudioPipelines { link_id }] - ))); - assert!(matches!( - events.last(), - Some(TelephonyServiceEvent::Snapshot(snapshot)) - if snapshot.active_call.as_ref().is_some_and(|active| { - active.link_id == link_id && active.status == SignallingStatus::Established - }) - )); } #[tokio::test] @@ -594,7 +590,6 @@ async fn answer_transport_backpressure_rolls_back_without_publishing_a_prefix() let active = service.core.active_call().unwrap(); assert_eq!(active.call.status(), SignallingStatus::Ringing); assert!(!active.call.answered()); - assert!(service.answering.is_none()); assert!(matches!( transport_rx.try_recv().unwrap(), @@ -603,46 +598,42 @@ async fn answer_transport_backpressure_rolls_back_without_publishing_a_prefix() assert!(transport_rx.try_recv().is_err()); } -#[tokio::test] -async fn answering_retries_are_bounded_and_timeout_terminates_connecting_call() { - let config = TelephonyServiceConfig { - answer_retry_interval: Some(Duration::from_millis(10)), - answer_timeout: Some(Duration::from_millis(40)), - ..TelephonyServiceConfig::default() - }; +#[tokio::test(start_paused = true)] +async fn answered_callee_sends_one_answer_and_never_times_out_waiting_for_echo() { let (mut service, _receiver, link_id, mut transport_rx, mut event_rx) = - ringing_incoming_service(16, 16, config); + ringing_incoming_service(16, 64, TelephonyServiceConfig::default()); let _destination_registration = transport_rx.try_recv().unwrap(); service.answer_exact(link_id).await.unwrap(); + let _ = take_outbound(&mut transport_rx); + let _ = take_outbound(&mut transport_rx); let _ = collect_ready_service_events(&mut event_rx); - let _ = take_outbound(&mut transport_rx); - let _ = take_outbound(&mut transport_rx); - service.answering.as_mut().unwrap().next_retry_at = Some(Instant::now()); - assert!(service.handle_due_answer_retry().await); - assert!(matches!( - event_rx.try_recv().unwrap(), - TelephonyServiceEvent::Drive(_) - )); - let _ = take_outbound(&mut transport_rx); - let _ = take_outbound(&mut transport_rx); - - service.answering.as_mut().unwrap().expires_at = Some(Instant::now()); - assert!(service.handle_due_answer_retry().await); - assert!(service.core.active_call().is_none()); - assert!(service.answering.is_none()); + for _ in 0..100 { + tokio::time::advance(Duration::from_millis(100)).await; + assert!(service.handle_due_timeout().await); + } + while let Ok(message) = transport_rx.try_recv() { + assert!( + !matches!( + message, + TransportMessage::Outbound(_) + | TransportMessage::SendLinkEndpoint { .. } + | TransportMessage::SendLinkEndpointBestEffort { .. } + ), + "no answer retry is sent: {message:?}" + ); + } let events = collect_ready_service_events(&mut event_rx); - assert!(events.iter().any(|event| matches!( - event, - TelephonyServiceEvent::CallTerminated { - link_id: terminated, - reason: Some(SignallingStatus::Connecting), - } if *terminated == link_id - ))); - assert!(matches!( - events.last(), - Some(TelephonyServiceEvent::Snapshot(snapshot)) if snapshot.active_call.is_none() - )); + let active = service + .core + .active_call() + .unwrap_or_else(|| panic!("{events:?}")); + assert_eq!(active.call.status(), SignallingStatus::Established); + assert!( + !events + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })) + ); } #[test] @@ -711,10 +702,17 @@ fn outgoing_signalling_from_lxst_packets_drives_call_setup() { link_id, profile: Profile::LatencyLow, }, - TelephonyCommand::PrepareDialingPipelines { link_id }, - TelephonyCommand::SendSignal { + TelephonyCommand::SelectMode { link_id, - signal: Signal::from(Profile::LatencyLow), + mode: CallMode::FullDuplex, + }, + TelephonyCommand::PrepareDialingPipelines { link_id }, + TelephonyCommand::SendSignalPair { + link_id, + signals: [ + Signal::from(Profile::LatencyLow), + Signal::from(CallMode::FullDuplex) + ], }, TelephonyCommand::StartDialTone { link_id }, ] @@ -894,7 +892,9 @@ fn runtime_snapshot_reports_busy_pending_and_active_call_state() { role: CallRole::Incoming, status: SignallingStatus::Ringing, profile: None, + mode: None, answered: false, + transmit_squelched: false, }), } ); @@ -1312,7 +1312,7 @@ fn rns_endpoint_try_drive_ready_pumps_reticulum_handshake_events() { } #[tokio::test] -async fn discover_remote_telephony_peer_uses_recalled_identity_and_refreshes_path() { +async fn discover_remote_telephony_peer_uses_recalled_identity_without_path_request() { let local_identity = Identity::new(); let remote_identity = Identity::new(); let remote_hash = remote_identity.hash; @@ -1338,16 +1338,6 @@ async fn discover_remote_telephony_peer_uses_recalled_identity_and_refreshes_pat recalled_destination(destination_hash, 3, remote_public_key), ))) .unwrap(); - - let request_path = transport_rx.recv().await.unwrap(); - let TransportMessage::RequestPath { - destination_hash: requested_hash, - } = request_path - else { - panic!("expected RequestPath, got {request_path:?}"); - }; - assert_eq!(requested_hash, destination_hash); - assert!(transport_rx.try_recv().is_err()); }; let (peer, ()) = tokio::join!(discovery, transport); @@ -1360,6 +1350,10 @@ async fn discover_remote_telephony_peer_uses_recalled_identity_and_refreshes_pat hops: 3, } ); + assert!( + transport_rx.try_recv().is_err(), + "no path request for a known peer" + ); } #[tokio::test] @@ -1388,18 +1382,6 @@ async fn discover_remote_telephony_peer_requests_path_when_identity_is_not_recal .send(TransportQueryResponse::RecalledDestination(None)) .unwrap(); - let rpc = transport_rx.recv().await.unwrap(); - let TransportMessage::Rpc { query, response_tx } = rpc else { - panic!("expected DropPath Rpc, got {rpc:?}"); - }; - assert!(matches!( - query, - TransportQuery::DropPath { - dest - } if dest == destination_hash - )); - response_tx.send(TransportQueryResponse::Ok).unwrap(); - let request_path = transport_rx.recv().await.unwrap(); let TransportMessage::RequestPath { destination_hash: requested_hash, @@ -1534,18 +1516,6 @@ async fn begin_outgoing_link_discovers_announce_and_sends_link_request() { .send(TransportQueryResponse::RecalledDestination(None)) .unwrap(); - let rpc = transport_rx.recv().await.unwrap(); - let TransportMessage::Rpc { query, response_tx } = rpc else { - panic!("expected DropPath Rpc, got {rpc:?}"); - }; - assert!(matches!( - query, - TransportQuery::DropPath { - dest - } if dest == destination_hash - )); - response_tx.send(TransportQueryResponse::Ok).unwrap(); - let request_path = transport_rx.recv().await.unwrap(); let TransportMessage::RequestPath { destination_hash: requested_hash, @@ -1588,15 +1558,6 @@ async fn begin_outgoing_link_discovers_announce_and_sends_link_request() { )])) .unwrap(); - let request_path = transport_rx.recv().await.unwrap(); - let TransportMessage::RequestPath { - destination_hash: requested_hash, - } = request_path - else { - panic!("expected link RequestPath, got {request_path:?}"); - }; - assert_eq!(requested_hash, destination_hash); - let register_link = transport_rx.recv().await.unwrap(); let TransportMessage::RegisterDestination { hash: registered_link_id, @@ -1674,8 +1635,8 @@ async fn telephony_service_registered_helper_wires_channels_and_lifecycle() { assert_deregistered_destination(&mut transport_rx, destination_hash); } -#[tokio::test] -async fn telephony_service_announces_on_start() { +#[tokio::test(start_paused = true)] +async fn telephony_service_announces_once_after_first_job_interval() { let local_identity = Identity::new(); let destination_hash = telephony_destination_hash(&local_identity.hash); let (transport_tx, mut transport_rx) = mpsc::channel(8); @@ -1688,7 +1649,6 @@ async fn telephony_service_announces_on_start() { &local_identity, TelephonyServiceConfig { poll_interval: Duration::from_millis(10), - announce_interval: None, ..TelephonyServiceConfig::default() }, TelephonyServiceChannelConfig::default(), @@ -1698,7 +1658,13 @@ async fn telephony_service_announces_on_start() { let _listener_registration = transport_rx.recv().await.unwrap(); let service_task = tokio::spawn(service.run()); - let announce = timeout(Duration::from_secs(1), transport_rx.recv()) + assert!( + timeout(Duration::from_millis(4_900), transport_rx.recv()) + .await + .is_err(), + "Python Telephone does not announce during construction" + ); + let announce = timeout(Duration::from_millis(200), transport_rx.recv()) .await .unwrap() .unwrap(); @@ -1714,6 +1680,12 @@ async fn telephony_service_announces_on_start() { let announce_data = AnnounceData::unpack(&announce.raw[data_offset..], header.flags.context_flag).unwrap(); announce_data.validate(&destination_hash).unwrap(); + assert!( + timeout(Duration::from_secs(60), transport_rx.recv()) + .await + .is_err(), + "no startup announce burst by default" + ); control_tx.send(TelephonyControl::Shutdown).await.unwrap(); let stopped = timeout(Duration::from_secs(1), event_rx.recv()) @@ -1724,8 +1696,8 @@ async fn telephony_service_announces_on_start() { service_task.await.unwrap(); } -#[tokio::test] -async fn telephony_service_retries_startup_announces_before_regular_interval() { +#[tokio::test(start_paused = true)] +async fn telephony_service_startup_announce_burst_is_opt_in() { let local_identity = Identity::new(); let destination_hash = telephony_destination_hash(&local_identity.hash); let (transport_tx, mut transport_rx) = mpsc::channel(8); @@ -1751,7 +1723,7 @@ async fn telephony_service_retries_startup_announces_before_regular_interval() { let service_task = tokio::spawn(service.run()); for _ in 0..3 { - let announce = timeout(Duration::from_secs(1), transport_rx.recv()) + let announce = timeout(Duration::from_secs(6), transport_rx.recv()) .await .unwrap() .unwrap(); @@ -1870,6 +1842,7 @@ async fn telephony_service_outgoing_discovery_does_not_block_controls() { .send(TelephonyControl::Call { remote_identity: remote_hash, profile: Some(Profile::QualityMedium), + mode: None, discovery_timeout: Duration::from_millis(100), }) .await @@ -1913,17 +1886,6 @@ async fn telephony_service_outgoing_discovery_does_not_block_controls() { response_tx .send(TransportQueryResponse::RecalledDestination(None)) .unwrap(); - let rpc = transport_rx.recv().await.unwrap(); - let TransportMessage::Rpc { query, response_tx } = rpc else { - panic!("expected DropPath Rpc, got {rpc:?}"); - }; - assert!(matches!( - query, - TransportQuery::DropPath { - dest - } if dest == remote_destination_hash - )); - response_tx.send(TransportQueryResponse::Ok).unwrap(); let request_path = transport_rx.recv().await.unwrap(); let TransportMessage::RequestPath { destination_hash } = request_path else { @@ -1954,6 +1916,17 @@ async fn telephony_service_outgoing_discovery_does_not_block_controls() { message: Error::RemoteTelephonyPeerNotDiscovered.to_string(), } ); + let event = timeout(Duration::from_secs(1), event_rx.recv()) + .await + .unwrap() + .unwrap(); + assert!(matches!( + event, + TelephonyServiceEvent::Snapshot(TelephonyRuntimeSnapshot { + active_call: None, + .. + }) + )); control_tx.send(TelephonyControl::Shutdown).await.unwrap(); let stopped = timeout(Duration::from_secs(1), event_rx.recv()) @@ -1996,6 +1969,7 @@ async fn telephony_service_call_control_discovers_peer_and_emits_started() { .send(TelephonyControl::Call { remote_identity: remote_hash, profile: Some(Profile::LatencyLow), + mode: None, discovery_timeout: Duration::from_secs(1), }) .await @@ -2024,18 +1998,6 @@ async fn telephony_service_call_control_discovers_peer_and_emits_started() { .send(TransportQueryResponse::RecalledDestination(None)) .unwrap(); - let rpc = transport_rx.recv().await.unwrap(); - let TransportMessage::Rpc { query, response_tx } = rpc else { - panic!("expected DropPath Rpc, got {rpc:?}"); - }; - assert!(matches!( - query, - TransportQuery::DropPath { - dest - } if dest == destination_hash - )); - response_tx.send(TransportQueryResponse::Ok).unwrap(); - let request_path = transport_rx.recv().await.unwrap(); let TransportMessage::RequestPath { destination_hash: requested_hash, @@ -2078,15 +2040,6 @@ async fn telephony_service_call_control_discovers_peer_and_emits_started() { )])) .unwrap(); - let request_path = transport_rx.recv().await.unwrap(); - let TransportMessage::RequestPath { - destination_hash: requested_hash, - } = request_path - else { - panic!("expected link RequestPath, got {request_path:?}"); - }; - assert_eq!(requested_hash, destination_hash); - let register_link = transport_rx.recv().await.unwrap(); let TransportMessage::RegisterDestination { hash: registered_link_id, @@ -2130,7 +2083,9 @@ async fn telephony_service_call_control_discovers_peer_and_emits_started() { role: CallRole::Outgoing, status: SignallingStatus::Calling, profile: Some(Profile::LatencyLow), + mode: None, answered: false, + transmit_squelched: false, }), }) ); @@ -2873,7 +2828,9 @@ async fn telephony_service_stops_media_streams_on_established_profile_switch() { status: SignallingStatus::Established, profile: Some(new_profile), remote_identity: identity(0xB0), + mode: Some(CallMode::FullDuplex), answered: false, + transmit_squelched: false, }), }) ); @@ -3148,15 +3105,6 @@ fn outgoing_link_attempt_promotes_after_proof_and_drives_available_signal() { ) .unwrap(); - let request_path = transport_rx.try_recv().unwrap(); - let TransportMessage::RequestPath { - destination_hash: requested_hash, - } = request_path - else { - panic!("expected RequestPath, got {request_path:?}"); - }; - assert_eq!(requested_hash, destination_hash); - let register_link = transport_rx.try_recv().unwrap(); let TransportMessage::RegisterDestination { hash: registered_link_id, @@ -4189,7 +4137,7 @@ async fn native_codec2_duplex_and_input_lease_use_the_real_link() { 81 } ); - let mut decoder = media::AudioDecoder::new(profile).unwrap(); + let mut decoder = media::ReceiveDecoder::new(profile); assert_eq!( decoder .decode_frame(&packet.frames[0]) @@ -4257,7 +4205,7 @@ fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() { let mut packet = encoder .encode_frame(&synthetic_frame_for_profile(profile)) .unwrap(); - let mut decoder = media::AudioDecoder::new(profile).unwrap(); + let mut decoder = media::ReceiveDecoder::new(profile); let mode = packet.payload[0]; packet.payload[0] ^= 1; assert!(decoder.decode_frame(&packet).is_err()); @@ -4265,3 +4213,556 @@ fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() { assert!(decoder.decode_frame(&packet).is_ok()); } } + +fn upstream_media_vectors() -> serde_json::Value { + let vectors: serde_json::Value = + serde_json::from_str(include_str!("../tests/fixtures/lxst_060_media.json")).unwrap(); + assert_eq!(vectors["lxst_version"], "0.6.0"); + assert_eq!(vectors["rns_version"], "1.6.0"); + vectors +} + +#[test] +fn receive_decoder_follows_codec_of_each_frame_in_an_upstream_batch() { + let vectors = upstream_media_vectors(); + let profile = Profile::QualityMedium; + let mut decoder = media::ReceiveDecoder::new(profile); + for entry in vectors["mixed_batch"].as_array().unwrap() { + let bytes = hex::decode(entry["wire_hex"].as_str().unwrap()).unwrap(); + let frame = Frame::from_wire_bytes(&bytes).unwrap(); + let decoded = decoder + .decode_frame(&frame) + .unwrap_or_else(|err| panic!("{}: {err}", entry["name"])); + // Upstream decoded at 48 kHz; the local profile plays at its own rate. + let upstream_ms = entry["decoded_sample_frames"].as_u64().unwrap() as f64 / 48.0; + let local_ms = + decoded.sample_frames() as f64 * 1000.0 / f64::from(profile.sample_rate_hz()); + assert!( + (upstream_ms - local_ms).abs() < 1.0, + "{}: upstream {upstream_ms} ms, Rust {local_ms} ms", + entry["name"] + ); + assert_eq!(decoded.channels, profile.channels()); + } +} + +#[test] +fn receive_decoder_skips_only_a_corrupt_frame() { + let vectors = upstream_media_vectors(); + let mut decoder = media::ReceiveDecoder::new(Profile::QualityMedium); + let frames = vectors["mixed_batch"] + .as_array() + .unwrap() + .iter() + .map(|entry| { + Frame::from_wire_bytes(&hex::decode(entry["wire_hex"].as_str().unwrap()).unwrap()) + .unwrap() + }) + .collect::>(); + let mut corrupt = frames[1].clone(); + corrupt.payload[0] = 0x7F; + assert!(decoder.decode_frame(&frames[0]).is_ok()); + assert!(decoder.decode_frame(&corrupt).is_err()); + assert!(decoder.decode_frame(&frames[2]).is_ok()); +} + +#[test] +fn profile_buffer_frames_match_upstream_table() { + let vectors = upstream_media_vectors(); + for (wire, frames) in vectors["buffer_frames"].as_object().unwrap() { + let profile = Profile::from_wire(wire.parse().unwrap()).unwrap(); + assert_eq!( + u64::from(profile.buffer_frames()), + frames.as_u64().unwrap(), + "{profile:?}" + ); + } +} + +#[test] +fn raw_float128_matches_upstream_binary128_bytes() { + let vectors = upstream_media_vectors(); + let raw128 = &vectors["raw128"]; + if raw128["longdouble_bits"] != 128 || raw128["longdouble_nmant"] != 112 { + // Vectors produced on a platform without IEEE binary128 long double. + return; + } + let payload = hex::decode(raw128["payload_hex"].as_str().unwrap()).unwrap(); + let samples = raw128["samples"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_f64().unwrap() as f32) + .collect::>(); + let frame = RawAudioFrame::new(1, samples.clone()).unwrap(); + assert_eq!(frame.to_payload(RawBitDepth::Float128).unwrap(), payload); + assert_eq!( + RawAudioFrame::from_payload(&payload).unwrap().samples, + samples + ); +} + +#[test] +fn preferred_mode_signals_use_python_wire_values() { + assert_eq!(Signal::from_wire(0xF1), Signal::from(CallMode::FullDuplex)); + assert_eq!(Signal::from_wire(0xF2), Signal::from(CallMode::HalfDuplex)); + assert_eq!(Signal::from_wire(0xF0), Signal::PreferredMode(0)); + assert_eq!(Signal::from_wire(0xF3).wire_value(), 0xF3); + assert_eq!( + Signal::from_wire(0xFF + 0x40), + Signal::from(Profile::QualityMedium) + ); +} + +fn outgoing_service_at_status( + status: Option, + profile: Profile, + config: TelephonyServiceConfig, +) -> ( + TelephonyService, + Link, + LinkId, + mpsc::Receiver, + mpsc::Receiver, +) { + let (sender, receiver) = active_link_pair(); + let link_id = sender.link_id; + let (transport_tx, mut transport_rx) = mpsc::channel(32); + let mut endpoint = TelephonyRnsEndpoint::register(transport_tx, &Identity::new()).unwrap(); + let _listener_registration = transport_rx.try_recv().unwrap(); + let (_link_event_tx, event_rx) = mpsc::channel(4); + endpoint.outgoing_links.insert( + link_id, + OutgoingLinkState { + link: sender, + event_rx, + endpoint: None, + }, + ); + let mut core = TelephonyRuntimeCore::new(); + core.start_outgoing_call(link_id, identity(0xC1), Some(profile)) + .unwrap(); + let order = [ + SignallingStatus::Available, + SignallingStatus::Ringing, + SignallingStatus::Connecting, + SignallingStatus::Established, + ]; + if let Some(target) = status { + for step in order { + core.accept_lxst_plaintext(link_id, &packet([Signal::from(step)])) + .unwrap(); + if step == target { + break; + } + } + } + let (_control_tx, control_rx) = mpsc::channel(4); + let (event_tx, event_rx) = mpsc::channel(64); + ( + TelephonyService::with_config(endpoint, core, control_rx, event_tx, config), + receiver, + link_id, + transport_rx, + event_rx, + ) +} + +fn quiet_config() -> TelephonyServiceConfig { + TelephonyServiceConfig { + announce_on_start: false, + announce_interval: None, + ..TelephonyServiceConfig::default() + } +} + +#[test] +fn caller_sends_profile_and_mode_in_one_packet_on_ringing() { + let (mut service, receiver, link_id, mut transport_rx, _events) = outgoing_service_at_status( + Some(SignallingStatus::Available), + Profile::QualityMedium, + quiet_config(), + ); + let step = service + .core + .accept_lxst_plaintext(link_id, &packet([Signal::from(SignallingStatus::Ringing)])) + .unwrap(); + service.endpoint.execute_commands(&step.commands).unwrap(); + let (_header, encrypted) = take_outbound(&mut transport_rx); + let plaintext = receiver.decrypt(&encrypted).unwrap(); + // Bytes produced by upstream LXST 0.6.0 for QUALITY_MEDIUM / MODE_FULL_DUPLEX. + assert_eq!(hex::encode(&plaintext), "810092cd013fccf1"); + assert!(transport_rx.try_recv().is_err()); +} + +#[tokio::test(start_paused = true)] +async fn outgoing_call_ends_when_callee_does_not_ring_within_connect_time() { + let (mut service, _receiver, _link_id, _transport_rx, mut events) = outgoing_service_at_status( + Some(SignallingStatus::Available), + Profile::QualityMedium, + quiet_config(), + ); + let _ = service.refresh_active_timeout(); + tokio::time::advance(Duration::from_millis(4_900)).await; + assert!(service.handle_due_timeout().await); + assert!(service.core.active_call().is_some()); + tokio::time::advance(Duration::from_millis(100)).await; + assert!(service.handle_due_timeout().await); + assert!(service.core.active_call().is_none()); + assert!( + collect_ready_service_events(&mut events) + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })) + ); +} + +#[tokio::test(start_paused = true)] +async fn ringing_outgoing_call_ends_at_wait_time_from_call_start() { + let (mut service, _receiver, link_id, _transport_rx, _events) = + outgoing_service_at_status(None, Profile::QualityMedium, quiet_config()); + let _ = service.refresh_active_timeout(); + tokio::time::advance(Duration::from_secs(4)).await; + for status in [SignallingStatus::Available, SignallingStatus::Ringing] { + service + .core + .accept_lxst_plaintext(link_id, &packet([Signal::from(status)])) + .unwrap(); + } + let _ = service.refresh_active_timeout(); + tokio::time::advance(Duration::from_millis(65_900)).await; + assert!(service.handle_due_timeout().await); + assert!(service.core.active_call().is_some()); + tokio::time::advance(Duration::from_millis(100)).await; + assert!(service.handle_due_timeout().await); + assert!(service.core.active_call().is_none()); +} + +#[tokio::test] +async fn squelched_call_sends_no_media() { + let profile = Profile::QualityMedium; + let (mut service, _receiver, _link_id, mut transport_rx, _events) = + outgoing_service_at_status(Some(SignallingStatus::Established), profile, quiet_config()); + assert!( + service + .handle_control(TelephonyControl::SquelchTransmit(true)) + .await + ); + service + .send_opus_frames(profile, vec![synthetic_frame_for_profile(profile)]) + .await + .unwrap(); + assert!(transport_rx.try_recv().is_err()); + assert!( + service + .handle_control(TelephonyControl::SquelchTransmit(false)) + .await + ); + service + .send_opus_frames(profile, vec![synthetic_frame_for_profile(profile)]) + .await + .unwrap(); + let _ = take_outbound(&mut transport_rx); +} + +#[test] +fn unanswered_incoming_call_drops_a_packet_from_its_first_signal_below_mode() { + for stop in [ + Signal::from(SignallingStatus::Connecting), + Signal::Raw(0x50), + ] { + let link_id = link(0x61); + let mut core = TelephonyRuntimeCore::new(); + core.incoming_link_established(link_id); + core.caller_identified(link_id, identity(0x5A)).unwrap(); + let step = core + .accept_lxst_plaintext( + link_id, + &packet([ + Signal::from(Profile::BandwidthLow), + stop, + Signal::from(CallMode::HalfDuplex), + ]), + ) + .unwrap(); + assert_eq!( + step.commands, + vec![ + TelephonyCommand::SelectProfile { + link_id, + profile: Profile::BandwidthLow, + }, + TelephonyCommand::IgnoredSignal { + link_id, + signal: stop, + }, + ] + ); + assert_eq!(core.snapshot().active_call.unwrap().mode, None); + } +} + +#[tokio::test] +async fn remote_half_duplex_switch_squelches_and_local_switch_signals() { + let profile = Profile::QualityMedium; + let (mut service, receiver, link_id, mut transport_rx, _events) = + outgoing_service_at_status(Some(SignallingStatus::Established), profile, quiet_config()); + let step = service + .core + .accept_lxst_plaintext(link_id, &packet([Signal::from(CallMode::HalfDuplex)])) + .unwrap(); + assert_eq!( + step.commands, + vec![TelephonyCommand::SwitchMode { + link_id, + mode: CallMode::HalfDuplex, + }] + ); + service + .send_opus_frames(profile, vec![synthetic_frame_for_profile(profile)]) + .await + .unwrap(); + assert!(transport_rx.try_recv().is_err()); + + assert!( + service + .handle_control(TelephonyControl::SwitchMode { + mode: CallMode::FullDuplex, + }) + .await + ); + let (_header, encrypted) = take_outbound(&mut transport_rx); + let sent = LxstPacket::decode(&receiver.decrypt(&encrypted).unwrap()).unwrap(); + assert_eq!(sent.signals, vec![Signal::from(CallMode::FullDuplex)]); + assert!( + !service + .core + .snapshot() + .active_call + .unwrap() + .transmit_squelched + ); +} + +#[tokio::test(start_paused = true)] +async fn line_is_busy_while_outgoing_call_discovers_path() { + let (transport_tx, mut transport_rx) = mpsc::channel(32); + let endpoint = TelephonyRnsEndpoint::register(transport_tx, &Identity::new()).unwrap(); + let _listener_registration = transport_rx.try_recv().unwrap(); + let (_control_tx, control_rx) = mpsc::channel(4); + let (event_tx, mut events) = mpsc::channel(64); + let mut service = TelephonyService::with_config( + endpoint, + TelephonyRuntimeCore::new(), + control_rx, + event_tx, + quiet_config(), + ); + assert!( + service + .handle_control(TelephonyControl::Call { + remote_identity: identity(0xD1), + profile: None, + mode: None, + discovery_timeout: Duration::from_secs(30), + }) + .await + ); + assert!(service.core.line_busy()); + let incoming = link(0xD2); + assert_eq!( + service.core.incoming_link_established(incoming), + vec![ + TelephonyCommand::SendSignal { + link_id: incoming, + signal: Signal::from(SignallingStatus::Busy), + }, + TelephonyCommand::TeardownLink { link_id: incoming }, + ] + ); + + assert!( + service + .handle_control(TelephonyControl::Hangup { + ring_timeout: false + }) + .await + ); + assert!(!service.core.line_busy()); + assert!( + collect_ready_service_events(&mut events) + .iter() + .any(|event| matches!( + event, + TelephonyServiceEvent::OutgoingCallFailed { message, .. } if message == "cancelled" + )) + ); + assert_eq!( + service.core.incoming_link_established(link(0xD3)), + vec![TelephonyCommand::SendSignal { + link_id: link(0xD3), + signal: Signal::from(SignallingStatus::Available), + }] + ); +} + +#[tokio::test] +async fn hangup_during_discovery_also_ends_the_active_call() { + let (mut service, receiver, link_id, mut transport_rx, mut events) = + ringing_incoming_service(16, 32, quiet_config()); + let _destination_registration = transport_rx.try_recv().unwrap(); + service.outgoing_discovery = Some(OutgoingDiscoveryState { + remote_identity: identity(0xD4), + profile: None, + mode: None, + }); + assert!( + service + .handle_control(TelephonyControl::Hangup { + ring_timeout: false + }) + .await + ); + assert!(service.outgoing_discovery.is_none()); + assert!(service.core.active_call().is_none()); + let (_header, encrypted) = take_outbound(&mut transport_rx); + let sent = LxstPacket::decode(&receiver.decrypt(&encrypted).unwrap()).unwrap(); + assert_eq!(sent.signals, vec![Signal::from(SignallingStatus::Rejected)]); + assert!( + collect_ready_service_events(&mut events) + .iter() + .any(|event| matches!( + event, + TelephonyServiceEvent::CallTerminated { link_id: ended, .. } if *ended == link_id + )) + ); +} + +#[tokio::test(start_paused = true)] +async fn path_discovery_is_bounded_by_wait_time_from_call_start() { + let (transport_tx, mut transport_rx) = mpsc::channel(32); + let endpoint = TelephonyRnsEndpoint::register(transport_tx, &Identity::new()).unwrap(); + let _listener_registration = transport_rx.try_recv().unwrap(); + let (control_tx, control_rx) = mpsc::channel(4); + let (event_tx, mut events) = mpsc::channel(64); + let service = TelephonyService::with_config( + endpoint, + TelephonyRuntimeCore::new(), + control_rx, + event_tx, + TelephonyServiceConfig { + outgoing_call_timeout: Some(Duration::from_secs(3)), + ..quiet_config() + }, + ); + let task = tokio::spawn(service.run()); + let started = Instant::now(); + control_tx + .send(TelephonyControl::Call { + remote_identity: identity(0xD5), + profile: None, + mode: None, + discovery_timeout: Duration::from_secs(10), + }) + .await + .unwrap(); + let responder = tokio::spawn(async move { + while let Some(message) = transport_rx.recv().await { + if let TransportMessage::Rpc { query, response_tx } = message { + let response = match query { + TransportQuery::DropPath { .. } => TransportQueryResponse::Ok, + _ => TransportQueryResponse::RecalledDestination(None), + }; + let _ = response_tx.send(response); + } + } + }); + loop { + let event = timeout(Duration::from_secs(20), events.recv()) + .await + .unwrap() + .unwrap(); + if matches!(event, TelephonyServiceEvent::OutgoingCallFailed { .. }) { + break; + } + } + let elapsed = started.elapsed(); + assert!(elapsed <= Duration::from_millis(3_200), "{elapsed:?}"); + control_tx.send(TelephonyControl::Shutdown).await.unwrap(); + task.await.unwrap(); + responder.abort(); +} + +#[tokio::test] +async fn known_peer_call_sends_no_path_request_or_drop() { + let remote = Identity::new(); + let remote_destination = telephony_destination_hash(&remote.hash); + let (transport_tx, mut transport_rx) = mpsc::channel(64); + let endpoint = TelephonyRnsEndpoint::register(transport_tx, &Identity::new()).unwrap(); + let _listener_registration = transport_rx.try_recv().unwrap(); + let (control_tx, control_rx) = mpsc::channel(4); + let (event_tx, mut events) = mpsc::channel(64); + let task = tokio::spawn( + TelephonyService::with_config( + endpoint, + TelephonyRuntimeCore::new(), + control_rx, + event_tx, + quiet_config(), + ) + .run(), + ); + control_tx + .send(TelephonyControl::Call { + remote_identity: remote.hash, + profile: None, + mode: None, + discovery_timeout: Duration::from_secs(5), + }) + .await + .unwrap(); + let (mut path_requests, mut drops, mut link_requests) = (0, 0, 0); + while link_requests == 0 { + let message = timeout(Duration::from_secs(5), transport_rx.recv()) + .await + .unwrap() + .unwrap(); + match message { + TransportMessage::RequestPath { destination_hash } + | TransportMessage::RequestPathWithOptions { + destination_hash, .. + } if destination_hash == remote_destination => path_requests += 1, + TransportMessage::AwaitPath { reply, .. } => { + let _ = reply.send(true); + } + TransportMessage::SendLinkRequest { result_tx, .. } => { + link_requests += 1; + let _ = result_tx.send(Ok(())); + } + TransportMessage::Rpc { query, response_tx } => { + let response = match query { + TransportQuery::RecallDestination { dest } => { + TransportQueryResponse::RecalledDestination(Some(recalled_destination( + dest, + 1, + remote.get_public_key(), + ))) + } + TransportQuery::DropPath { .. } => { + drops += 1; + TransportQueryResponse::Ok + } + TransportQuery::GetPathTable => { + TransportQueryResponse::PathTable(vec![path_entry(remote_destination, 1)]) + } + _ => TransportQueryResponse::Ok, + }; + let _ = response_tx.send(response); + } + _ => {} + } + while events.try_recv().is_ok() {} + } + assert_eq!((path_requests, drops), (0, 0)); + control_tx.send(TelephonyControl::Shutdown).await.unwrap(); + task.abort(); +} diff --git a/crates/lxst-telephony/tests/fixtures/lxst_060_media.json b/crates/lxst-telephony/tests/fixtures/lxst_060_media.json new file mode 100644 index 0000000..3032b48 --- /dev/null +++ b/crates/lxst-telephony/tests/fixtures/lxst_060_media.json @@ -0,0 +1,68 @@ +{ + "lxst_version": "0.6.0", + "rns_version": "1.6.0", + "generator": "crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py", + "buffer_frames": { + "16": 2, + "32": 2, + "48": 2, + "64": 5, + "80": 5, + "96": 5, + "112": 2, + "128": 3 + }, + "frame_time_ms": { + "16": 400, + "32": 320, + "48": 200, + "64": 60, + "80": 60, + "96": 60, + "112": 10, + "128": 20 + }, + "telephone_timeouts": { + "RING_TIME": 60, + "WAIT_TIME": 70, + "CONNECT_TIME": 5 + }, + "raw128": { + "machine": "aarch64", + "longdouble_bits": 128, + "longdouble_nmant": 112, + "samples": [ + 0.0, + 0.5, + -0.25, + 1.0 + ], + "payload_hex": "c0000000000000000000000000000000000000000000000000000000000000fe3f0000000000000000000000000000fdbf0000000000000000000000000000ff3f", + "decoded": [ + 0.0, + 0.5, + -0.25, + 1.0 + ] + }, + "mixed_batch": [ + { + "name": "opus_60ms", + "codec": 1, + "wire_hex": "01db037b5af3c47e60df913de2a4bc5f21a2bd4eb9afea6c144d002a6a9a8c966f0ffd97d00daeb04dcf27e9a5f40332fd4ef0fcea52582fae", + "decoded_sample_frames": 2880 + }, + { + "name": "codec2_3200_200ms", + "codec": 2, + "wire_hex": "0206c07d231bd4ace738c0002900d6bdeb5ac681000019f81dd0c5b962029b86d5ffc5884a0094bd6b5ac591840194adebdac5802900d6bdeb5ac581000019f81dd0c5b962029b86d5ffc5884a0094bd6b5a", + "decoded_sample_frames": 9595 + }, + { + "name": "opus_20ms", + "codec": 1, + "wire_hex": "01d8b51a679c5c8787e2a9b61c6bc130233e9db6b2", + "decoded_sample_frames": 960 + } + ] +} \ No newline at end of file diff --git a/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py b/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py new file mode 100644 index 0000000..118957e --- /dev/null +++ b/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py @@ -0,0 +1,78 @@ +"""LXST 0.6.0 media-path vectors, produced only by calling upstream code. + +usage: PYTHONPATH=: python crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py + +Emits: + buffer_frames: Profiles.get_buffer_frames(p) for every profile constant. + telephone_timeouts: Telephone.RING_TIME / WAIT_TIME / CONNECT_TIME. + raw128: upstream Raw(bitdepth=128).encode of fixed samples (platform-specific; records + platform.machine() and numpy longdouble info) and Raw().decode of those bytes. + mixed_batch: wire frames (codec header byte + payload) produced by upstream encoders for + one LXST packet that switches codec mid-batch: Opus VOICE_MEDIUM 60 ms, Codec2 3200 + 200 ms, Opus VOICE_MEDIUM 20 ms; plus the per-frame sample counts upstream decodes + with LinkSource-style per-frame codec switching (Network.py:114-135). +""" +import json, platform, sys +import numpy as np +import RNS +import LXST +from LXST._version import __version__ as LXST_VERSION +from LXST.Codecs import Raw, Opus, Codec2, codec_header_byte, codec_type +from LXST.Primitives.Telephony import Profiles, Telephone + +assert LXST_VERSION == "0.6.0", LXST_VERSION +assert RNS.__version__ == "1.6.0", RNS.__version__ + + +class Src: # encoder "source" attribute: only samplerate is read + def __init__(self, rate): self.samplerate = rate + + +class Sink: # decoder "sink": samplerate/channels are read + def __init__(self, rate, ch): self.samplerate = rate; self.channels = ch + + +def tone(rate, ms): + n = int(rate * ms / 1000) + t = np.arange(n) / rate + return (0.3 * np.sin(2 * np.pi * 440 * t)).reshape(n, 1).astype("float32") + + +out = {"lxst_version": LXST_VERSION, "rns_version": RNS.__version__, + "generator": "crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py"} +profiles = {k: getattr(Profiles, k) for k in ["BANDWIDTH_ULTRA_LOW", "BANDWIDTH_VERY_LOW", "BANDWIDTH_LOW", + "QUALITY_MEDIUM", "QUALITY_HIGH", "QUALITY_MAX", "LATENCY_ULTRA_LOW", "LATENCY_LOW"]} +out["buffer_frames"] = {str(v): Profiles.get_buffer_frames(v) for v in profiles.values()} +out["frame_time_ms"] = {str(v): Profiles.get_frame_time(v) for v in profiles.values()} +out["telephone_timeouts"] = {"RING_TIME": Telephone.RING_TIME, "WAIT_TIME": Telephone.WAIT_TIME, + "CONNECT_TIME": Telephone.CONNECT_TIME} + +samples = np.array([[0.0], [0.5], [-0.25], [1.0]], dtype="float32") +raw = Raw(channels=1, bitdepth=128) +enc = raw.encode(samples) +dec = Raw().decode(enc) +out["raw128"] = {"machine": platform.machine(), "longdouble_bits": int(np.finfo(np.longdouble).bits), + "longdouble_nmant": int(np.finfo(np.longdouble).nmant), + "samples": samples[:, 0].tolist(), "payload_hex": enc.hex(), + "decoded": [float(x) for x in dec[:, 0]]} + +frames = [] +o = Opus(profile=Opus.PROFILE_VOICE_MEDIUM); o.source = Src(24000) +frames.append(("opus_60ms", codec_header_byte(Opus) + o.encode(tone(24000, 60)))) +c = Codec2(mode=Codec2.CODEC2_3200); c.source = Src(8000) +frames.append(("codec2_3200_200ms", codec_header_byte(Codec2) + c.encode(np.repeat(tone(8000, 200), 2, axis=1)))) +frames.append(("opus_20ms", codec_header_byte(Opus) + o.encode(tone(24000, 20)))) + +# Upstream receive-side per-frame codec switching, as in LinkSource._packet. +sink = Sink(48000, 1) +codec = Opus(); codec.sink = sink +decoded = [] +for name, fb in frames: + ft = codec_type(fb[0]) + if type(codec) != ft: + codec = ft(); codec.sink = sink + d = codec.decode(fb[1:]) + decoded.append({"name": name, "codec": int(fb[0]), "wire_hex": fb.hex(), "decoded_sample_frames": int(d.shape[0])}) +out["mixed_batch"] = decoded +open(sys.argv[1], "w").write(json.dumps(out, indent=1)) +print(json.dumps(out, indent=1)[:3000]) diff --git a/crates/lxst-telephony/tests/python_telephone_helper.rs b/crates/lxst-telephony/tests/python_telephone_helper.rs index 8a15523..2f0728f 100644 --- a/crates/lxst-telephony/tests/python_telephone_helper.rs +++ b/crates/lxst-telephony/tests/python_telephone_helper.rs @@ -69,7 +69,8 @@ fn python_telephone_helper_loads_reference_and_creates_destination() { .expect("READY event"); assert_eq!(ready["app_name"], "lxst"); assert_eq!(ready["primitive_name"], "telephony"); - assert_eq!(ready["lxst_version"], "0.4.5"); + assert_eq!(ready["lxst_version"], "0.6.0"); + assert_eq!(ready["rns_version"], "1.6.0"); let lxst_root = PathBuf::from(ready["lxst_root"].as_str().expect("LXST root")); if let Ok(configured) = std::env::var("LXST_UPSTREAM_DIR") { let configured = PathBuf::from(configured) @@ -77,7 +78,10 @@ fn python_telephone_helper_loads_reference_and_creates_destination() { .expect("configured LXST upstream exists"); assert_eq!(lxst_root, configured); } else { - assert!(lxst_root.ends_with(Path::new("upstream").join("LXST"))); + assert!( + lxst_root.ends_with(Path::new("upstream").join("LXST")) + || lxst_root.ends_with(Path::new("upstream").join("candidate").join("LXST")) + ); } assert!(ready["codec2_stubbed"].is_boolean()); assert_eq!(ready["headless_audio"], true); diff --git a/crates/lxst-telephony/tests/python_telephone_live_interop.rs b/crates/lxst-telephony/tests/python_telephone_live_interop.rs index 4b071da..752a4fa 100644 --- a/crates/lxst-telephony/tests/python_telephone_live_interop.rs +++ b/crates/lxst-telephony/tests/python_telephone_live_interop.rs @@ -24,7 +24,7 @@ use serde_json::{Value, json}; use tokio::sync::mpsc; use lxst_core::{ - CallRole, FrameStreamEvent, Profile, RawAudioFrame, RawBitDepth, SignallingStatus, + CallMode, CallRole, FrameStreamEvent, Profile, RawAudioFrame, RawBitDepth, SignallingStatus, SyntheticSource, SyntheticSourceKind, TELEPHONY_DESTINATION_NAME, }; use lxst_telephony::{ @@ -92,6 +92,15 @@ impl PythonTelephoneHost { } fn spawn_with_tcp(port: u16, tcp_role: &str, enable_transport: bool) -> Self { + Self::spawn_with_env(port, tcp_role, enable_transport, &[]) + } + + fn spawn_with_env( + port: u16, + tcp_role: &str, + enable_transport: bool, + env: &[(&str, &str)], + ) -> Self { let storage = temp_storage("rs-lxst-python-telephone-live"); std::fs::create_dir_all(&storage).expect("create Python helper storage"); let log_path = storage.join("helper.stderr.log"); @@ -119,6 +128,9 @@ impl PythonTelephoneHost { .stdout(Stdio::piped()) .stderr(Stdio::from(log_file)); add_platform_python_library_path(&mut command); + for (key, value) in env { + command.env(key, value); + } if enable_transport { command.arg("--enable-transport"); } @@ -751,6 +763,7 @@ impl RustCallerSession { .send(TelephonyControl::Call { remote_identity: remote_identity_hash, profile: Some(profile), + mode: None, discovery_timeout: Duration::from_secs(5), }) .await @@ -1141,6 +1154,7 @@ async fn rust_to_rust_call_establishes_through_python_transport_hub() { .send(TelephonyControl::Call { remote_identity: callee.identity.hash, profile: Some(Profile::QualityMedium), + mode: None, discovery_timeout: Duration::from_secs(10), }) .await @@ -1237,7 +1251,8 @@ async fn rust_telephony_startup_retry_announces_after_late_tcp_hub_connection() let announce = wait_for_announce( &mut caller_announces, callee.destination_hash, - Duration::from_secs(5), + // The first announce follows one job interval, as in Python. + Duration::from_secs(10), "callee startup retry after late TCP hub connection", ) .await; @@ -2322,6 +2337,7 @@ async fn rust_service_outgoing_timeout_ends_python_ringing_call_without_audio() .send(TelephonyControl::Call { remote_identity: remote_identity_hash, profile: None, + mode: None, discovery_timeout: Duration::from_secs(5), }) .await @@ -2586,6 +2602,7 @@ async fn rust_service_sends_raw_media_to_python_established_call() { .send(TelephonyControl::Call { remote_identity: remote_identity_hash, profile: None, + mode: None, discovery_timeout: Duration::from_secs(5), }) .await @@ -2806,6 +2823,7 @@ async fn rust_service_receives_python_raw_media_on_established_call() { .send(TelephonyControl::Call { remote_identity: remote_identity_hash, profile: None, + mode: None, discovery_timeout: Duration::from_secs(5), }) .await @@ -2929,3 +2947,367 @@ async fn rust_service_decodes_python_opus_voice_profile_matrix() { session.shutdown().await; } } + +struct ServiceCallPair { + helper: PythonTelephoneHost, + actor_tx: mpsc::Sender, + control_tx: mpsc::Sender, + events: mpsc::Receiver, + python_identity: [u8; 16], + rust_destination: [u8; 16], + service_task: tokio::task::JoinHandle<()>, + tasks: Vec>, +} + +impl ServiceCallPair { + async fn connect(env: &[(&str, &str)]) -> Self { + let port = free_tcp_port(); + let (actor_tx, server, mut handle_rx) = spawn_rust_actor_and_tcp(port).await; + let mut announce_rx = register_telephony_announce_handler(&actor_tx).await; + let helper = PythonTelephoneHost::spawn_with_env(port, "client", false, env); + let ready = helper.wait_event("READY", Duration::from_secs(10)); + assert_eq!(ready["lxst_version"], "0.6.0"); + let python_identity = hash_from_ready(&ready, "identity_hash"); + let python_destination = hash_from_ready(&ready, "destination_hash"); + let accepted = tokio::time::timeout(Duration::from_secs(15), handle_rx.recv()) + .await + .expect("Python helper TCP connection") + .expect("TCP accept channel"); + let (id, entry, read_task) = register_interface_entry(accepted); + actor_tx + .send(TransportMessage::RegisterInterface { id, entry }) + .await + .unwrap(); + + let endpoint = TelephonyRnsEndpoint::register(actor_tx.clone(), &Identity::new()) + .expect("register Rust Telephone endpoint"); + let rust_destination = endpoint.destination_hash; + let (control_tx, control_rx) = mpsc::channel(16); + let (event_tx, events) = mpsc::channel(256); + let service = TelephonyService::with_config( + endpoint, + TelephonyRuntimeCore::new(), + control_rx, + event_tx, + TelephonyServiceConfig { + poll_interval: Duration::from_millis(20), + announce_on_start: false, + announce_interval: None, + ..TelephonyServiceConfig::default() + }, + ); + let service_task = tokio::spawn(service.run()); + control_tx.send(TelephonyControl::Announce).await.unwrap(); + helper.send_announce(); + wait_for_announce( + &mut announce_rx, + python_destination, + Duration::from_secs(15), + "Python Telephone", + ) + .await; + tokio::time::sleep(Duration::from_millis(500)).await; + Self { + helper, + actor_tx, + control_tx, + events, + python_identity, + rust_destination, + service_task, + tasks: vec![read_task, server.read_task], + } + } + + async fn wait_event( + &mut self, + label: &str, + timeout: Duration, + matches: impl Fn(&TelephonyServiceEvent) -> bool, + ) -> TelephonyServiceEvent { + wait_matching_service_event(&mut self.events, timeout, label, matches).await + } + + async fn wait_snapshot( + &mut self, + label: &str, + matches: impl Fn(&ActiveCallSnapshot) -> bool, + ) -> ActiveCallSnapshot { + let event = self + .wait_event(label, Duration::from_secs(10), |event| { + matches!(event, TelephonyServiceEvent::Snapshot(snapshot) + if snapshot.active_call.as_ref().is_some_and(&matches)) + }) + .await; + let TelephonyServiceEvent::Snapshot(snapshot) = event else { + unreachable!() + }; + snapshot.active_call.unwrap() + } + + fn drain(&mut self) -> Vec { + let mut events = Vec::new(); + while let Ok(event) = self.events.try_recv() { + events.push(event); + } + events + } + + async fn python_calls_rust_and_rust_answers(&mut self, mode: Option) -> [u8; 16] { + self.helper.send(json!({ + "cmd": "call", + "id": "call", + "target_destination_hash": hex::encode(self.rust_destination), + "mode": mode, + })); + self.helper + .wait_event("CALL_REQUESTED", Duration::from_secs(20)); + let python_identity = self.python_identity; + let incoming = self + .wait_event("incoming call", Duration::from_secs(15), |event| { + matches!(event, TelephonyServiceEvent::IncomingCall { remote_identity, .. } + if *remote_identity == python_identity) + }) + .await; + let TelephonyServiceEvent::IncomingCall { link_id, .. } = incoming else { + unreachable!() + }; + tokio::time::sleep(Duration::from_millis(300)).await; + let answered = lxst_telephony::request_answer(&self.control_tx, link_id) + .await + .expect("Rust answer"); + assert_eq!(answered.status, SignallingStatus::Established); + link_id + } + + async fn rust_calls_python_and_python_answers(&mut self, mode: Option) { + self.control_tx + .send(TelephonyControl::Call { + remote_identity: self.python_identity, + profile: None, + mode, + discovery_timeout: Duration::from_secs(15), + }) + .await + .unwrap(); + self.helper.wait_event("RINGING", Duration::from_secs(20)); + // Answer only after the caller's profile and mode packet has reached Python. + let mode_signal = 0xF0 + u64::from(mode.unwrap_or(CallMode::DEFAULT).wire_value()); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let signals = self.helper.wait_event("SIGNALS", Duration::from_secs(10)); + if signals["signals"] + .as_array() + .is_some_and(|all| all.iter().any(|v| v.as_u64() == Some(mode_signal))) + { + break; + } + assert!(Instant::now() < deadline, "no mode signal reached Python"); + } + self.helper.send(json!({"cmd": "answer", "id": "answer"})); + let answered = self.helper.wait_event("ANSWERED", Duration::from_secs(5)); + assert_eq!(answered["accepted"], true); + self.wait_snapshot("Rust caller established", |call| { + call.status == SignallingStatus::Established + }) + .await; + } + + fn python_snapshot(&mut self) -> Value { + self.helper.send(json!({"cmd": "snapshot", "id": "snap"})); + self.helper.wait_event("SNAPSHOT", Duration::from_secs(5)) + } + + async fn shutdown(self) { + let _ = self.control_tx.send(TelephonyControl::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(2), self.service_task).await; + drop(self.actor_tx); + for task in self.tasks { + task.abort(); + } + drop(self.helper); + } +} + +impl PythonTelephoneHost { + fn send_announce(&self) { + let mut stdin = &self.stdin; + writeln!(stdin, "{}", json!({"cmd": "announce", "id": "announce"})).unwrap(); + stdin.flush().unwrap(); + } + + fn count_stashed(&self, name: &str, within: Duration) -> usize { + let _ = self.try_wait_event("__none__", within); + self.stashed_events + .lock() + .expect("event stash") + .iter() + .filter(|event| event["event"] == name) + .count() + } +} + +#[serial_test::serial(python_lxst_live)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires opt-in live Python LXST/Reticulum TCP interop"] +async fn python_caller_with_slow_pipelines_is_answered_once_by_rust_service() { + let mut pair = ServiceCallPair::connect(&[("LXST_HELPER_OPEN_DELAY", "6.0")]).await; + pair.python_calls_rust_and_rust_answers(None).await; + // Python establishes once and the Rust callee does not give up while the caller is slow. + let established = pair + .helper + .count_stashed("ESTABLISHED", Duration::from_secs(9)); + let opened = pair.helper.count_stashed("OPEN_PIPELINES", Duration::ZERO); + let ended = pair.helper.count_stashed("ENDED", Duration::ZERO); + let terminated = pair + .drain() + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })); + assert_eq!((established, opened, ended, terminated), (1, 1, 0, false)); + pair.shutdown().await; +} + +#[serial_test::serial(python_lxst_live)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires opt-in live Python LXST/Reticulum TCP interop"] +async fn rust_caller_is_answered_once_by_python_callee() { + let mut pair = ServiceCallPair::connect(&[]).await; + pair.rust_calls_python_and_python_answers(None).await; + tokio::time::sleep(Duration::from_secs(6)).await; + let terminated = pair + .drain() + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })); + assert!(!terminated); + assert_eq!(pair.helper.count_stashed("ENDED", Duration::ZERO), 0); + pair.shutdown().await; +} + +#[serial_test::serial(python_lxst_live)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires opt-in live Python LXST/Reticulum TCP interop"] +async fn python_half_duplex_caller_sets_rust_callee_mode_and_squelch() { + let mut pair = ServiceCallPair::connect(&[]).await; + pair.python_calls_rust_and_rust_answers(Some(2)).await; + let call = pair + .wait_snapshot("Rust callee half duplex", |call| { + call.status == SignallingStatus::Established + }) + .await; + assert_eq!(call.mode, Some(CallMode::HalfDuplex)); + assert!(call.transmit_squelched); + pair.helper + .wait_event("ESTABLISHED", Duration::from_secs(5)); + let python = pair.python_snapshot(); + assert_eq!(python["active_call"]["call_mode"], 2); + assert_eq!(python["active_call"]["squelched"], true); + + // Mid-call switch from Python reaches Rust. + pair.helper + .send(json!({"cmd": "switch_mode", "id": "fdx", "mode": 1})); + pair.helper + .wait_event("MODE_SWITCHED", Duration::from_secs(5)); + let call = pair + .wait_snapshot("Rust follows Python full duplex", |call| { + call.mode == Some(CallMode::FullDuplex) + }) + .await; + assert!(!call.transmit_squelched); + pair.shutdown().await; +} + +#[serial_test::serial(python_lxst_live)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires opt-in live Python LXST/Reticulum TCP interop"] +async fn rust_half_duplex_caller_sets_python_callee_mode_and_switch_reaches_python() { + let mut pair = ServiceCallPair::connect(&[]).await; + pair.rust_calls_python_and_python_answers(Some(CallMode::HalfDuplex)) + .await; + let python = pair.python_snapshot(); + assert_eq!(python["active_call"]["call_mode"], 2, "{python}"); + assert_eq!(python["active_call"]["squelched"], true); + + pair.control_tx + .send(TelephonyControl::SwitchMode { + mode: CallMode::FullDuplex, + }) + .await + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let python = pair.python_snapshot(); + if python["active_call"]["call_mode"] == 1 { + assert_eq!(python["active_call"]["squelched"], false); + break; + } + assert!(Instant::now() < deadline, "Python did not follow: {python}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + pair.shutdown().await; +} + +#[serial_test::serial(python_lxst_live)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires opt-in live Python LXST/Reticulum TCP interop"] +async fn python_caller_gets_busy_while_rust_service_discovers_a_path() { + let mut pair = ServiceCallPair::connect(&[]).await; + pair.control_tx + .send(TelephonyControl::Call { + remote_identity: Identity::new().hash, + profile: None, + mode: None, + discovery_timeout: Duration::from_secs(30), + }) + .await + .unwrap(); + pair.wait_event("pending", Duration::from_secs(5), |event| { + matches!(event, TelephonyServiceEvent::OutgoingCallPending { .. }) + }) + .await; + pair.helper.send(json!({ + "cmd": "call", + "id": "call", + "target_destination_hash": hex::encode(pair.rust_destination), + })); + // Python may report BUSY or, if the link close wins the race, ENDED. + let deadline = Instant::now() + Duration::from_secs(15); + let mut signals = Vec::new(); + loop { + if let Some(event) = pair + .helper + .try_wait_event("SIGNALS", Duration::from_millis(200)) + { + signals.push(event["signals"].clone()); + } + let ended = pair + .helper + .stashed_events + .lock() + .unwrap() + .iter() + .any(|event| event["event"] == "BUSY" || event["event"] == "ENDED"); + if ended { + break; + } + assert!( + Instant::now() < deadline, + "Python call did not end: {signals:?}" + ); + } + while let Some(event) = pair.helper.try_wait_event("SIGNALS", Duration::ZERO) { + signals.push(event["signals"].clone()); + } + let flat = signals + .iter() + .flat_map(|list| list.as_array().cloned().unwrap_or_default()) + .filter_map(|value| value.as_u64()) + .collect::>(); + assert!(flat.contains(&0), "Python never received BUSY: {flat:?}"); + assert!(!flat.contains(&4), "Python received RINGING: {flat:?}"); + let rang = pair + .drain() + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::IncomingCall { .. })); + assert!(!rang); + pair.shutdown().await; +} diff --git a/tools/common/lxst_reference.py b/tools/common/lxst_reference.py index 3513f41..5217f5a 100644 --- a/tools/common/lxst_reference.py +++ b/tools/common/lxst_reference.py @@ -23,8 +23,14 @@ def main_root() -> Path: return repo_root().parent +def _upstream_checkout(name: str) -> Path: + # A candidate worktree holds the next reference release until the pins move. + candidate = main_root() / "upstream" / "candidate" / name + return candidate if candidate.exists() else main_root() / "upstream" / name + + def upstream_lxst_root() -> Path: - return Path(os.environ.get("LXST_UPSTREAM_DIR", main_root() / "upstream" / "LXST")).resolve() + return Path(os.environ.get("LXST_UPSTREAM_DIR", _upstream_checkout("LXST"))).resolve() def upstream_reticulum_root() -> Path: @@ -32,7 +38,7 @@ def upstream_reticulum_root() -> Path: if configured: return Path(configured).resolve() - upstream = main_root() / "upstream" / "Reticulum" + upstream = _upstream_checkout("Reticulum") if upstream.exists(): return upstream.resolve() diff --git a/tools/interop/lxst_telephone_helper.py b/tools/interop/lxst_telephone_helper.py index c3963db..311b2d5 100644 --- a/tools/interop/lxst_telephone_helper.py +++ b/tools/interop/lxst_telephone_helper.py @@ -86,6 +86,12 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None: self.should_run = False self.samplerate = 48000 self.channels = 1 + self.buffer_max_height = 3 + self.autostart_min = 1 + self.streaming = False + + def wait_for_frames(self): + return None def start(self): self.should_run = True @@ -249,6 +255,8 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None: Telephony.Pipeline = HeadlessPipeline Telephony.BandPass = NoopFilter Telephony.AGC = NoopFilter + if hasattr(Telephony, "EchoSuppressor"): + Telephony.EchoSuppressor = NoopFilter if not opus_available: original_get_codec = Telephony.Profiles.get_codec @@ -277,6 +285,20 @@ def patch_signalling_events(Telephony) -> None: Telephony.Telephone.signalling_received = signalling_received +def patch_open_pipelines_observer(Telephony) -> None: + # LXST_HELPER_OPEN_DELAY delays the caller's pipeline setup to model a slow or distant phone. + delay = float(os.environ.get("LXST_HELPER_OPEN_DELAY", "0") or 0) + original = Telephony.Telephone._Telephone__open_pipelines + + def open_pipelines(self, identity): + emit({"event": "OPEN_PIPELINES"}) + if delay and self.active_call is not None and getattr(self.active_call, "is_outgoing", False): + time.sleep(delay) + return original(self, identity) + + Telephony.Telephone._Telephone__open_pipelines = open_pipelines + + def setup_python_stack(): global _RNS, _LXST, _Telephony, _np, _opus_available _RNS, _LXST, codec2_stubbed = import_rns_lxst() @@ -286,6 +308,7 @@ def setup_python_stack(): _opus_available = python_opus_available(Telephony) patch_headless_audio(Telephony, _LXST, np, _opus_available) patch_signalling_events(Telephony) + patch_open_pipelines_observer(Telephony) _Telephony = Telephony _np = np return codec2_stubbed @@ -299,6 +322,8 @@ def snapshot_event(): active = { "identity_hash": bytes(remote.hash).hex() if remote else None, "profile": getattr(telephone.active_call, "profile", None), + "call_mode": getattr(telephone.active_call, "call_mode", None), + "squelched": bool(getattr(getattr(telephone.active_call, "packetizer", None), "squelched", False)), "status": telephone.call_status, "answered": bool(getattr(telephone.active_call, "answered", False)), } @@ -322,6 +347,7 @@ def emit_ready(identity, telephone, codec2_stubbed): "app_name": "lxst", "primitive_name": "telephony", "lxst_version": lxst_version, + "rns_version": _RNS.__version__, "lxst_root": str(upstream_lxst_root()), "codec2_stubbed": bool(codec2_stubbed), "headless_audio": True, @@ -491,7 +517,7 @@ def handle_command(command: dict, args) -> bool: } ) return True - _telephone.call(identity, profile=command.get("profile")) + _telephone.call(identity, profile=command.get("profile"), mode=command.get("mode")) emit( { "event": "CALL_REQUESTED", @@ -547,6 +573,16 @@ def handle_command(command: dict, args) -> bool: emit({"event": "OPUS_FRAME_SENT", "id": command.get("id"), "sent": sent}) return True + if cmd == "switch_mode": + _telephone.switch_mode(int(command["mode"])) + emit({"event": "MODE_SWITCHED", "id": command.get("id"), "mode": _telephone.active_mode}) + return True + + if cmd == "unsquelch": + _telephone.unsquelch_transmit() + emit({"event": "UNSQUELCHED", "id": command.get("id")}) + return True + if cmd == "switch_profile": profile = int(command["profile"]) _telephone.switch_profile(profile) diff --git a/tools/reference/lxst_reference_lock.json b/tools/reference/lxst_reference_lock.json index 2f94b49..273df6c 100644 --- a/tools/reference/lxst_reference_lock.json +++ b/tools/reference/lxst_reference_lock.json @@ -1,38 +1,38 @@ { - "commit": "1194c9011fe6402edc7aebe7ffe9650ea3b1afee", + "commit": "6a329bf6d956ca8b15077d4c470afe4cb7c669cc", "dirty": false, "files": { "LXST/Codecs/Codec2.py": { - "bytes": 4107, - "sha256": "e43a0be0b3b5b66665c47f468e8b102040632652a88e73598fc8cdbad8d4819a" + "bytes": 4221, + "sha256": "bb5727a4da4083ceddc0f692a12cf4aa17c8ad48c4394bcc71a61d4bdf5d572c" }, "LXST/Codecs/Opus.py": { - "bytes": 7806, - "sha256": "0f0e6f9ffa48e899a80220b33485226fc411d70cd07dce3ff0b7582a208deb03" + "bytes": 8688, + "sha256": "bd3c7b0d777bddfbfc80acd51765b3d9bf623ba02bc0f1d1a6e128a2ab5bdd48" }, "LXST/Codecs/Raw.py": { - "bytes": 2316, - "sha256": "8bda42cb8602797e7ef62dd71bac074d2ec547278ec2b0bc5bf8bcb7c100a026" + "bytes": 2451, + "sha256": "bce228630cf26a0c3a72b8d068eef3f9bbd099f077184b4ebf467259a42dbb0f" }, "LXST/Codecs/__init__.py": { - "bytes": 704, - "sha256": "48c3f7adaf9c89326a81abf29f394f9857b11ea17315b3790214eaf7d45c03de" + "bytes": 739, + "sha256": "7977e713a3b8fa2167762db122024d1dcad8d09a1e8d98d25099271b22abfe1b" }, "LXST/Network.py": { - "bytes": 6172, - "sha256": "3da8422a5c2c73f6e9c7d8e784b1e9cb307d079ebb5bf99183fc5daadfbd9701" + "bytes": 6458, + "sha256": "1f58806a43b2eadac536e1062857493fede551688ef92414b427aaffd6492923" }, "LXST/Primitives/Telephony.py": { - "bytes": 37026, - "sha256": "35b2a4093368223145a548ac671504b43a4dcdac62368db754b082fe40138825" + "bytes": 46484, + "sha256": "da13879d66d2f4f83ea3b39c141a6566f29fc0ef7c96636a4c0b5dd619c0ab1c" }, "LXST/_version.py": { "bytes": 22, - "sha256": "12b90b908d930c15f5388aa2d8619adb408f7aee1972e9448be5df7d16cb53a3" + "sha256": "7080f58cb9c2fef8f8f0680c37a61bd4503726c43de73366087991604f131616" } }, "missing_files": [], - "package_version": "0.4.5", + "package_version": "0.6.0", "remote": "https://github.com/markqvist/LXST.git", "upstream": "../upstream/LXST" }