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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! Implementation of a [`Component`].

mod ice_candidates;
mod local_sdp;
mod tracks_repository;
mod watchers;

use std::{cell::Cell, collections::HashSet, rc::Rc};

use futures::{future::LocalBoxFuture, StreamExt as _, TryFutureExt as _};
use medea_client_api_proto::{
    self as proto, IceCandidate, IceServer, NegotiationRole, PeerId as Id,
    TrackId,
};
use medea_reactive::{AllProcessed, ObservableCell, ProgressableCell};
use proto::{ConnectionMode, MemberId};
use tracerr::Traced;

use crate::{
    media::LocalTracksConstraints,
    peer::{
        media::{receiver, sender},
        LocalStreamUpdateCriteria, PeerConnection, UpdateLocalStreamError,
    },
    utils::{component, AsProtoState, SynchronizableState, Updatable},
};

use self::{
    ice_candidates::IceCandidates, local_sdp::LocalSdp,
    tracks_repository::TracksRepository,
};

/// Synchronization state of a [`Component`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SyncState {
    /// State desynced, and should be synced on a RPC reconnection.
    Desynced,

    /// State syncs with a Media Server state.
    Syncing,

    /// State is synced.
    Synced,
}

/// Negotiation state of the [`Component`].
///
/// ```ignore
///           +--------+
///           |        |
/// +-------->+ Stable +<----------+
/// |         |        |           |
/// |         +---+----+           |
/// |             |                |
/// |             v                |
/// |      +------+-------+        |
/// |      |              |        |
/// |      | WaitLocalSdp +<----+  |
/// |      |              |     |  |
/// |      +------+-------+     |  |
/// |             |             |  |
/// |             v             |  |
/// |  +----------+----------+  |  |
/// |  |                     |  |  |
/// +--+ WaitLocalSdpApprove +--+  |
///    |                     |     |
///    +----------+----------+     |
///               |                |
///               v                |
///       +-------+-------+        |
///       |               |        |
///       | WaitRemoteSdp |        |
///       |               |        |
///       +-------+-------+        |
///               |                |
///               |                |
///               +----------------+
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NegotiationState {
    /// [`Component`] is new or negotiation is completed.
    Stable,

    /// [`Component`] waits for a local SDP offer generating.
    WaitLocalSdp,

    /// [`Component`] waits for a local SDP being approved by server.
    WaitLocalSdpApprove,

    /// [`Component`] waits for a remote SDP offer.
    WaitRemoteSdp,
}

/// State of a [`Component`].
#[derive(Debug)]
pub struct State {
    /// ID of this [`Component`].
    id: Id,

    /// Indicator whether this `Peer` is working in a [P2P mesh] or [SFU] mode.
    ///
    /// [P2P mesh]: https://webrtcglossary.com/mesh
    /// [SFU]: https://webrtcglossary.com/sfu
    connection_mode: ConnectionMode,

    /// All [`sender::State`]s of this [`Component`].
    senders: TracksRepository<sender::State>,

    /// All [`receiver::State`]s of this [`Component`].
    receivers: TracksRepository<receiver::State>,

    /// Indicator whether this [`Component`] should relay all media through a
    /// TURN server forcibly.
    force_relay: bool,

    /// List of [`IceServer`]s which this [`Component`] should use.
    ice_servers: Vec<IceServer>,

    /// Current [`NegotiationRole`] of this [`Component`].
    negotiation_role: ProgressableCell<Option<NegotiationRole>>,

    /// Negotiation state of this [`Component`].
    negotiation_state: ObservableCell<NegotiationState>,

    /// Local session description of this [`Component`].
    local_sdp: LocalSdp,

    /// Remote session description of this [`Component`].
    remote_sdp: ProgressableCell<Option<String>>,

    /// Indicates whether ICE restart should be performed.
    restart_ice: Cell<bool>,

    /// All [`IceCandidate`]s of this [`Component`].
    ice_candidates: IceCandidates,

    /// Indicator whether [`State::update_local_stream`] method should be
    /// called if some [`sender`] wants to update a local stream.
    maybe_update_local_stream: ObservableCell<bool>,

    /// Indicator whether there is some information about tracks to provide
    /// into [`Connections`].
    ///
    /// [`Connections`]: crate::connection::Connections
    maybe_update_connections:
        ObservableCell<Option<(TrackId, HashSet<MemberId>)>>,

    /// Synchronization state of this [`Component`].
    sync_state: ObservableCell<SyncState>,
}

