diff --git a/CHANGELOG.md b/CHANGELOG.md index 81295ed..d7b7dd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +### Embedded sessions + +- Add a no_std LXST boundary with fixed parser/queue limits and authenticated, + accepted, audio-ready PTT gating. Share profile IDs, codec aggregation and + call transitions with the host API. Bound profile fallback and answer retries; + fence audio reconfiguration completions and require release after a Talk timeout. + ### Codec foundations - Add an opt-in, allocation-free `no_std` native Rust Codec2 crate for 1600/3200 diff --git a/Cargo.lock b/Cargo.lock index ab76b5f..12adc0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -573,6 +573,15 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "lxst-embedded" +version = "0.2.0" +dependencies = [ + "lxst-codec2", + "lxst-core", + "thiserror 2.0.18", +] + [[package]] name = "lxst-rns" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index 70d0794..816ac91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "2" members = [ "crates/lxst-core", "crates/lxst-codec2", + "crates/lxst-embedded", "crates/lxst-rns", "crates/lxst-telephony", ] diff --git a/README.md b/README.md index d10a060..b1cdabe 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Opus telephony release. processing over an application-supplied `Codec2Backend`. It uses caller-owned PCM16/output buffers, validates complete packets before calling the backend, and requires replacement after a backend error. This is a codec integration -boundary; a qualified Codec2 implementation and telephony stream integration +boundary; device qualification and telephony stream integration are still required. Its mode header belongs to LXST, not LXMF audio fields. ## Build It @@ -257,6 +257,14 @@ Applications still own platform integration: Ratspeak uses this boundary for its native voice-call feature. +## Embedded protocol boundary + +[`lxst-embedded`](crates/lxst-embedded/README.md) shares the trusted host profile +and transition sources, with bounded borrowed MessagePack parsing, fixed media +queues and explicit authenticated-session/PTT gates. It is a no_std embedding +boundary; board drivers, transport ownership and product integration remain +application responsibilities. + ## Embedded Codec2 backend [`lxst-codec2`](crates/lxst-codec2/README.md) supplies bounded native Rust diff --git a/THIRD_PARTY_LICENSES.json b/THIRD_PARTY_LICENSES.json index 3896f32..f382d3a 100644 --- a/THIRD_PARTY_LICENSES.json +++ b/THIRD_PARTY_LICENSES.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "scope": "Adapted Codec2 and all registry third-party normal/build dependencies reachable from rsLXST workspace members across declared targets; dev-only and first-party path packages are excluded.", - "cargoLockSha256": "ea2327255af9e42663e04f2a30e3aeca494b339c1ad118205f91636af776bbb5", + "cargoLockSha256": "d89f1983abe87e964464193fdda5503b4eade5283405291a958dec77559e66cb", "packages": [ { "name": "aes", diff --git a/api/README.md b/api/README.md index c5b0fac..af4e5f1 100644 --- a/api/README.md +++ b/api/README.md @@ -14,7 +14,7 @@ The compiled `lxst-telephony` `service` example exercises this path. ## Stability -All three packages are experimental: +All workspace packages are experimental: - `lxst-core` contains codec, profile, stream, signalling, and wire concepts; - `lxst-rns` binds media packets to Reticulum Links; and diff --git a/api/fixtures/Cargo.lock b/api/fixtures/Cargo.lock index b4c36e3..18ec06c 100644 --- a/api/fixtures/Cargo.lock +++ b/api/fixtures/Cargo.lock @@ -414,6 +414,14 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "lxst-embedded" +version = "0.2.0" +dependencies = [ + "lxst-codec2", + "thiserror 2.0.20", +] + [[package]] name = "lxst-rns" version = "0.2.0" @@ -450,6 +458,7 @@ version = "0.0.0" dependencies = [ "lxst-codec2", "lxst-core", + "lxst-embedded", "lxst-telephony", "rns-identity", "rns-transport", diff --git a/api/fixtures/Cargo.toml b/api/fixtures/Cargo.toml index 087c84f..13301b5 100644 --- a/api/fixtures/Cargo.toml +++ b/api/fixtures/Cargo.toml @@ -7,6 +7,7 @@ publish = false [workspace] [dependencies] +lxst-embedded = { path = "../../crates/lxst-embedded" } lxst-codec2 = { path = "../../crates/lxst-codec2" } lxst-core = { path = "../../crates/lxst-core" } lxst-telephony = { path = "../../crates/lxst-telephony" } diff --git a/api/fixtures/src/lib.rs b/api/fixtures/src/lib.rs index ebad8c2..acf815f 100644 --- a/api/fixtures/src/lib.rs +++ b/api/fixtures/src/lib.rs @@ -71,3 +71,15 @@ pub mod bounded_codec2 { codec.decode(packet, output) } } + +pub mod embedded { + use lxst_embedded::{CallRole, ConfigError, Session, SessionConfig}; + pub fn construct(role: CallRole, config: SessionConfig) -> Result { + Session::new(role, config, 0) + } + pub fn parse( + bytes: &[u8], + ) -> Result, lxst_embedded::wire::Error> { + lxst_embedded::wire::Packet::decode(bytes) + } +} diff --git a/api/snapshots/manifest-contract.json b/api/snapshots/manifest-contract.json index 2a3ffbf..b96c83a 100644 --- a/api/snapshots/manifest-contract.json +++ b/api/snapshots/manifest-contract.json @@ -101,6 +101,49 @@ } ] }, + { + "name": "lxst-embedded", + "version": "0.2.0", + "rustVersion": "1.87", + "edition": "2024", + "features": {}, + "targets": [ + { + "name": "lxst_embedded", + "kind": [ + "lib" + ], + "crateTypes": [ + "lib" + ], + "requiredFeatures": [] + } + ], + "dependencies": [ + { + "name": "lxst-codec2", + "rename": null, + "kind": null, + "target": null, + "requirement": "^0.2.0", + "optional": false, + "defaultFeatures": true, + "features": [], + "sourceKind": "path" + }, + { + "name": "thiserror", + "rename": null, + "kind": null, + "target": null, + "requirement": "^2", + "optional": false, + "defaultFeatures": false, + "features": [], + "sourceKind": "registry" + } + ] + }, { "name": "lxst-rns", "version": "0.2.0", diff --git a/api/stability.json b/api/stability.json index df929df..9277acc 100644 --- a/api/stability.json +++ b/api/stability.json @@ -23,6 +23,7 @@ "capturedOn": "2026-10-01", "review": { "areas": [ + "Shared host/embedded profiles and transitions, bounded wire/parser/session/media queue", "Allocation-free native 1600/3200 Codec2 state initialized in caller storage", "Bounded fixed-profile Codec2 packet processing and caller-owned PCM/output buffers", "Native Codec2 backend contract and failure-state ownership", @@ -40,14 +41,14 @@ "TelephonyService::new", "TelephonyService::with_config" ], - "classification": "additive experimental native Codec2 backend and packet boundary; no automatic telephony activation", + "classification": "additive experimental embedded boundary; existing host API retained", "publicApiDiff": { "added": 50, "removed": 0 }, "semver": "additive experimental API in the unreleased 0.2 line; no existing signatures removed or changed", "deprecations": "none", - "wirePersistenceRuntimeImpact": "Existing wire IDs, profiles, persistence and live streams unchanged. New opt-in packet adapter validates fixed-profile Codec2 payloads and latches backend failures.", + "wirePersistenceRuntimeImpact": "Wire IDs and packet forms unchanged. Existing host transitions now share an allocation-free core with a bounded embedded facade; the new session facade gates media on authenticated identity, acceptance, audio readiness and a fresh local PTT press. Firmware integration remains separate.", "platformEvidence": [ "68 lxst-core tests including existing Python wire/raw parity", "stable and Rust 1.87 strict Clippy", @@ -55,10 +56,13 @@ "24 actual Rust Codec2 packet-boundary cases against native frames and C reference data; codec quality and allocation qualification remain separate", "separate Rust candidate no_std compile on pinned ESP32-S3 toolchain; no on-device runtime claim", "Native zero-allocation contract, independent duplex histories and 20000 arbitrary decoder frames", - "12 bounded backend/C reference packet cases, exact locked ESP32-S3 compiler build and stable/MSRV strict Clippy" + "12 bounded backend/C reference packet cases, exact locked ESP32-S3 compiler build and stable/MSRV strict Clippy", + "Embedded/full Rust canonical packets and shared transition parity; bounded malformed/random input and PTT privacy/lifecycle tests", + "Standalone embedded boundary builds no_std with the selected ESP32-S3 compiler" ], "newPackages": [ - "lxst-codec2" + "lxst-codec2", + "lxst-embedded" ] } }, @@ -72,6 +76,15 @@ "itemCount": 17, "sha256": "2f44f014e8789d1a96abed0000abf6f31f43fef34f54fcf59f28aa6a0fc8e5d1" }, + { + "name": "lxst-embedded", + "manifestPath": "Cargo.toml", + "tier": "experimental", + "compatibility": "reviewed-snapshot", + "snapshot": "api/snapshots/lxst-embedded.txt", + "itemCount": 0, + "sha256": "0000000000000000000000000000000000000000000000000000000000000000" + }, { "name": "lxst-core", "manifestPath": "Cargo.toml", diff --git a/crates/lxst-core/src/codec2.rs b/crates/lxst-core/src/codec2.rs index 921059f..1a2fecd 100644 --- a/crates/lxst-core/src/codec2.rs +++ b/crates/lxst-core/src/codec2.rs @@ -1,204 +1,4 @@ -//! Bounded LXST Codec2 packet processing over caller-owned PCM and byte buffers. -//! -//! A backend processes native Codec2 frames. This module owns the LXST mode -//! header and profile aggregation; it does not own LXMF memo containers or their -//! different audio-mode identifiers. Backend memory, math, timing and supported -//! modes must be qualified separately before selecting one for a device. - -use crate::{AudioCodec, Codec2Mode, Profile}; -use thiserror::Error; - -/// A stateful native Codec2 implementation at one fixed mode, mono 8 kHz PCM16. -/// -/// Each operation receives exactly one native frame and an exactly sized output. -/// Implementations must not retain the borrowed buffers. A backend error may -/// advance its state: the caller must discard that packet and replace the codec -/// before continuing. Construction, scratch storage and reset belong to the -/// backend owner, allowing host and embedded implementations to differ. -pub trait Codec2Backend { - type Error; - - fn mode(&self) -> Codec2Mode; - fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error>; - fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error>; -} - -#[derive(Debug, Error, PartialEq, Eq)] -pub enum Codec2PacketError { - #[error("profile {0:?} does not use Codec2")] - NonCodec2Profile(Profile), - #[error("Codec2 backend mode {actual:?} does not match {expected:?}")] - BackendModeMismatch { - expected: Codec2Mode, - actual: Codec2Mode, - }, - #[error("Codec2 PCM sample count {actual} does not match {expected}")] - SampleCount { expected: usize, actual: usize }, - #[error("Codec2 output capacity {actual} is below {required}")] - OutputCapacity { required: usize, actual: usize }, - #[error("Codec2 payload length {actual} does not match {expected}")] - PayloadLength { expected: usize, actual: usize }, - #[error("Codec2 mode header {actual:#04x} does not match {expected:#04x}")] - ModeHeader { expected: u8, actual: u8 }, - #[error("Codec2 backend failed: {0}")] - Backend(E), - #[error("Codec2 must be replaced after a backend failure")] - Failed, -} - -/// One fixed-profile LXST Codec2 stream. Wrapper operations allocate no memory. -/// -/// The native backend may allocate; this type makes no claim about its footprint. -/// Use separate instances for independent streams. Mode/profile changes require -/// a new instance so predictor state cannot leak between differently framed media. -pub struct Codec2PacketCodec { - backend: B, - profile: Profile, - mode: Codec2Mode, - native_samples: usize, - native_bytes: usize, - failed: bool, -} - -impl Codec2PacketCodec { - pub fn new(profile: Profile, backend: B) -> Result> { - let AudioCodec::Codec2(mode) = profile.audio_codec() else { - return Err(Codec2PacketError::NonCodec2Profile(profile)); - }; - if backend.mode() != mode { - return Err(Codec2PacketError::BackendModeMismatch { - expected: mode, - actual: backend.mode(), - }); - } - // 700C carries 28 bits in FOUR bytes per native frame. Padding is per - // native frame, not once over the aggregated 400 ms packet. - let (native_samples, native_bytes) = match profile { - Profile::BandwidthUltraLow => (320, 4), - Profile::BandwidthVeryLow => (320, 8), - Profile::BandwidthLow => (160, 8), - _ => return Err(Codec2PacketError::NonCodec2Profile(profile)), - }; - Ok(Self { - backend, - profile, - mode, - native_samples, - native_bytes, - failed: false, - }) - } - - pub const fn profile(&self) -> Profile { - self.profile - } - - pub const fn mode(&self) -> Codec2Mode { - self.mode - } - - pub const fn sample_frames(&self) -> usize { - self.profile.sample_frames_per_packet() - } - - /// Payload bytes including the mode header, excluding the outer codec byte. - pub const fn payload_bytes(&self) -> usize { - 1 + self.sample_frames() / self.native_samples * self.native_bytes - } - - fn ready(&self) -> Result<(), Codec2PacketError> { - if self.failed { - return Err(Codec2PacketError::Failed); - } - let actual = self.backend.mode(); - if actual != self.mode { - return Err(Codec2PacketError::BackendModeMismatch { - expected: self.mode, - actual, - }); - } - Ok(()) - } - - /// Encode exactly one profile packet. PCM is mono 8 kHz, signed 16-bit. - /// - /// Capacity/shape errors leave backend and output unchanged. A backend error - /// invalidates this stream and the partially written output; replace it before - /// reuse. Bytes beyond the returned length remain untouched. - pub fn encode_into( - &mut self, - pcm: &[i16], - output: &mut [u8], - ) -> Result> { - self.ready()?; - if pcm.len() != self.sample_frames() { - return Err(Codec2PacketError::SampleCount { - expected: self.sample_frames(), - actual: pcm.len(), - }); - } - let required = self.payload_bytes(); - if output.len() < required { - return Err(Codec2PacketError::OutputCapacity { - required, - actual: output.len(), - }); - } - for (samples, bytes) in pcm - .chunks_exact(self.native_samples) - .zip(output[1..required].chunks_exact_mut(self.native_bytes)) - { - if let Err(error) = self.backend.encode_native(samples, bytes) { - self.failed = true; - return Err(Codec2PacketError::Backend(error)); - } - } - output[0] = self.mode.header(); - Ok(required) - } - - /// Decode exactly one negotiated-profile payload, including its mode header. - /// - /// A peer cannot trigger mode changes, unbounded frame counts or allocations - /// through this wrapper. The backend is never called on malformed payloads. - /// On backend failure discard the partial PCM and replace this stream. - pub fn decode_into( - &mut self, - payload: &[u8], - output: &mut [i16], - ) -> Result> { - self.ready()?; - if payload.len() != self.payload_bytes() { - return Err(Codec2PacketError::PayloadLength { - expected: self.payload_bytes(), - actual: payload.len(), - }); - } - if payload[0] != self.mode.header() { - return Err(Codec2PacketError::ModeHeader { - expected: self.mode.header(), - actual: payload[0], - }); - } - let required = self.sample_frames(); - if output.len() < required { - return Err(Codec2PacketError::OutputCapacity { - required, - actual: output.len(), - }); - } - for (bytes, samples) in payload[1..] - .chunks_exact(self.native_bytes) - .zip(output[..required].chunks_exact_mut(self.native_samples)) - { - if let Err(error) = self.backend.decode_native(bytes, samples) { - self.failed = true; - return Err(Codec2PacketError::Backend(error)); - } - } - Ok(required) - } -} +include!("shared/codec2.rs"); #[cfg(test)] mod tests; diff --git a/crates/lxst-core/src/lib.rs b/crates/lxst-core/src/lib.rs index 2c0b15a..7537427 100644 --- a/crates/lxst-core/src/lib.rs +++ b/crates/lxst-core/src/lib.rs @@ -4,14 +4,21 @@ //! avoids audio and Reticulum runtime dependencies so packet/profile parity can //! be tested in isolation. +#[path = "shared/actions.rs"] +mod actions; +#[path = "shared/telephony.rs"] +mod call_state; mod codec2; mod opus; +#[path = "shared/profile.rs"] mod profile; mod raw; mod stream; mod synthetic; mod telephony; mod wire; +#[path = "shared/wire_types.rs"] +mod wire_types; pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError}; pub use opus::{ diff --git a/crates/lxst-core/src/shared/actions.rs b/crates/lxst-core/src/shared/actions.rs new file mode 100644 index 0000000..11b2fd8 --- /dev/null +++ b/crates/lxst-core/src/shared/actions.rs @@ -0,0 +1,35 @@ +use crate::Signal; +use crate::call_state::TelephonyAction; + +/// Every current transition emits at most four ordered actions. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Actions { + items: [TelephonyAction; 4], + length: usize, +} +impl Actions { + pub(crate) fn new() -> Self { + Self { + items: [const { TelephonyAction::IgnoreSignal(Signal::Raw(0)) }; 4], + length: 0, + } + } + pub(crate) fn from_array(items: [TelephonyAction; N]) -> Self { + let mut actions = Self::new(); + for item in items { + actions.push(item); + } + actions + } + pub(crate) fn push(&mut self, action: TelephonyAction) { + assert!( + self.length < self.items.len(), + "transition action capacity exceeded" + ); + self.items[self.length] = action; + self.length += 1; + } + pub fn as_slice(&self) -> &[TelephonyAction] { + &self.items[..self.length] + } +} diff --git a/crates/lxst-core/src/shared/codec2.rs b/crates/lxst-core/src/shared/codec2.rs new file mode 100644 index 0000000..521cbdd --- /dev/null +++ b/crates/lxst-core/src/shared/codec2.rs @@ -0,0 +1,201 @@ +// Bounded LXST Codec2 packet processing over caller-owned PCM and byte buffers. +// +// A backend processes native Codec2 frames. This module owns the LXST mode +// header and profile aggregation; it does not own LXMF memo containers or their +// different audio-mode identifiers. Backend memory, math, timing and supported +// modes must be qualified separately before selecting one for a device. + +use crate::{AudioCodec, Codec2Mode, Profile}; +use thiserror::Error; + +/// A stateful native Codec2 implementation at one fixed mode, mono 8 kHz PCM16. +/// +/// Each operation receives exactly one native frame and an exactly sized output. +/// Implementations must not retain the borrowed buffers. A backend error may +/// advance its state: the caller must discard that packet and replace the codec +/// before continuing. Construction, scratch storage and reset belong to the +/// backend owner, allowing host and embedded implementations to differ. +pub trait Codec2Backend { + type Error; + + fn mode(&self) -> Codec2Mode; + fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error>; + fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error>; +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum Codec2PacketError { + #[error("profile {0:?} does not use Codec2")] + NonCodec2Profile(Profile), + #[error("Codec2 backend mode {actual:?} does not match {expected:?}")] + BackendModeMismatch { + expected: Codec2Mode, + actual: Codec2Mode, + }, + #[error("Codec2 PCM sample count {actual} does not match {expected}")] + SampleCount { expected: usize, actual: usize }, + #[error("Codec2 output capacity {actual} is below {required}")] + OutputCapacity { required: usize, actual: usize }, + #[error("Codec2 payload length {actual} does not match {expected}")] + PayloadLength { expected: usize, actual: usize }, + #[error("Codec2 mode header {actual:#04x} does not match {expected:#04x}")] + ModeHeader { expected: u8, actual: u8 }, + #[error("Codec2 backend failed: {0}")] + Backend(E), + #[error("Codec2 must be replaced after a backend failure")] + Failed, +} + +/// One fixed-profile LXST Codec2 stream. Wrapper operations allocate no memory. +/// +/// The native backend may allocate; this type makes no claim about its footprint. +/// Use separate instances for independent streams. Mode/profile changes require +/// a new instance so predictor state cannot leak between differently framed media. +pub struct Codec2PacketCodec { + backend: B, + profile: Profile, + mode: Codec2Mode, + native_samples: usize, + native_bytes: usize, + failed: bool, +} + +impl Codec2PacketCodec { + pub fn new(profile: Profile, backend: B) -> Result> { + let AudioCodec::Codec2(mode) = profile.audio_codec() else { + return Err(Codec2PacketError::NonCodec2Profile(profile)); + }; + if backend.mode() != mode { + return Err(Codec2PacketError::BackendModeMismatch { + expected: mode, + actual: backend.mode(), + }); + } + // 700C carries 28 bits in FOUR bytes per native frame. Padding is per + // native frame, not once over the aggregated 400 ms packet. + let (native_samples, native_bytes) = match profile { + Profile::BandwidthUltraLow => (320, 4), + Profile::BandwidthVeryLow => (320, 8), + Profile::BandwidthLow => (160, 8), + _ => return Err(Codec2PacketError::NonCodec2Profile(profile)), + }; + Ok(Self { + backend, + profile, + mode, + native_samples, + native_bytes, + failed: false, + }) + } + + pub const fn profile(&self) -> Profile { + self.profile + } + + pub const fn mode(&self) -> Codec2Mode { + self.mode + } + + pub const fn sample_frames(&self) -> usize { + self.profile.sample_frames_per_packet() + } + + /// Payload bytes including the mode header, excluding the outer codec byte. + pub const fn payload_bytes(&self) -> usize { + 1 + self.sample_frames() / self.native_samples * self.native_bytes + } + + fn ready(&self) -> Result<(), Codec2PacketError> { + if self.failed { + return Err(Codec2PacketError::Failed); + } + let actual = self.backend.mode(); + if actual != self.mode { + return Err(Codec2PacketError::BackendModeMismatch { + expected: self.mode, + actual, + }); + } + Ok(()) + } + + /// Encode exactly one profile packet. PCM is mono 8 kHz, signed 16-bit. + /// + /// Capacity/shape errors leave backend and output unchanged. A backend error + /// invalidates this stream and the partially written output; replace it before + /// reuse. Bytes beyond the returned length remain untouched. + pub fn encode_into( + &mut self, + pcm: &[i16], + output: &mut [u8], + ) -> Result> { + self.ready()?; + if pcm.len() != self.sample_frames() { + return Err(Codec2PacketError::SampleCount { + expected: self.sample_frames(), + actual: pcm.len(), + }); + } + let required = self.payload_bytes(); + if output.len() < required { + return Err(Codec2PacketError::OutputCapacity { + required, + actual: output.len(), + }); + } + for (samples, bytes) in pcm + .chunks_exact(self.native_samples) + .zip(output[1..required].chunks_exact_mut(self.native_bytes)) + { + if let Err(error) = self.backend.encode_native(samples, bytes) { + self.failed = true; + return Err(Codec2PacketError::Backend(error)); + } + } + output[0] = self.mode.header(); + Ok(required) + } + + /// Decode exactly one negotiated-profile payload, including its mode header. + /// + /// A peer cannot trigger mode changes, unbounded frame counts or allocations + /// through this wrapper. The backend is never called on malformed payloads. + /// On backend failure discard the partial PCM and replace this stream. + pub fn decode_into( + &mut self, + payload: &[u8], + output: &mut [i16], + ) -> Result> { + self.ready()?; + if payload.len() != self.payload_bytes() { + return Err(Codec2PacketError::PayloadLength { + expected: self.payload_bytes(), + actual: payload.len(), + }); + } + if payload[0] != self.mode.header() { + return Err(Codec2PacketError::ModeHeader { + expected: self.mode.header(), + actual: payload[0], + }); + } + let required = self.sample_frames(); + if output.len() < required { + return Err(Codec2PacketError::OutputCapacity { + required, + actual: output.len(), + }); + } + for (bytes, samples) in payload[1..] + .chunks_exact(self.native_bytes) + .zip(output[..required].chunks_exact_mut(self.native_samples)) + { + if let Err(error) = self.backend.decode_native(bytes, samples) { + self.failed = true; + return Err(Codec2PacketError::Backend(error)); + } + } + Ok(required) + } +} diff --git a/crates/lxst-core/src/profile.rs b/crates/lxst-core/src/shared/profile.rs similarity index 99% rename from crates/lxst-core/src/profile.rs rename to crates/lxst-core/src/shared/profile.rs index 2d48dde..72aaf1f 100644 --- a/crates/lxst-core/src/profile.rs +++ b/crates/lxst-core/src/shared/profile.rs @@ -1,4 +1,4 @@ -use crate::wire::{Codec2Mode, CodecKind}; +use crate::{Codec2Mode, CodecKind}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[repr(u32)] diff --git a/crates/lxst-core/src/shared/telephony.rs b/crates/lxst-core/src/shared/telephony.rs new file mode 100644 index 0000000..49fc3ef --- /dev/null +++ b/crates/lxst-core/src/shared/telephony.rs @@ -0,0 +1,274 @@ +use crate::actions::Actions; +use crate::{Profile, Signal, SignallingStatus}; + +macro_rules! actions { + ($($value:expr),* $(,)?) => { Actions::from_array([$($value),*]) }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum CallRole { + Incoming, + Outgoing, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TelephonyAction { + SendSignal(Signal), + IdentifyLocalIdentity, + SelectProfile(Profile), + PrepareDialingPipelines, + ResetDialingPipelines, + OpenAudioPipelines, + StartAudioPipelines, + StartDialTone, + Terminate(Option), + TeardownLink, + RingIncomingCall, + SwitchProfile(Profile), + IgnoreSignal(Signal), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CallState { + role: CallRole, + status: SignallingStatus, + profile: Option, + answered: bool, +} + +impl CallState { + pub fn outgoing(profile: Option) -> Self { + Self { + role: CallRole::Outgoing, + status: SignallingStatus::Calling, + profile, + answered: false, + } + } + + pub fn incoming() -> Self { + Self { + role: CallRole::Incoming, + status: SignallingStatus::Available, + profile: None, + answered: false, + } + } + + pub const fn role(&self) -> CallRole { + self.role + } + + pub const fn status(&self) -> SignallingStatus { + self.status + } + + pub const fn profile(&self) -> Option { + self.profile + } + + pub const fn answered(&self) -> bool { + self.answered + } + + pub fn incoming_link_established(line_busy: bool) -> Actions { + if line_busy { + actions![ + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)), + TelephonyAction::TeardownLink, + ] + } else { + actions![TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Available, + ))] + } + } + + pub fn caller_identified(&mut self, line_busy: bool, allowed: bool) -> Actions { + if line_busy || !allowed { + return actions![ + TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)), + TelephonyAction::TeardownLink, + ]; + } + + let mut actions = Actions::new(); + actions.push(TelephonyAction::ResetDialingPipelines); + self.push_status_signal(SignallingStatus::Ringing, &mut actions); + actions.push(TelephonyAction::RingIncomingCall); + actions + } + + pub fn answer(&mut self) -> Actions { + if self.role != CallRole::Incoming || self.status != SignallingStatus::Ringing { + return Actions::new(); + } + + let mut actions = Actions::new(); + self.answered = true; + self.ensure_profile(&mut actions); + 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, + ))); + actions + } + + /// Re-send the wire-compatible answer offer without reopening pipelines + /// or changing local state. The service bounds these retries and stops as + /// soon as the outgoing peer's ESTABLISHED echo is observed. + 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(_)) + { + return actions![TelephonyAction::IgnoreSignal(signal)]; + } + + match signal { + Signal::Status(SignallingStatus::Busy) => { + actions![TelephonyAction::Terminate(Some(SignallingStatus::Busy))] + } + Signal::Status(SignallingStatus::Rejected) => { + actions![TelephonyAction::Terminate(Some(SignallingStatus::Rejected))] + } + Signal::Status(SignallingStatus::Calling) => { + actions![TelephonyAction::IgnoreSignal(signal)] + } + Signal::Status(SignallingStatus::Available) => { + if self.status.wire_value() >= SignallingStatus::Available.wire_value() { + return actions![TelephonyAction::IgnoreSignal(signal)]; + } + self.status = SignallingStatus::Available; + actions![TelephonyAction::IdentifyLocalIdentity] + } + Signal::Status(SignallingStatus::Ringing) => { + if self.status.wire_value() >= SignallingStatus::Ringing.wire_value() { + return actions![TelephonyAction::IgnoreSignal(signal)]; + } + let mut actions = Actions::new(); + self.status = SignallingStatus::Ringing; + self.ensure_profile(&mut actions); + actions.push(TelephonyAction::PrepareDialingPipelines); + if let Some(profile) = self.profile { + actions.push(TelephonyAction::SendSignal(Signal::from(profile))); + } + actions.push(TelephonyAction::StartDialTone); + actions + } + Signal::Status(SignallingStatus::Connecting) => { + 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. + return actions![TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Established, + ))]; + } + if self.status.wire_value() >= SignallingStatus::Connecting.wire_value() { + return actions![TelephonyAction::IgnoreSignal(signal)]; + } + self.status = SignallingStatus::Connecting; + let mut actions = actions![ + TelephonyAction::ResetDialingPipelines, + 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, + ))); + } + actions + } + Signal::Status(SignallingStatus::Established) => { + if self.status == SignallingStatus::Established { + return actions![TelephonyAction::IgnoreSignal(signal)]; + } + self.status = SignallingStatus::Established; + actions![TelephonyAction::StartAudioPipelines] + } + Signal::PreferredProfile(profile) => { + if self.profile == Some(profile) { + return Actions::new(); + } + + self.profile = Some(profile); + if self.status == SignallingStatus::Established { + actions![TelephonyAction::SwitchProfile(profile)] + } else { + actions![TelephonyAction::SelectProfile(profile)] + } + } + Signal::Raw(_) => actions![TelephonyAction::IgnoreSignal(signal)], + } + } + + pub fn switch_profile(&mut self, profile: Profile) -> Actions { + if self.profile == Some(profile) { + return Actions::new(); + } + + self.profile = Some(profile); + if self.status == SignallingStatus::Established { + actions![ + TelephonyAction::SendSignal(Signal::from(profile)), + TelephonyAction::SwitchProfile(profile), + ] + } else { + actions![TelephonyAction::SelectProfile(profile)] + } + } + + pub fn hangup(&mut self, ring_timeout: bool) -> Actions { + let mut actions = Actions::new(); + + if self.role == CallRole::Incoming + && self.status == SignallingStatus::Ringing + && !ring_timeout + { + actions.push(TelephonyAction::SendSignal(Signal::from( + SignallingStatus::Rejected, + ))); + } + + actions.push(TelephonyAction::TeardownLink); + self.status = SignallingStatus::Available; + self.answered = false; + actions + } + + fn ensure_profile(&mut self, actions: &mut Actions) { + let profile = self.profile.unwrap_or(Profile::DEFAULT); + self.profile = Some(profile); + actions.push(TelephonyAction::SelectProfile(profile)); + } + + fn push_status_signal(&mut self, status: SignallingStatus, actions: &mut Actions) { + if status.is_auto_status() { + self.status = status; + } + actions.push(TelephonyAction::SendSignal(Signal::from(status))); + } +} diff --git a/crates/lxst-core/src/shared/wire_types.rs b/crates/lxst-core/src/shared/wire_types.rs new file mode 100644 index 0000000..0346dae --- /dev/null +++ b/crates/lxst-core/src/shared/wire_types.rs @@ -0,0 +1,121 @@ +// 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::wire::Error; +const PREFERRED_PROFILE_BASE: u32 = 0xFF; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum CodecKind { + Raw = 0x00, + Opus = 0x01, + Codec2 = 0x02, + Null = 0xFF, +} + +impl CodecKind { + pub const fn wire_id(self) -> u8 { + self as u8 + } + + pub const fn from_wire(id: u8) -> Result { + match id { + 0x00 => Ok(Self::Raw), + 0x01 => Ok(Self::Opus), + 0x02 => Ok(Self::Codec2), + 0xFF => Ok(Self::Null), + other => Err(Error::UnknownCodec(other)), + } + } + + pub const fn is_transmittable(self) -> bool { + !matches!(self, Self::Null) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Signal { + Status(SignallingStatus), + PreferredProfile(Profile), + Raw(u32), +} + +impl Signal { + pub const fn wire_value(self) -> u32 { + match self { + Self::Status(status) => status.wire_value(), + Self::PreferredProfile(profile) => PREFERRED_PROFILE_BASE + profile.wire_value(), + Self::Raw(value) => value, + } + } + + pub const fn from_wire(value: u32) -> Self { + if let Some(status) = SignallingStatus::from_wire(value) { + Self::Status(status) + } else if value >= PREFERRED_PROFILE_BASE { + let profile_value = value - PREFERRED_PROFILE_BASE; + if let Some(profile) = Profile::from_wire(profile_value) { + Self::PreferredProfile(profile) + } else { + Self::Raw(value) + } + } else { + Self::Raw(value) + } + } +} + +impl From for Signal { + fn from(value: SignallingStatus) -> Self { + Self::Status(value) + } +} + +impl From for Signal { + fn from(value: Profile) -> Self { + Self::PreferredProfile(value) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum Codec2Mode { + Mode700C = 0x00, + Mode1200 = 0x01, + Mode1300 = 0x02, + Mode1400 = 0x03, + Mode1600 = 0x04, + Mode2400 = 0x05, + Mode3200 = 0x06, +} + +impl Codec2Mode { + pub const fn from_header(byte: u8) -> Result { + match byte { + 0x00 => Ok(Self::Mode700C), + 0x01 => Ok(Self::Mode1200), + 0x02 => Ok(Self::Mode1300), + 0x03 => Ok(Self::Mode1400), + 0x04 => Ok(Self::Mode1600), + 0x05 => Ok(Self::Mode2400), + 0x06 => Ok(Self::Mode3200), + other => Err(Error::UnknownCodec2Mode(other)), + } + } + + pub const fn header(self) -> u8 { + self as u8 + } + + pub const fn bitrate(self) -> u16 { + match self { + Self::Mode700C => 700, + Self::Mode1200 => 1200, + Self::Mode1300 => 1300, + Self::Mode1400 => 1400, + Self::Mode1600 => 1600, + Self::Mode2400 => 2400, + Self::Mode3200 => 3200, + } + } +} diff --git a/crates/lxst-core/src/telephony.rs b/crates/lxst-core/src/telephony.rs index 5719a42..5b9cc5d 100644 --- a/crates/lxst-core/src/telephony.rs +++ b/crates/lxst-core/src/telephony.rs @@ -1,270 +1,60 @@ +use crate::call_state::CallState; +pub use crate::call_state::{CallRole, TelephonyAction}; use crate::{Profile, Signal, SignallingStatus}; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum CallRole { - Incoming, - Outgoing, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TelephonyAction { - SendSignal(Signal), - IdentifyLocalIdentity, - SelectProfile(Profile), - PrepareDialingPipelines, - ResetDialingPipelines, - OpenAudioPipelines, - StartAudioPipelines, - StartDialTone, - Terminate(Option), - TeardownLink, - RingIncomingCall, - SwitchProfile(Profile), - IgnoreSignal(Signal), -} - +/// Allocating host facade over the same bounded transition core used on MCUs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TelephonyCall { - role: CallRole, - status: SignallingStatus, - profile: Option, - answered: bool, + state: CallState, } - impl TelephonyCall { pub fn outgoing(profile: Option) -> Self { Self { - role: CallRole::Outgoing, - status: SignallingStatus::Calling, - profile, - answered: false, + state: CallState::outgoing(profile), } } - pub fn incoming() -> Self { Self { - role: CallRole::Incoming, - status: SignallingStatus::Available, - profile: None, - answered: false, + state: CallState::incoming(), } } - pub const fn role(&self) -> CallRole { - self.role + self.state.role() } - pub const fn status(&self) -> SignallingStatus { - self.status + self.state.status() } - pub const fn profile(&self) -> Option { - self.profile + self.state.profile() } - pub const fn answered(&self) -> bool { - self.answered + self.state.answered() } - pub fn incoming_link_established(line_busy: bool) -> Vec { - if line_busy { - vec![ - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)), - TelephonyAction::TeardownLink, - ] - } else { - vec![TelephonyAction::SendSignal(Signal::from( - SignallingStatus::Available, - ))] - } + CallState::incoming_link_established(line_busy) + .as_slice() + .to_vec() } - pub fn caller_identified(&mut self, line_busy: bool, allowed: bool) -> Vec { - if line_busy || !allowed { - return vec![ - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Busy)), - TelephonyAction::TeardownLink, - ]; - } - - let mut actions = Vec::new(); - actions.push(TelephonyAction::ResetDialingPipelines); - self.push_status_signal(SignallingStatus::Ringing, &mut actions); - actions.push(TelephonyAction::RingIncomingCall); - actions + self.state + .caller_identified(line_busy, allowed) + .as_slice() + .to_vec() } - pub fn answer(&mut self) -> Vec { - if self.role != CallRole::Incoming || self.status != SignallingStatus::Ringing { - return Vec::new(); - } - - let mut actions = Vec::new(); - self.answered = true; - self.ensure_profile(&mut actions); - 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, - ))); - actions + self.state.answer().as_slice().to_vec() } - - /// Re-send the wire-compatible answer offer without reopening pipelines - /// or changing local state. The service bounds these retries and stops as - /// soon as the outgoing peer's ESTABLISHED echo is observed. pub fn retry_answer(&self) -> Vec { - if self.role != CallRole::Incoming - || !self.answered - || self.status != SignallingStatus::Connecting - { - return Vec::new(); - } - - vec![ - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Connecting)), - TelephonyAction::SendSignal(Signal::from(SignallingStatus::Established)), - ] + self.state.retry_answer().as_slice().to_vec() } - pub fn receive_signal(&mut self, signal: Signal) -> Vec { - if self.role == CallRole::Incoming && !self.answered && matches!(signal, Signal::Status(_)) - { - return vec![TelephonyAction::IgnoreSignal(signal)]; - } - - match signal { - Signal::Status(SignallingStatus::Busy) => { - vec![TelephonyAction::Terminate(Some(SignallingStatus::Busy))] - } - Signal::Status(SignallingStatus::Rejected) => { - vec![TelephonyAction::Terminate(Some(SignallingStatus::Rejected))] - } - Signal::Status(SignallingStatus::Calling) => { - vec![TelephonyAction::IgnoreSignal(signal)] - } - Signal::Status(SignallingStatus::Available) => { - if self.status.wire_value() >= SignallingStatus::Available.wire_value() { - return vec![TelephonyAction::IgnoreSignal(signal)]; - } - self.status = SignallingStatus::Available; - vec![TelephonyAction::IdentifyLocalIdentity] - } - Signal::Status(SignallingStatus::Ringing) => { - if self.status.wire_value() >= SignallingStatus::Ringing.wire_value() { - return vec![TelephonyAction::IgnoreSignal(signal)]; - } - let mut actions = Vec::new(); - self.status = SignallingStatus::Ringing; - self.ensure_profile(&mut actions); - actions.push(TelephonyAction::PrepareDialingPipelines); - if let Some(profile) = self.profile { - actions.push(TelephonyAction::SendSignal(Signal::from(profile))); - } - actions.push(TelephonyAction::StartDialTone); - actions - } - Signal::Status(SignallingStatus::Connecting) => { - 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. - return vec![TelephonyAction::SendSignal(Signal::from( - SignallingStatus::Established, - ))]; - } - if self.status.wire_value() >= SignallingStatus::Connecting.wire_value() { - return vec![TelephonyAction::IgnoreSignal(signal)]; - } - self.status = SignallingStatus::Connecting; - let mut actions = vec![ - TelephonyAction::ResetDialingPipelines, - 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, - ))); - } - actions - } - Signal::Status(SignallingStatus::Established) => { - if self.status == SignallingStatus::Established { - return vec![TelephonyAction::IgnoreSignal(signal)]; - } - self.status = SignallingStatus::Established; - vec![TelephonyAction::StartAudioPipelines] - } - Signal::PreferredProfile(profile) => { - if self.profile == Some(profile) { - return Vec::new(); - } - - self.profile = Some(profile); - if self.status == SignallingStatus::Established { - vec![TelephonyAction::SwitchProfile(profile)] - } else { - vec![TelephonyAction::SelectProfile(profile)] - } - } - Signal::Raw(_) => vec![TelephonyAction::IgnoreSignal(signal)], - } + self.state.receive_signal(signal).as_slice().to_vec() } - pub fn switch_profile(&mut self, profile: Profile) -> Vec { - if self.profile == Some(profile) { - return Vec::new(); - } - - self.profile = Some(profile); - if self.status == SignallingStatus::Established { - vec![ - TelephonyAction::SendSignal(Signal::from(profile)), - TelephonyAction::SwitchProfile(profile), - ] - } else { - vec![TelephonyAction::SelectProfile(profile)] - } + self.state.switch_profile(profile).as_slice().to_vec() } - pub fn hangup(&mut self, ring_timeout: bool) -> Vec { - let mut actions = Vec::new(); - - if self.role == CallRole::Incoming - && self.status == SignallingStatus::Ringing - && !ring_timeout - { - actions.push(TelephonyAction::SendSignal(Signal::from( - SignallingStatus::Rejected, - ))); - } - - actions.push(TelephonyAction::TeardownLink); - self.status = SignallingStatus::Available; - self.answered = false; - actions - } - - fn ensure_profile(&mut self, actions: &mut Vec) { - let profile = self.profile.unwrap_or(Profile::DEFAULT); - self.profile = Some(profile); - actions.push(TelephonyAction::SelectProfile(profile)); - } - - fn push_status_signal(&mut self, status: SignallingStatus, actions: &mut Vec) { - if status.is_auto_status() { - self.status = status; - } - actions.push(TelephonyAction::SendSignal(Signal::from(status))); + self.state.hangup(ring_timeout).as_slice().to_vec() } } diff --git a/crates/lxst-core/src/wire.rs b/crates/lxst-core/src/wire.rs index a1e0b01..1dadded 100644 --- a/crates/lxst-core/src/wire.rs +++ b/crates/lxst-core/src/wire.rs @@ -3,13 +3,12 @@ use rmpv::decode::read_value; use rmpv::encode::write_value; use thiserror::Error; -use crate::profile::{Profile, SignallingStatus}; +#[cfg(test)] +use crate::profile::Profile; pub const FIELD_SIGNALLING: u8 = 0x00; pub const FIELD_FRAMES: u8 = 0x01; -const PREFERRED_PROFILE_BASE: u32 = 0xFF; - #[derive(Debug, Error, PartialEq, Eq)] pub enum Error { #[error("msgpack decode error: {0}")] @@ -46,78 +45,7 @@ pub enum Error { UnknownCodec2Mode(u8), } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum CodecKind { - Raw = 0x00, - Opus = 0x01, - Codec2 = 0x02, - Null = 0xFF, -} - -impl CodecKind { - pub const fn wire_id(self) -> u8 { - self as u8 - } - - pub const fn from_wire(id: u8) -> Result { - match id { - 0x00 => Ok(Self::Raw), - 0x01 => Ok(Self::Opus), - 0x02 => Ok(Self::Codec2), - 0xFF => Ok(Self::Null), - other => Err(Error::UnknownCodec(other)), - } - } - - pub const fn is_transmittable(self) -> bool { - !matches!(self, Self::Null) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum Signal { - Status(SignallingStatus), - PreferredProfile(Profile), - Raw(u32), -} - -impl Signal { - pub const fn wire_value(self) -> u32 { - match self { - Self::Status(status) => status.wire_value(), - Self::PreferredProfile(profile) => PREFERRED_PROFILE_BASE + profile.wire_value(), - Self::Raw(value) => value, - } - } - - pub const fn from_wire(value: u32) -> Self { - if let Some(status) = SignallingStatus::from_wire(value) { - Self::Status(status) - } else if value >= PREFERRED_PROFILE_BASE { - let profile_value = value - PREFERRED_PROFILE_BASE; - if let Some(profile) = Profile::from_wire(profile_value) { - Self::PreferredProfile(profile) - } else { - Self::Raw(value) - } - } else { - Self::Raw(value) - } - } -} - -impl From for Signal { - fn from(value: SignallingStatus) -> Self { - Self::Status(value) - } -} - -impl From for Signal { - fn from(value: Profile) -> Self { - Self::PreferredProfile(value) - } -} +pub use crate::wire_types::{Codec2Mode, CodecKind, Signal}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Frame { @@ -361,49 +289,6 @@ impl RawFrameHeader { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum Codec2Mode { - Mode700C = 0x00, - Mode1200 = 0x01, - Mode1300 = 0x02, - Mode1400 = 0x03, - Mode1600 = 0x04, - Mode2400 = 0x05, - Mode3200 = 0x06, -} - -impl Codec2Mode { - pub const fn from_header(byte: u8) -> Result { - match byte { - 0x00 => Ok(Self::Mode700C), - 0x01 => Ok(Self::Mode1200), - 0x02 => Ok(Self::Mode1300), - 0x03 => Ok(Self::Mode1400), - 0x04 => Ok(Self::Mode1600), - 0x05 => Ok(Self::Mode2400), - 0x06 => Ok(Self::Mode3200), - other => Err(Error::UnknownCodec2Mode(other)), - } - } - - pub const fn header(self) -> u8 { - self as u8 - } - - pub const fn bitrate(self) -> u16 { - match self { - Self::Mode700C => 700, - Self::Mode1200 => 1200, - Self::Mode1300 => 1300, - Self::Mode1400 => 1400, - Self::Mode1600 => 1600, - Self::Mode2400 => 2400, - Self::Mode3200 => 3200, - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/lxst-embedded/Cargo.toml b/crates/lxst-embedded/Cargo.toml new file mode 100644 index 0000000..f064629 --- /dev/null +++ b/crates/lxst-embedded/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "lxst-embedded" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish.workspace = true +description = "Bounded no_std LXST framing and authenticated PTT session policy" + +[dependencies] +thiserror = { version = "2", default-features = false } +lxst-codec2 = { path = "../lxst-codec2", version = "0.2.0" } + +[dev-dependencies] +lxst-core = { path = "../lxst-core", version = "0.2.0" } diff --git a/crates/lxst-embedded/README.md b/crates/lxst-embedded/README.md new file mode 100644 index 0000000..83a080c --- /dev/null +++ b/crates/lxst-embedded/README.md @@ -0,0 +1,39 @@ +# Embedded LXST boundary + +`no_std`, allocation-free MessagePack framing, call policy, native Codec2 packet +adaptation and a three-frame arrival-order queue. It supplies no threads, audio +drivers, identities, transport, storage or global state. + +Profile tables, wire identifiers, native packet aggregation and call transitions +are compiled directly from the shared sources in `lxst-core/src/shared`. The +host `TelephonyCall` API retains its allocating return values as a facade over +the same fixed action list. Preserve this shared source layout in source bundles; +these unpublished workspace crates are built from the complete repository. + +`wire::Packet` borrows validated input with fixed ceilings (512 packet bytes, +eight signals, four frames, 256 bytes per codec frame). It rejects duplicates, +trailing data, excessive nesting and oversized declared containers. Unknown +metadata is skipped within those limits. `wire::encode` matches the full Rust +encoder's canonical MessagePack forms and validates before writing output. +The negotiated Reticulum Link MDU can be smaller than the parser ceiling; the +embedding transport must enforce its exact current MDU before sending. + +`Session` wraps the shared transitions with verified-peer, local acceptance, +audio-readiness, profile and PTT gates. The embedding Link owner alone calls +`peer_verified`, after checking the exact identity and interface incarnation. +Opening or answering never starts capture. Only a fresh Talk press can start it; +release, timeout, reconfiguration and teardown stop it. Input edges and worker +completions must carry session/view generations; audio configuration completions +also carry `audio_generation`. Capability sets express previously qualified +local codec/route budgets, not peer capabilities or an extension to LXST. + +Unsupported preferences receive one supported suggestion with a deadline; +repeated unsupported preferences close the session. Local PTT does not grant a +remote floor: while capturing, conflicting receive audio is discarded. The +queue uses local expiry times; it cannot infer a sender timestamp, recover packet +order, claim delivery or route speech through LXMF propagation. + +The native `Codec2Backend` implementation borrows a codec initialized in final +storage. It never moves a large codec state onto the task stack. Only 1600/3200 +are implemented; profile metadata for 700C is not a 700C backend. Opus must be +separately qualified before including it in a device's admitted profile set. diff --git a/crates/lxst-embedded/src/lib.rs b/crates/lxst-embedded/src/lib.rs new file mode 100644 index 0000000..323bad9 --- /dev/null +++ b/crates/lxst-embedded/src/lib.rs @@ -0,0 +1,45 @@ +//! Allocation-free LXST wire/session boundary for constrained clients. +//! Shared profile, wire identifiers and telephony transitions come directly from +//! lxst-core. Authentication, permissions, audio devices and routing are owned by +//! the embedding runtime; parsing bytes never establishes a trusted identity. +#![no_std] + +#[path = "../../lxst-core/src/shared/actions.rs"] +mod actions; +#[path = "../../lxst-core/src/shared/telephony.rs"] +mod call_state; +#[path = "../../lxst-core/src/shared/profile.rs"] +mod profile; +pub mod wire; +#[path = "../../lxst-core/src/shared/wire_types.rs"] +mod wire_types; + +pub use actions::Actions; +pub use call_state::{CallRole, CallState, TelephonyAction}; +pub use profile::{AudioCodec, OpusApplication, OpusProfile, Profile, SignallingStatus}; +pub use wire_types::{Codec2Mode, CodecKind, Signal}; + +#[path = "../../lxst-core/src/shared/codec2.rs"] +mod codec2; +pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError}; +mod session; +pub use session::{ConfigError, EndReason, Event, Events, ProfileSet, Session, SessionConfig}; + +impl Codec2Backend for &mut lxst_codec2::Codec { + type Error = lxst_codec2::Error; + fn mode(&self) -> Codec2Mode { + match lxst_codec2::Codec::mode(self) { + lxst_codec2::Mode::Rate1600 => Codec2Mode::Mode1600, + lxst_codec2::Mode::Rate3200 => Codec2Mode::Mode3200, + } + } + fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error> { + self.encode(pcm, encoded) + } + fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> { + self.decode(encoded, pcm) + } +} + +mod queue; +pub use queue::{MediaQueue, QueueError}; diff --git a/crates/lxst-embedded/src/queue.rs b/crates/lxst-embedded/src/queue.rs new file mode 100644 index 0000000..8ee8455 --- /dev/null +++ b/crates/lxst-embedded/src/queue.rs @@ -0,0 +1,121 @@ +//! Local arrival/capture deadlines, not a claim about end-to-end packet age. +//! LXST has no sequence/timestamp in its baseline wire contract. +use crate::wire::MAX_FRAME_BYTES; +const CAPACITY: usize = 3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QueueError { + EmptyPayload, + PayloadTooLarge, + Expired, + OutputCapacity, +} +#[derive(Clone, Copy)] +struct Slot { + bytes: [u8; MAX_FRAME_BYTES], + length: usize, + expires: u64, + generation: u32, +} +impl Slot { + const EMPTY: Self = Self { + bytes: [0; MAX_FRAME_BYTES], + length: 0, + expires: 0, + generation: 0, + }; +} +/// Three arrival-ordered encoded frames. Pressure drops the oldest frame; +/// draining discards expired and stale-generation frames before returning data. +pub struct MediaQueue { + slots: [Slot; CAPACITY], + head: usize, + length: usize, + dropped: u64, +} +impl Default for MediaQueue { + fn default() -> Self { + Self::new() + } +} +impl MediaQueue { + pub const fn new() -> Self { + Self { + slots: [Slot::EMPTY; CAPACITY], + head: 0, + length: 0, + dropped: 0, + } + } + pub const fn len(&self) -> usize { + self.length + } + pub const fn is_empty(&self) -> bool { + self.length == 0 + } + pub const fn dropped(&self) -> u64 { + self.dropped + } + pub fn clear(&mut self) { + self.slots.fill(Slot::EMPTY); + self.head = 0; + self.length = 0; + } + fn retire(&mut self, dropped: bool) { + self.slots[self.head] = Slot::EMPTY; + self.head = (self.head + 1) % CAPACITY; + self.length -= 1; + if dropped { + self.dropped = self.dropped.saturating_add(1); + } + } + pub fn push( + &mut self, + bytes: &[u8], + generation: u32, + now_ms: u64, + expires_ms: u64, + ) -> Result<(), QueueError> { + if bytes.is_empty() { + return Err(QueueError::EmptyPayload); + } + if bytes.len() > MAX_FRAME_BYTES { + return Err(QueueError::PayloadTooLarge); + } + if expires_ms <= now_ms { + return Err(QueueError::Expired); + } + if self.length == CAPACITY { + self.retire(true); + } + let slot = &mut self.slots[(self.head + self.length) % CAPACITY]; + slot.bytes[..bytes.len()].copy_from_slice(bytes); + slot.length = bytes.len(); + slot.expires = expires_ms; + slot.generation = generation; + self.length += 1; + Ok(()) + } + pub fn pop( + &mut self, + now_ms: u64, + generation: u32, + output: &mut [u8], + ) -> Result, QueueError> { + while self.length != 0 { + let slot = &self.slots[self.head]; + if slot.expires <= now_ms || slot.generation != generation { + self.retire(true); + continue; + } + if output.len() < slot.length { + return Err(QueueError::OutputCapacity); + } + let length = slot.length; + output[..length].copy_from_slice(&slot.bytes[..length]); + self.retire(false); + return Ok(Some(length)); + } + Ok(None) + } +} diff --git a/crates/lxst-embedded/src/session.rs b/crates/lxst-embedded/src/session.rs new file mode 100644 index 0000000..449b609 --- /dev/null +++ b/crates/lxst-embedded/src/session.rs @@ -0,0 +1,356 @@ +//! 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}; + +const SETUP_MS: u64 = 30_000; +const RING_MS: u64 = 90_000; +const ANSWER_MS: u64 = 10_000; +const PROFILE_MS: u64 = 5_000; +pub const TALK_LIMIT_MS: u64 = 30_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProfileSet(u8); +impl ProfileSet { + pub const CODEC2: Self = Self(0b0000_0110); + pub const OPUS_MEDIUM: Self = Self(0b0000_1000); + pub const fn contains(self, profile: Profile) -> bool { + self.0 & (1 << (profile.wire_value() / 16 - 1)) != 0 + } + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } + pub const fn only(profile: Profile) -> Self { + Self(1 << (profile.wire_value() / 16 - 1)) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SessionConfig { + /// The embedder must qualify each selected codec and route before admission. + pub allowed: ProfileSet, + pub preferred: Profile, + pub capture: bool, + pub playback: bool, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ConfigError { + NoAudioDirection, + UnsupportedPreferredProfile, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EndReason { + Local, + Remote, + Rejected, + Busy, + Timeout, + ProfileUnsupported, + AudioUnavailable, + RouteLost, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Event { + Transition(TelephonyAction), + Capture(bool), + FlushMedia, + Ended(EndReason), +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Events { + items: [Event; 8], + length: usize, +} +impl Events { + fn new() -> Self { + Self { + items: [const { Event::FlushMedia }; 8], + length: 0, + } + } + fn push(&mut self, event: Event) { + assert!(self.length < self.items.len()); + self.items[self.length] = event; + self.length += 1; + } + fn transitions(&mut self, actions: Actions) { + for action in actions.as_slice() { + self.push(Event::Transition(action.clone())); + } + } + pub fn as_slice(&self) -> &[Event] { + &self.items[..self.length] + } +} + +#[derive(Debug)] +pub struct Session { + call: CallState, + config: SessionConfig, + verified: bool, + linked: bool, + ready: bool, + transmitting: bool, + input_down: bool, + audio_generation: u32, + ended: Option, + deadline: u64, + talk_started: u64, + suggested: bool, + profile_deadline: Option, + answer_retry: u64, + retries: u8, +} +impl Session { + pub fn new(role: CallRole, config: SessionConfig, now_ms: u64) -> Result { + if !config.capture && !config.playback { + return Err(ConfigError::NoAudioDirection); + } + if !config.allowed.contains(config.preferred) { + return Err(ConfigError::UnsupportedPreferredProfile); + } + let mut call = match role { + CallRole::Incoming => CallState::incoming(), + CallRole::Outgoing => CallState::outgoing(Some(config.preferred)), + }; + call.switch_profile(config.preferred); + Ok(Self { + call, + config, + verified: false, + linked: false, + ready: false, + transmitting: false, + input_down: false, + audio_generation: 1, + ended: None, + deadline: now_ms.saturating_add(SETUP_MS), + talk_started: 0, + suggested: false, + profile_deadline: None, + answer_retry: 0, + retries: 0, + }) + } + pub const fn status(&self) -> SignallingStatus { + self.call.status() + } + pub const fn profile(&self) -> Option { + self.call.profile() + } + pub const fn ended(&self) -> Option { + self.ended + } + pub const fn audio_generation(&self) -> u32 { + self.audio_generation + } + pub const fn transmitting(&self) -> bool { + self.transmitting + } + pub fn media_ready(&self) -> bool { + self.ended.is_none() + && self.linked + && self.verified + && self.ready + && self.profile_deadline.is_none() + && self.call.status() == SignallingStatus::Established + } + pub fn playback_allowed(&self) -> bool { + self.media_ready() && self.config.playback && !self.transmitting + } + + pub fn link_established(&mut self) -> Events { + let mut events = Events::new(); + if self.ended.is_some() || self.linked { + return events; + } + self.linked = true; + if self.call.role() == CallRole::Incoming { + events.transitions(CallState::incoming_link_established(false)); + } + events + } + /// Call only after the Link owner verified the exact peer identity for this + /// session and immutable route. Parsing a signal cannot invoke this authority. + pub fn peer_verified(&mut self, now_ms: u64) -> Events { + let mut events = Events::new(); + if self.ended.is_some() || !self.linked || self.verified { + return events; + } + self.verified = true; + if self.call.role() == CallRole::Incoming { + self.deadline = now_ms.saturating_add(RING_MS); + events.transitions(self.call.caller_identified(false, true)); + events.push(Event::Transition(TelephonyAction::SendSignal( + self.config.preferred.into(), + ))); + } + events + } + pub fn answer(&mut self, now_ms: u64) -> Events { + let mut events = Events::new(); + if self.ended.is_some() + || !self.verified + || self.call.role() != CallRole::Incoming + || self.call.status() != SignallingStatus::Ringing + { + return events; + } + self.deadline = now_ms.saturating_add(ANSWER_MS); + self.answer_retry = now_ms.saturating_add(1000); + events.transitions(self.call.answer()); + events + } + pub fn receive_signal(&mut self, signal: Signal, now_ms: u64) -> Events { + let mut events = Events::new(); + if self.ended.is_some() || !self.linked || !self.verified { + return events; + } + if let Signal::PreferredProfile(profile) = signal { + if !self.config.allowed.contains(profile) { + if self.suggested { + return self.end(EndReason::ProfileUnsupported); + } + self.suggested = true; + self.profile_deadline = Some(now_ms.saturating_add(PROFILE_MS)); + self.stop_capture(&mut events); + events.push(Event::FlushMedia); + events.push(Event::Transition(TelephonyAction::SendSignal( + self.call.profile().unwrap_or(self.config.preferred).into(), + ))); + return events; + } + self.profile_deadline = None; + if self.call.profile() != Some(profile) { + self.stop_capture(&mut events); + self.ready = false; + self.audio_generation = self.audio_generation.wrapping_add(1); + events.push(Event::FlushMedia); + } + } + if let Signal::Status(status) = signal { + match status { + SignallingStatus::Busy => return self.end(EndReason::Busy), + SignallingStatus::Rejected => return self.end(EndReason::Rejected), + SignallingStatus::Calling => return events, + _ => {} + } + let current = self.call.status(); + let allowed = match self.call.role() { + CallRole::Incoming => { + self.call.answered() && status == SignallingStatus::Established + } + CallRole::Outgoing => match status { + SignallingStatus::Available => matches!( + current, + SignallingStatus::Calling | SignallingStatus::Available + ), + SignallingStatus::Ringing => matches!( + current, + SignallingStatus::Available | SignallingStatus::Ringing + ), + SignallingStatus::Connecting => matches!( + current, + SignallingStatus::Ringing + | SignallingStatus::Connecting + | SignallingStatus::Established + ), + SignallingStatus::Established => matches!( + current, + SignallingStatus::Connecting | SignallingStatus::Established + ), + _ => false, + }, + }; + 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); + } + } + events.transitions(self.call.receive_signal(signal)); + events + } + /// A successfully configured device/codec is necessary but never starts capture. + pub fn audio_ready(&mut self, generation: u32, success: bool) -> Events { + if self.ended.is_some() || generation != self.audio_generation { + return Events::new(); + } + if !success { + return self.end(EndReason::AudioUnavailable); + } + self.ready = true; + Events::new() + } + /// The embedder must fence input edges by session and view generation. + pub fn set_transmitting(&mut self, pressed: bool, now_ms: u64) -> Events { + let mut events = Events::new(); + if !pressed { + self.input_down = false; + self.stop_capture(&mut events); + events.push(Event::FlushMedia); + } else if !self.input_down { + self.input_down = true; + if !self.media_ready() || !self.config.capture { + return events; + } + self.transmitting = true; + self.talk_started = now_ms; + events.push(Event::FlushMedia); + events.push(Event::Capture(true)); + } + events + } + fn stop_capture(&mut self, events: &mut Events) { + if self.transmitting { + self.transmitting = false; + events.push(Event::Capture(false)); + } + } + pub fn tick(&mut self, now_ms: u64) -> Events { + let mut events = Events::new(); + if self.ended.is_some() { + return events; + } + if self + .profile_deadline + .is_some_and(|deadline| now_ms >= deadline) + { + return self.end(EndReason::ProfileUnsupported); + } + if self.status() != SignallingStatus::Established && now_ms >= self.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 { + let mut events = Events::new(); + if self.ended.is_some() { + return events; + } + self.stop_capture(&mut events); + events.push(Event::FlushMedia); + self.ready = false; + self.ended = Some(reason); + events.transitions(self.call.hangup(reason == EndReason::Timeout)); + events.push(Event::Ended(reason)); + events + } +} diff --git a/crates/lxst-embedded/src/wire.rs b/crates/lxst-embedded/src/wire.rs new file mode 100644 index 0000000..a3955e6 --- /dev/null +++ b/crates/lxst-embedded/src/wire.rs @@ -0,0 +1,342 @@ +//! Borrowed, bounded MessagePack adaptation of lxst-core::wire. +use crate::{CodecKind, Signal}; + +pub const MAX_PACKET_BYTES: usize = 512; +pub const MAX_FRAME_BYTES: usize = 256; +pub const MAX_SIGNALS: usize = 8; +pub const MAX_FRAMES: usize = 4; +const MAX_FIELDS: usize = 16; +const MAX_DEPTH: usize = 8; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Error { + Truncated, + Shape, + Limit, + DuplicateField, + TrailingData, + OutputCapacity, + UnknownCodec(u8), + UnknownCodec2Mode(u8), + EmptyFrame, + NonTransmittableCodec(CodecKind), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Frame<'a> { + pub codec: CodecKind, + pub payload: &'a [u8], +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Packet<'a> { + signals: [Signal; MAX_SIGNALS], + signal_count: usize, + frames: [Frame<'a>; MAX_FRAMES], + frame_count: usize, +} +impl<'a> Packet<'a> { + pub fn signals(&self) -> &[Signal] { + &self.signals[..self.signal_count] + } + pub fn frames(&self) -> &[Frame<'a>] { + &self.frames[..self.frame_count] + } + + pub fn decode(bytes: &'a [u8]) -> Result { + if bytes.len() > MAX_PACKET_BYTES { + return Err(Error::Limit); + } + let mut reader = Reader { bytes, offset: 0 }; + let fields = reader.map_len()?; + if fields > MAX_FIELDS { + return Err(Error::Limit); + } + let mut packet = Self { + signals: [Signal::Raw(0); MAX_SIGNALS], + signal_count: 0, + frames: [Frame { + codec: CodecKind::Null, + payload: &[], + }; MAX_FRAMES], + frame_count: 0, + }; + let mut seen = 0; + for _ in 0..fields { + let key = reader.uint()?; + if key > u8::MAX as u64 { + return Err(Error::Shape); + } + match key { + 0 => { + if seen & 1 != 0 { + return Err(Error::DuplicateField); + } + seen |= 1; + let count = reader.array_len()?.unwrap_or(1); + if count > MAX_SIGNALS { + return Err(Error::Limit); + } + for signal in &mut packet.signals[..count] { + let raw = u32::try_from(reader.uint()?).map_err(|_| Error::Shape)?; + *signal = Signal::from_wire(raw); + } + packet.signal_count = count; + } + 1 => { + if seen & 2 != 0 { + return Err(Error::DuplicateField); + } + seen |= 2; + let count = reader.array_len()?.unwrap_or(1); + if count > MAX_FRAMES { + return Err(Error::Limit); + } + for frame in &mut packet.frames[..count] { + let bytes = reader.binary()?; + let (&codec, payload) = bytes.split_first().ok_or(Error::EmptyFrame)?; + if bytes.len() > MAX_FRAME_BYTES { + return Err(Error::Limit); + } + let codec = CodecKind::from_wire(codec)?; + if !codec.is_transmittable() { + return Err(Error::NonTransmittableCodec(codec)); + } + *frame = Frame { codec, payload }; + } + packet.frame_count = count; + } + _ => reader.skip(0)?, + } + } + if reader.offset != bytes.len() { + return Err(Error::TrailingData); + } + Ok(packet) + } +} + +struct Reader<'a> { + bytes: &'a [u8], + offset: usize, +} +impl<'a> Reader<'a> { + fn take(&mut self, count: usize) -> Result<&'a [u8], Error> { + let end = self.offset.checked_add(count).ok_or(Error::Limit)?; + let value = self.bytes.get(self.offset..end).ok_or(Error::Truncated)?; + self.offset = end; + Ok(value) + } + fn byte(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + fn number(&mut self, size: usize) -> Result { + Ok(self + .take(size)? + .iter() + .fold(0, |value, byte| value << 8 | u64::from(*byte))) + } + fn uint(&mut self) -> Result { + match self.byte()? { + value @ 0..=127 => Ok(u64::from(value)), + 0xcc => self.number(1), + 0xcd => self.number(2), + 0xce => self.number(4), + 0xcf => self.number(8), + tag @ 0xd0..=0xd3 => { + let size = 1 << (tag - 0xd0); + let value = self.number(size)?; + if value >> (size * 8 - 1) != 0 { + Err(Error::Shape) + } else { + Ok(value) + } + } + _ => Err(Error::Shape), + } + } + fn map_len(&mut self) -> Result { + match self.byte()? { + tag @ 0x80..=0x8f => Ok(usize::from(tag & 15)), + 0xde => Ok(self.number(2)? as usize), + 0xdf => usize::try_from(self.number(4)?).map_err(|_| Error::Limit), + _ => Err(Error::Shape), + } + } + fn array_len(&mut self) -> Result, Error> { + let tag = *self.bytes.get(self.offset).ok_or(Error::Truncated)?; + let count = match tag { + 0x90..=0x9f => { + self.offset += 1; + usize::from(tag & 15) + } + 0xdc => { + self.offset += 1; + self.number(2)? as usize + } + 0xdd => { + self.offset += 1; + usize::try_from(self.number(4)?).map_err(|_| Error::Limit)? + } + _ => return Ok(None), + }; + Ok(Some(count)) + } + fn binary(&mut self) -> Result<&'a [u8], Error> { + let count = match self.byte()? { + 0xc4 => self.number(1)?, + 0xc5 => self.number(2)?, + 0xc6 => self.number(4)?, + _ => return Err(Error::Shape), + }; + self.take(usize::try_from(count).map_err(|_| Error::Limit)?) + } + fn skip(&mut self, depth: usize) -> Result<(), Error> { + if depth > MAX_DEPTH { + return Err(Error::Limit); + } + let tag = self.byte()?; + let (bytes, children) = match tag { + 0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => (0, 0), + 0x80..=0x8f => (0, usize::from(tag & 15) * 2), + 0x90..=0x9f => (0, usize::from(tag & 15)), + 0xa0..=0xbf => (usize::from(tag & 31), 0), + 0xcc | 0xd0 => (1, 0), + 0xcd | 0xd1 => (2, 0), + 0xce | 0xd2 | 0xca => (4, 0), + 0xcf | 0xd3 | 0xcb => (8, 0), + 0xc4 | 0xd9 => (self.number(1)? as usize, 0), + 0xc5 | 0xda => (self.number(2)? as usize, 0), + 0xc6 | 0xdb => ( + usize::try_from(self.number(4)?).map_err(|_| Error::Limit)?, + 0, + ), + 0xdc..=0xdf => { + let size = if tag & 1 == 0 { 2 } else { 4 }; + let count = usize::try_from(self.number(size)?).map_err(|_| Error::Limit)?; + let children = count + .checked_mul(if tag >= 0xde { 2 } else { 1 }) + .ok_or(Error::Limit)?; + (0, children) + } + 0xd4..=0xd8 => (1 + (1 << (tag - 0xd4)), 0), + 0xc7..=0xc9 => { + let count = + usize::try_from(self.number(1 << (tag - 0xc7))?).map_err(|_| Error::Limit)?; + (count.checked_add(1).ok_or(Error::Limit)?, 0) + } + _ => return Err(Error::Shape), + }; + if children > MAX_PACKET_BYTES { + return Err(Error::Limit); + } + self.take(bytes)?; + for _ in 0..children { + self.skip(depth + 1)?; + } + Ok(()) + } +} + +fn uint_bytes(value: u32) -> usize { + match value { + 0..=127 => 1, + 128..=255 => 2, + 256..=65535 => 3, + _ => 5, + } +} + +/// Encode the same canonical map/array/binary forms as the full Rust codec. +/// Validation precedes all writes; malformed shape/capacity leaves output intact. +pub fn encode(signals: &[Signal], frames: &[Frame<'_>], output: &mut [u8]) -> Result { + if signals.len() > MAX_SIGNALS || frames.len() > MAX_FRAMES { + return Err(Error::Limit); + } + let mut size = 1; + if !signals.is_empty() { + size += 2 + signals + .iter() + .map(|v| uint_bytes(v.wire_value())) + .sum::(); + } + if !frames.is_empty() { + size += 1 + usize::from(frames.len() > 1); + for frame in frames { + if !frame.codec.is_transmittable() { + return Err(Error::NonTransmittableCodec(frame.codec)); + } + if frame.payload.len() >= MAX_FRAME_BYTES { + return Err(Error::Limit); + } + let length = frame.payload.len() + 1; + size += length + if length <= 255 { 2 } else { 3 }; + } + } + if size > MAX_PACKET_BYTES { + return Err(Error::Limit); + } + if output.len() < size { + return Err(Error::OutputCapacity); + } + let mut writer = Writer { output, offset: 0 }; + writer.byte(0x80 | (u8::from(!signals.is_empty()) + u8::from(!frames.is_empty()))); + if !signals.is_empty() { + writer.byte(0); + writer.byte(0x90 | signals.len() as u8); + for signal in signals { + writer.uint(signal.wire_value()); + } + } + if !frames.is_empty() { + writer.byte(1); + if frames.len() > 1 { + writer.byte(0x90 | frames.len() as u8); + } + for frame in frames { + let length = frame.payload.len() + 1; + if length <= 255 { + writer.byte(0xc4); + writer.byte(length as u8); + } else { + writer.byte(0xc5); + writer.bytes(&(length as u16).to_be_bytes()); + } + writer.byte(frame.codec.wire_id()); + writer.bytes(frame.payload); + } + } + debug_assert_eq!(writer.offset, size); + Ok(size) +} +struct Writer<'a> { + output: &'a mut [u8], + offset: usize, +} +impl Writer<'_> { + fn byte(&mut self, value: u8) { + self.output[self.offset] = value; + self.offset += 1; + } + fn bytes(&mut self, bytes: &[u8]) { + self.output[self.offset..self.offset + bytes.len()].copy_from_slice(bytes); + self.offset += bytes.len(); + } + fn uint(&mut self, value: u32) { + match value { + 0..=127 => self.byte(value as u8), + 128..=255 => { + self.byte(0xcc); + self.byte(value as u8); + } + 256..=65535 => { + self.byte(0xcd); + self.bytes(&(value as u16).to_be_bytes()); + } + _ => { + self.byte(0xce); + self.bytes(&value.to_be_bytes()); + } + } + } +} diff --git a/crates/lxst-embedded/tests/queue_codec.rs b/crates/lxst-embedded/tests/queue_codec.rs new file mode 100644 index 0000000..a479442 --- /dev/null +++ b/crates/lxst-embedded/tests/queue_codec.rs @@ -0,0 +1,57 @@ +use lxst_embedded::{Codec2PacketCodec, MediaQueue, Profile, QueueError}; +#[test] +fn stalled_media_drops_old_frames_and_never_crosses_generations() { + let mut queue = MediaQueue::new(); + for value in 1..=4 { + queue.push(&[value, value], 7, 10, 100).unwrap(); + } + assert_eq!(queue.len(), 3); + assert_eq!(queue.dropped(), 1); + let mut output = [0xa5; 8]; + assert_eq!( + queue.pop(11, 7, &mut output[..1]), + Err(QueueError::OutputCapacity) + ); + assert_eq!(queue.len(), 3); + assert_eq!(output, [0xa5; 8]); + assert_eq!(queue.pop(12, 7, &mut output), Ok(Some(2))); + assert_eq!(output[..2], [2, 2]); + assert_eq!(queue.pop(100, 7, &mut output), Ok(None)); + assert_eq!(queue.dropped(), 3); + queue.push(&[5], 7, 100, 110).unwrap(); + assert_eq!(queue.pop(101, 8, &mut output), Ok(None)); + assert_eq!(queue.push(&[6], 8, 110, 110), Err(QueueError::Expired)); + queue.push(&[7], 8, 120, 130).unwrap(); + queue.clear(); + assert_eq!(queue.pop(121, 8, &mut output), Ok(None)); + assert_eq!(queue.dropped(), 4); +} +#[test] +fn borrowed_native_backend_runs_shared_packet_adapter_without_state_moves() { + for (mode, profile, bytes, samples) in [ + ( + lxst_codec2::Mode::Rate1600, + Profile::BandwidthVeryLow, + 65, + 2560, + ), + (lxst_codec2::Mode::Rate3200, Profile::BandwidthLow, 81, 1600), + ] { + let mut storage = Box::::new_uninit(); + let native = lxst_codec2::Codec::initialise(&mut storage, mode); + let mut codec = Codec2PacketCodec::new(profile, native).unwrap(); + let mut output = [0xa5; 90]; + let pcm = [0; 2560]; + assert_eq!( + codec.encode_into(&pcm[..samples], &mut output).unwrap(), + bytes + ); + let mut decoded = [123; 2568]; + assert_eq!( + codec.decode_into(&output[..bytes], &mut decoded).unwrap(), + samples + ); + assert!(decoded[samples..].iter().all(|v| *v == 123)); + assert!(output[bytes..].iter().all(|v| *v == 0xa5)); + } +} diff --git a/crates/lxst-embedded/tests/session.rs b/crates/lxst-embedded/tests/session.rs new file mode 100644 index 0000000..69c011b --- /dev/null +++ b/crates/lxst-embedded/tests/session.rs @@ -0,0 +1,215 @@ +use lxst_embedded::{ + CallRole, EndReason, Event, Profile, ProfileSet, Session, SessionConfig, Signal, + SignallingStatus as Status, TelephonyAction as Action, +}; + +fn config() -> SessionConfig { + SessionConfig { + allowed: ProfileSet::CODEC2, + preferred: Profile::BandwidthVeryLow, + capture: true, + playback: true, + } +} +fn connect(role: CallRole) -> Session { + let mut session = Session::new(role, config(), 0).unwrap(); + session.link_established(); + session.peer_verified(1); + match role { + CallRole::Incoming => { + session.answer(5); + } + CallRole::Outgoing => { + for status in [Status::Available, Status::Ringing, Status::Connecting] { + session.receive_signal(status.into(), 5); + } + } + } + session.audio_ready(session.audio_generation(), true); + session.receive_signal(Status::Established.into(), 6); + assert!(session.media_ready()); + session +} +#[test] +fn media_requires_identity_acceptance_correct_order_readiness_and_fresh_press() { + for role in [CallRole::Incoming, CallRole::Outgoing] { + let mut session = Session::new(role, config(), 0).unwrap(); + session.set_transmitting(true, 0); + session.audio_ready(session.audio_generation(), true); + for status in [ + Status::Available, + Status::Ringing, + Status::Connecting, + Status::Established, + ] { + session.receive_signal(status.into(), 1); + } + assert!(!session.media_ready()); + session.link_established(); + session.receive_signal(Status::Established.into(), 2); + assert!(!session.media_ready()); + session.peer_verified(3); + session.receive_signal(Status::Established.into(), 4); + assert!(!session.media_ready()); + if role == CallRole::Incoming { + session.answer(5); + } else { + for status in [Status::Available, Status::Ringing, Status::Connecting] { + session.receive_signal(status.into(), 5); + } + } + session.receive_signal(Status::Established.into(), 6); + assert!(session.media_ready()); + assert!(!session.transmitting()); + // A press held across establishment is not a new capture request. + assert!(session.set_transmitting(true, 7).as_slice().is_empty()); + session.set_transmitting(false, 8); + assert_eq!( + session.set_transmitting(true, 9).as_slice(), + &[Event::FlushMedia, Event::Capture(true)] + ); + assert!(!session.playback_allowed()); + assert_eq!( + session.set_transmitting(false, 10).as_slice(), + &[Event::Capture(false), Event::FlushMedia] + ); + assert!(session.playback_allowed()); + } +} +#[test] +fn timeout_teardown_and_stale_setup_never_restart_capture() { + let mut session = connect(CallRole::Outgoing); + session.set_transmitting(true, 100); + assert_eq!( + session.tick(30100).as_slice(), + &[Event::Capture(false), Event::FlushMedia] + ); + assert!(session.set_transmitting(true, 30101).as_slice().is_empty()); + session.set_transmitting(false, 30102); + session.set_transmitting(true, 30103); + let old = session.audio_generation(); + let events = session.receive_signal(Profile::BandwidthLow.into(), 30104); + assert_eq!( + &events.as_slice()[..2], + &[Event::Capture(false), Event::FlushMedia] + ); + assert!(!session.media_ready()); + session.audio_ready(old, true); + assert!(!session.media_ready()); + session.audio_ready(session.audio_generation(), true); + assert!(session.media_ready()); + assert!(session.set_transmitting(true, 30105).as_slice().is_empty()); + session.set_transmitting(false, 30106); + session.set_transmitting(true, 30107); + let events = session.end(EndReason::RouteLost); + assert_eq!(events.as_slice()[0], Event::Capture(false)); + assert_eq!( + events.as_slice().last(), + Some(&Event::Ended(EndReason::RouteLost)) + ); + assert!(session.set_transmitting(true, 30108).as_slice().is_empty()); + assert!( + session + .audio_ready(session.audio_generation(), true) + .as_slice() + .is_empty() + ); + assert!(!session.media_ready()); +} +#[test] +fn unsupported_profile_has_one_bounded_offer_then_closes() { + let mut session = connect(CallRole::Outgoing); + session.set_transmitting(true, 10); + let events = session.receive_signal(Profile::QualityHigh.into(), 11); + assert_eq!( + events.as_slice(), + &[ + Event::Capture(false), + Event::FlushMedia, + Event::Transition(Action::SendSignal(Profile::BandwidthVeryLow.into())), + ] + ); + assert!(!session.media_ready()); + assert!(session.tick(5010).as_slice().is_empty()); + session.tick(5011); + assert_eq!(session.ended(), Some(EndReason::ProfileUnsupported)); + let mut session = connect(CallRole::Incoming); + 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); + assert_eq!(session.ended(), Some(EndReason::ProfileUnsupported)); +} +#[test] +fn retries_are_bounded_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())) + ); + } + assert!(session.tick(4002).as_slice().is_empty()); + session.tick(10002); + assert_eq!(session.ended(), Some(EndReason::Timeout)); + for (capture, playback) in [(true, false), (false, true)] { + let mut cfg = config(); + cfg.capture = capture; + cfg.playback = playback; + let mut session = Session::new(CallRole::Incoming, cfg, 0).unwrap(); + session.link_established(); + session.peer_verified(1); + session.answer(2); + session.audio_ready(session.audio_generation(), true); + session.receive_signal(Status::Established.into(), 3); + assert_eq!(session.playback_allowed(), playback); + session.set_transmitting(true, 4); + assert_eq!(session.transmitting(), capture); + } +} +#[test] +fn adversarial_event_sequences_remain_bounded() { + let mut rng = 401_u32; + for role in [CallRole::Incoming, CallRole::Outgoing] { + for _ in 0..1000 { + let mut session = Session::new(role, config(), 0).unwrap(); + for now in 0..100 { + rng = rng.wrapping_mul(1664525).wrapping_add(1013904223); + match rng % 10 { + 0 => { + session.link_established(); + } + 1 => { + session.peer_verified(now); + } + 2 => { + session.answer(now); + } + 3 => { + session.audio_ready(session.audio_generation(), true); + } + 4 => { + session.set_transmitting(true, now); + } + 5 => { + session.set_transmitting(false, now); + } + 6 => { + session.tick(now); + } + _ => { + session.receive_signal(Signal::from_wire((rng >> 16) % 512), now); + } + } + if session.transmitting() { + assert!(session.media_ready()); + } + } + } + } +} diff --git a/crates/lxst-embedded/tests/wire.rs b/crates/lxst-embedded/tests/wire.rs new file mode 100644 index 0000000..9be8e8f --- /dev/null +++ b/crates/lxst-embedded/tests/wire.rs @@ -0,0 +1,146 @@ +use lxst_embedded::wire::{self, Error, Frame, Packet}; +use lxst_embedded::{CodecKind, Profile, Signal}; + +#[test] +fn bounded_wire_matches_full_rust_canonical_packets() { + let signal_values = [0, 6, 127, 128, 255, 256, 65535, u32::MAX]; + for count in 0..=8 { + let signals: Vec<_> = signal_values[..count] + .iter() + .map(|v| Signal::from_wire(*v)) + .collect(); + for lengths in [vec![], vec![0], vec![64], vec![255], vec![0, 64, 80, 120]] { + let payloads: Vec<_> = lengths.iter().map(|n| vec![0x5a; *n]).collect(); + let frames: Vec<_> = payloads + .iter() + .map(|p| Frame { + codec: CodecKind::Codec2, + payload: p, + }) + .collect(); + let host = lxst_core::LxstPacket { + signals: signals + .iter() + .map(|s| lxst_core::Signal::from_wire(s.wire_value())) + .collect(), + frames: payloads + .iter() + .map(|p| lxst_core::Frame::new(lxst_core::CodecKind::Codec2, p.clone())) + .collect(), + }; + let expected = host.encode().unwrap(); + let mut encoded = [0xa5; 512]; + let size = wire::encode(&signals, &frames, &mut encoded).unwrap(); + assert_eq!(encoded[..size], expected); + assert!(encoded[size..].iter().all(|v| *v == 0xa5)); + let decoded = Packet::decode(&encoded[..size]).unwrap(); + assert_eq!(decoded.signals(), signals); + assert_eq!(decoded.frames(), frames); + for end in 0..size { + assert!(Packet::decode(&encoded[..end]).is_err()); + } + let mut too_small = vec![0xa5; size - 1]; + assert_eq!( + wire::encode(&signals, &frames, &mut too_small), + Err(Error::OutputCapacity) + ); + assert!(too_small.iter().all(|v| *v == 0xa5)); + } + } +} + +#[test] +fn equivalent_integer_and_container_forms_remain_compatible() { + for bytes in [ + vec![0x81, 0, 4], + vec![0xde, 0, 1, 0xcc, 0, 0xdc, 0, 1, 0xd1, 0, 4], + vec![ + 0xdf, 0, 0, 0, 1, 0, 0xdd, 0, 0, 0, 1, 0xd3, 0, 0, 0, 0, 0, 0, 0, 4, + ], + ] { + let packet = Packet::decode(&bytes).unwrap(); + assert_eq!(packet.signals()[0].wire_value(), 4); + assert_eq!( + lxst_core::LxstPacket::decode(&bytes).unwrap().signals[0].wire_value(), + 4 + ); + } + for bytes in [ + vec![0x81, 1, 0xc5, 0, 2, 2, 4], + vec![0x81, 1, 0xc6, 0, 0, 0, 2, 2, 4], + ] { + assert_eq!(Packet::decode(&bytes).unwrap().frames()[0].payload, &[4]); + } + // Unknown metadata is skipped, bounded by packet bytes and nesting depth. + let bytes = [0x82, 8, 0x92, 0xc0, 0x81, 0xa1, b'a', 0xc7, 1, 3, 8, 0, 4]; + assert_eq!(Packet::decode(&bytes).unwrap().signals()[0].wire_value(), 4); +} + +#[test] +fn hostile_shapes_are_rejected_without_unbounded_work() { + for bytes in [ + vec![0x81, 0, 0xff], + vec![0x81, 0, 0xd0, 0xff], + vec![0x81, 0, 0xcf, 1, 0, 0, 0, 0, 0, 0, 0], + vec![0x81, 0, 0xdd, 255, 255, 255, 255], + vec![0x81, 1, 0xc6, 255, 255, 255, 255], + vec![0x81, 1, 0xc4, 0], + vec![0x81, 1, 0xc4, 1, 255], + vec![0x82, 0, 4, 0, 4], + vec![0x81, 0, 4, 0], + vec![0x81, 1, 0x95], + vec![0x81, 0, 0x99], + vec![ + 0x81, 8, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0, + ], + ] { + assert!(Packet::decode(&bytes).is_err(), "accepted {bytes:x?}"); + } + let mut output = [0xa5; 512]; + let frames = [Frame { + codec: CodecKind::Null, + payload: &[], + }]; + assert_eq!( + wire::encode(&[], &frames, &mut output), + Err(Error::NonTransmittableCodec(CodecKind::Null)) + ); + assert_eq!(output, [0xa5; 512]); + let mut random = 123_u32; + let mut bytes = [0; 520]; + for iteration in 0..100000 { + let length = iteration % bytes.len(); + for byte in &mut bytes[..length] { + random = random.wrapping_mul(1664525).wrapping_add(1013904223); + *byte = (random >> 24) as u8; + } + let _ = Packet::decode(&bytes[..length]); + } +} + +#[test] +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] { + 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:?}")); + assert_eq!(embedded.status().wire_value(), host.status().wire_value()); + } + // 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] { + let mut call = CallState::incoming(); + call.caller_identified(false, true); + call.receive_signal(Signal::from_wire(first)); + call.answer(); + call.receive_signal(Signal::from_wire(second)); + call.retry_answer(); + call.hangup(false); + assert_eq!(call.status(), SignallingStatus::Available); + } + } +} diff --git a/tools/check-source-release.py b/tools/check-source-release.py index 0ad74e7..48ade5e 100644 --- a/tools/check-source-release.py +++ b/tools/check-source-release.py @@ -11,7 +11,7 @@ import sys ROOT = Path(__file__).resolve().parents[1] -EXPECTED_PACKAGES = {"lxst-core", "lxst-codec2", "lxst-rns", "lxst-telephony"} +EXPECTED_PACKAGES = {"lxst-core", "lxst-codec2", "lxst-embedded", "lxst-rns", "lxst-telephony"} EXPECTED_MSRV = "1.87" EXPECTED_RETICULUM_VERSION = "1.3.0" EXPECTED_RETICULUM_COMMIT = "d4183434fcb969799c208ddcf140bae7550c14fe"