rtci-stream-driver 0.6.1

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
Documentation
//! Perfect negotiation (feature `peer`): the W3C pattern for two peers that may both offer at
//! once (webrtc-pc section 10.7 "Perfect negotiation example"). One side is *polite*: when
//! offers cross ("glare"), it rolls its own back and answers the peer's; the *impolite* side
//! ignores the peer's colliding offer and waits for the answer to its own. Each side then
//! renegotiates whenever its connection says so, and every collision settles by itself.
//!
//! [`PerfectNegotiation`] is that state machine over an `RTCPeerConnection`, sans I/O: the
//! application calls it on negotiation-needed, on each description and candidate from the
//! peer, and sends what it returns. `parolnet-rtc`'s `polite` setting, and what any
//! application that renegotiates in both directions needs, in one place.
//!
//! The engine's `set_local_description` is synchronous, so the example's `makingOffer` (an
//! offer whose `setLocalDescription` has not finished) never holds here: a collision is an
//! offer that arrives while the signalling state is not `stable`.
//!
//! As in the example, what is sent is the connection's `localDescription` after it was set
//! (with the candidates gathered so far), and the signalling channel must keep each
//! direction's order: a description, then the candidates gathered after it. A candidate that
//! overtakes the description it belongs to finds no remote description
//! (`ErrNoRemoteDescription`) and is an error unless this side ignores the peer's offer; the
//! candidates the impolite side drops with an ignored offer reach it again in the polite
//! side's answer, which carries them.

use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::sdp::{RTCSdpType, RTCSessionDescription};
use rtci::peer_connection::state::RTCSignalingState;
use rtci::peer_connection::transport::RTCIceCandidateInit;
use rtci::shared::error::Result;
use std::time::Instant;

/// The perfect negotiation state of one side (see the [module documentation](self)).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PerfectNegotiation {
    polite: bool,
    ignore_offer: bool,
    collisions: u64,
}

impl PerfectNegotiation {
    /// One side: `polite` rolls back its own offer when offers cross; the other side must be
    /// impolite (one of each, decided by the application: the callee polite, say).
    pub fn new(polite: bool) -> Self {
        Self {
            polite,
            ignore_offer: false,
            collisions: 0,
        }
    }

    /// Whether this side is the polite one.
    pub fn polite(&self) -> bool {
        self.polite
    }

    /// How many colliding offers arrived so far (rolled back for, or ignored).
    pub fn collisions(&self) -> u64 {
        self.collisions
    }

    /// The connection needs negotiation (`OnNegotiationNeededEvent`): in the `stable` state an
    /// offer is created and set as the local description; send it (the local description,
    /// with the candidates gathered so far) to the peer, before any candidate gathered after. `None` while a
    /// negotiation is under way (the connection says so again once it is back in `stable`).
    ///
    /// # Errors
    ///
    /// The offer could not be created or set.
    pub fn on_negotiation_needed(
        &mut self,
        pc: &mut RTCPeerConnection,
        now: Instant,
    ) -> Result<Option<RTCSessionDescription>> {
        if pc.signaling_state() != RTCSignalingState::Stable {
            return Ok(None);
        }
        let offer = pc.create_offer(None)?;
        pc.set_local_description(now, offer.clone())?;
        Ok(Some(pc.local_description().unwrap_or(offer)))
    }

    /// A description from the peer. An offer that collides with this side's own is ignored
    /// by the impolite side (`Ok(None)`), and taken by the polite side after rolling its own
    /// back (W3C webrtc-pc section 4.4.1.5: rollback). An offer taken is answered: send the
    /// answer returned. An answer is applied; nothing to send.
    ///
    /// # Errors
    ///
    /// The description could not be applied, or the answer created.
    pub fn on_remote_description(
        &mut self,
        pc: &mut RTCPeerConnection,
        now: Instant,
        description: RTCSessionDescription,
    ) -> Result<Option<RTCSessionDescription>> {
        let offer = description.sdp_type == RTCSdpType::Offer;
        let collision = offer && pc.signaling_state() != RTCSignalingState::Stable;
        if collision {
            self.collisions += 1;
        }
        self.ignore_offer = !self.polite && collision;
        if self.ignore_offer {
            return Ok(None);
        }
        if collision {
            pc.set_local_description(now, RTCSessionDescription::rollback(None)?)?;
        }
        pc.set_remote_description(now, description)?;
        if !offer {
            return Ok(None);
        }
        let answer = pc.create_answer(None)?;
        pc.set_local_description(now, answer.clone())?;
        Ok(Some(pc.local_description().unwrap_or(answer)))
    }