impl State {
    /// Creates a new [`State`] with the provided data.
    #[must_use]
    pub fn new(
        id: Id,
        ice_servers: Vec<IceServer>,
        force_relay: bool,
        negotiation_role: Option<NegotiationRole>,
        connection_mode: ConnectionMode,
    ) -> Self {
        Self {
            id,
            connection_mode,
            senders: TracksRepository::new(),
            receivers: TracksRepository::new(),
            ice_servers,
            force_relay,
            remote_sdp: ProgressableCell::new(None),
            local_sdp: LocalSdp::new(),
            negotiation_role: ProgressableCell::new(negotiation_role),
            negotiation_state: ObservableCell::new(NegotiationState::Stable),
            restart_ice: Cell::new(false),
            ice_candidates: IceCandidates::new(),
            maybe_update_local_stream: ObservableCell::new(false),
            maybe_update_connections: ObservableCell::new(None),
            sync_state: ObservableCell::new(SyncState::Synced),
        }
    }

    /// Returns [`ConnectionMode`] of this [`State`].
    #[must_use]
    pub const fn connection_mode(&self) -> ConnectionMode {
        self.connection_mode
    }

    /// Returns [`Id`] of this [`State`].
    #[must_use]
    pub const fn id(&self) -> Id {
        self.id
    }

    /// Returns all [`IceServer`]s of this [`State`].
    #[must_use]
    pub const fn ice_servers(&self) -> &Vec<IceServer> {
        &self.ice_servers
    }

    /// Indicates whether [`PeerConnection`] should be relayed forcibly.
    #[must_use]
    pub const fn force_relay(&self) -> bool {
        self.force_relay
    }

    /// Inserts a new [`sender::State`] into this [`State`].
    pub fn insert_sender(&self, track_id: TrackId, sender: Rc<sender::State>) {
        self.senders.insert(track_id, sender);
    }

    /// Inserts a new [`receiver::State`] into this [`State`].
    pub fn insert_receiver(
        &self,
        track_id: TrackId,
        receiver: Rc<receiver::State>,
    ) {
        self.receivers.insert(track_id, receiver);
    }

    /// Returns [`Rc`] to the [`sender::State`] with the provided [`TrackId`].
    #[must_use]
    pub fn get_sender(&self, track_id: TrackId) -> Option<Rc<sender::State>> {
        self.senders.get(track_id)
    }

    /// Returns [`Rc`] to the [`receiver::State`] with the provided [`TrackId`].
    #[must_use]
    pub fn get_receiver(
        &self,
        track_id: TrackId,
    ) -> Option<Rc<receiver::State>> {
        self.receivers.get(track_id)
    }

    /// Returns IDs of all the send [`TrackId`]s.
    pub fn get_send_tracks(&self) -> Vec<TrackId> {
        self.senders.ids()
    }

    /// Returns IDs of all the receive [`TrackId`]s.
    pub fn get_recv_tracks(&self) -> Vec<TrackId> {
        self.receivers.ids()
    }

    /// Sets [`NegotiationRole`] of this [`State`] to the provided one.
    pub async fn set_negotiation_role(
        &self,
        negotiation_role: NegotiationRole,
    ) {
        _ = self
            .negotiation_role
            .subscribe()
            .any(|val| async move { val.is_none() })
            .await;
        self.negotiation_role.set(Some(negotiation_role));
    }

    /// Sets [`State::restart_ice`] to `true`.
    pub fn restart_ice(&self) {
        self.restart_ice.set(true);
    }

    /// Removes [`sender::State`] or [`receiver::State`] with the provided
    /// [`TrackId`].
    pub fn remove_track(&self, track_id: TrackId) {
        if !self.receivers.remove(track_id) {
            _ = self.senders.remove(track_id);
        }
    }

    /// Sets remote SDP offer to the provided value.
    pub fn set_remote_sdp(&self, sdp: String) {
        self.remote_sdp.set(Some(sdp));
    }

    /// Adds [`IceCandidate`] for the [`State`].
    pub fn add_ice_candidate(&self, ice_candidate: IceCandidate) {
        self.ice_candidates.add(ice_candidate);
    }

    /// Marks current local SDP as approved by server.
    pub fn apply_local_sdp(&self, sdp: String) {
        self.local_sdp.approved_set(sdp);
    }

    /// Stops all timeouts of the [`State`].
    ///
    /// Stops local SDP rollback timeout.
    pub fn stop_timeouts(&self) {
        self.local_sdp.stop_timeout();
    }

    /// Resumes all timeouts of the [`State`].
    ///
    /// Resumes local SDP rollback timeout.
    pub fn resume_timeouts(&self) {
        self.local_sdp.resume_timeout();
    }

