rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
//! RFC 7164 section 5, the receive side: "generating or using NTP timestamps during the entire
//! last second of a day on which a positive leap second has been scheduled SHOULD be avoided",
//! and section 5.1 lets a receiver assume one at the end of every month. A received RFC 6051
//! `ntp-64` timestamp from the two seconds around a month end does not become the stream's
//! RTP-to-NTP mapping, and a received `abs-capture-time` from there gives the source no
//! capture time; the same values outside the window are used.

use super::*;
use crate::media_stream::track::MediaStreamTrack;
use crate::rtp_transceiver::rtp_sender::{
    RTCRtpCodec, RTCRtpCodecParameters, RTCRtpEncodingParameters, RtpCodecKind,
};
use crate::rtp_transceiver::{RTCRtpTransceiverDirection, RTCRtpTransceiverInit};
use bytes::Bytes;
use interceptor::Registry;
use sansio::Protocol as _;
use shared::TransportContext;
use shared::marshal::Marshal;
use shared::time::near_leap_second;

const SSRC: u32 = 1000;
const PT: u8 = 111;
const NTP_64_ID: u8 = 5;
const ABS_CAPTURE_TIME_ID: u8 = 6;

/// NTP seconds of 2026-12-31 23:59:59 UTC (the last second of a month) and of 2026-12-15
/// 12:00:00 UTC (the middle of one).
const LAST_SECOND_OF_DECEMBER: u64 = 4_007_750_399;
const MID_DECEMBER: u64 = 4_006_324_800;

fn ntp(seconds: u64, fraction: u32) -> u64 {
    (seconds << 32) | u64::from(fraction)
}

fn opus() -> RTCRtpCodecParameters {
    RTCRtpCodecParameters {
        rtp_codec: RTCRtpCodec {
            mime_type: "audio/opus".to_owned(),
            clock_rate: 48_000,
            channels: 2,
            sdp_fmtp_line: String::new(),
            rtcp_feedback: vec![],
        },
        payload_type: PT,
    }
}

fn coding() -> RTCRtpCodingParameters {
    RTCRtpCodingParameters {
        rid: String::new(),
        ssrc: Some(SSRC),
        rtx: None,
        fec: None,
        ..Default::default()
    }
}

fn transceiver() -> RTCRtpTransceiverInternal {
    let mut transceiver = RTCRtpTransceiverInternal::new(
        RtpCodecKind::Audio,
        None,
        RTCRtpTransceiverInit {
            direction: RTCRtpTransceiverDirection::Recvonly,
            streams: vec![],
            send_encodings: vec![],
        },
    );
    let receiver = transceiver.receiver_mut().as_mut().unwrap();
    receiver.set_coding_parameters(vec![coding()]);
    receiver.set_codec_preferences(vec![opus()]);
    receiver.set_track(MediaStreamTrack::new(
        "stream".to_string(),
        "track".to_string(),
        "label".to_string(),
        RtpCodecKind::Audio,
        vec![RTCRtpEncodingParameters {
            rtp_coding_parameters: coding(),
            active: true,
            codec: RTCRtpCodec::default(),
            max_bitrate: 0,
            max_framerate: None,
            scale_resolution_down_by: None,
            priority: Default::default(),
            network_priority: None,
            scalability_mode: None,
            scale_resolution_down_to: None,
            ptime: None,
            adaptive_ptime: false,
        }],
    ));
    transceiver
}

fn media_engine() -> MediaEngine {
    let mut media_engine = MediaEngine::default();
    media_engine
        .register_codec(opus(), RtpCodecKind::Audio)
        .expect("opus");
    for (uri, id) in [
        (rtp::extension::NTP_64_URI, NTP_64_ID),
        (rtp::extension::ABS_CAPTURE_TIME_URI, ABS_CAPTURE_TIME_ID),
    ] {
        media_engine
            .register_header_extension(
                RTCRtpHeaderExtensionCapability {
                    uri: uri.to_owned(),
                },
                RtpCodecKind::Audio,
                None,
            )
            .expect("extension");
        media_engine
            .update_header_extension(u16::from(id), uri, RtpCodecKind::Audio)
            .expect("negotiate the extension");
    }
    media_engine
}

/// What one packet carries: an `ntp-64` timestamp, an `abs-capture-time` capture time.
#[derive(Default, Clone, Copy)]
struct Stamps {
    ntp_64: Option<u64>,
    capture: Option<u64>,
}