    /// A candidate from the peer, delivered after the description it follows. One that fails
    /// while this side ignores the peer's offer belongs to that offer and is dropped, as the
    /// W3C example does.
    ///
    /// # Errors
    ///
    /// The connection refused the candidate otherwise (`ErrNoRemoteDescription` for one
    /// delivered ahead of the peer's description: the signalling reordered them).
    pub fn on_remote_candidate(
        &mut self,
        pc: &mut RTCPeerConnection,
        candidate: RTCIceCandidateInit,
    ) -> Result<()> {
        match pc.add_remote_candidate(candidate) {
            Err(e) if !self.ignore_offer => Err(e),
            _ => Ok(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rtci::peer_connection::RTCPeerConnectionBuilder;

    fn pc(now: Instant) -> RTCPeerConnection {
        RTCPeerConnectionBuilder::new()
            .build(now)
            .expect("a connection")
    }

    // W3C webrtc-pc 10.7: both sides offer at once; the polite one rolls back and answers,
    // the impolite one ignores the colliding offer; both end stable, and the polite side's
    // own change is negotiated next.
    #[test]
    fn crossing_offers_settle_with_the_polite_side_rolling_back() {
        let now = Instant::now();
        let (mut polite_pc, mut impolite_pc) = (pc(now), pc(now));
        let (mut polite, mut impolite) = (
            PerfectNegotiation::new(true),
            PerfectNegotiation::new(false),
        );
        polite_pc.create_data_channel("p", None).unwrap();
        impolite_pc.create_data_channel("i", None).unwrap();
        let from_polite = polite
            .on_negotiation_needed(&mut polite_pc, now)
            .unwrap()
            .expect("an offer");
        let from_impolite = impolite
            .on_negotiation_needed(&mut impolite_pc, now)
            .unwrap()
            .expect("an offer");

        // The offers cross.
        assert!(
            impolite
                .on_remote_description(&mut impolite_pc, now, from_polite)
                .unwrap()
                .is_none(),
            "the impolite side ignores the colliding offer"
        );
        let answer = polite
            .on_remote_description(&mut polite_pc, now, from_impolite)
            .unwrap()
            .expect("the polite side answers");
        assert_eq!(polite_pc.signaling_state(), RTCSignalingState::Stable);
        assert!(
            impolite
                .on_remote_description(&mut impolite_pc, now, answer)
                .unwrap()
                .is_none()
        );
        assert_eq!(impolite_pc.signaling_state(), RTCSignalingState::Stable);
        assert_eq!((polite.collisions(), impolite.collisions()), (1, 1));

        // The polite side's rolled-back change goes out now.
        let again = polite
            .on_negotiation_needed(&mut polite_pc, now)
            .unwrap()
            .expect("the polite side offers again");
        let answer = impolite
            .on_remote_description(&mut impolite_pc, now, again)
            .unwrap()
            .expect("taken: no collision");
        polite
            .on_remote_description(&mut polite_pc, now, answer)
            .unwrap();
        assert_eq!(polite_pc.signaling_state(), RTCSignalingState::Stable);
        assert_eq!(impolite_pc.signaling_state(), RTCSignalingState::Stable);
    }

    // No negotiation starts while one is under way.
    #[test]
    fn negotiation_needed_waits_for_stable() {
        let now = Instant::now();
        let mut a = pc(now);
        let mut side = PerfectNegotiation::new(false);
        a.create_data_channel("a", None).unwrap();
        assert!(side.on_negotiation_needed(&mut a, now).unwrap().is_some());
        assert!(side.on_negotiation_needed(&mut a, now).unwrap().is_none());
    }
}