#[cfg(test)]
mod tone_test;
use bytes::{BufMut, Bytes, BytesMut};
use shared::error::{Error, Result};
use super::red::RedEncoder;
pub const TONE_DEFAULT_CLOCK_RATE: u32 = 8000;
const MAX_MODULATION: u16 = 0x01FF;
const MAX_VOLUME: u8 = 0x3F;
const MAX_FREQUENCY: u16 = 0x0FFF;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Tone {
pub modulation: u16,
pub modulation_divided_by_three: bool,
pub volume: u8,
pub duration: u16,
pub frequencies: Vec<u16>,
}
impl Tone {
pub fn marshal(&self) -> Result<Bytes> {
if self.modulation > MAX_MODULATION
|| self.volume > MAX_VOLUME
|| self.duration == 0
|| self.frequencies.iter().any(|f| *f > MAX_FREQUENCY)
{
return Err(Error::Other(format!("not a valid tone: {self:?}")));
}
let mut out = BytesMut::with_capacity(4 + 2 * self.frequencies.len());
out.put_u16(
(self.modulation << 7)
| (u16::from(self.modulation_divided_by_three) << 6)
| u16::from(self.volume),
);
out.put_u16(self.duration);
for frequency in &self.frequencies {
out.put_u16(*frequency);
}
Ok(out.freeze())
}
pub fn unmarshal(payload: &[u8]) -> Option<Tone> {
if payload.len() < 4 || !payload.len().is_multiple_of(2) {
return None;
}
let first = u16::from_be_bytes([payload[0], payload[1]]);
let duration = u16::from_be_bytes([payload[2], payload[3]]);
if duration == 0 {
return None;
}
Some(Tone {
modulation: first >> 7,
modulation_divided_by_three: first & 0x40 != 0,
volume: (first & 0x3F) as u8,
duration,
frequencies: payload[4..]
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_be_bytes(*pair) & MAX_FREQUENCY)
.collect(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TonePacket {
pub timestamp: u32,
pub marker: bool,
pub payload: Bytes,
}
#[derive(Debug, Clone, Copy)]
pub struct ToneSender {
pub packet_duration: u16,
}
impl ToneSender {
pub fn packets(&self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
let step = u32::from(self.packet_duration.max(1));
let mut packets = vec![];
let mut at = 0u32;
while at < total {
let duration = (total - at).min(step) as u16;
let report = Tone {
duration,
..tone.clone()
};
packets.push(TonePacket {
timestamp: timestamp.wrapping_add(at),
marker: packets.is_empty(),
payload: report.marshal()?,
});
at += u32::from(duration);
}
Ok(packets)
}
}
pub const TONE_HIGH_LOSS_FRACTION: u8 = 26;
pub const TONE_LOW_LOSS_FRACTION: u8 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ToneIntervalControl {
initial: u16,
maximum: u16,
max_increase: u16,
high_loss: u8,
low_loss: u8,
current: u16,
}
impl ToneIntervalControl {
pub fn new(initial: u16, maximum: u16, max_increase: u16) -> Self {
let initial = initial.max(1);
ToneIntervalControl {
initial,
maximum: maximum.max(initial),
max_increase: max_increase.max(1),
high_loss: TONE_HIGH_LOSS_FRACTION,
low_loss: TONE_LOW_LOSS_FRACTION,
current: initial,
}
}
pub fn with_loss_thresholds(mut self, high: u8, low: u8) -> Self {
self.high_loss = high;
self.low_loss = low;
self
}
pub fn packet_duration(&self) -> u16 {
self.current
}
pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
if fraction_lost >= self.high_loss {
self.current = self
.current
.saturating_add(self.max_increase)
.min(self.maximum);
} else if fraction_lost <= self.low_loss {
self.current = self
.current
.saturating_sub(self.max_increase)
.max(self.initial);
}
self.current
}
pub fn sender(&self) -> ToneSender {
ToneSender {
packet_duration: self.current,
}
}
}
pub const TONE_DEFAULT_REDUNDANCY: usize = 1;
pub const TONE_DEFAULT_MAX_PAYLOAD_SIZE: usize = 1000;
#[derive(Debug, Clone)]
pub struct RedundantToneSender {
tone_payload_type: u8,
red_payload_type: u8,
control: ToneIntervalControl,
max_payload_size: usize,
red: RedEncoder,
}
impl RedundantToneSender {
pub fn new(
tone_payload_type: u8,
red_payload_type: u8,
control: ToneIntervalControl,
) -> Result<Self> {
if tone_payload_type > 0x7F || red_payload_type > 0x7F {
return Err(Error::Other(format!(
"payload types {tone_payload_type} / {red_payload_type}: more than 127"
)));
}
Ok(RedundantToneSender {
tone_payload_type,
red_payload_type,
control,
max_payload_size: TONE_DEFAULT_MAX_PAYLOAD_SIZE,
red: RedEncoder::new(TONE_DEFAULT_REDUNDANCY, TONE_DEFAULT_MAX_PAYLOAD_SIZE),
})
}
pub fn with_redundancy(mut self, levels: usize) -> Self {
self.red = RedEncoder::new(levels, self.max_payload_size);
self
}
pub fn payload_type(&self) -> u8 {
self.red_payload_type
}
pub fn control(&self) -> &ToneIntervalControl {
&self.control
}
pub fn on_receiver_report(&mut self, fraction_lost: u8) -> u16 {
self.control.on_receiver_report(fraction_lost)
}
pub fn reset(&mut self) {
self.red.reset();
}
pub fn packets(&mut self, tone: &Tone, timestamp: u32, total: u32) -> Result<Vec<TonePacket>> {
let plain = self.control.sender().packets(tone, timestamp, total)?;
plain
.into_iter()
.map(|packet| {
Ok(TonePacket {
payload: self.red.encode(
self.tone_payload_type,
packet.timestamp,
packet.payload,
)?,
..packet
})
})
.collect()
}
}