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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use crate::*;
use std::sync::{Arc, Mutex, Weak};
use tx5_go_pion_sys::API;

/// ICE server configuration.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(crate = "tx5_core::deps::serde", rename_all = "camelCase")]
pub struct IceServer {
    /// Url list.
    pub urls: Vec<String>,

    /// Optional username.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,

    /// Optional credential.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credential: Option<String>,
}

/// Configuration for a go pion webrtc PeerConnection.
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(crate = "tx5_core::deps::serde", rename_all = "camelCase")]
pub struct PeerConnectionConfig {
    /// ICE server list.
    pub ice_servers: Vec<IceServer>,
}

impl From<PeerConnectionConfig> for GoBufRef<'static> {
    fn from(p: PeerConnectionConfig) -> Self {
        GoBufRef::json(p)
    }
}

impl From<&PeerConnectionConfig> for GoBufRef<'static> {
    fn from(p: &PeerConnectionConfig) -> Self {
        GoBufRef::json(p)
    }
}

/// Configuration for a go pion webrtc DataChannel.
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(crate = "tx5_core::deps::serde", rename_all = "camelCase")]
pub struct DataChannelConfig {
    /// DataChannel Label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

impl From<DataChannelConfig> for GoBufRef<'static> {
    fn from(p: DataChannelConfig) -> Self {
        GoBufRef::json(p)
    }
}

impl From<&DataChannelConfig> for GoBufRef<'static> {
    fn from(p: &DataChannelConfig) -> Self {
        GoBufRef::json(p)
    }
}

/// Configuration for a go pion webrtc PeerConnection offer.
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(crate = "tx5_core::deps::serde", rename_all = "camelCase")]
pub struct OfferConfig {}

impl From<OfferConfig> for GoBufRef<'static> {
    fn from(p: OfferConfig) -> Self {
        GoBufRef::json(p)
    }
}

impl From<&OfferConfig> for GoBufRef<'static> {
    fn from(p: &OfferConfig) -> Self {
        GoBufRef::json(p)
    }
}

/// Configuration for a go pion webrtc PeerConnection answer.
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(crate = "tx5_core::deps::serde", rename_all = "camelCase")]
pub struct AnswerConfig {}

impl From<AnswerConfig> for GoBufRef<'static> {
    fn from(p: AnswerConfig) -> Self {
        GoBufRef::json(p)
    }
}

impl From<&AnswerConfig> for GoBufRef<'static> {
    fn from(p: &AnswerConfig) -> Self {
        GoBufRef::json(p)
    }
}

pub(crate) struct PeerConCore {
    peer_con_id: usize,
    con_state: PeerConnectionState,
    evt_send: tokio::sync::mpsc::UnboundedSender<PeerConnectionEvent>,
    drop_err: Error,
}

impl Drop for PeerConCore {
    fn drop(&mut self) {
        let _ = self
            .evt_send
            .send(PeerConnectionEvent::Error(self.drop_err.clone()));
        unregister_peer_con(self.peer_con_id);
        unsafe {
            API.peer_con_free(self.peer_con_id);
        }
    }
}

impl PeerConCore {
    pub fn new(
        peer_con_id: usize,
        evt_send: tokio::sync::mpsc::UnboundedSender<PeerConnectionEvent>,
    ) -> Self {
        Self {
            peer_con_id,
            con_state: PeerConnectionState::New,
            evt_send,
            drop_err: Error::id("PeerConnectionDropped").into(),
        }
    }

    pub fn close(&mut self, err: Error) {
        // self.evt_send.send_err() is called in Drop impl
        self.drop_err = err;
    }
}

#[derive(Clone)]
pub(crate) struct WeakPeerCon(
    pub(crate) Weak<Mutex<std::result::Result<PeerConCore, Error>>>,
);

macro_rules! peer_con_strong_core {
    ($inner:expr, $ident:ident, $block:block) => {
        match &mut *$inner.lock().unwrap() {
            Ok($ident) => $block,
            Err(err) => Result::Err(err.clone().into()),
        }
    };
}

macro_rules! peer_con_weak_core {
    ($inner:expr, $ident:ident, $block:block) => {
        match $inner.upgrade() {
            Some(strong) => peer_con_strong_core!(strong, $ident, $block),
            None => Result::Err(Error::id("PeerConnectionClosed")),
        }
    };
}

impl WeakPeerCon {
    pub fn send_evt(&self, evt: PeerConnectionEvent) -> Result<()> {
        peer_con_weak_core!(self.0, core, {
            core.evt_send
                .send(evt)
                .map_err(|_| Error::id("PeerConnectionClosed"))
        })
    }
}

/// A go pion webrtc PeerConnection.
pub struct PeerConnection(Arc<Mutex<std::result::Result<PeerConCore, Error>>>);

