-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathnative.rs
More file actions
276 lines (238 loc) · 7.94 KB
/
Copy pathnative.rs
File metadata and controls
276 lines (238 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! Native WebRTC client surface (INTERFACE_DESIGN §15.3).
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use rvoip_core::capability::CapabilityDescriptor;
use rvoip_core::ids::{ConnectionId, SessionId};
use webrtc::data_channel::DataChannel;
use webrtc::peer_connection::{RTCIceCandidateInit, RTCSdpType, RTCSessionDescription};
use crate::config::WebRtcConfig;
use crate::errors::{Result, WebRtcError};
use crate::peer::{PeerRole, RvoipPeerConnection};
/// Thin newtype over webrtc-rs SDP offer.
#[derive(Clone)]
pub struct Offer(pub String);
impl fmt::Debug for Offer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Offer")
.field("sdp_bytes", &self.0.len())
.finish()
}
}
/// Thin newtype over webrtc-rs SDP answer.
#[derive(Clone)]
pub struct Answer {
pub sdp: String,
/// Server-side [`ConnectionId`] when signaling returns one (WebSocket answer).
pub connection_id: Option<String>,
}
impl fmt::Debug for Answer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Answer")
.field("sdp_bytes", &self.sdp.len())
.field("connection_id_present", &self.connection_id.is_some())
.field(
"connection_id_bytes",
&self.connection_id.as_deref().map(str::len),
)
.finish()
}
}
impl Answer {
pub fn new(sdp: impl Into<String>) -> Self {
Self {
sdp: sdp.into(),
connection_id: None,
}
}
}
/// Thin newtype over ICE candidate init JSON.
#[derive(Clone)]
pub struct IceCandidate(pub String);
impl fmt::Debug for IceCandidate {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("IceCandidate")
.field("candidate_bytes", &self.0.len())
.finish()
}
}
/// Outbound call target (thin until `rvoip-client` exists).
#[derive(Clone)]
pub enum CallTarget {
Uri(String),
Participant(String),
}
impl fmt::Debug for CallTarget {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let (kind, value_bytes) = match self {
Self::Uri(value) => ("uri", value.len()),
Self::Participant(value) => ("participant", value.len()),
};
formatter
.debug_struct("CallTarget")
.field("kind", &kind)
.field("value_bytes", &value_bytes)
.finish()
}
}
/// Session medium.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionMedium {
Audio,
Video,
AudioVideo,
}
/// Handle returned from [`WebRtcClient::call`].
///
/// Cloning a handle increments the refcount on the underlying peer connection;
/// the connection closes only when the last clone is dropped. For deterministic
/// teardown call [`SessionHandle::close`] explicitly — `Drop` is best-effort.
#[derive(Clone)]
pub struct SessionHandle {
session_id: SessionId,
connection_id: ConnectionId,
target: CallTarget,
medium: SessionMedium,
answer: Answer,
peer: Arc<RvoipPeerConnection>,
data_channel: Arc<dyn DataChannel>,
/// When all clones drop, the strong count hits 1 here and the Drop impl
/// fires a detached close on the underlying peer.
closed: Arc<std::sync::atomic::AtomicBool>,
}
impl SessionHandle {
pub fn session_id(&self) -> &SessionId {
&self.session_id
}
pub fn connection_id(&self) -> &ConnectionId {
&self.connection_id
}
pub fn target(&self) -> &CallTarget {
&self.target
}
pub fn medium(&self) -> SessionMedium {
self.medium
}
pub fn answer(&self) -> &Answer {
&self.answer
}
pub fn peer(&self) -> &Arc<RvoipPeerConnection> {
&self.peer
}
pub fn data_channel(&self) -> &Arc<dyn DataChannel> {
&self.data_channel
}
/// Wait until ICE/DTLS reaches connected.
pub async fn wait_connected(&self, timeout: Duration) -> Result<()> {
self.peer.wait_connected(timeout).await
}
/// Explicitly close the peer connection. Idempotent — subsequent calls
/// (or `Drop`) are no-ops.
pub async fn close(&self) -> Result<()> {
if self.closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
return Ok(());
}
self.peer.close().await
}
}
impl Drop for SessionHandle {
fn drop(&mut self) {
// Only the last clone runs the actual close — `peer` Arc refcount tells
// us if anyone else still holds the peer (the comprehensive checks
// hand the peer around via `session.peer()`).
if self.closed.load(std::sync::atomic::Ordering::Acquire) {
return;
}
if Arc::strong_count(&self.peer) <= 1 {
// Best-effort detached close — Drop is sync.
let peer = Arc::clone(&self.peer);
let closed = Arc::clone(&self.closed);
tokio::spawn(async move {
if !closed.swap(true, std::sync::atomic::Ordering::AcqRel) {
let _ = peer.close().await;
}
});
}
}
}
/// Signaling transport abstraction (WebSocket JSON, WHIP, custom).
#[async_trait::async_trait]
pub trait Signaler: Send + Sync {
async fn send_offer(&self, offer: &Offer) -> Result<Answer>;
async fn send_answer(&self, answer: &Answer) -> Result<()>;
async fn send_ice(&self, candidate: &IceCandidate) -> Result<()>;
}
pub struct WebRtcClient {
config: WebRtcConfig,
signaler_uri: String,
peer: Arc<RvoipPeerConnection>,
session_id: SessionId,
connection_id: ConnectionId,
}
impl WebRtcClient {
/// Connect using WebRTC configuration and a signaling URI (used by custom signalers).
pub async fn connect(
config: WebRtcConfig,
signaler_uri: impl Into<String>,
) -> Result<Arc<Self>> {
let peer = RvoipPeerConnection::new(&config, PeerRole::Offerer).await?;
Ok(Arc::new(Self {
config,
signaler_uri: signaler_uri.into(),
peer,
session_id: SessionId::new(),
connection_id: ConnectionId::new(),
}))
}
pub fn signaler_uri(&self) -> &str {
&self.signaler_uri
}
pub fn session_id(&self) -> &SessionId {
&self.session_id
}
pub fn connection_id(&self) -> &ConnectionId {
&self.connection_id
}
pub fn capabilities(&self) -> CapabilityDescriptor {
self.config.capabilities.clone()
}
/// Place an outbound call: add tracks + data channel, create offer, exchange via signaler.
pub async fn call<S: Signaler>(
&self,
signaler: &S,
target: CallTarget,
medium: SessionMedium,
) -> Result<SessionHandle> {
let data_channel =
crate::client::comprehensive::prepare_offer_media(&self.peer, medium).await?;
let offer_sdp = self.peer.create_offer_and_gather().await?;
let answer = signaler.send_offer(&Offer(offer_sdp)).await?;
self.peer.set_remote_answer(&answer.sdp).await?;
Ok(SessionHandle {
session_id: self.session_id.clone(),
connection_id: self.connection_id.clone(),
target,
medium,
answer,
peer: Arc::clone(&self.peer),
data_channel,
closed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
})
}
pub fn peer(&self) -> &Arc<RvoipPeerConnection> {
&self.peer
}
pub fn parse_offer(sdp: &str) -> Result<RTCSessionDescription> {
crate::sdp::parse_sdp(sdp, RTCSdpType::Offer)
}
pub fn parse_answer(sdp: &str) -> Result<RTCSessionDescription> {
crate::sdp::parse_sdp(sdp, RTCSdpType::Answer)
}
pub fn parse_ice_candidate(json: &str) -> Result<RTCIceCandidateInit> {
serde_json::from_str(json)
.map_err(|e| WebRtcError::Signaling(format!("ice candidate json: {e}")))
}
}