rtci_stream_driver/negotiation.rs
1//! Perfect negotiation (feature `peer`): the W3C pattern for two peers that may both offer at
2//! once (webrtc-pc section 10.7 "Perfect negotiation example"). One side is *polite*: when
3//! offers cross ("glare"), it rolls its own back and answers the peer's; the *impolite* side
4//! ignores the peer's colliding offer and waits for the answer to its own. Each side then
5//! renegotiates whenever its connection says so, and every collision settles by itself.
6//!
7//! [`PerfectNegotiation`] is that state machine over an `RTCPeerConnection`, sans I/O: the
8//! application calls it on negotiation-needed, on each description and candidate from the
9//! peer, and sends what it returns. `parolnet-rtc`'s `polite` setting, and what any
10//! application that renegotiates in both directions needs, in one place.
11//!
12//! The engine's `set_local_description` is synchronous, so the example's `makingOffer` (an
13//! offer whose `setLocalDescription` has not finished) never holds here: a collision is an
14//! offer that arrives while the signalling state is not `stable`.
15//!
16//! As in the example, what is sent is the connection's `localDescription` after it was set
17//! (with the candidates gathered so far), and the signalling channel must keep each
18//! direction's order: a description, then the candidates gathered after it. A candidate that
19//! overtakes the description it belongs to finds no remote description
20//! (`ErrNoRemoteDescription`) and is an error unless this side ignores the peer's offer; the
21//! candidates the impolite side drops with an ignored offer reach it again in the polite
22//! side's answer, which carries them.
23
24use rtci::peer_connection::RTCPeerConnection;
25use rtci::peer_connection::sdp::{RTCSdpType, RTCSessionDescription};
26use rtci::peer_connection::state::RTCSignalingState;
27use rtci::peer_connection::transport::RTCIceCandidateInit;
28use rtci::shared::error::Result;
29use std::time::Instant;
30
31/// The perfect negotiation state of one side (see the [module documentation](self)).
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct PerfectNegotiation {
34 polite: bool,
35 ignore_offer: bool,
36 collisions: u64,
37}
38
39impl PerfectNegotiation {
40 /// One side: `polite` rolls back its own offer when offers cross; the other side must be
41 /// impolite (one of each, decided by the application: the callee polite, say).
42 pub fn new(polite: bool) -> Self {
43 Self {
44 polite,
45 ignore_offer: false,
46 collisions: 0,
47 }
48 }
49
50 /// Whether this side is the polite one.
51 pub fn polite(&self) -> bool {
52 self.polite
53 }
54
55 /// How many colliding offers arrived so far (rolled back for, or ignored).
56 pub fn collisions(&self) -> u64 {
57 self.collisions
58 }
59
60 /// The connection needs negotiation (`OnNegotiationNeededEvent`): in the `stable` state an
61 /// offer is created and set as the local description; send it (the local description,
62 /// with the candidates gathered so far) to the peer, before any candidate gathered after. `None` while a
63 /// negotiation is under way (the connection says so again once it is back in `stable`).
64 ///
65 /// # Errors
66 ///
67 /// The offer could not be created or set.
68 pub fn on_negotiation_needed(
69 &mut self,
70 pc: &mut RTCPeerConnection,
71 now: Instant,
72 ) -> Result<Option<RTCSessionDescription>> {
73 if pc.signaling_state() != RTCSignalingState::Stable {
74 return Ok(None);
75 }
76 let offer = pc.create_offer(None)?;
77 pc.set_local_description(now, offer.clone())?;
78 Ok(Some(pc.local_description().unwrap_or(offer)))
79 }
80
81 /// A description from the peer. An offer that collides with this side's own is ignored
82 /// by the impolite side (`Ok(None)`), and taken by the polite side after rolling its own
83 /// back (W3C webrtc-pc section 4.4.1.5: rollback). An offer taken is answered: send the
84 /// answer returned. An answer is applied; nothing to send.
85 ///
86 /// # Errors
87 ///
88 /// The description could not be applied, or the answer created.
89 pub fn on_remote_description(
90 &mut self,
91 pc: &mut RTCPeerConnection,
92 now: Instant,
93 description: RTCSessionDescription,
94 ) -> Result<Option<RTCSessionDescription>> {
95 let offer = description.sdp_type == RTCSdpType::Offer;
96 let collision = offer && pc.signaling_state() != RTCSignalingState::Stable;
97 if collision {
98 self.collisions += 1;
99 }
100 self.ignore_offer = !self.polite && collision;
101 if self.ignore_offer {
102 return Ok(None);
103 }
104 if collision {
105 pc.set_local_description(now, RTCSessionDescription::rollback(None)?)?;
106 }
107 pc.set_remote_description(now, description)?;
108 if !offer {
109 return Ok(None);
110 }
111 let answer = pc.create_answer(None)?;
112 pc.set_local_description(now, answer.clone())?;
113 Ok(Some(pc.local_description().unwrap_or(answer)))
114 }
115
116 /// A candidate from the peer, delivered after the description it follows. One that fails
117 /// while this side ignores the peer's offer belongs to that offer and is dropped, as the
118 /// W3C example does.
119 ///
120 /// # Errors
121 ///
122 /// The connection refused the candidate otherwise (`ErrNoRemoteDescription` for one
123 /// delivered ahead of the peer's description: the signalling reordered them).
124 pub fn on_remote_candidate(
125 &mut self,
126 pc: &mut RTCPeerConnection,
127 candidate: RTCIceCandidateInit,
128 ) -> Result<()> {
129 match pc.add_remote_candidate(candidate) {
130 Err(e) if !self.ignore_offer => Err(e),
131 _ => Ok(()),
132 }
133 }
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139 use rtci::peer_connection::RTCPeerConnectionBuilder;
140
141 fn pc(now: Instant) -> RTCPeerConnection {
142 RTCPeerConnectionBuilder::new()
143 .build(now)
144 .expect("a connection")
145 }
146
147 // W3C webrtc-pc 10.7: both sides offer at once; the polite one rolls back and answers,
148 // the impolite one ignores the colliding offer; both end stable, and the polite side's
149 // own change is negotiated next.
150 #[test]
151 fn crossing_offers_settle_with_the_polite_side_rolling_back() {
152 let now = Instant::now();
153 let (mut polite_pc, mut impolite_pc) = (pc(now), pc(now));
154 let (mut polite, mut impolite) = (
155 PerfectNegotiation::new(true),
156 PerfectNegotiation::new(false),
157 );
158 polite_pc.create_data_channel("p", None).unwrap();
159 impolite_pc.create_data_channel("i", None).unwrap();
160 let from_polite = polite
161 .on_negotiation_needed(&mut polite_pc, now)
162 .unwrap()
163 .expect("an offer");
164 let from_impolite = impolite
165 .on_negotiation_needed(&mut impolite_pc, now)
166 .unwrap()
167 .expect("an offer");
168
169 // The offers cross.
170 assert!(
171 impolite
172 .on_remote_description(&mut impolite_pc, now, from_polite)
173 .unwrap()
174 .is_none(),
175 "the impolite side ignores the colliding offer"
176 );
177 let answer = polite
178 .on_remote_description(&mut polite_pc, now, from_impolite)
179 .unwrap()
180 .expect("the polite side answers");
181 assert_eq!(polite_pc.signaling_state(), RTCSignalingState::Stable);
182 assert!(
183 impolite
184 .on_remote_description(&mut impolite_pc, now, answer)
185 .unwrap()
186 .is_none()
187 );
188 assert_eq!(impolite_pc.signaling_state(), RTCSignalingState::Stable);
189 assert_eq!((polite.collisions(), impolite.collisions()), (1, 1));
190
191 // The polite side's rolled-back change goes out now.
192 let again = polite
193 .on_negotiation_needed(&mut polite_pc, now)
194 .unwrap()
195 .expect("the polite side offers again");
196 let answer = impolite
197 .on_remote_description(&mut impolite_pc, now, again)
198 .unwrap()
199 .expect("taken: no collision");
200 polite
201 .on_remote_description(&mut polite_pc, now, answer)
202 .unwrap();
203 assert_eq!(polite_pc.signaling_state(), RTCSignalingState::Stable);
204 assert_eq!(impolite_pc.signaling_state(), RTCSignalingState::Stable);
205 }
206
207 // No negotiation starts while one is under way.
208 #[test]
209 fn negotiation_needed_waits_for_stable() {
210 let now = Instant::now();
211 let mut a = pc(now);
212 let mut side = PerfectNegotiation::new(false);
213 a.create_data_channel("a", None).unwrap();
214 assert!(side.on_negotiation_needed(&mut a, now).unwrap().is_some());
215 assert!(side.on_negotiation_needed(&mut a, now).unwrap().is_none());
216 }
217}