    /// Returns [`Future`] resolving once
    /// [getUserMedia()][1]/[getDisplayMedia()][2] request for the provided
    /// [`TrackId`]s is resolved.
    ///
    /// [`Result`] returned by this [`Future`] will be the same as the result of
    /// the [getUserMedia()][1]/[getDisplayMedia()][2] request.
    ///
    /// Returns last known [getUserMedia()][1]/[getDisplayMedia()][2] request's
    /// [`Result`], if currently no such requests are running for the provided
    /// [`TrackId`]s.
    ///
    /// [`Future`]: std::future::Future
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    /// [2]: https://w3.org/TR/screen-capture/#dom-mediadevices-getdisplaymedia
    pub fn local_stream_update_result(
        &self,
        tracks_ids: HashSet<TrackId>,
    ) -> LocalBoxFuture<'static, Result<(), Traced<UpdateLocalStreamError>>>
    {
        Box::pin(
            self.senders
                .local_stream_update_result(tracks_ids)
                .map_err(tracerr::map_from_and_wrap!()),
        )
    }

    /// Returns [`Future`] resolving when all [`sender::State`]'s and
    /// [`receiver::State`]'s updates will be applied.
    ///
    /// [`Future`]: std::future::Future
    pub fn when_all_updated(&self) -> AllProcessed<'static> {
        medea_reactive::when_all_processed(vec![
            self.senders.when_updated().into(),
            self.receivers.when_updated().into(),
        ])
    }

    /// Updates a local `MediaStream` based on a
    /// [`sender::State::is_local_stream_update_needed`].
    ///
    /// Resets a [`sender::State`] local stream update when it's updated.
    async fn update_local_stream(
        &self,
        peer: &Rc<PeerConnection>,
    ) -> Result<(), Traced<UpdateLocalStreamError>> {
        let mut criteria = LocalStreamUpdateCriteria::empty();
        let senders = self.senders.get_outdated();
        for s in &senders {
            criteria.add(s.media_kind(), s.media_source());
        }
        let res = peer
            .update_local_stream(criteria)
            .await
            .map_err(tracerr::map_from_and_wrap!())
            .map(drop);
        for s in senders {
            if let Err(err) = res.clone() {
                s.failed_local_stream_update(err);
            } else {
                s.local_stream_updated();
            }
        }
        res
    }

    /// Inserts the provided [`proto::Track`] to this [`State`].
    pub fn insert_track(
        &self,
        track: &proto::Track,
        send_constraints: LocalTracksConstraints,
    ) {
        match &track.direction {
            proto::Direction::Send { receivers, mid } => {
                self.senders.insert(
                    track.id,
                    Rc::new(sender::State::new(
                        track.id,
                        mid.clone(),
                        track.media_type,
                        track.media_direction,
                        track.muted,
                        receivers.clone(),
                        send_constraints,
                        self.connection_mode,
                    )),
                );
            }
            proto::Direction::Recv { sender, mid } => {
                self.receivers.insert(
                    track.id,
                    Rc::new(receiver::State::new(
                        track.id,
                        mid.clone(),
                        track.media_type,
                        track.media_direction,
                        track.muted,
                        sender.clone(),
                        self.connection_mode,
                    )),
                );
            }
        }
    }

    /// Returns [`Future`] resolving once all senders inserts and removes are
    /// processed.
    ///
    /// [`Future`]: std::future::Future
    pub fn when_all_senders_processed(&self) -> AllProcessed<'static> {
        self.senders.when_all_processed()
    }

    /// Returns [`Future`] resolving once all [`State::receivers`]' inserts and
    /// removes are processed.
    ///
    /// [`Future`]: std::future::Future
    fn when_all_receivers_processed(&self) -> AllProcessed<'static> {
        self.receivers.when_all_processed()
    }

    /// Patches [`sender::State`] or [`receiver::State`] with the provided
    /// [`proto::TrackPatchEvent`].
    ///
    /// Schedules a local stream update.
    pub async fn patch_track(&self, patch: proto::TrackPatchEvent) {
        if let Some(receivers) = &patch.receivers {
            _ = self.maybe_update_connections.when_eq(None).await;
            self.maybe_update_connections
                .set(Some((patch.id, receivers.clone().into_iter().collect())));
        }

        if let Some(sender) = self.get_sender(patch.id) {
            sender.update(patch);
            _ = self.maybe_update_local_stream.when_eq(false).await;
            self.maybe_update_local_stream.set(true);
        } else if let Some(receiver) = self.get_receiver(patch.id) {
            receiver.update(&patch);
        } else {
            log::warn!("Cannot apply patch to `Track`: {}", patch.id.0);
        }
    }

    /// Returns the current SDP offer of this [`State`].
    #[must_use]
    pub fn current_sdp_offer(&self) -> Option<String> {
        self.local_sdp.current()
    }
}

/// Component responsible for a [`PeerConnection`] updating.
pub type Component = component::Component<State, PeerConnection>;

impl AsProtoState for State {
    type Output = proto::state::Peer;

