telephony: match LXST 0.6.0 signalling, profiles, and call modes

This commit is contained in:
DeFiDude committed 2026-11-10 01:51:43 -07:00
1 parent cb857c69d0
commit 1c037655b2
30 files changed
+2398 -593

No files matched your search

+22
View File
@@ -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
+1
View File
@@ -219,6 +219,7 @@ control_tx
.send(TelephonyControl::Call {
remote_identity,
profile: Some(Profile::QualityMedium),
mode: None,
discovery_timeout: Duration::from_secs(8),
})
.await?;
+33 -1
View File
@@ -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<Self>
pub const fn lxst_core::CallMode::name(self) -> &'static str
pub const fn lxst_core::CallMode::wire_value(self) -> u8
impl core::convert::From<lxst_core::CallMode> 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<Self>
@@ -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<Self, lxst_core::Error>
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<lxst_core::CallMode> for lxst_core::Signal
pub fn lxst_core::Signal::from(lxst_core::CallMode) -> Self
impl core::convert::From<lxst_core::Profile> for lxst_core::Signal
pub fn lxst_core::Signal::from(lxst_core::Profile) -> Self
impl core::convert::From<lxst_core::SignallingStatus> 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<lxst_core::SignallingStatus>)
@@ -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<lxst_core::RawAudioFrame, lxst_core::OpusCodecError>
pub fn lxst_core::OpusMonoDecoder::new() -> core::result::Result<Self, lxst_core::OpusCodecError>
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<lxst_core::RawAudioFrame, lxst_core::OpusCodecError>
pub fn lxst_core::OpusPacketDecoder::new(u32, u8) -> core::result::Result<Self, lxst_core::OpusCodecError>
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<f32>
@@ -308,9 +333,11 @@ impl lxst_core::RawAudioFrame
pub fn lxst_core::RawAudioFrame::from_frame(&lxst_core::Frame) -> core::result::Result<Self, lxst_core::Error>
pub fn lxst_core::RawAudioFrame::from_payload(&[u8]) -> core::result::Result<Self, lxst_core::Error>
pub fn lxst_core::RawAudioFrame::new(u8, impl core::convert::Into<alloc::vec::Vec<f32>>) -> core::result::Result<Self, lxst_core::Error>
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<lxst_core::Frame, lxst_core::Error>
pub fn lxst_core::RawAudioFrame::to_payload(&self, lxst_core::RawBitDepth) -> core::result::Result<alloc::vec::Vec<u8>, lxst_core::Error>
pub fn lxst_core::RawAudioFrame::with_channels(self, u8) -> core::result::Result<Self, lxst_core::Error>
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<lxst_core::TelephonyAction>
pub const fn lxst_core::TelephonyCall::answered(&self) -> bool
pub fn lxst_core::TelephonyCall::caller_identified(&mut self, bool, bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
pub fn lxst_core::TelephonyCall::disable_remote_mode_follow(&mut self)
pub fn lxst_core::TelephonyCall::hangup(&mut self, bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
pub fn lxst_core::TelephonyCall::incoming() -> Self
pub fn lxst_core::TelephonyCall::incoming_link_established(bool) -> alloc::vec::Vec<lxst_core::TelephonyAction>
pub const fn lxst_core::TelephonyCall::mode(&self) -> core::option::Option<lxst_core::CallMode>
pub fn lxst_core::TelephonyCall::outgoing(core::option::Option<lxst_core::Profile>) -> Self
pub fn lxst_core::TelephonyCall::outgoing_with_mode(core::option::Option<lxst_core::Profile>, core::option::Option<lxst_core::CallMode>) -> Self
pub const fn lxst_core::TelephonyCall::profile(&self) -> core::option::Option<lxst_core::Profile>
pub fn lxst_core::TelephonyCall::receive_signal(&mut self, lxst_core::Signal) -> alloc::vec::Vec<lxst_core::TelephonyAction>
pub fn lxst_core::TelephonyCall::retry_answer(&self) -> alloc::vec::Vec<lxst_core::TelephonyAction>
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<lxst_core::TelephonyAction>
pub fn lxst_core::TelephonyCall::switch_profile(&mut self, lxst_core::Profile) -> alloc::vec::Vec<lxst_core::TelephonyAction>
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
+29 -1
View File
@@ -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<lxst_embedded::CallMode> for lxst_embedded::wire::Signal
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self
impl core::convert::From<lxst_embedded::Profile> for lxst_embedded::wire::Signal
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self
impl core::convert::From<lxst_embedded::SignallingStatus> 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<Self>
pub const fn lxst_embedded::CallMode::name(self) -> &'static str
pub const fn lxst_embedded::CallMode::wire_value(self) -> u8
impl core::convert::From<lxst_embedded::CallMode> 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<Self>
@@ -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<lxst_embedded::CallMode> for lxst_embedded::wire::Signal
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::CallMode) -> Self
impl core::convert::From<lxst_embedded::Profile> for lxst_embedded::wire::Signal
pub fn lxst_embedded::wire::Signal::from(lxst_embedded::Profile) -> Self
impl core::convert::From<lxst_embedded::SignallingStatus> 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<lxst_embedded::SignallingStatus>)
@@ -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<lxst_embedded::CallMode>
pub fn lxst_embedded::CallState::outgoing(core::option::Option<lxst_embedded::Profile>) -> Self
pub fn lxst_embedded::CallState::outgoing_with_mode(core::option::Option<lxst_embedded::Profile>, core::option::Option<lxst_embedded::CallMode>) -> Self
pub const fn lxst_embedded::CallState::profile(&self) -> core::option::Option<lxst_embedded::Profile>
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<B>
impl<B: lxst_embedded::Codec2Backend> lxst_embedded::Codec2PacketCodec<B>
pub fn lxst_embedded::Codec2PacketCodec<B>::decode_into(&mut self, &[u8], &mut [i16]) -> core::result::Result<usize, lxst_embedded::Codec2PacketError<<B as lxst_embedded::Codec2Backend>::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<lxst_embedded::EndReason>
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<lxst_embedded::CallMode>
pub fn lxst_embedded::Session::new(lxst_embedded::CallRole, lxst_embedded::SessionConfig, u64) -> core::result::Result<Self, lxst_embedded::ConfigError>
pub fn lxst_embedded::Session::peer_verified(&mut self, u64) -> lxst_embedded::Events
pub fn lxst_embedded::Session::playback_allowed(&self) -> bool
+27 -2
View File
@@ -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<core::result::Result<lxst_telephony::ActiveCallSnapshot, lxst_telephony::Error>>
pub lxst_telephony::TelephonyControl::Call
pub lxst_telephony::TelephonyControl::Call::discovery_timeout: core::time::Duration
pub lxst_telephony::TelephonyControl::Call::mode: core::option::Option<lxst_core::profile::CallMode>
pub lxst_telephony::TelephonyControl::Call::profile: core::option::Option<lxst_core::profile::Profile>
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<lxs
pub lxst_telephony::TelephonyControl::SetAccessPolicy(lxst_telephony::CallerAccessPolicy)
pub lxst_telephony::TelephonyControl::SetExternalBusy(bool)
pub lxst_telephony::TelephonyControl::Shutdown
pub lxst_telephony::TelephonyControl::SquelchTransmit(bool)
pub lxst_telephony::TelephonyControl::StartAudioReceiveStream
pub lxst_telephony::TelephonyControl::StartAudioReceiveStream::frames: tokio::sync::mpsc::bounded::Sender<lxst_core::raw::RawAudioFrame>
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<lxst_core::profile::CallMode>
pub lxst_telephony::ActiveCallSnapshot::profile: core::option::Option<lxst_core::profile::Profile>
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<Output = core::result::Result<(), lxst_telephony::Error>> + 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<lxst_core::profile::Profile>, core::time::Duration) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
pub fn lxst_telephony::TelephonyRnsEndpoint::begin_outgoing_link_with_mode(&mut self, &mut lxst_telephony::TelephonyRuntimeCore, lxst_telephony::IdentityHash, [u8; 64], core::option::Option<lxst_core::profile::Profile>, core::option::Option<lxst_core::profile::CallMode>, u8) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
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<lxst_core::profile::Profile>, u8) -> core::result::Result<lxst_telephony::LinkId, lxst_telephony::Error>
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<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
pub fn lxst_telephony::TelephonyRuntimeCore::caller_identified(&mut self, lxst_telephony::LinkId, lxst_telephony::IdentityHash) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, 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<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
pub fn lxst_telephony::TelephonyRuntimeCore::incoming_link_established(&mut self, lxst_telephony::LinkId) -> alloc::vec::Vec<lxst_telephony::TelephonyCommand>
@@ -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<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, 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<lxst_telephony::TelephonyCommand>
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<lxst_core::profile::Profile>) -> 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<lxst_core::profile::Profile>, core::option::Option<lxst_core::profile::CallMode>) -> core::result::Result<(), lxst_telephony::Error>
pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_mode(&mut self, lxst_core::profile::CallMode) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, lxst_telephony::Error>
pub fn lxst_telephony::TelephonyRuntimeCore::switch_active_profile(&mut self, lxst_core::profile::Profile) -> core::result::Result<alloc::vec::Vec<lxst_telephony::TelephonyCommand>, 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<core::time::Duration>
pub lxst_telephony::TelephonyServiceConfig::announce_on_start: bool
pub lxst_telephony::TelephonyServiceConfig::answer_retry_interval: core::option::Option<core::time::Duration>
pub lxst_telephony::TelephonyServiceConfig::answer_timeout: core::option::Option<core::time::Duration>
pub lxst_telephony::TelephonyServiceConfig::connect_timeout: core::option::Option<core::time::Duration>
pub lxst_telephony::TelephonyServiceConfig::incoming_ring_timeout: core::option::Option<core::time::Duration>
pub lxst_telephony::TelephonyServiceConfig::media_frames_per_tick: usize
pub lxst_telephony::TelephonyServiceConfig::outgoing_call_timeout: core::option::Option<core::time::Duration>
@@ -348,8 +369,12 @@ pub lxst_telephony::TelephonyStep::inbound: core::option::Option<lxst_rns::Inbou
impl lxst_telephony::TelephonyStep
pub fn lxst_telephony::TelephonyStep::commands(alloc::vec::Vec<lxst_telephony::TelephonyCommand>) -> 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<rns_transport::messages::TransportMessage>, &[u8; 64], &rns_identity::identity::Identity, &mut rns_link::link::Link, &lxst_telephony::TelephonyCommand) -> core::result::Result<lxst_telephony::TelephonyCommandEffect, lxst_telephony::Error>
pub async fn lxst_telephony::request_answer(&tokio::sync::mpsc::bounded::Sender<lxst_telephony::TelephonyControl>, lxst_telephony::LinkId) -> core::result::Result<lxst_telephony::ActiveCallSnapshot, lxst_telephony::Error>
pub fn lxst_telephony::signalling_packet(lxst_core::wire::Signal) -> lxst_core::wire::LxstPacket
+6 -6
View File
@@ -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": [
+2 -2
View File
@@ -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,
+82 -1
View File
@@ -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<OpusDecoder>; 2],
}
impl OpusPacketDecoder {
pub fn new(sample_rate_hz: u32, channels: u8) -> Result<Self, OpusCodecError> {
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<RawAudioFrame, OpusCodecError> {
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,
+80 -14
View File
@@ -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<Self, Error> {
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::<f32>() / 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<Vec<u8>, 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<Vec<f32>, 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<u8>) {
}
}
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<u8>) {
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)]
+3 -3
View File
@@ -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,
}
}
+5 -1
View File
@@ -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),
}
+53
View File
@@ -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<Self> {
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),
+108 -34
View File
@@ -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<Profile>,
/// Raw mode value; Python stores unknown modes without acting on them.
mode: Option<u8>,
answered: bool,
transmit_squelched: bool,
remote_mode_follow_disabled: bool,
}
impl CallState {
pub fn outgoing(profile: Option<Profile>) -> Self {
Self::outgoing_with_mode(profile, None)
}
pub fn outgoing_with_mode(profile: Option<Profile>, mode: Option<CallMode>) -> 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<CallMode> {
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) {
+13 -1
View File
@@ -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<SignallingStatus> for Signal {
}
}
impl From<CallMode> for Signal {
fn from(value: CallMode) -> Self {
Self::PreferredMode(value.wire_value())
}
}
impl From<Profile> for Signal {
fn from(value: Profile) -> Self {
Self::PreferredProfile(value)
+145 -20
View File
@@ -12,6 +12,11 @@ impl TelephonyCall {
state: CallState::outgoing(profile),
}
}
pub fn outgoing_with_mode(profile: Option<Profile>, mode: Option<CallMode>) -> 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<CallMode> {
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<TelephonyAction> {
self.state.switch_mode(mode).as_slice().to_vec()
}
pub fn incoming_link_established(line_busy: bool) -> Vec<TelephonyAction> {
CallState::incoming_link_established(line_busy)
.as_slice()
@@ -43,9 +63,6 @@ impl TelephonyCall {
pub fn answer(&mut self) -> Vec<TelephonyAction> {
self.state.answer().as_slice().to_vec()
}
pub fn retry_answer(&self) -> Vec<TelephonyAction> {
self.state.retry_answer().as_slice().to_vec()
}
pub fn receive_signal(&mut self, signal: Signal) -> Vec<TelephonyAction> {
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);
+1 -1
View File
@@ -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"]
+32 -26
View File
@@ -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<EndReason>,
deadline: u64,
connect_deadline: Option<u64>,
talk_started: u64,
suggested: bool,
profile_deadline: Option<u64>,
answer_retry: u64,
retries: u8,
}
impl Session {
pub fn new(role: CallRole, config: SessionConfig, now_ms: u64) -> Result<Self, ConfigError> {
@@ -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<Profile> {
self.call.profile()
}
pub const fn mode(&self) -> Option<CallMode> {
self.call.mode()
}
pub const fn ended(&self) -> Option<EndReason> {
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 {
+81 -18
View File
@@ -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);
}
+17 -3
View File
@@ -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);
}
+1
View File
@@ -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
File diff suppressed because it is too large. Load diff
+77 -32
View File
@@ -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<Codec>);
@@ -74,33 +74,11 @@ impl Codec2Audio {
result?;
Ok(Frame::new(CodecKind::Codec2, payload))
}
fn decode(&mut self, frame: &Frame) -> Result<RawAudioFrame, Error> {
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::<Vec<_>>();
self.pcm.fill(0);
Ok(RawAudioFrame {
channels: 1,
samples,
})
}
}
pub(crate) enum AudioEncoder {
Opus(Box<OpusEncoderState>),
Codec2(Codec2Audio),
}
pub(crate) enum AudioDecoder {
Opus(Box<OpusDecoderState>),
Codec2(Codec2Audio),
}
impl AudioEncoder {
pub(crate) fn new(profile: Profile) -> Result<Self, Error> {
match profile.audio_codec() {
@@ -115,17 +93,84 @@ impl AudioEncoder {
}
}
}
impl AudioDecoder {
pub(crate) fn new(profile: Profile) -> Result<Self, Error> {
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<OpusPacketDecoder>,
codec2: Vec<(Codec2Mode, Box<Codec>)>,
}
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<RawAudioFrame, Error> {
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<RawAudioFrame, Error> {
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::<Codec>::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()))
}
}
File diff suppressed because it is too large. Load diff
@@ -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
}
]
}
@@ -0,0 +1,78 @@
"""LXST 0.6.0 media-path vectors, produced only by calling upstream code.
usage: PYTHONPATH=<RNS 1.6.0>:<LXST 0.6.0> python crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py <out.json>
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])
@@ -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);
@@ -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<TransportMessage>,
control_tx: mpsc::Sender<TelephonyControl>,
events: mpsc::Receiver<TelephonyServiceEvent>,
python_identity: [u8; 16],
rust_destination: [u8; 16],
service_task: tokio::task::JoinHandle<()>,
tasks: Vec<tokio::task::JoinHandle<()>>,
}
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<TelephonyServiceEvent> {
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>) -> [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<CallMode>) {
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::<Vec<_>>();
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;
}
+8 -2
View File
@@ -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()
+37 -1
View File
@@ -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)
+15 -15
View File
@@ -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"
}