/// After each of `packets` (one 20 ms apart, sequence numbers from 1) passed the handler: the
/// stream's in-band NTP mapping (its NTP timestamp) and the synchronization source's capture
/// time.
fn after_each(packets: &[Stamps]) -> Vec<(Option<u64>, Option<f64>)> {
    let media_engine = media_engine();
    let mut transceivers = vec![transceiver()];
    let mut stats = RTCStatsAccumulator::new();
    let mut ctx = InterceptorHandlerContext {
        is_dtls_handshake_complete: true,
        ..Default::default()
    };
    let mut chain = Registry::new().build();
    let base = Instant::now();
    let mut seen = Vec::new();
    for (i, stamps) in packets.iter().enumerate() {
        let mut header = rtp::Header {
            version: 2,
            payload_type: PT,
            sequence_number: 1 + i as u16,
            timestamp: 960 * (1 + i as u32),
            ssrc: SSRC,
            ..Default::default()
        };
        if let Some(ntp_time) = stamps.ntp_64 {
            let value = rtp::extension::ntp_timestamp_extension::Ntp64Extension { ntp_time }
                .marshal()
                .expect("ntp-64");
            header
                .set_extension(NTP_64_ID, value.freeze())
                .expect("extension");
        }
        if let Some(timestamp) = stamps.capture {
            let value = rtp::extension::abs_capture_time_extension::AbsCaptureTimeExtension {
                timestamp,
                estimated_capture_clock_offset: None,
            }
            .marshal()
            .expect("abs-capture-time");
            header
                .set_extension(ABS_CAPTURE_TIME_ID, value.freeze())
                .expect("extension");
        }
        {
            let mut handler = InterceptorHandler::new(
                &mut ctx,
                &mut transceivers,
                &media_engine,
                &mut chain,
                &mut stats,
                None,
            );
            handler
                .handle_read(TaggedRTCMessageInternal {
                    now: base + Duration::from_millis(20 * i as u64),
                    transport: TransportContext::default(),
                    message: RTCMessageInternal::Rtp(RTPMessage::Packet(Packet::Rtp(
                        rtp::Packet {
                            header,
                            payload: Bytes::from_static(&[1, 2, 3]),
                        },
                    ))),
                })
                .expect("handle_read");
            while handler.poll_read().is_some() {}
        }
        let mapping = stats
            .inbound_rtp_streams
            .get(&SSRC)
            .and_then(|stream| stream.in_band_ntp)
            .map(|(ntp, _, _)| ntp);
        let capture = transceivers[0]
            .receiver()
            .as_ref()
            .and_then(|receiver| receiver.get_synchronization_sources().next())
            .and_then(|source| source.capture_timestamp);
        seen.push((mapping, capture));
    }
    seen
}

#[test]
fn the_window_is_the_two_seconds_around_the_end_of_a_month() {
    // The constants are what the tests below take them for.
    assert!(near_leap_second(ntp(LAST_SECOND_OF_DECEMBER, 1 << 31)));
    assert!(near_leap_second(ntp(LAST_SECOND_OF_DECEMBER + 1, 1 << 31)));
    assert!(!near_leap_second(ntp(LAST_SECOND_OF_DECEMBER - 1, 1 << 31)));
    assert!(!near_leap_second(ntp(MID_DECEMBER, 0)));
}

#[test]
fn an_in_band_ntp_timestamp_near_a_leap_second_is_not_used() {
    let before = ntp(MID_DECEMBER, 0);
    let seen = after_each(&[
        Stamps {
            ntp_64: Some(before),
            ..Default::default()
        },
        Stamps {
            ntp_64: Some(ntp(LAST_SECOND_OF_DECEMBER, 1 << 31)),
            ..Default::default()
        },
        Stamps {
            ntp_64: Some(ntp(LAST_SECOND_OF_DECEMBER + 1, 1 << 30)),
            ..Default::default()
        },
        Stamps {
            ntp_64: Some(ntp(LAST_SECOND_OF_DECEMBER + 2, 0)),
            ..Default::default()
        },
    ]);
    let mappings: Vec<Option<u64>> = seen.iter().map(|(mapping, _)| *mapping).collect();
    assert_eq!(
        mappings,
        vec![
            // A timestamp outside the window is taken (the precondition: the stream exists and
            // reads the element).
            Some(before),
            // 23:59:59.5 and 00:00:00.25: the mapping stays as it was.
            Some(before),
            Some(before),
            // 00:00:01 is past the window: taken.
            Some(ntp(LAST_SECOND_OF_DECEMBER + 2, 0)),
        ]
    );
}

#[test]
fn an_absolute_capture_time_near_a_leap_second_is_not_used() {
    // Outside the window: the source's capture time is the element's, in milliseconds on the
    // NTP clock.
    let seen = after_each(&[Stamps {
        capture: Some(ntp(MID_DECEMBER, 0)),
        ..Default::default()
    }]);
    let expected = MID_DECEMBER as f64 * 1000.0;
    let capture = seen[0]
        .1
        .expect("a capture time outside the window is used");
    assert!(
        (capture - expected).abs() < 1.0,
        "{capture} against {expected}"
    );

    // Inside it, on a source that had none: none.
    for at in [
        ntp(LAST_SECOND_OF_DECEMBER, 1 << 31),
        ntp(LAST_SECOND_OF_DECEMBER + 1, 1 << 30),
    ] {
        let seen = after_each(&[Stamps {
            capture: Some(at),
            ..Default::default()
        }]);
        assert_eq!(seen[0].1, None, "a capture time in the window is not used");
    }
}