    fn as_proto(&self) -> Self::Output {
        Self::Output {
            id: self.id,
            connection_mode: self.connection_mode,
            senders: self.senders.as_proto(),
            receivers: self.receivers.as_proto(),
            ice_candidates: self.ice_candidates.as_proto(),
            force_relay: self.force_relay,
            ice_servers: self.ice_servers.clone(),
            negotiation_role: self.negotiation_role.get(),
            local_sdp: self.local_sdp.current(),
            remote_sdp: self.remote_sdp.get(),
            restart_ice: self.restart_ice.get(),
        }
    }
}

impl SynchronizableState for State {
    type Input = proto::state::Peer;

    fn from_proto(
        from: Self::Input,
        send_cons: &LocalTracksConstraints,
    ) -> Self {
        let state = Self::new(
            from.id,
            from.ice_servers,
            from.force_relay,
            from.negotiation_role,
            from.connection_mode,
        );

        for (id, sender) in from.senders {
            state.senders.insert(
                id,
                Rc::new(sender::State::from_proto(sender, send_cons)),
            );
        }
        for (id, receiver) in from.receivers {
            state.receivers.insert(
                id,
                Rc::new(receiver::State::from_proto(receiver, send_cons)),
            );
        }
        for ice_candidate in from.ice_candidates {
            state.ice_candidates.add(ice_candidate);
        }

        state
    }

    fn apply(&self, state: Self::Input, send_cons: &LocalTracksConstraints) {
        if state.negotiation_role.is_some() {
            self.negotiation_role.set(state.negotiation_role);
        }
        if state.restart_ice {
            self.restart_ice.set(true);
        }
        if let Some(sdp_offer) = state.local_sdp {
            self.local_sdp.approved_set(sdp_offer);
        }
        self.remote_sdp.set(state.remote_sdp);
        self.ice_candidates.apply(state.ice_candidates, send_cons);
        self.senders.apply(state.senders, send_cons);
        self.receivers.apply(state.receivers, send_cons);

        self.sync_state.set(SyncState::Synced);
    }
}

impl Updatable for State {
    fn when_stabilized(&self) -> AllProcessed<'static> {
        medea_reactive::when_all_processed(vec![
            self.senders.when_stabilized().into(),
            self.receivers.when_stabilized().into(),
        ])
    }

    fn when_updated(&self) -> AllProcessed<'static> {
        medea_reactive::when_all_processed(vec![
            self.receivers.when_updated().into(),
            self.senders.when_updated().into(),
        ])
    }

    fn connection_lost(&self) {
        self.sync_state.set(SyncState::Desynced);
        self.senders.connection_lost();
        self.receivers.connection_lost();
    }

    fn connection_recovered(&self) {
        self.sync_state.set(SyncState::Syncing);
        self.senders.connection_recovered();
        self.receivers.connection_recovered();
    }
}

#[cfg(feature = "mockable")]
#[allow(clippy::multiple_inherent_impl)]
impl State {
    /// Waits for a [`State::remote_sdp`] change to be applied.
    pub async fn when_remote_sdp_processed(&self) {
        self.remote_sdp.when_all_processed().await;
    }

    /// Resets a [`NegotiationRole`] of this [`State`] to [`None`].
    pub fn reset_negotiation_role(&self) {
        self.negotiation_state.set(NegotiationState::Stable);
        self.negotiation_role.set(None);
    }

    /// Returns the current [`NegotiationRole`] of this [`State`].
    #[must_use]
    pub fn negotiation_role(&self) -> Option<NegotiationRole> {
        self.negotiation_role.get()
    }

    /// Returns [`Future`] resolving once local SDP approve is needed.
    pub fn when_local_sdp_approve_needed(
        &self,
    ) -> impl std::future::Future<Output = ()> {
        use futures::FutureExt as _;
        self.negotiation_state
            .when_eq(NegotiationState::WaitLocalSdpApprove)
            .map(drop)
    }

    /// Stabilizes all [`receiver::State`]s of this [`State`].
    pub fn stabilize_all(&self) {
        self.receivers.stabilize_all();
    }

    /// Waits until a [`State::local_sdp`] is resolved and returns its new
    /// value.
    pub async fn when_local_sdp_updated(&self) -> Option<String> {
        use futures::StreamExt as _;

        self.local_sdp.subscribe().skip(1).next().await.flatten()
    }

    /// Waits until all [`State::senders`]' and [`State::receivers`]' inserts
    /// are processed.
    pub async fn when_all_tracks_created(&self) {
        medea_reactive::when_all_processed(vec![
            self.senders.when_insert_processed().into(),
            self.receivers.when_insert_processed().into(),
        ])
        .await;
    }

    /// Sets [`State::sync_state`] to the [`SyncState::Synced`].
    pub fn synced(&self) {
        self.senders.synced();
        self.receivers.synced();
        self.sync_state.set(SyncState::Synced);
    }
}