diff --git a/CHANGELOG.md b/CHANGELOG.md index c591edb..49d0bdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +### Codec foundations + +- Add a fixed-profile Codec2 packet adapter over caller-owned PCM16/output + buffers and an application-supplied native backend. Reject malformed lengths, + unexpected modes and insufficient capacity before codec processing; stop + further processing after a backend failure. Preserve native 700C frame padding. + Codec backend selection and live Codec2 telephony remain separate work. + ### Build and compatibility - Restricted rsReticulum compatibility to the 1.3 patch line and updated the pinned source. Codec dependencies and telephony APIs are unchanged. diff --git a/README.md b/README.md index 31db568..029690b 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,13 @@ The experimental release is to cover basic voice calls, with several features st Those are expected future work. They should not be implied by the first public Opus telephony release. +`lxst-core::Codec2PacketCodec` provides bounded, fixed-profile Codec2 packet +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 +are still required. Its mode header belongs to LXST, not LXMF audio fields. + ## Build It The current development layout requires `rsReticulum` as a sibling checkout diff --git a/api/fixtures/Cargo.lock b/api/fixtures/Cargo.lock index 9c2298f..00ffb28 100644 --- a/api/fixtures/Cargo.lock +++ b/api/fixtures/Cargo.lock @@ -435,6 +435,7 @@ dependencies = [ name = "lxst-telephony-api-fixture" version = "0.0.0" dependencies = [ + "lxst-core", "lxst-telephony", "rns-identity", "rns-transport", diff --git a/api/fixtures/Cargo.toml b/api/fixtures/Cargo.toml index 8f68274..656483d 100644 --- a/api/fixtures/Cargo.toml +++ b/api/fixtures/Cargo.toml @@ -7,6 +7,7 @@ publish = false [workspace] [dependencies] +lxst-core = { path = "../../crates/lxst-core" } lxst-telephony = { path = "../../crates/lxst-telephony" } rns-identity = { path = "../../../rsReticulum/crates/rns-identity" } rns-transport = { path = "../../../rsReticulum/crates/rns-transport" } diff --git a/api/fixtures/src/lib.rs b/api/fixtures/src/lib.rs index 22daaf8..4a078fb 100644 --- a/api/fixtures/src/lib.rs +++ b/api/fixtures/src/lib.rs @@ -26,3 +26,30 @@ pub mod retained { (endpoint, runtime) } } + +pub mod codec2 { + use lxst_core::{Codec2Backend, Codec2PacketCodec, Codec2PacketError, Profile}; + + pub fn construct( + profile: Profile, + backend: B, + ) -> Result, Codec2PacketError> { + Codec2PacketCodec::new(profile, backend) + } + + pub fn encode( + codec: &mut Codec2PacketCodec, + pcm: &[i16], + output: &mut [u8], + ) -> Result> { + codec.encode_into(pcm, output) + } + + pub fn decode( + codec: &mut Codec2PacketCodec, + packet: &[u8], + output: &mut [i16], + ) -> Result> { + codec.decode_into(packet, output) + } +} diff --git a/crates/lxst-core/src/codec2.rs b/crates/lxst-core/src/codec2.rs new file mode 100644 index 0000000..921059f --- /dev/null +++ b/crates/lxst-core/src/codec2.rs @@ -0,0 +1,204 @@ +//! 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) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/lxst-core/src/codec2/tests.rs b/crates/lxst-core/src/codec2/tests.rs new file mode 100644 index 0000000..453864a --- /dev/null +++ b/crates/lxst-core/src/codec2/tests.rs @@ -0,0 +1,215 @@ +use super::*; +use std::cell::Cell; +use std::rc::Rc; + +struct Backend { + mode: Codec2Mode, + calls: Rc>, + fail_at: Option, +} + +impl Codec2Backend for Backend { + type Error = &'static str; + + fn mode(&self) -> Codec2Mode { + self.mode + } + + fn encode_native(&mut self, pcm: &[i16], encoded: &mut [u8]) -> Result<(), Self::Error> { + let count = self.calls.get() + 1; + self.calls.set(count); + assert_eq!( + pcm.len(), + if self.mode == Codec2Mode::Mode3200 { + 160 + } else { + 320 + } + ); + assert_eq!( + encoded.len(), + if self.mode == Codec2Mode::Mode700C { + 4 + } else { + 8 + } + ); + if self.fail_at == Some(count) { + return Err("injected codec failure"); + } + encoded.fill(count as u8); + Ok(()) + } + + fn decode_native(&mut self, encoded: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> { + let mut scratch = [0; 8]; + self.encode_native(pcm, &mut scratch[..encoded.len()])?; + pcm.fill(i16::from(encoded[0])); + Ok(()) + } +} + +fn codec( + profile: Profile, + fail_at: Option, +) -> (Codec2PacketCodec, Rc>) { + let AudioCodec::Codec2(mode) = profile.audio_codec() else { + panic!("test profile") + }; + let calls = Rc::new(Cell::new(0)); + let backend = Backend { + mode, + calls: calls.clone(), + fail_at, + }; + (Codec2PacketCodec::new(profile, backend).unwrap(), calls) +} + +#[test] +fn profile_packets_preserve_native_frame_padding_and_output_tails() { + for (profile, samples, bytes, count) in [ + (Profile::BandwidthUltraLow, 3200, 41, 10), + (Profile::BandwidthVeryLow, 2560, 65, 8), + (Profile::BandwidthLow, 1600, 81, 10), + ] { + let (mut encoder, calls) = codec(profile, None); + assert_eq!(encoder.profile(), profile); + assert_eq!(encoder.sample_frames(), samples); + assert_eq!(encoder.payload_bytes(), bytes); + let pcm = vec![100; samples]; + let mut payload = [0xED; 96]; + assert_eq!(encoder.encode_into(&pcm, &mut payload).unwrap(), bytes); + assert_eq!(calls.get(), count); + assert_eq!(payload[0], encoder.mode().header()); + assert!(payload[bytes..].iter().all(|x| *x == 0xED)); + for (i, frame) in payload[1..bytes] + .chunks_exact((bytes - 1) / count) + .enumerate() + { + assert!(frame.iter().all(|x| usize::from(*x) == i + 1)); + } + let (mut decoder, calls) = codec(profile, None); + let mut decoded = vec![-123; samples + 8]; + assert_eq!( + decoder + .decode_into(&payload[..bytes], &mut decoded) + .unwrap(), + samples + ); + assert_eq!(calls.get(), count); + assert!(decoded[samples..].iter().all(|x| *x == -123)); + for (i, frame) in decoded[..samples].chunks_exact(samples / count).enumerate() { + assert!(frame.iter().all(|x| *x == (i + 1) as i16)); + } + } +} + +#[test] +fn reject_non_codec2_profiles_and_backend_mode_mismatch() { + for profile in Profile::ORDER { + let backend = Backend { + mode: Codec2Mode::Mode1600, + calls: Rc::new(Cell::new(0)), + fail_at: None, + }; + let result = Codec2PacketCodec::new(profile, backend); + match profile.audio_codec() { + AudioCodec::Opus(_) => assert!( + matches!(result, Err(Codec2PacketError::NonCodec2Profile(p)) if p == profile) + ), + AudioCodec::Codec2(Codec2Mode::Mode1600) => assert!(result.is_ok()), + AudioCodec::Codec2(_) => assert!(matches!( + result, + Err(Codec2PacketError::BackendModeMismatch { .. }) + )), + } + } +} + +#[test] +fn all_malformed_lengths_headers_and_capacities_fail_before_backend_or_output_mutation() { + for profile in [ + Profile::BandwidthUltraLow, + Profile::BandwidthVeryLow, + Profile::BandwidthLow, + ] { + let (mut codec, calls) = codec(profile, None); + let mut payload = vec![0; codec.payload_bytes() + 1]; + payload[0] = codec.mode().header(); + let mut output = vec![-123; codec.sample_frames()]; + for length in 0..=payload.len() { + if length == codec.payload_bytes() { + continue; + } + assert!(matches!( + codec.decode_into(&payload[..length], &mut output), + Err(Codec2PacketError::PayloadLength { .. }) + )); + } + payload.pop(); + for header in 0..=255 { + if header == codec.mode().header() { + continue; + } + payload[0] = header; + assert!(matches!( + codec.decode_into(&payload, &mut output), + Err(Codec2PacketError::ModeHeader { .. }) + )); + } + payload[0] = codec.mode().header(); + for capacity in [0, 1, codec.sample_frames() - 1] { + assert!(matches!( + codec.decode_into(&payload, &mut output[..capacity]), + Err(Codec2PacketError::OutputCapacity { .. }) + )); + } + assert!(output.iter().all(|x| *x == -123)); + payload.fill(0xEA); + for samples in [0, 1, codec.sample_frames() - 1, codec.sample_frames() + 1] { + assert!(matches!( + codec.encode_into(&vec![0; samples], &mut payload), + Err(Codec2PacketError::SampleCount { .. }) + )); + } + for capacity in [0, 1, codec.payload_bytes() - 1] { + assert!(matches!( + codec.encode_into(&output, &mut payload[..capacity]), + Err(Codec2PacketError::OutputCapacity { .. }) + )); + } + assert!(payload.iter().all(|x| *x == 0xEA)); + assert_eq!(calls.get(), 0); + // A rejected input must not poison a valid stream. + assert!(codec.encode_into(&output, &mut payload).is_ok()); + } +} + +#[test] +fn backend_failure_latches_both_directions_until_replacement() { + for encode_first in [true, false] { + let (mut codec, calls) = codec(Profile::BandwidthVeryLow, Some(3)); + let mut payload = [0; 65]; + payload[0] = Codec2Mode::Mode1600.header(); + let mut pcm = [0; 2560]; + let result = if encode_first { + codec.encode_into(&pcm, &mut payload) + } else { + codec.decode_into(&payload, &mut pcm) + }; + assert_eq!( + result, + Err(Codec2PacketError::Backend("injected codec failure")) + ); + assert_eq!(calls.get(), 3); + assert_eq!( + codec.encode_into(&pcm, &mut payload), + Err(Codec2PacketError::Failed) + ); + assert_eq!( + codec.decode_into(&payload, &mut pcm), + Err(Codec2PacketError::Failed) + ); + assert_eq!(calls.get(), 3); + } +} diff --git a/crates/lxst-core/src/lib.rs b/crates/lxst-core/src/lib.rs index b873046..2c0b15a 100644 --- a/crates/lxst-core/src/lib.rs +++ b/crates/lxst-core/src/lib.rs @@ -4,6 +4,7 @@ //! avoids audio and Reticulum runtime dependencies so packet/profile parity can //! be tested in isolation. +mod codec2; mod opus; mod profile; mod raw; @@ -12,6 +13,7 @@ mod synthetic; mod telephony; mod wire; +pub use codec2::{Codec2Backend, Codec2PacketCodec, Codec2PacketError}; pub use opus::{ OPUS_ENCODED_FRAME_MAX_BYTES, OPUS_ENCODED_PACKET_MAX_BYTES, OPUS_MONO_DECODE_SAMPLE_RATE_HZ, OpusCodecError, OpusDecoderState, OpusEncoderState, OpusMonoDecoder,