use crate::stream_info::StreamInfo;
use crate::{Attribute, Interceptor, Packet, TaggedPacket};
use rtp::extension::ntp_timestamp_extension::{
NTP_56_URI, NTP_64_URI, Ntp56Extension, Ntp64Extension,
};
use sansio::Protocol;
use shared::error::Error;
use shared::marshal::Marshal;
use shared::time::SystemInstant;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};
pub const NTP_TIMESTAMP_SLOT: usize = 1_850;
pub const NTP_TIMESTAMP_INITIAL_WINDOW: Duration = Duration::from_secs(5);
pub const NTP_TIMESTAMP_INTERVAL: Duration = Duration::from_secs(1);
#[derive(Debug, Clone)]
pub struct NtpTimestampBuilder {
initial_window: Duration,
interval: Duration,
wall_clock: Option<SystemInstant>,
}
impl Default for NtpTimestampBuilder {
fn default() -> Self {
Self {
initial_window: NTP_TIMESTAMP_INITIAL_WINDOW,
interval: NTP_TIMESTAMP_INTERVAL,
wall_clock: None,
}
}
}
impl NtpTimestampBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn with_initial_window(mut self, window: Duration) -> Self {
self.initial_window = window;
self
}
pub fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
self.wall_clock = Some(anchor);
self
}
pub fn build(self) -> NtpTimestampInterceptor {
NtpTimestampInterceptor {
initial_window: self.initial_window,
interval: self.interval,
wall_clock: self.wall_clock,
streams: HashMap::new(),
read_queue: VecDeque::new(),
write_queue: VecDeque::new(),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Stamped {
id: u8,
short: bool,
first_packet: Option<Instant>,
last_frame: Option<(u32, Instant)>,
}
pub struct NtpTimestampInterceptor {
initial_window: Duration,
interval: Duration,
wall_clock: Option<SystemInstant>,
streams: HashMap<u32, Stamped>,
read_queue: VecDeque<TaggedPacket>,
write_queue: VecDeque<TaggedPacket>,
}
impl NtpTimestampInterceptor {
pub fn new() -> Self {
NtpTimestampBuilder::new().build()
}
fn wanted(&self, stream: &mut Stamped, timestamp: u32, now: Instant) -> bool {
let first = *stream.first_packet.get_or_insert(now);
if now.saturating_duration_since(first) < self.initial_window {
return true;
}
match stream.last_frame {
Some((frame, _)) if frame == timestamp => true,
Some((_, at)) if now.saturating_duration_since(at) < self.interval => false,
_ => {
stream.last_frame = Some((timestamp, now));
true
}
}
}
}
impl Default for NtpTimestampInterceptor {
fn default() -> Self {
Self::new()
}
}
impl Protocol<TaggedPacket, TaggedPacket, ()> for NtpTimestampInterceptor {
type Rout = TaggedPacket;
type Wout = TaggedPacket;
type Eout = ();
type Error = Error;
type Time = Instant;
fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
self.read_queue.push_back(msg);
Ok(())
}
fn poll_read(&mut self) -> Option<Self::Rout> {
self.read_queue.pop_front()
}
fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
let retransmission = msg
.message
.attributes
.iter()
.any(|attribute| matches!(attribute, Attribute::Retransmission));
if let Packet::Rtp(packet) = &mut msg.message.packet
&& !retransmission
&& let Some(mut stream) = self.streams.get(&packet.header.ssrc).copied()
{
if self.wanted(&mut stream, packet.header.timestamp, msg.now) {
let ntp = self
.wall_clock
.unwrap_or_else(|| SystemInstant::shared(msg.now))
.ntp(msg.now);
let value = if stream.short {
Ntp56Extension::new(ntp).marshal()
} else {
Ntp64Extension { ntp_time: ntp }.marshal()
};
if let Ok(value) = value {
let _ = packet
.header
.set_extension_upgrading(stream.id, value.freeze());
}
}
self.streams.insert(packet.header.ssrc, stream);
}
self.write_queue.push_back(msg);
Ok(())
}
fn poll_write(&mut self) -> Option<Self::Wout> {
self.write_queue.pop_front()
}
fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
Ok(())
}
fn poll_timeout(&mut self) -> Option<Self::Time> {
None
}
}
impl Interceptor for NtpTimestampInterceptor {
fn bind_local_stream(&mut self, info: &StreamInfo) {
let id = |uri: &str| {
info.rtp_header_extensions
.iter()
.find(|ext| ext.uri == uri)
.and_then(|ext| u8::try_from(ext.id).ok())
.filter(|id| *id != 0)
};
let negotiated = id(NTP_64_URI)
.map(|id| (id, false))
.or_else(|| id(NTP_56_URI).map(|id| (id, true)));
match negotiated {
Some((id, short)) => {
self.streams.entry(info.ssrc).or_insert(Stamped {
id,
short,
first_packet: None,
last_frame: None,
});
}
None => {
self.streams.remove(&info.ssrc);
}
}
}
fn unbind_local_stream(&mut self, info: &StreamInfo) {
self.streams.remove(&info.ssrc);
}
fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
}