From 54f87117303c2a256415d4b22fe85b4d563849cb Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:18:02 -0700 Subject: [PATCH] telephony: establish the caller sooner; embedded call times can be set --- CHANGELOG.md | 9 +- api/snapshots/lxst-core.txt | 1 + api/snapshots/lxst-embedded.txt | 10 ++ api/stability.json | 8 +- crates/lxst-core/src/shared/telephony.rs | 21 +++- crates/lxst-core/src/telephony.rs | 84 +++++++++++++ crates/lxst-embedded/src/lib.rs | 4 +- crates/lxst-embedded/src/session.rs | 37 ++++-- crates/lxst-embedded/tests/session.rs | 53 +++++++- crates/lxst-telephony/src/lib.rs | 10 +- crates/lxst-telephony/src/tests.rs | 2 +- .../tests/fixtures/lxst_060_media.json | 68 ---------- .../tests/fixtures/lxst_media_fixtures.py | 78 ------------ .../tests/fixtures/media_vectors.json | 15 +++ .../tests/python_telephone_live_interop.rs | 56 ++++++++- tools/fixtures/lxst_media_fixtures.py | 118 ++++++++++++++++++ tools/interop/lxst_telephone_helper.py | 25 +++- 17 files changed, 421 insertions(+), 178 deletions(-) delete mode 100644 crates/lxst-telephony/tests/fixtures/lxst_060_media.json delete mode 100644 crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py create mode 100644 crates/lxst-telephony/tests/fixtures/media_vectors.json create mode 100644 tools/fixtures/lxst_media_fixtures.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7823fcd..406d0ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,13 @@ Parity with Python LXST 0.6.0. Several experimental APIs change. 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. +- `lxst-embedded` sessions default to the 60, 70, and 5 second ring, wait, + and connect times; `SessionConfig::times` (`CallTimes`) changes them. +- A caller is established once it has handled CONNECTING, so a lost + ESTABLISHED no longer ends the call at the wait time. Its audio, and media + sent or received, still start only on the callee's ESTABLISHED + (`audio_started`). +- The media vector generator moved to `tools/fixtures/lxst_media_fixtures.py`. ## 0.3.1 - 2026-11-08 diff --git a/api/snapshots/lxst-core.txt b/api/snapshots/lxst-core.txt index 5e7e207..15f3c76 100644 --- a/api/snapshots/lxst-core.txt +++ b/api/snapshots/lxst-core.txt @@ -364,6 +364,7 @@ pub struct lxst_core::TelephonyCall impl lxst_core::TelephonyCall pub fn lxst_core::TelephonyCall::answer(&mut self) -> alloc::vec::Vec pub const fn lxst_core::TelephonyCall::answered(&self) -> bool +pub const fn lxst_core::TelephonyCall::audio_started(&self) -> bool pub fn lxst_core::TelephonyCall::caller_identified(&mut self, bool, bool) -> alloc::vec::Vec pub fn lxst_core::TelephonyCall::disable_remote_mode_follow(&mut self) pub fn lxst_core::TelephonyCall::hangup(&mut self, bool) -> alloc::vec::Vec diff --git a/api/snapshots/lxst-embedded.txt b/api/snapshots/lxst-embedded.txt index 38f8833..a9c83f9 100644 --- a/api/snapshots/lxst-embedded.txt +++ b/api/snapshots/lxst-embedded.txt @@ -244,6 +244,7 @@ pub struct lxst_embedded::CallState 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 const fn lxst_embedded::CallState::audio_started(&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 @@ -260,6 +261,14 @@ pub const fn lxst_embedded::CallState::status(&self) -> lxst_embedded::Signallin 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::CallTimes +pub lxst_embedded::CallTimes::connect_ms: u64 +pub lxst_embedded::CallTimes::ring_ms: u64 +pub lxst_embedded::CallTimes::wait_ms: u64 +impl lxst_embedded::CallTimes +pub const lxst_embedded::CallTimes::DEFAULT: Self +impl core::default::Default for lxst_embedded::CallTimes +pub fn lxst_embedded::CallTimes::default() -> Self pub struct lxst_embedded::Codec2PacketCodec impl lxst_embedded::Codec2PacketCodec pub fn lxst_embedded::Codec2PacketCodec::decode_into(&mut self, &[u8], &mut [i16]) -> core::result::Result::Error>> @@ -315,6 +324,7 @@ pub lxst_embedded::SessionConfig::allowed: lxst_embedded::ProfileSet pub lxst_embedded::SessionConfig::capture: bool pub lxst_embedded::SessionConfig::playback: bool pub lxst_embedded::SessionConfig::preferred: lxst_embedded::Profile +pub lxst_embedded::SessionConfig::times: lxst_embedded::CallTimes pub trait lxst_embedded::Codec2Backend pub type lxst_embedded::Codec2Backend::Error pub fn lxst_embedded::Codec2Backend::decode_native(&mut self, &[u8], &mut [i16]) -> core::result::Result<(), Self::Error> diff --git a/api/stability.json b/api/stability.json index 31da249..f096157 100644 --- a/api/stability.json +++ b/api/stability.json @@ -33,8 +33,8 @@ "tier": "experimental", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxst-embedded.txt", - "itemCount": 327, - "sha256": "072f231f31bce55c2aa0b5466988b3e62af42f66cc5e30b8f7c2572b1eef0d8d" + "itemCount": 337, + "sha256": "e4a86f580d90b6b5589fa0e91ac6d426b7df5d7f10e753683061d7184f64d425" }, { "name": "lxst-core", @@ -42,8 +42,8 @@ "tier": "experimental", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxst-core.txt", - "itemCount": 396, - "sha256": "a55ad460bfe1c4a2d689ed94dda09ff2625d9c3aee05285bf1cbd792f6d72f1e" + "itemCount": 397, + "sha256": "7edc5748c8b212d551756681cbc0815da6102accb5a59126b43d3b23233096cd" }, { "name": "lxst-rns", diff --git a/crates/lxst-core/src/shared/telephony.rs b/crates/lxst-core/src/shared/telephony.rs index 2a08739..39bffa1 100644 --- a/crates/lxst-core/src/shared/telephony.rs +++ b/crates/lxst-core/src/shared/telephony.rs @@ -13,6 +13,7 @@ pub struct CallState { /// Raw mode value; Python stores unknown modes without acting on them. mode: Option, answered: bool, + pipelines_started: bool, transmit_squelched: bool, remote_mode_follow_disabled: bool, } @@ -29,6 +30,7 @@ impl CallState { profile, mode: mode.map(|mode| mode.wire_value()), answered: false, + pipelines_started: false, transmit_squelched: false, remote_mode_follow_disabled: false, } @@ -41,6 +43,7 @@ impl CallState { profile: None, mode: None, answered: false, + pipelines_started: false, transmit_squelched: false, remote_mode_follow_disabled: false, } @@ -62,6 +65,11 @@ impl CallState { self.answered } + /// Whether audio pipelines were started; a caller only starts them on the callee's ESTABLISHED. + pub const fn audio_started(&self) -> bool { + self.pipelines_started + } + /// Selected call mode, or `None` before selection or for an unknown remote mode. pub const fn mode(&self) -> Option { match self.mode { @@ -127,6 +135,7 @@ impl CallState { actions.push(TelephonyAction::OpenAudioPipelines); self.push_status_signal(SignallingStatus::Established, &mut actions); actions.push(TelephonyAction::StartAudioPipelines); + self.pipelines_started = true; actions } @@ -189,19 +198,18 @@ impl CallState { TelephonyAction::OpenAudioPipelines, ]; if self.role == CallRole::Outgoing { - // This mirrors Python Telephone.__open_pipelines(): the - // caller echoes ESTABLISHED after observing CONNECTING. - actions.push(TelephonyAction::SendSignal(Signal::from( - SignallingStatus::Established, - ))); + // Python's caller signals ESTABLISHED once its pipelines are open, + // which makes its own call status ESTABLISHED. + self.push_status_signal(SignallingStatus::Established, &mut actions); } actions } Signal::Status(SignallingStatus::Established) => { - if self.status == SignallingStatus::Established { + if self.role != CallRole::Outgoing || self.pipelines_started { return actions![TelephonyAction::IgnoreSignal(signal)]; } self.status = SignallingStatus::Established; + self.pipelines_started = true; actions![TelephonyAction::StartAudioPipelines] } Signal::PreferredProfile(profile) => { @@ -286,6 +294,7 @@ impl CallState { actions.push(TelephonyAction::TeardownLink); self.status = SignallingStatus::Available; self.answered = false; + self.pipelines_started = false; actions } diff --git a/crates/lxst-core/src/telephony.rs b/crates/lxst-core/src/telephony.rs index e9d662d..824a43d 100644 --- a/crates/lxst-core/src/telephony.rs +++ b/crates/lxst-core/src/telephony.rs @@ -34,6 +34,9 @@ impl TelephonyCall { pub const fn answered(&self) -> bool { self.state.answered() } + pub const fn audio_started(&self) -> bool { + self.state.audio_started() + } pub const fn mode(&self) -> Option { self.state.mode() } @@ -203,6 +206,87 @@ mod tests { assert_eq!(outgoing.status(), SignallingStatus::Established); } + #[test] + fn caller_is_established_after_connecting_and_starts_audio_on_callee_established() { + let mut call = TelephonyCall::outgoing(None); + call.receive_signal(Signal::from(SignallingStatus::Available)); + call.receive_signal(Signal::from(SignallingStatus::Ringing)); + call.receive_signal(Signal::from(SignallingStatus::Connecting)); + assert_eq!(call.status(), SignallingStatus::Established); + assert_eq!( + call.receive_signal(Signal::from(SignallingStatus::Established)), + vec![TelephonyAction::StartAudioPipelines] + ); + assert_eq!( + call.receive_signal(Signal::from(SignallingStatus::Established)), + vec![TelephonyAction::IgnoreSignal(Signal::from( + SignallingStatus::Established + ))] + ); + } + + fn signals(packet: &str) -> Vec { + crate::LxstPacket::decode(&hex::decode(packet).unwrap()) + .unwrap() + .signals + } + + fn sent(actions: &[TelephonyAction]) -> Vec> { + actions + .iter() + .filter_map(|action| match action { + TelephonyAction::SendSignal(signal) => Some(vec![*signal]), + TelephonyAction::SendSignalPair(first, second) => Some(vec![*first, *second]), + _ => None, + }) + .map(|signals| crate::LxstPacket::signalling(signals).encode().unwrap()) + .collect() + } + + // Packets recorded from the rsLXST 0.3.1 call state machine; it decodes the mode + // byte of a profile-and-mode packet as an ignored raw signal. + #[test] + fn caller_completes_a_call_with_a_0_3_1_callee() { + let mut call = TelephonyCall::outgoing(None); + let mut out = Vec::new(); + for packet in ["81009103", "81009104", "81009105", "81009106", "81009105"] { + for signal in signals(packet) { + out.extend(sent(&call.receive_signal(signal))); + } + } + assert_eq!( + out.iter().map(hex::encode).collect::>(), + ["810092cd013fccf1", "81009106", "81009106"] + ); + assert_eq!(call.status(), SignallingStatus::Established); + assert!(call.audio_started()); + } + + #[test] + fn callee_completes_a_call_with_a_0_3_1_caller() { + let mut call = TelephonyCall::incoming(); + call.caller_identified(false, true); + for signal in signals("810091cd013f") { + call.receive_signal(signal); + } + assert_eq!( + sent(&call.answer()) + .iter() + .map(hex::encode) + .collect::>(), + ["81009105", "81009106"] + ); + for signal in signals("81009106") { + assert!(matches!( + call.receive_signal(signal).as_slice(), + [TelephonyAction::IgnoreSignal(_)] + )); + } + assert_eq!(call.status(), SignallingStatus::Established); + assert_eq!(call.profile(), Some(Profile::QualityMedium)); + assert_eq!(call.mode(), Some(CallMode::FullDuplex)); + } + #[test] fn ringing_sends_profile_and_requested_mode_in_one_packet() { let mut call = TelephonyCall::outgoing_with_mode( diff --git a/crates/lxst-embedded/src/lib.rs b/crates/lxst-embedded/src/lib.rs index 6a3e351..46f3819 100644 --- a/crates/lxst-embedded/src/lib.rs +++ b/crates/lxst-embedded/src/lib.rs @@ -24,7 +24,9 @@ pub use wire::{Codec2Mode, CodecKind, Signal}; mod codec2; pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError}; mod session; -pub use session::{ConfigError, EndReason, Event, Events, ProfileSet, Session, SessionConfig}; +pub use session::{ + CallTimes, ConfigError, EndReason, Event, Events, ProfileSet, Session, SessionConfig, +}; impl Codec2Backend for &mut lxst_codec2::Codec { type Error = lxst_codec2::Error; diff --git a/crates/lxst-embedded/src/session.rs b/crates/lxst-embedded/src/session.rs index a35fb5b..f6413a4 100644 --- a/crates/lxst-embedded/src/session.rs +++ b/crates/lxst-embedded/src/session.rs @@ -6,12 +6,6 @@ use crate::{ /// Local limit for an incoming link to identify its caller; Python has no counterpart. const SETUP_MS: u64 = 30_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; @@ -31,6 +25,29 @@ impl ProfileSet { } } +/// Call setup limits in milliseconds; the defaults are Python `Telephone`'s. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CallTimes { + /// Python `CONNECT_TIME` (`set_connect_timeout`): the callee must ring within this time of the call start. + pub connect_ms: u64, + /// Python `wait_time`, measured from the start of the outgoing call. + pub wait_ms: u64, + /// Python `ring_time`. + pub ring_ms: u64, +} +impl CallTimes { + pub const DEFAULT: Self = Self { + connect_ms: 5_000, + wait_ms: 70_000, + ring_ms: 60_000, + }; +} +impl Default for CallTimes { + fn default() -> Self { + Self::DEFAULT + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SessionConfig { /// The embedder must qualify each selected codec and route before admission. @@ -38,6 +55,7 @@ pub struct SessionConfig { pub preferred: Profile, pub capture: bool, pub playback: bool, + pub times: CallTimes, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ConfigError { @@ -131,11 +149,11 @@ impl Session { ended: None, deadline: now_ms.saturating_add(match role { CallRole::Incoming => SETUP_MS, - CallRole::Outgoing => WAIT_MS, + CallRole::Outgoing => config.times.wait_ms, }), connect_deadline: match role { CallRole::Incoming => None, - CallRole::Outgoing => Some(now_ms.saturating_add(CONNECT_MS)), + CallRole::Outgoing => Some(now_ms.saturating_add(config.times.connect_ms)), }, talk_started: 0, suggested: false, @@ -167,6 +185,7 @@ impl Session { && self.ready && self.profile_deadline.is_none() && self.call.status() == SignallingStatus::Established + && self.call.audio_started() } pub fn playback_allowed(&self) -> bool { self.media_ready() && self.config.playback && !self.transmitting @@ -192,7 +211,7 @@ impl Session { } self.verified = true; if self.call.role() == CallRole::Incoming { - self.deadline = now_ms.saturating_add(RING_MS); + self.deadline = now_ms.saturating_add(self.config.times.ring_ms); events.transitions(self.call.caller_identified(false, true)); events.push(Event::Transition(TelephonyAction::SendSignal( self.config.preferred.into(), diff --git a/crates/lxst-embedded/tests/session.rs b/crates/lxst-embedded/tests/session.rs index c8b54a6..7a53414 100644 --- a/crates/lxst-embedded/tests/session.rs +++ b/crates/lxst-embedded/tests/session.rs @@ -1,6 +1,6 @@ use lxst_embedded::{ - CallMode, CallRole, CallState, EndReason, Event, Profile, ProfileSet, Session, SessionConfig, - Signal, SignallingStatus as Status, TelephonyAction as Action, + CallMode, CallRole, CallState, CallTimes, EndReason, Event, Profile, ProfileSet, Session, + SessionConfig, Signal, SignallingStatus as Status, TelephonyAction as Action, }; #[test] @@ -80,6 +80,7 @@ fn config() -> SessionConfig { preferred: Profile::BandwidthVeryLow, capture: true, playback: true, + times: CallTimes::default(), } } fn connect(role: CallRole) -> Session { @@ -367,3 +368,51 @@ fn preferred_mode_signal_is_recorded_by_the_session() { assert_eq!(session.mode(), Some(CallMode::HalfDuplex)); assert_eq!(session.ended(), None); } + +#[test] +fn configured_call_times_replace_the_python_defaults() { + let slow = SessionConfig { + times: CallTimes { + connect_ms: 20_000, + wait_ms: 200_000, + ring_ms: 150_000, + }, + ..config() + }; + let mut outgoing = Session::new(CallRole::Outgoing, slow, 0).unwrap(); + outgoing.link_established(); + outgoing.peer_verified(1); + outgoing.tick(19_999); + assert_eq!(outgoing.ended(), None); + outgoing.receive_signal(Status::Available.into(), 19_999); + outgoing.receive_signal(Status::Ringing.into(), 19_999); + outgoing.tick(199_999); + assert_eq!(outgoing.ended(), None); + outgoing.tick(200_000); + assert_eq!(outgoing.ended(), Some(EndReason::Timeout)); + + let mut incoming = Session::new(CallRole::Incoming, slow, 0).unwrap(); + incoming.link_established(); + incoming.peer_verified(0); + incoming.tick(149_999); + assert_eq!(incoming.ended(), None); + incoming.tick(150_000); + assert_eq!(incoming.ended(), Some(EndReason::Timeout)); +} + +#[test] +fn caller_keeps_call_past_wait_time_when_callee_established_is_lost() { + let mut session = Session::new(CallRole::Outgoing, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(1); + for status in [Status::Available, Status::Ringing, Status::Connecting] { + session.receive_signal(status.into(), 100); + } + session.audio_ready(session.audio_generation(), true); + assert_eq!(session.status(), Status::Established); + assert!(!session.media_ready()); + session.tick(70_001); + assert_eq!(session.ended(), None); + session.receive_signal(Status::Established.into(), 70_002); + assert!(session.media_ready()); +} diff --git a/crates/lxst-telephony/src/lib.rs b/crates/lxst-telephony/src/lib.rs index ac18e7a..ed22058 100644 --- a/crates/lxst-telephony/src/lib.rs +++ b/crates/lxst-telephony/src/lib.rs @@ -1811,7 +1811,7 @@ impl TelephonyService { frames_tx: mpsc::Sender, ) -> Result<(), Error> { let active = self.core.active_call().ok_or(Error::NoActiveCall)?; - if active.call.status() != SignallingStatus::Established { + if active.call.status() != SignallingStatus::Established || !active.call.audio_started() { return Err(Error::CallNotEstablished); } @@ -1858,7 +1858,7 @@ impl TelephonyService { frames_rx: mpsc::Receiver, ) -> Result<(), Error> { let active = self.core.active_call().ok_or(Error::NoActiveCall)?; - if active.call.status() != SignallingStatus::Established { + if active.call.status() != SignallingStatus::Established || !active.call.audio_started() { return Err(Error::CallNotEstablished); } let active_profile = active.call.profile().unwrap_or(Profile::DEFAULT); @@ -2042,7 +2042,7 @@ impl TelephonyService { frames: Vec, ) -> Result<(), Error> { let active = self.core.active_call().ok_or(Error::NoActiveCall)?; - if active.call.status() != SignallingStatus::Established { + if active.call.status() != SignallingStatus::Established || !active.call.audio_started() { return Err(Error::CallNotEstablished); } // A squelched Python Packetizer drops frames silently. @@ -2075,7 +2075,7 @@ impl TelephonyService { frames: Vec, ) -> Result<(), Error> { let active = self.core.active_call().ok_or(Error::NoActiveCall)?; - if active.call.status() != SignallingStatus::Established { + if active.call.status() != SignallingStatus::Established || !active.call.audio_started() { return Err(Error::CallNotEstablished); } let active_profile = active.call.profile().unwrap_or(Profile::DEFAULT); @@ -2226,7 +2226,7 @@ impl TelephonyService { return Err(Error::WrongActiveLink); } let link_id = active.link_id; - if active.call.status() != SignallingStatus::Established { + if active.call.status() != SignallingStatus::Established || !active.call.audio_started() { return Ok((Vec::new(), Vec::new())); } let profile = active.call.profile().unwrap_or(Profile::DEFAULT); diff --git a/crates/lxst-telephony/src/tests.rs b/crates/lxst-telephony/src/tests.rs index b854c52..214c460 100644 --- a/crates/lxst-telephony/src/tests.rs +++ b/crates/lxst-telephony/src/tests.rs @@ -4219,7 +4219,7 @@ fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() { fn upstream_media_vectors() -> serde_json::Value { let vectors: serde_json::Value = - serde_json::from_str(include_str!("../tests/fixtures/lxst_060_media.json")).unwrap(); + serde_json::from_str(include_str!("../tests/fixtures/media_vectors.json")).unwrap(); assert_eq!(vectors["lxst_version"], "0.6.0"); assert_eq!(vectors["rns_version"], "1.6.0"); vectors diff --git a/crates/lxst-telephony/tests/fixtures/lxst_060_media.json b/crates/lxst-telephony/tests/fixtures/lxst_060_media.json deleted file mode 100644 index 3032b48..0000000 --- a/crates/lxst-telephony/tests/fixtures/lxst_060_media.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "lxst_version": "0.6.0", - "rns_version": "1.6.0", - "generator": "crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py", - "buffer_frames": { - "16": 2, - "32": 2, - "48": 2, - "64": 5, - "80": 5, - "96": 5, - "112": 2, - "128": 3 - }, - "frame_time_ms": { - "16": 400, - "32": 320, - "48": 200, - "64": 60, - "80": 60, - "96": 60, - "112": 10, - "128": 20 - }, - "telephone_timeouts": { - "RING_TIME": 60, - "WAIT_TIME": 70, - "CONNECT_TIME": 5 - }, - "raw128": { - "machine": "aarch64", - "longdouble_bits": 128, - "longdouble_nmant": 112, - "samples": [ - 0.0, - 0.5, - -0.25, - 1.0 - ], - "payload_hex": "c0000000000000000000000000000000000000000000000000000000000000fe3f0000000000000000000000000000fdbf0000000000000000000000000000ff3f", - "decoded": [ - 0.0, - 0.5, - -0.25, - 1.0 - ] - }, - "mixed_batch": [ - { - "name": "opus_60ms", - "codec": 1, - "wire_hex": "01db037b5af3c47e60df913de2a4bc5f21a2bd4eb9afea6c144d002a6a9a8c966f0ffd97d00daeb04dcf27e9a5f40332fd4ef0fcea52582fae", - "decoded_sample_frames": 2880 - }, - { - "name": "codec2_3200_200ms", - "codec": 2, - "wire_hex": "0206c07d231bd4ace738c0002900d6bdeb5ac681000019f81dd0c5b962029b86d5ffc5884a0094bd6b5ac591840194adebdac5802900d6bdeb5ac581000019f81dd0c5b962029b86d5ffc5884a0094bd6b5a", - "decoded_sample_frames": 9595 - }, - { - "name": "opus_20ms", - "codec": 1, - "wire_hex": "01d8b51a679c5c8787e2a9b61c6bc130233e9db6b2", - "decoded_sample_frames": 960 - } - ] -} \ No newline at end of file diff --git a/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py b/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py deleted file mode 100644 index 118957e..0000000 --- a/crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py +++ /dev/null @@ -1,78 +0,0 @@ -"""LXST 0.6.0 media-path vectors, produced only by calling upstream code. - -usage: PYTHONPATH=: python crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py - -Emits: - buffer_frames: Profiles.get_buffer_frames(p) for every profile constant. - telephone_timeouts: Telephone.RING_TIME / WAIT_TIME / CONNECT_TIME. - raw128: upstream Raw(bitdepth=128).encode of fixed samples (platform-specific; records - platform.machine() and numpy longdouble info) and Raw().decode of those bytes. - mixed_batch: wire frames (codec header byte + payload) produced by upstream encoders for - one LXST packet that switches codec mid-batch: Opus VOICE_MEDIUM 60 ms, Codec2 3200 - 200 ms, Opus VOICE_MEDIUM 20 ms; plus the per-frame sample counts upstream decodes - with LinkSource-style per-frame codec switching (Network.py:114-135). -""" -import json, platform, sys -import numpy as np -import RNS -import LXST -from LXST._version import __version__ as LXST_VERSION -from LXST.Codecs import Raw, Opus, Codec2, codec_header_byte, codec_type -from LXST.Primitives.Telephony import Profiles, Telephone - -assert LXST_VERSION == "0.6.0", LXST_VERSION -assert RNS.__version__ == "1.6.0", RNS.__version__ - - -class Src: # encoder "source" attribute: only samplerate is read - def __init__(self, rate): self.samplerate = rate - - -class Sink: # decoder "sink": samplerate/channels are read - def __init__(self, rate, ch): self.samplerate = rate; self.channels = ch - - -def tone(rate, ms): - n = int(rate * ms / 1000) - t = np.arange(n) / rate - return (0.3 * np.sin(2 * np.pi * 440 * t)).reshape(n, 1).astype("float32") - - -out = {"lxst_version": LXST_VERSION, "rns_version": RNS.__version__, - "generator": "crates/lxst-telephony/tests/fixtures/lxst_media_fixtures.py"} -profiles = {k: getattr(Profiles, k) for k in ["BANDWIDTH_ULTRA_LOW", "BANDWIDTH_VERY_LOW", "BANDWIDTH_LOW", - "QUALITY_MEDIUM", "QUALITY_HIGH", "QUALITY_MAX", "LATENCY_ULTRA_LOW", "LATENCY_LOW"]} -out["buffer_frames"] = {str(v): Profiles.get_buffer_frames(v) for v in profiles.values()} -out["frame_time_ms"] = {str(v): Profiles.get_frame_time(v) for v in profiles.values()} -out["telephone_timeouts"] = {"RING_TIME": Telephone.RING_TIME, "WAIT_TIME": Telephone.WAIT_TIME, - "CONNECT_TIME": Telephone.CONNECT_TIME} - -samples = np.array([[0.0], [0.5], [-0.25], [1.0]], dtype="float32") -raw = Raw(channels=1, bitdepth=128) -enc = raw.encode(samples) -dec = Raw().decode(enc) -out["raw128"] = {"machine": platform.machine(), "longdouble_bits": int(np.finfo(np.longdouble).bits), - "longdouble_nmant": int(np.finfo(np.longdouble).nmant), - "samples": samples[:, 0].tolist(), "payload_hex": enc.hex(), - "decoded": [float(x) for x in dec[:, 0]]} - -frames = [] -o = Opus(profile=Opus.PROFILE_VOICE_MEDIUM); o.source = Src(24000) -frames.append(("opus_60ms", codec_header_byte(Opus) + o.encode(tone(24000, 60)))) -c = Codec2(mode=Codec2.CODEC2_3200); c.source = Src(8000) -frames.append(("codec2_3200_200ms", codec_header_byte(Codec2) + c.encode(np.repeat(tone(8000, 200), 2, axis=1)))) -frames.append(("opus_20ms", codec_header_byte(Opus) + o.encode(tone(24000, 20)))) - -# Upstream receive-side per-frame codec switching, as in LinkSource._packet. -sink = Sink(48000, 1) -codec = Opus(); codec.sink = sink -decoded = [] -for name, fb in frames: - ft = codec_type(fb[0]) - if type(codec) != ft: - codec = ft(); codec.sink = sink - d = codec.decode(fb[1:]) - decoded.append({"name": name, "codec": int(fb[0]), "wire_hex": fb.hex(), "decoded_sample_frames": int(d.shape[0])}) -out["mixed_batch"] = decoded -open(sys.argv[1], "w").write(json.dumps(out, indent=1)) -print(json.dumps(out, indent=1)[:3000]) diff --git a/crates/lxst-telephony/tests/fixtures/media_vectors.json b/crates/lxst-telephony/tests/fixtures/media_vectors.json new file mode 100644 index 0000000..79c940b --- /dev/null +++ b/crates/lxst-telephony/tests/fixtures/media_vectors.json @@ -0,0 +1,15 @@ +{ + "generator": "tools/fixtures/lxst_media_fixtures.py", + "lxst_version": "0.6.0", + "lxst_commit": "6a329bf6d956ca8b15077d4c470afe4cb7c669cc", + "rns_version": "1.6.0", + "rns_commit": "cb1260891d1b6da8f6e9b21542c4f0cc0725cac4", + "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}, + "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} + ] +} diff --git a/crates/lxst-telephony/tests/python_telephone_live_interop.rs b/crates/lxst-telephony/tests/python_telephone_live_interop.rs index 752a4fa..8ae38a4 100644 --- a/crates/lxst-telephony/tests/python_telephone_live_interop.rs +++ b/crates/lxst-telephony/tests/python_telephone_live_interop.rs @@ -2961,6 +2961,10 @@ struct ServiceCallPair { impl ServiceCallPair { async fn connect(env: &[(&str, &str)]) -> Self { + Self::connect_with_config(env, TelephonyServiceConfig::default()).await + } + + async fn connect_with_config(env: &[(&str, &str)], config: TelephonyServiceConfig) -> 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; @@ -2993,7 +2997,7 @@ impl ServiceCallPair { poll_interval: Duration::from_millis(20), announce_on_start: false, announce_interval: None, - ..TelephonyServiceConfig::default() + ..config }, ); let service_task = tokio::spawn(service.run()); @@ -3183,6 +3187,56 @@ async fn rust_caller_is_answered_once_by_python_callee() { 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_keeps_call_when_python_callee_established_is_lost() { + let wait = Duration::from_secs(10); + let mut pair = ServiceCallPair::connect_with_config( + &[("LXST_HELPER_DROP_SENT", "6")], + TelephonyServiceConfig { + outgoing_call_timeout: Some(wait), + ..TelephonyServiceConfig::default() + }, + ) + .await; + pair.rust_calls_python_and_python_answers(None).await; + tokio::time::sleep(wait + Duration::from_secs(2)).await; + let terminated = pair + .drain() + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })); + assert!(!terminated, "Rust caller ended the call at its wait time"); + assert_eq!(pair.helper.count_stashed("ENDED", Duration::ZERO), 0); + let python = pair.python_snapshot(); + assert_eq!(python["active_call"]["status"], 6, "{python}"); + 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_keeps_call_when_rust_callee_established_is_lost() { + let wait = 8; + let mut pair = ServiceCallPair::connect(&[ + ("LXST_HELPER_DROP_RECEIVED", "6"), + ("LXST_HELPER_WAIT_TIME", "8"), + ]) + .await; + pair.python_calls_rust_and_rust_answers(None).await; + tokio::time::sleep(Duration::from_secs(wait + 2)).await; + assert_eq!(pair.helper.count_stashed("ENDED", Duration::ZERO), 0); + let python = pair.python_snapshot(); + assert_eq!(python["active_call"]["status"], 6, "{python}"); + assert_eq!(python["active_call"]["audio_started"], false, "{python}"); + let terminated = pair + .drain() + .iter() + .any(|event| matches!(event, TelephonyServiceEvent::CallTerminated { .. })); + assert!(!terminated); + 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"] diff --git a/tools/fixtures/lxst_media_fixtures.py b/tools/fixtures/lxst_media_fixtures.py new file mode 100644 index 0000000..cb64596 --- /dev/null +++ b/tools/fixtures/lxst_media_fixtures.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Generate LXST media-path vectors by calling upstream Python LXST. + +usage: python tools/fixtures/lxst_media_fixtures.py crates/lxst-telephony/tests/fixtures/media_vectors.json + +Upstream checkouts come from LXST_UPSTREAM_DIR / RETICULUM_UPSTREAM_DIR, or the +workspace upstream directory (see tools/common/lxst_reference.py). Real Opus and +Codec2 codecs are required: the generator refuses to run with the Codec2 stub. + +Emits buffer_frames and frame_time_ms per profile, raw128 (Raw(bitdepth=128) bytes, +platform-specific) and mixed_batch (one packet switching codec mid-batch, with the +sample counts upstream's per-frame codec switching decodes, Network.py LinkSource). +""" + +from __future__ import annotations + +import json +import platform +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "common")) +from lxst_reference import git_output, prepare_python_path, upstream_lxst_root, upstream_reticulum_root # noqa: E402 + +try: + import pycodec2 # noqa: F401 loaded first so the locator never installs its Codec2 stub +except ImportError: + raise SystemExit("pycodec2 is not installed; Codec2 vectors need the real codec") + +prepare_python_path() + +import numpy as np # noqa: E402 +import RNS # noqa: E402 +from LXST._version import __version__ as LXST_VERSION # noqa: E402 +from LXST.Codecs import Codec2, Opus, Raw, codec_header_byte, codec_type # noqa: E402 +from LXST.Primitives.Telephony import Profiles # noqa: E402 + +assert LXST_VERSION == "0.6.0", LXST_VERSION +assert RNS.__version__ == "1.6.0", RNS.__version__ + + +class Src: # encoders read only samplerate from their source + def __init__(self, rate): + self.samplerate = rate + + +class Sink: # decoders read samplerate and channels from their sink + def __init__(self, rate, channels): + self.samplerate = rate + self.channels = channels + + +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") + + +def main() -> None: + out_path = Path(sys.argv[1]) + lxst_root = upstream_lxst_root() + out = { + "generator": "tools/fixtures/lxst_media_fixtures.py", + "lxst_version": LXST_VERSION, + "lxst_commit": git_output(["rev-parse", "HEAD"], lxst_root), + "rns_version": RNS.__version__, + "rns_commit": git_output(["rev-parse", "HEAD"], upstream_reticulum_root()), + } + profiles = [Profiles.BANDWIDTH_ULTRA_LOW, Profiles.BANDWIDTH_VERY_LOW, Profiles.BANDWIDTH_LOW, + Profiles.QUALITY_MEDIUM, Profiles.QUALITY_HIGH, Profiles.QUALITY_MAX, + Profiles.LATENCY_ULTRA_LOW, Profiles.LATENCY_LOW] + out["buffer_frames"] = {str(p): Profiles.get_buffer_frames(p) for p in profiles} + out["frame_time_ms"] = {str(p): Profiles.get_frame_time(p) for p in profiles} + + samples = np.array([[0.0], [0.5], [-0.25], [1.0]], dtype="float32") + encoded = Raw(channels=1, bitdepth=128).encode(samples) + decoded = Raw().decode(encoded) + 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": encoded.hex(), + "decoded": [float(x) for x in decoded[:, 0]]} + + frames = [] + opus = Opus(profile=Opus.PROFILE_VOICE_MEDIUM) + opus.source = Src(24000) + frames.append(("opus_60ms", codec_header_byte(Opus) + opus.encode(tone(24000, 60)))) + codec2 = Codec2(mode=Codec2.CODEC2_3200) + codec2.source = Src(8000) + frames.append(("codec2_3200_200ms", codec_header_byte(Codec2) + codec2.encode(np.repeat(tone(8000, 200), 2, axis=1)))) + frames.append(("opus_20ms", codec_header_byte(Opus) + opus.encode(tone(24000, 20)))) + + sink = Sink(48000, 1) + codec = Opus() + codec.sink = sink + batch = [] + for name, wire in frames: + frame_codec = codec_type(wire[0]) + if type(codec) != frame_codec: + codec = frame_codec() + codec.sink = sink + samples_out = codec.decode(wire[1:]) + batch.append({"name": name, "codec": int(wire[0]), "wire_hex": wire.hex(), + "decoded_sample_frames": int(samples_out.shape[0])}) + out["mixed_batch"] = batch + + lines = [] + for key, value in out.items(): + if isinstance(value, list): + items = ",\n".join(" " + json.dumps(item) for item in value) + lines.append(f"{json.dumps(key)}: [\n{items}\n ]") + else: + lines.append(f"{json.dumps(key)}: {json.dumps(value)}") + out_path.write_text("{\n " + ",\n ".join(lines) + "\n}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/interop/lxst_telephone_helper.py b/tools/interop/lxst_telephone_helper.py index 311b2d5..e582827 100644 --- a/tools/interop/lxst_telephone_helper.py +++ b/tools/interop/lxst_telephone_helper.py @@ -277,14 +277,35 @@ def patch_headless_audio(Telephony, LXST, np, opus_available: bool) -> None: def patch_signalling_events(Telephony) -> None: original = Telephony.Telephone.signalling_received + # LXST_HELPER_DROP_RECEIVED lists signal values this phone never sees, to model loss. + dropped = {int(value) for value in os.environ.get("LXST_HELPER_DROP_RECEIVED", "").split(",") if value.strip()} def signalling_received(self, signals, source): emit({"event": "SIGNALS", "signals": [int(signal) for signal in signals]}) + signals = [signal for signal in signals if int(signal) not in dropped] return original(self, signals, source) Telephony.Telephone.signalling_received = signalling_received +def patch_dropped_signals() -> None: + # LXST_HELPER_DROP_SENT lists signal values this phone never puts on the wire, to model loss. + dropped = {int(value) for value in os.environ.get("LXST_HELPER_DROP_SENT", "").split(",") if value.strip()} + if not dropped: + return + import LXST.Network as Network + + original = Network.SignallingReceiver.signal + + def signal(self, signal, destination, immediate=True): + signals = signal if type(signal) == list else [signal] + kept = [value for value in signals if value not in dropped] + if kept: + return original(self, kept, destination, immediate) + + Network.SignallingReceiver.signal = signal + + 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) @@ -309,6 +330,7 @@ def setup_python_stack(): patch_headless_audio(Telephony, _LXST, np, _opus_available) patch_signalling_events(Telephony) patch_open_pipelines_observer(Telephony) + patch_dropped_signals() _Telephony = Telephony _np = np return codec2_stubbed @@ -326,6 +348,7 @@ def snapshot_event(): "squelched": bool(getattr(getattr(telephone.active_call, "packetizer", None), "squelched", False)), "status": telephone.call_status, "answered": bool(getattr(telephone.active_call, "answered", False)), + "audio_started": bool(telephone.audio_input is not None and telephone.audio_input.should_run), } return { @@ -417,7 +440,7 @@ def create_telephone(args): telephone = _Telephony.Telephone( identity, ring_time=args.ring_time, - wait_time=args.wait_time, + wait_time=float(os.environ.get("LXST_HELPER_WAIT_TIME", args.wait_time)), ) configure_callbacks(telephone) _telephone = telephone