mirror of
https://github.com/ratspeak/rsLXST
synced 2026-11-22 23:10:37 +00:00
telephony: add native Codec2 streams and revocable PTT leases
This commit is contained in:
1 parent
f9c97a011f
commit
e8c1a8d85a
11 files changed
+621
-16
No files matched your search
Generated
+1
@@ -602,6 +602,7 @@ version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"lxst-codec2",
|
||||
"lxst-core",
|
||||
"lxst-rns",
|
||||
"rns-crypto",
|
||||
|
||||
@@ -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": "d89f1983abe87e964464193fdda5503b4eade5283405291a958dec77559e66cb",
|
||||
"cargoLockSha256": "f0a803031d628d68904e4f1ced49378c9bc494ca3efdad111cac6b9bc1aef784",
|
||||
"packages": [
|
||||
{
|
||||
"name": "aes",
|
||||
|
||||
@@ -57,3 +57,19 @@ cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
Snapshot updates require a clean source commit and an explicit review recorded
|
||||
in `api/stability.json`. Additions, removals, deprecations, platform impact, and
|
||||
version consequences must be reviewed before accepting new evidence.
|
||||
|
||||
## Live audio and constrained peers
|
||||
|
||||
`SendAudioFrames`, `StartAudioStream` and the corresponding receive/stop controls
|
||||
accept negotiated Opus and native Codec2 1600/3200 profiles. Original Opus
|
||||
controls remain available. Codec2 media emits `Audio*` service events; the
|
||||
existing Opus event stream is unchanged. 700C is not implemented.
|
||||
|
||||
`StartAudioStream` binds the exact active Link and optionally shares an
|
||||
`AudioTransmitGate` with the local input owner. Renew one press serial while
|
||||
held, use a newer serial on release, and close the gate when its owner retires.
|
||||
Expired, cancelled or superseded input cannot admit queued PCM; new edges clear
|
||||
pending PCM. The gate times out after 750 ms without renewal and after a ten
|
||||
second burst. This is local PTT policy, not a remote floor-control extension.
|
||||
Applications must still bind UI events to the current call and stop on lost
|
||||
focus, suspension and release. No memo/container format is changed.
|
||||
Generated
+1
@@ -440,6 +440,7 @@ name = "lxst-telephony"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"lxst-codec2",
|
||||
"lxst-core",
|
||||
"lxst-rns",
|
||||
"rns-crypto",
|
||||
|
||||
@@ -83,3 +83,24 @@ pub mod embedded {
|
||||
lxst_embedded::wire::Packet::decode(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod live_audio {
|
||||
use lxst_core::{Profile, RawAudioFrame};
|
||||
use lxst_telephony::{AudioTransmitGate, LinkId, TelephonyControl};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
pub fn stream(
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
frames: mpsc::Receiver<RawAudioFrame>,
|
||||
) -> (Arc<AudioTransmitGate>, TelephonyControl) {
|
||||
let gate = Arc::new(AudioTransmitGate::new());
|
||||
let command = TelephonyControl::StartAudioStream {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
gate: Some(gate.clone()),
|
||||
};
|
||||
(gate, command)
|
||||
}
|
||||
}
|
||||
@@ -277,6 +277,17 @@
|
||||
"features": [],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
{
|
||||
"name": "lxst-codec2",
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": null,
|
||||
"requirement": "^0.2.0",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
"sourceKind": "path"
|
||||
},
|
||||
{
|
||||
"name": "lxst-core",
|
||||
"rename": null,
|
||||
|
||||
@@ -9,6 +9,7 @@ publish.workspace = true
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
lxst-core.workspace = true
|
||||
lxst-codec2 = { path = "../lxst-codec2", version = "0.2.0" }
|
||||
lxst-rns.workspace = true
|
||||
rns-crypto.workspace = true
|
||||
rns-identity.workspace = true
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A release-aware local PTT lease. A stalled UI stops media within 750 ms;
|
||||
/// a ten-second burst requires a new release/press. It adds no LXST wire fields.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct AudioTransmitGate {
|
||||
state: Mutex<State>,
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct State {
|
||||
serial: u64,
|
||||
began: Option<Instant>,
|
||||
until: Option<Instant>,
|
||||
blocked: bool,
|
||||
}
|
||||
impl AudioTransmitGate {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
/// Monotonically increasing serial for each edge; renew using the press
|
||||
/// serial. A delayed press/renew after a later release is rejected.
|
||||
pub fn update(&self, serial: u64, pressed: bool) -> bool {
|
||||
self.update_at(serial, pressed, Instant::now())
|
||||
}
|
||||
fn update_at(&self, serial: u64, pressed: bool, now: Instant) -> bool {
|
||||
let Ok(mut state) = self.state.lock() else {
|
||||
return false;
|
||||
};
|
||||
if serial == 0 || serial < state.serial {
|
||||
return false;
|
||||
}
|
||||
if serial > state.serial {
|
||||
state.serial = serial;
|
||||
state.began = None;
|
||||
state.until = None;
|
||||
if !pressed {
|
||||
state.blocked = false;
|
||||
return true;
|
||||
}
|
||||
if state.blocked {
|
||||
return false;
|
||||
}
|
||||
state.began = Some(now);
|
||||
}
|
||||
if !pressed {
|
||||
state.began = None;
|
||||
state.until = None;
|
||||
state.blocked = false;
|
||||
return true;
|
||||
}
|
||||
if state.blocked || state.began.is_none() {
|
||||
return false;
|
||||
}
|
||||
if now.duration_since(state.began.unwrap()) >= Duration::from_secs(10)
|
||||
|| state.until.is_some_and(|end| now >= end)
|
||||
{
|
||||
state.blocked = true;
|
||||
state.until = None;
|
||||
return false;
|
||||
}
|
||||
state.until = Some(now + Duration::from_millis(750));
|
||||
true
|
||||
}
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.state.lock().map(|s| s.serial).unwrap_or(0)
|
||||
}
|
||||
/// Permanently revoke this owner; replace it for a new session.
|
||||
pub fn close(&self) {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
state.serial = u64::MAX;
|
||||
state.until = None;
|
||||
state.began = None;
|
||||
state.blocked = true;
|
||||
}
|
||||
}
|
||||
pub fn allows(&self) -> bool {
|
||||
self.allows_at(Instant::now())
|
||||
}
|
||||
fn allows_at(&self, now: Instant) -> bool {
|
||||
let Ok(mut state) = self.state.try_lock() else {
|
||||
return false;
|
||||
};
|
||||
let allowed = !state.blocked
|
||||
&& state.until.is_some_and(|end| now < end)
|
||||
&& state
|
||||
.began
|
||||
.is_some_and(|begin| now.duration_since(begin) < Duration::from_secs(10));
|
||||
if !allowed && state.began.is_some() {
|
||||
state.blocked = true;
|
||||
state.until = None;
|
||||
}
|
||||
allowed
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn release_stale_renew_stall_and_burst_are_fenced() {
|
||||
let gate = AudioTransmitGate::new();
|
||||
let start = Instant::now();
|
||||
assert!(!gate.allows_at(start));
|
||||
assert!(gate.update_at(1, true, start));
|
||||
assert!(gate.allows_at(start));
|
||||
assert!(gate.update_at(2, false, start));
|
||||
assert!(!gate.update_at(1, true, start));
|
||||
assert!(gate.update_at(3, true, start));
|
||||
assert!(!gate.allows_at(start + Duration::from_secs(1)));
|
||||
assert!(!gate.update_at(4, true, start + Duration::from_secs(1))); // new press still requires release after timeout
|
||||
assert!(gate.update_at(5, false, start));
|
||||
assert!(gate.update_at(6, true, start));
|
||||
for ms in (250..10000).step_by(250) {
|
||||
assert!(gate.update_at(6, true, start + Duration::from_millis(ms)));
|
||||
}
|
||||
assert!(!gate.update_at(6, true, start + Duration::from_secs(10)));
|
||||
assert!(!gate.allows_at(start + Duration::from_secs(10)));
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,9 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use bytes::Bytes;
|
||||
use lxst_core::{
|
||||
CallRole, CodecKind, Frame, FrameStreamEvent, LxstPacket, OpusCodecError, OpusDecoderState,
|
||||
OpusEncoderState, Profile, RawAudioFrame, RawBitDepth, Signal, SignallingStatus,
|
||||
TELEPHONY_DESTINATION_NAME, TelephonyAction, TelephonyCall,
|
||||
CallRole, CodecKind, Frame, FrameStreamEvent, LxstPacket, OpusCodecError, Profile,
|
||||
RawAudioFrame, RawBitDepth, Signal, SignallingStatus, TELEPHONY_DESTINATION_NAME,
|
||||
TelephonyAction, TelephonyCall,
|
||||
};
|
||||
use lxst_rns::{
|
||||
InboundLxstPacket, LxstLinkIngress, LxstMediaEgress, PreparedLinkEndpointSend,
|
||||
@@ -40,6 +40,11 @@ use thiserror::Error;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::{Duration, Instant, timeout};
|
||||
|
||||
mod capture_gate;
|
||||
mod media;
|
||||
pub use capture_gate::AudioTransmitGate;
|
||||
use media::{AudioDecoder, AudioEncoder};
|
||||
|
||||
pub type LinkId = [u8; 16];
|
||||
pub type IdentityHash = [u8; 16];
|
||||
|
||||
@@ -55,6 +60,8 @@ pub enum Error {
|
||||
Rns(#[from] lxst_rns::Error),
|
||||
#[error("LXST Opus codec error: {0}")]
|
||||
Opus(#[from] OpusCodecError),
|
||||
#[error("LXST audio codec error: {0}")]
|
||||
Audio(String),
|
||||
#[error("unknown LXST link")]
|
||||
UnknownLink,
|
||||
#[error("line is busy")]
|
||||
@@ -751,6 +758,22 @@ pub enum TelephonyControl {
|
||||
bit_depth: RawBitDepth,
|
||||
frames: Vec<RawAudioFrame>,
|
||||
},
|
||||
/// Encode negotiated Opus or native Codec2 1600/3200 PCM.
|
||||
SendAudioFrames {
|
||||
profile: Profile,
|
||||
frames: Vec<RawAudioFrame>,
|
||||
},
|
||||
StartAudioStream {
|
||||
link_id: LinkId,
|
||||
gate: Option<std::sync::Arc<AudioTransmitGate>>,
|
||||
profile: Profile,
|
||||
frames: mpsc::Receiver<RawAudioFrame>,
|
||||
},
|
||||
StopAudioStream,
|
||||
StartAudioReceiveStream {
|
||||
frames: mpsc::Sender<RawAudioFrame>,
|
||||
},
|
||||
StopAudioReceiveStream,
|
||||
SendOpusFrames {
|
||||
profile: Profile,
|
||||
frames: Vec<RawAudioFrame>,
|
||||
@@ -867,6 +890,35 @@ pub enum TelephonyServiceEvent {
|
||||
frames: usize,
|
||||
dropped: usize,
|
||||
},
|
||||
AudioFramesReceived {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
frames: Vec<RawAudioFrame>,
|
||||
},
|
||||
AudioTransmitStreamStarted {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
},
|
||||
AudioTransmitStreamStopped {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
reason: OpusTransmitStreamStopReason,
|
||||
},
|
||||
AudioReceiveStreamStarted {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
},
|
||||
AudioReceiveStreamStopped {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
reason: OpusReceiveStreamStopReason,
|
||||
},
|
||||
AudioReceiveStreamFrames {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
frames: usize,
|
||||
dropped: usize,
|
||||
},
|
||||
Snapshot(TelephonyRuntimeSnapshot),
|
||||
Drive(TelephonyDriveStep),
|
||||
Error {
|
||||
@@ -975,19 +1027,21 @@ struct TelephonyServiceMedia {
|
||||
struct ActiveOpusEncoder {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
encoder: OpusEncoderState,
|
||||
encoder: AudioEncoder,
|
||||
}
|
||||
|
||||
struct ActiveOpusDecoder {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
decoder: OpusDecoderState,
|
||||
decoder: AudioDecoder,
|
||||
}
|
||||
|
||||
struct ActiveOpusTransmitStream {
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
frames_rx: mpsc::Receiver<RawAudioFrame>,
|
||||
gate: Option<std::sync::Arc<AudioTransmitGate>>,
|
||||
gate_serial: u64,
|
||||
}
|
||||
|
||||
struct ActiveOpusReceiveStream {
|
||||
@@ -1076,7 +1130,7 @@ impl TelephonyServiceMedia {
|
||||
&mut self,
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
) -> Result<&mut OpusEncoderState, OpusCodecError> {
|
||||
) -> Result<&mut AudioEncoder, Error> {
|
||||
let needs_new = self
|
||||
.opus_encoder
|
||||
.as_ref()
|
||||
@@ -1087,7 +1141,7 @@ impl TelephonyServiceMedia {
|
||||
self.opus_encoder = Some(ActiveOpusEncoder {
|
||||
link_id,
|
||||
profile,
|
||||
encoder: OpusEncoderState::new(profile)?,
|
||||
encoder: AudioEncoder::new(profile)?,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1102,7 +1156,7 @@ impl TelephonyServiceMedia {
|
||||
&mut self,
|
||||
link_id: LinkId,
|
||||
profile: Profile,
|
||||
) -> Result<&mut OpusDecoderState, OpusCodecError> {
|
||||
) -> Result<&mut AudioDecoder, Error> {
|
||||
let needs_new = self
|
||||
.opus_decoder
|
||||
.as_ref()
|
||||
@@ -1113,7 +1167,7 @@ impl TelephonyServiceMedia {
|
||||
self.opus_decoder = Some(ActiveOpusDecoder {
|
||||
link_id,
|
||||
profile,
|
||||
decoder: OpusDecoderState::new(profile)?,
|
||||
decoder: AudioDecoder::new(profile)?,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1397,30 +1451,55 @@ impl TelephonyService {
|
||||
Err(err) => emit_service_error(self.event_tx.clone(), err).await,
|
||||
};
|
||||
}
|
||||
TelephonyControl::SendOpusFrames { profile, frames } => {
|
||||
TelephonyControl::SendOpusFrames { profile, frames }
|
||||
| TelephonyControl::SendAudioFrames { profile, frames } => {
|
||||
return match self.send_opus_frames(profile, frames).await {
|
||||
Ok(()) => true,
|
||||
Err(err) => emit_service_error(self.event_tx.clone(), err).await,
|
||||
};
|
||||
}
|
||||
TelephonyControl::StartAudioStream {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
gate,
|
||||
} => {
|
||||
if self
|
||||
.core
|
||||
.active_call()
|
||||
.is_none_or(|call| call.link_id != link_id)
|
||||
{
|
||||
return emit_service_error(self.event_tx.clone(), Error::WrongActiveLink).await;
|
||||
}
|
||||
return match self.start_opus_stream(profile, frames).await {
|
||||
Ok(()) => {
|
||||
if let Some(stream) = self.media.opus_transmit_stream.as_mut() {
|
||||
stream.gate = gate;
|
||||
}
|
||||
true
|
||||
}
|
||||
Err(err) => emit_service_error(self.event_tx.clone(), err).await,
|
||||
};
|
||||
}
|
||||
TelephonyControl::StartOpusStream { profile, frames } => {
|
||||
return match self.start_opus_stream(profile, frames).await {
|
||||
Ok(()) => true,
|
||||
Err(err) => emit_service_error(self.event_tx.clone(), err).await,
|
||||
};
|
||||
}
|
||||
TelephonyControl::StopOpusStream => {
|
||||
TelephonyControl::StopOpusStream | TelephonyControl::StopAudioStream => {
|
||||
return self
|
||||
.stop_opus_stream(OpusTransmitStreamStopReason::Requested)
|
||||
.await;
|
||||
}
|
||||
TelephonyControl::StartOpusReceiveStream { frames } => {
|
||||
TelephonyControl::StartOpusReceiveStream { frames }
|
||||
| TelephonyControl::StartAudioReceiveStream { frames } => {
|
||||
return match self.start_opus_receive_stream(frames).await {
|
||||
Ok(()) => true,
|
||||
Err(err) => emit_service_error(self.event_tx.clone(), err).await,
|
||||
};
|
||||
}
|
||||
TelephonyControl::StopOpusReceiveStream => {
|
||||
TelephonyControl::StopOpusReceiveStream | TelephonyControl::StopAudioReceiveStream => {
|
||||
return self
|
||||
.stop_opus_receive_stream(OpusReceiveStreamStopReason::Requested)
|
||||
.await;
|
||||
@@ -1636,6 +1715,8 @@ impl TelephonyService {
|
||||
link_id,
|
||||
profile,
|
||||
frames_rx,
|
||||
gate: None,
|
||||
gate_serial: 0,
|
||||
});
|
||||
|
||||
if emit_service_event(
|
||||
@@ -1687,13 +1768,24 @@ impl TelephonyService {
|
||||
|
||||
fn drain_opus_stream_frames(&mut self) -> Option<(Profile, Vec<RawAudioFrame>, bool)> {
|
||||
let stream = self.media.opus_transmit_stream.as_mut()?;
|
||||
if let Some(gate) = &stream.gate {
|
||||
let serial = gate.serial();
|
||||
if serial != stream.gate_serial {
|
||||
while stream.frames_rx.try_recv().is_ok() {}
|
||||
stream.gate_serial = serial;
|
||||
}
|
||||
}
|
||||
let mut frames = Vec::new();
|
||||
let mut source_closed = false;
|
||||
let max_frames = self.config.media_frames_per_tick.max(1);
|
||||
|
||||
for _ in 0..max_frames {
|
||||
match stream.frames_rx.try_recv() {
|
||||
Ok(frame) => frames.push(frame),
|
||||
Ok(frame) => {
|
||||
if stream.gate.as_ref().is_none_or(|gate| gate.allows()) {
|
||||
frames.push(frame);
|
||||
}
|
||||
}
|
||||
Err(mpsc::error::TryRecvError::Empty) => break,
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
source_closed = true;
|
||||
@@ -1844,6 +1936,12 @@ impl TelephonyService {
|
||||
}
|
||||
|
||||
let link_id = active.link_id;
|
||||
let gate = self
|
||||
.media
|
||||
.opus_transmit_stream
|
||||
.as_ref()
|
||||
.and_then(|stream| stream.gate.clone());
|
||||
let serial = gate.as_ref().map(|gate| gate.serial());
|
||||
let frame_count = frames.len();
|
||||
let encoded = {
|
||||
let encoder = self.media.opus_encoder_for(link_id, profile)?;
|
||||
@@ -1852,6 +1950,21 @@ impl TelephonyService {
|
||||
.map(|frame| encoder.encode_frame(frame))
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
};
|
||||
if self
|
||||
.media
|
||||
.opus_transmit_stream
|
||||
.as_ref()
|
||||
.and_then(|stream| stream.gate.as_ref())
|
||||
.is_some_and(|gate| !gate.allows())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if gate
|
||||
.as_ref()
|
||||
.is_some_and(|gate| Some(gate.serial()) != serial)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let packet_count = self.endpoint.queue_frames(link_id, encoded)?;
|
||||
if emit_service_event(
|
||||
self.event_tx.clone(),
|
||||
@@ -1939,7 +2052,11 @@ impl TelephonyService {
|
||||
.frame_events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
FrameStreamEvent::Frame(frame) if frame.codec == CodecKind::Opus => Some(frame),
|
||||
FrameStreamEvent::Frame(frame)
|
||||
if matches!(frame.codec, CodecKind::Opus | CodecKind::Codec2) =>
|
||||
{
|
||||
Some(frame)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -1952,6 +2069,9 @@ impl TelephonyService {
|
||||
return Err(Error::WrongActiveLink);
|
||||
}
|
||||
let link_id = active.link_id;
|
||||
if active.call.status() != SignallingStatus::Established {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let profile = active.call.profile().unwrap_or(Profile::DEFAULT);
|
||||
let decoded = {
|
||||
let decoder = self.media.opus_decoder_for(active.link_id, profile)?;
|
||||
@@ -2284,6 +2404,65 @@ async fn emit_service_event(
|
||||
event_tx: mpsc::Sender<TelephonyServiceEvent>,
|
||||
event: TelephonyServiceEvent,
|
||||
) -> bool {
|
||||
let event = match event {
|
||||
TelephonyServiceEvent::OpusFramesReceived {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
} if profile.opus_payload_ceiling_bytes().is_none() => {
|
||||
TelephonyServiceEvent::AudioFramesReceived {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
}
|
||||
}
|
||||
TelephonyServiceEvent::OpusTransmitStreamStarted { link_id, profile }
|
||||
if profile.opus_payload_ceiling_bytes().is_none() =>
|
||||
{
|
||||
TelephonyServiceEvent::AudioTransmitStreamStarted { link_id, profile }
|
||||
}
|
||||
TelephonyServiceEvent::OpusTransmitStreamStopped {
|
||||
link_id,
|
||||
profile,
|
||||
reason,
|
||||
} if profile.opus_payload_ceiling_bytes().is_none() => {
|
||||
TelephonyServiceEvent::AudioTransmitStreamStopped {
|
||||
link_id,
|
||||
profile,
|
||||
reason,
|
||||
}
|
||||
}
|
||||
TelephonyServiceEvent::OpusReceiveStreamStarted { link_id, profile }
|
||||
if profile.opus_payload_ceiling_bytes().is_none() =>
|
||||
{
|
||||
TelephonyServiceEvent::AudioReceiveStreamStarted { link_id, profile }
|
||||
}
|
||||
TelephonyServiceEvent::OpusReceiveStreamStopped {
|
||||
link_id,
|
||||
profile,
|
||||
reason,
|
||||
} if profile.opus_payload_ceiling_bytes().is_none() => {
|
||||
TelephonyServiceEvent::AudioReceiveStreamStopped {
|
||||
link_id,
|
||||
profile,
|
||||
reason,
|
||||
}
|
||||
}
|
||||
TelephonyServiceEvent::OpusReceiveStreamFrames {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
dropped,
|
||||
} if profile.opus_payload_ceiling_bytes().is_none() => {
|
||||
TelephonyServiceEvent::AudioReceiveStreamFrames {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
dropped,
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
event_tx.send(event).await.is_ok()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Host PCM adapter. The same bounded native Codec2 backend and packet framing
|
||||
//! as handheld firmware; original Opus controls/events remain compatible.
|
||||
use crate::Error;
|
||||
use lxst_codec2::{Codec, Mode};
|
||||
use lxst_core::{
|
||||
AudioCodec, Codec2Backend, Codec2Mode, Codec2PacketCodec, CodecKind, Frame, OpusDecoderState,
|
||||
OpusEncoderState, Profile, RawAudioFrame,
|
||||
};
|
||||
|
||||
struct Native(Box<Codec>);
|
||||
impl Codec2Backend for Native {
|
||||
type Error = &'static str;
|
||||
fn mode(&self) -> Codec2Mode {
|
||||
match self.0.mode() {
|
||||
Mode::Rate1600 => Codec2Mode::Mode1600,
|
||||
Mode::Rate3200 => Codec2Mode::Mode3200,
|
||||
}
|
||||
}
|
||||
fn encode_native(&mut self, pcm: &[i16], bytes: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.0
|
||||
.encode(pcm, bytes)
|
||||
.map_err(|_| "invalid native frame")
|
||||
}
|
||||
fn decode_native(&mut self, bytes: &[u8], pcm: &mut [i16]) -> Result<(), Self::Error> {
|
||||
self.0
|
||||
.decode(bytes, pcm)
|
||||
.map_err(|_| "invalid native frame")
|
||||
}
|
||||
}
|
||||
pub(crate) struct Codec2Audio {
|
||||
codec: Codec2PacketCodec<Native>,
|
||||
pcm: Vec<i16>,
|
||||
}
|
||||
impl Codec2Audio {
|
||||
fn new(profile: Profile) -> Result<Self, Error> {
|
||||
let mode = match profile {
|
||||
Profile::BandwidthVeryLow => Mode::Rate1600,
|
||||
Profile::BandwidthLow => Mode::Rate3200,
|
||||
_ => return Err(Error::Audio("unsupported native Codec2 profile".into())),
|
||||
};
|
||||
let mut storage = Box::<Codec>::new_uninit();
|
||||
Codec::initialise(&mut storage, mode);
|
||||
// SAFETY: initialise completed in final storage above.
|
||||
let backend = Native(unsafe { storage.assume_init() });
|
||||
let codec =
|
||||
Codec2PacketCodec::new(profile, backend).map_err(|e| Error::Audio(e.to_string()))?;
|
||||
Ok(Self {
|
||||
pcm: vec![0; codec.sample_frames()],
|
||||
codec,
|
||||
})
|
||||
}
|
||||
fn encode(&mut self, frame: &RawAudioFrame) -> Result<Frame, Error> {
|
||||
if frame.channels != 1
|
||||
|| frame.samples.len() != self.pcm.len()
|
||||
|| frame.samples.iter().any(|v| !v.is_finite())
|
||||
{
|
||||
return Err(Error::Audio(
|
||||
"invalid Codec2 PCM shape or non-finite sample".into(),
|
||||
));
|
||||
}
|
||||
for (to, from) in self.pcm.iter_mut().zip(&frame.samples) {
|
||||
*to = (from.clamp(-1.0, 1.0) * 32768.0)
|
||||
.round()
|
||||
.clamp(-32768.0, 32767.0) as i16;
|
||||
}
|
||||
let mut payload = vec![0; self.codec.payload_bytes()];
|
||||
let result = self
|
||||
.codec
|
||||
.encode_into(&self.pcm, &mut payload)
|
||||
.map_err(|e| Error::Audio(e.to_string()));
|
||||
self.pcm.fill(0);
|
||||
result?;
|
||||
Ok(Frame::new(CodecKind::Codec2, payload))
|
||||
}
|
||||
fn decode(&mut self, frame: &Frame) -> Result<RawAudioFrame, Error> {
|
||||
if frame.codec != CodecKind::Codec2 {
|
||||
return Err(Error::Audio("unexpected media codec".into()));
|
||||
}
|
||||
self.codec
|
||||
.decode_into(&frame.payload, &mut self.pcm)
|
||||
.map_err(|e| Error::Audio(e.to_string()))?;
|
||||
let samples = self
|
||||
.pcm
|
||||
.iter()
|
||||
.map(|v| f32::from(*v) / 32768.0)
|
||||
.collect::<Vec<_>>();
|
||||
self.pcm.fill(0);
|
||||
Ok(RawAudioFrame {
|
||||
channels: 1,
|
||||
samples,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(crate) enum AudioEncoder {
|
||||
Opus(Box<OpusEncoderState>),
|
||||
Codec2(Codec2Audio),
|
||||
}
|
||||
pub(crate) enum AudioDecoder {
|
||||
Opus(Box<OpusDecoderState>),
|
||||
Codec2(Codec2Audio),
|
||||
}
|
||||
impl AudioEncoder {
|
||||
pub(crate) fn new(profile: Profile) -> Result<Self, Error> {
|
||||
match profile.audio_codec() {
|
||||
AudioCodec::Opus(_) => Ok(Self::Opus(Box::new(OpusEncoderState::new(profile)?))),
|
||||
AudioCodec::Codec2(_) => Ok(Self::Codec2(Codec2Audio::new(profile)?)),
|
||||
}
|
||||
}
|
||||
pub(crate) fn encode_frame(&mut self, frame: &RawAudioFrame) -> Result<Frame, Error> {
|
||||
match self {
|
||||
Self::Opus(codec) => Ok(codec.encode_frame(frame)?),
|
||||
Self::Codec2(codec) => codec.encode(frame),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl AudioDecoder {
|
||||
pub(crate) fn new(profile: Profile) -> Result<Self, Error> {
|
||||
match profile.audio_codec() {
|
||||
AudioCodec::Opus(_) => Ok(Self::Opus(Box::new(OpusDecoderState::new(profile)?))),
|
||||
AudioCodec::Codec2(_) => Ok(Self::Codec2(Codec2Audio::new(profile)?)),
|
||||
}
|
||||
}
|
||||
pub(crate) fn decode_frame(&mut self, frame: &Frame) -> Result<RawAudioFrame, Error> {
|
||||
match self {
|
||||
Self::Opus(codec) => Ok(codec.decode_frame(frame)?),
|
||||
Self::Codec2(codec) => codec.decode(frame),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3941,3 +3941,130 @@ fn outgoing_teardown_is_atomic_final_endpoint_send() {
|
||||
));
|
||||
assert!(transport_rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_codec2_duplex_and_input_lease_use_the_real_link() {
|
||||
use std::sync::Arc;
|
||||
for profile in [Profile::BandwidthVeryLow, Profile::BandwidthLow] {
|
||||
let (mut service, remote, link_id, incoming, mut events, mut transport) =
|
||||
established_outgoing_service_with_transport(profile, 0x95, 32);
|
||||
let gate = Arc::new(AudioTransmitGate::new());
|
||||
let (source, frames) = mpsc::channel(3);
|
||||
assert!(
|
||||
service
|
||||
.handle_control(TelephonyControl::StartAudioStream {
|
||||
link_id,
|
||||
profile,
|
||||
frames,
|
||||
gate: Some(gate.clone())
|
||||
})
|
||||
.await
|
||||
);
|
||||
assert!(matches!(
|
||||
events.recv().await.unwrap(),
|
||||
TelephonyServiceEvent::AudioTransmitStreamStarted { .. }
|
||||
));
|
||||
source
|
||||
.try_send(synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
assert!(service.pump_opus_stream().await);
|
||||
assert!(transport.try_recv().is_err());
|
||||
assert!(gate.update(1, true));
|
||||
// Opening a new lease drops any samples queued before that edge.
|
||||
source
|
||||
.try_send(synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
assert!(service.pump_opus_stream().await);
|
||||
assert!(transport.try_recv().is_err());
|
||||
source
|
||||
.try_send(synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
assert!(service.pump_opus_stream().await);
|
||||
assert!(matches!(
|
||||
events.recv().await.unwrap(),
|
||||
TelephonyServiceEvent::MediaSent { .. }
|
||||
));
|
||||
let (_, encrypted) = take_outbound(&mut transport);
|
||||
let packet = LxstPacket::decode(&remote.decrypt(&encrypted).unwrap()).unwrap();
|
||||
assert_eq!(packet.frames.len(), 1);
|
||||
assert_eq!(packet.frames[0].codec, CodecKind::Codec2);
|
||||
assert_eq!(
|
||||
packet.frames[0].payload.len(),
|
||||
if profile == Profile::BandwidthVeryLow {
|
||||
65
|
||||
} else {
|
||||
81
|
||||
}
|
||||
);
|
||||
let mut decoder = media::AudioDecoder::new(profile).unwrap();
|
||||
assert_eq!(
|
||||
decoder
|
||||
.decode_frame(&packet.frames[0])
|
||||
.unwrap()
|
||||
.sample_frames(),
|
||||
profile.sample_frames_per_packet()
|
||||
);
|
||||
source
|
||||
.try_send(synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
assert!(gate.update(2, false));
|
||||
assert!(!gate.update(1, true));
|
||||
assert!(service.pump_opus_stream().await);
|
||||
assert!(transport.try_recv().is_err());
|
||||
let (sink, mut output) = mpsc::channel(3);
|
||||
service.start_opus_receive_stream(sink).await.unwrap();
|
||||
assert!(matches!(
|
||||
events.recv().await.unwrap(),
|
||||
TelephonyServiceEvent::AudioReceiveStreamStarted { .. }
|
||||
));
|
||||
let mut encoder = media::AudioEncoder::new(profile).unwrap();
|
||||
let frame = encoder
|
||||
.encode_frame(&synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
let encrypted = remote
|
||||
.encrypt(&LxstPacket::frame(frame).encode().unwrap())
|
||||
.unwrap();
|
||||
incoming
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: Bytes::from(link_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::None,
|
||||
&encrypted,
|
||||
)),
|
||||
interface_id: 1,
|
||||
metrics: PacketMetrics::default(),
|
||||
})
|
||||
.unwrap();
|
||||
assert!(service.drive_ready().await);
|
||||
let decoded = output.try_recv().unwrap();
|
||||
assert_eq!(decoded.sample_frames(), profile.sample_frames_per_packet());
|
||||
assert!(
|
||||
decoded
|
||||
.samples
|
||||
.iter()
|
||||
.all(|v| v.is_finite() && (-1.0..=1.0).contains(v))
|
||||
);
|
||||
gate.close();
|
||||
assert!(!gate.update(3, true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_codec2_rejects_bad_shapes_and_mode_without_poisoning_valid_media() {
|
||||
for profile in [Profile::BandwidthVeryLow, Profile::BandwidthLow] {
|
||||
let mut encoder = media::AudioEncoder::new(profile).unwrap();
|
||||
let mut invalid = synthetic_frame_for_profile(profile);
|
||||
invalid.samples[0] = f32::NAN;
|
||||
assert!(encoder.encode_frame(&invalid).is_err());
|
||||
let mut packet = encoder
|
||||
.encode_frame(&synthetic_frame_for_profile(profile))
|
||||
.unwrap();
|
||||
let mut decoder = media::AudioDecoder::new(profile).unwrap();
|
||||
let mode = packet.payload[0];
|
||||
packet.payload[0] ^= 1;
|
||||
assert!(decoder.decode_frame(&packet).is_err());
|
||||
packet.payload[0] = mode;
|
||||
assert!(decoder.decode_frame(&packet).is_ok());
|
||||
}
|
||||
assert!(media::AudioEncoder::new(Profile::BandwidthUltraLow).is_err());
|
||||
}
|
||||
Reference in new issue
Block a user