impl PeerConnection {
    /// Construct a new PeerConnection.
    /// Warning: This returns an unbounded channel,
    /// you should process this as quickly and synchronously as possible
    /// to avoid a backlog filling up memory.
    pub async fn new<'a, B>(
        config: B,
    ) -> Result<(
        Self,
        tokio::sync::mpsc::UnboundedReceiver<PeerConnectionEvent>,
    )>
    where
        B: Into<GoBufRef<'a>>,
    {
        tx5_init().await.map_err(Error::err)?;
        init_evt_manager();
        r2id!(config);
        tokio::task::spawn_blocking(move || unsafe {
            let peer_con_id = API.peer_con_alloc(config)?;
            let (evt_send, evt_recv) = tokio::sync::mpsc::unbounded_channel();

            let strong = Arc::new(Mutex::new(Ok(PeerConCore::new(
                peer_con_id,
                evt_send,
            ))));

            let weak = WeakPeerCon(Arc::downgrade(&strong));

            register_peer_con(peer_con_id, weak);

            Ok((Self(strong), evt_recv))
        })
        .await?
    }

    /// Set the connection state. This should only be set based on connection state events
    /// coming from the underlying webrtc library.
    pub fn set_con_state(&self, con_state: PeerConnectionState) {
        let mut lock = self.0.lock().unwrap();
        if let Ok(core) = &mut *lock {
            core.con_state = con_state;
        } else {
            tracing::warn!(
                ?con_state,
                "Unable to set peer connection state: {:?}",
                self.get_peer_con_id()
            );
        }
    }

    /// Get the connection state.
    pub fn get_con_state(&self) -> Result<PeerConnectionState> {
        peer_con_strong_core!(self.0, core, { Ok(core.con_state) })
    }

    /// Close this connection.
    pub fn close<E: Into<Error>>(&self, err: E) {
        let err = err.into();
        let mut tmp = Err(err.clone());

        {
            let mut lock = self.0.lock().unwrap();
            let mut do_swap = false;
            if let Ok(core) = &mut *lock {
                core.close(err.clone());
                do_swap = true;
            }
            if do_swap {
                std::mem::swap(&mut *lock, &mut tmp);
            }
        }

        // make sure the above lock is released before this is dropped
        drop(tmp);
    }

    fn get_peer_con_id(&self) -> Result<usize> {
        peer_con_strong_core!(self.0, core, { Ok(core.peer_con_id) })
    }

    /// Get stats.
    pub async fn stats(&self) -> Result<GoBuf> {
        let peer_con_id = self.get_peer_con_id()?;

        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_stats(peer_con_id).map(GoBuf)
        })
        .await?
    }

    /// Create offer.
    pub async fn create_offer<'a, B>(&self, config: B) -> Result<GoBuf>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id = self.get_peer_con_id()?;

        r2id!(config);
        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_create_offer(peer_con_id, config).map(GoBuf)
        })
        .await?
    }

    /// Create answer.
    pub async fn create_answer<'a, B>(&self, config: B) -> Result<GoBuf>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id = self.get_peer_con_id()?;

        r2id!(config);
        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_create_answer(peer_con_id, config).map(GoBuf)
        })
        .await?
    }

    /// Set local description.
    pub async fn set_local_description<'a, B>(&self, desc: B) -> Result<()>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id = self.get_peer_con_id()?;

        r2id!(desc);
        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_set_local_desc(peer_con_id, desc)
        })
        .await?
    }

    /// Set remote description.
    pub async fn set_remote_description<'a, B>(&self, desc: B) -> Result<()>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id = self.get_peer_con_id()?;

        r2id!(desc);
        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_set_rem_desc(peer_con_id, desc)
        })
        .await?
    }

    /// Add ice candidate.
    pub async fn add_ice_candidate<'a, B>(&self, ice: B) -> Result<()>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id = self.get_peer_con_id()?;

        r2id!(ice);
        tokio::task::spawn_blocking(move || unsafe {
            API.peer_con_add_ice_candidate(peer_con_id, ice)
        })
        .await?
    }

    /// Create data channel.
    pub async fn create_data_channel<'a, B>(
        &self,
        config: B,
    ) -> Result<(
        DataChannel,
        tokio::sync::mpsc::UnboundedReceiver<DataChannelEvent>,
    )>
    where
        B: Into<GoBufRef<'a>>,
    {
        let peer_con_id =
            peer_con_strong_core!(self.0, core, { Ok(core.peer_con_id) })?;

        r2id!(config);
        tokio::task::spawn_blocking(move || unsafe {
            let data_chan_id =
                API.peer_con_create_data_chan(peer_con_id, config)?;
            Ok(DataChannel::new(data_chan_id))
        })
        .await?
    }
}