use bytes::Bytes;
use crossbeam_queue::ArrayQueue;
use std::sync::Arc;
use std::time::{Duration, Instant};
pub const SAMPLE_RATE: u32 = 48_000;
pub const FRAME_MS: u32 = 20;
pub const FRAME_SAMPLES: usize = 960;
pub(crate) const BLOCK_SAMPLES: usize = 480;
#[derive(Clone, Debug, PartialEq)]
pub struct EncodedFrame {
pub payload: Bytes,
pub ts48k: u32,
pub dtx: bool,
pub vad: bool,
pub level_dbov: f32,
}
#[derive(Clone, Debug)]
pub struct RecvFrame {
pub participant: u64,
pub payload: Bytes,
pub seq: u16,
pub ts48k: u32,
pub arrival: Instant,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncoderCfg {
pub bitrate_bps: u32,
pub fec: bool,
pub dtx: bool,
pub complexity: u8,
}
pub const FEC_LOSS_HINT_PCT: u8 = 10;
impl Default for EncoderCfg {
fn default() -> Self {
EncoderCfg {
bitrate_bps: 32_000,
fec: true,
dtx: true,
complexity: 9,
}
}
}
#[derive(Clone)]
pub struct FrameRx {
pub(crate) q: Arc<ArrayQueue<EncodedFrame>>,
}
impl FrameRx {
pub fn try_recv(&self) -> Option<EncodedFrame> {
self.q.pop()
}
pub fn recv_timeout(&self, timeout: Duration) -> Option<EncodedFrame> {
let deadline = Instant::now() + timeout;
loop {
if let Some(f) = self.q.pop() {
return Some(f);
}
if Instant::now() >= deadline {
return None;
}
std::thread::sleep(Duration::from_millis(1));
}
}
pub fn len(&self) -> usize {
self.q.len()
}
pub fn is_empty(&self) -> bool {
self.q.is_empty()
}
pub fn capacity(&self) -> usize {
self.q.capacity()
}
}
impl std::fmt::Debug for FrameRx {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameRx")
.field("len", &self.q.len())
.field("capacity", &self.q.capacity())
.finish()
}
}
pub(crate) fn dbov(x: &[f32]) -> f32 {
if x.is_empty() {
return -127.0;
}
let ms: f64 = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
dbov_from_mean_square(ms)
}
pub(crate) fn dbov_from_mean_square(ms: f64) -> f32 {
if ms <= 1e-13 {
return -127.0;
}
((10.0 * ms.log10()) as f32).clamp(-127.0, 0.0)
}