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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! [`PeerConnection`] media management.
//!
//! [`PeerConnection`]: crate::peer::PeerConnection

pub mod receiver;
pub mod sender;
mod transitable_state;

use std::{cell::RefCell, collections::HashMap, future::Future, rc::Rc};

use derive_more::{Display, From};
use futures::{
    channel::mpsc, future, future::LocalBoxFuture, FutureExt as _,
    TryFutureExt as _,
};
use medea_client_api_proto as proto;
#[cfg(feature = "mockable")]
use medea_client_api_proto::{ConnectionMode, MemberId};
use medea_client_api_proto::{EncodingParameters, SvcSettings};
use proto::{MediaSourceKind, MediaType, ScalabilityMode, TrackId};
use tracerr::Traced;

#[cfg(feature = "mockable")]
use crate::media::{LocalTracksConstraints, RecvConstraints};
use crate::{
    media::{track::local, MediaKind},
    peer::{LocalStreamUpdateCriteria, PeerEvent},
    platform,
    platform::{
        send_encoding_parameters::SendEncodingParameters, CodecCapability,
        TransceiverInit,
    },
    utils::{Caused, Component},
};

use super::tracks_request::TracksRequest;

#[doc(inline)]
pub use self::{
    receiver::Receiver,
    sender::Sender,
    transitable_state::{
        media_exchange_state, mute_state, InStable, InTransition,
        MediaExchangeState, MediaExchangeStateController, MediaState,
        MuteState, MuteStateController, TransitableState,
        TransitableStateController,
    },
};

/// Transceiver's sending ([`Sender`]) or receiving ([`Receiver`]) side.
pub trait TransceiverSide: MediaStateControllable {
    /// Returns [`TrackId`] of this [`TransceiverSide`].
    fn track_id(&self) -> TrackId;

    /// Returns [`MediaKind`] of this [`TransceiverSide`].
    fn kind(&self) -> MediaKind;

    /// Returns [`MediaSourceKind`] of this [`TransceiverSide`].
    fn source_kind(&self) -> MediaSourceKind;

    /// Returns `true` if this [`TransceiverSide`] currently can be
    /// disabled/enabled without [`LocalTracksConstraints`] updating.
    ///
    /// [`LocalTracksConstraints`]: super::LocalTracksConstraints
    fn is_transitable(&self) -> bool;
}

/// Default functions for dealing with [`MediaExchangeStateController`] and
/// [`MuteStateController`] for objects that use it.
pub trait MediaStateControllable {
    /// Returns reference to the [`MediaExchangeStateController`].
    #[must_use]
    fn media_exchange_state_controller(
        &self,
    ) -> Rc<MediaExchangeStateController>;

    /// Returns a reference to the [`MuteStateController`].
    #[must_use]
    fn mute_state_controller(&self) -> Rc<MuteStateController>;

    /// Returns [`MediaExchangeState`] of this [`MediaStateControllable`].
    fn media_exchange_state(&self) -> MediaExchangeState {
        self.media_exchange_state_controller().state()
    }

    /// Returns [`MuteState`] of this [`MediaStateControllable`].
    #[must_use]
    fn mute_state(&self) -> MuteState {
        self.mute_state_controller().state()
    }

    /// Sets current [`MediaState`] to [`TransitableState::Transition`].
    ///
    /// # Errors
    ///
    /// Implementors might return [`ProhibitedStateError`] if a transition
    /// cannot be made for some reason.
    fn media_state_transition_to(
        &self,
        desired_state: MediaState,
    ) -> Result<(), Traced<ProhibitedStateError>> {
        match desired_state {
            MediaState::MediaExchange(desired_state) => {
                self.media_exchange_state_controller()
                    .transition_to(desired_state);
            }
            MediaState::Mute(desired_state) => {
                self.mute_state_controller().transition_to(desired_state);
            }
        }

        Ok(())
    }

    /// Indicates whether [`Room`] should subscribe to the [`MediaState`] update
    /// when updating [`MediaStateControllable`] to the provided [`MediaState`].
    ///
    /// [`Room`]: crate::room::Room
    fn is_subscription_needed(&self, desired_state: MediaState) -> bool {
        match desired_state {
            MediaState::MediaExchange(media_exchange) => {
                let current = self.media_exchange_state();
                match current {
                    MediaExchangeState::Transition(_) => true,
                    MediaExchangeState::Stable(stable) => {
                        stable != media_exchange
                    }
                }
            }
            MediaState::Mute(mute_state) => {
                let current = self.mute_state();
                match current {
                    MuteState::Transition(_) => true,
                    MuteState::Stable(stable) => stable != mute_state,
                }
            }
        }
    }

    /// Indicates whether [`Room`] should send [`TrackPatchCommand`] to the
    /// server when updating [`MediaStateControllable`] to the provided
    /// [`MediaState`].
    ///
    /// [`TrackPatchCommand`]: medea_client_api_proto::TrackPatchCommand
    /// [`Room`]: crate::room::Room
    #[must_use]
    fn is_track_patch_needed(&self, desired_state: MediaState) -> bool {
        match desired_state {
            MediaState::MediaExchange(media_exchange) => {
                let current = self.media_exchange_state();
                match current {
                    MediaExchangeState::Stable(stable) => {
                        stable != media_exchange
                    }
                    MediaExchangeState::Transition(transition) => {
                        transition.intended() != media_exchange
                    }
                }
            }
            MediaState::Mute(mute_state) => {
                let current = self.mute_state();
                match current {
                    MuteState::Stable(stable) => stable != mute_state,
                    MuteState::Transition(transition) => {
                        transition.intended() != mute_state
                    }
                }
            }
        }
    }

    /// Returns [`Future`] which will be resolved when [`MediaState`] of this
    /// [`MediaStateControllable`] will be [`TransitableState::Stable`] or it's
    /// dropped.
    ///
    /// # Errors
    ///
    /// With an approved stable [`MediaState`] if transition to the
    /// `desired_state` cannot be made.
    ///
    /// [`Future`]: std::future::Future
    /// [`MediaState`]: super::MediaState
    fn when_media_state_stable(
        &self,
        desired_state: MediaState,
    ) -> LocalBoxFuture<'static, Result<(), MediaState>> {
        match desired_state {
            MediaState::Mute(desired_state) => self
                .mute_state_controller()
                .when_media_state_stable(desired_state)
                .map_err(MediaState::Mute)
                .boxed_local(),
            MediaState::MediaExchange(desired_state) => self
                .media_exchange_state_controller()
                .when_media_state_stable(desired_state)
                .map_err(MediaState::MediaExchange)
                .boxed_local(),
        }
    }
}

/// Direction of the `MediaTrack`.
#[derive(Clone, Copy, Debug)]
pub enum TrackDirection {
    /// Sends media data.
    Send,

    /// Receives media data.
    Recv,
}

/// Error occurring when media state transition is not allowed.
#[derive(Clone, Copy, Debug, Display)]
pub enum ProhibitedStateError {
    /// [`Sender`] cannot be disabled because it's required.
    #[display(
        "`MediaExchangeState` of `Sender` can't transit to \
         disabled state, because this `Sender` is required"
    )]
    CannotDisableRequiredSender,
}

/// Errors occurring in [`MediaConnections::insert_local_tracks()`] method.
#[derive(Caused, Clone, Debug, Display, From)]
#[cause(error = platform::Error)]
pub enum InsertLocalTracksError {
    /// [`local::Track`] doesn't satisfy [`Sender`]'s constraints.
    #[display("Provided `Track` doesn't satisfy senders constraints")]
    InvalidMediaTrack,

    /// There are not enough [`local::Track`]s being inserted into [`Sender`]s.
    #[display("Provided stream does not have all necessary `Track`s")]
    NotEnoughTracks,

    /// Insertion of a [`local::Track`] into a [`Sender`] fails.
    CouldNotInsertLocalTrack(#[cause] sender::InsertTrackError),
}

/// Errors occurring in [`MediaConnections::get_mids()`] method.
#[derive(Clone, Copy, Debug, Display)]
pub enum GetMidsError {
    /// Cannot get the `mid` from a [`Sender`].
    #[display("Peer has senders without mid")]
    SendersWithoutMid,

    /// Cannot get the `mid` from a [`Receiver`].
    #[display("Peer has receivers without mid")]
    ReceiversWithoutMid,
}

/// Returns the required [`CodecCapability`]s and [`ScalabilityMode`] for a
/// [`platform::Transceiver`] based on the provided [`SvcSettings`].
pub async fn probe_video_codecs(
    svc_settings: &Vec<SvcSettings>,
) -> (Vec<CodecCapability>, Option<ScalabilityMode>) {
    /// List of required codecs for every [`MediaKind::Video`] of a
    /// [`platform::Transceiver`].
    const REQUIRED_CODECS: [&str; 3] =
        ["video/rtx", "video/red", "video/ulpfec"];

    let mut target_scalability_mode = None;
    let mut target_codecs = Vec::new();

    let Ok(codecs) =
        CodecCapability::get_sender_codec_capabilities(MediaKind::Video).await
    else {
        return (target_codecs, target_scalability_mode);
    };

    let mut codecs: HashMap<String, Vec<_>> =
        codecs.into_iter().fold(HashMap::new(), |mut map, c| {
            map.entry(c.mime_type()).or_default().push(c);
            map
        });

    for svc in svc_settings {
        if let Some(mut codec_cap) = codecs.remove(svc.codec.mime_type()) {
            target_codecs.append(&mut codec_cap);
            target_scalability_mode = Some(svc.scalability_mode);
            break;
        }
    }
    if !target_codecs.is_empty() {
        #[expect(clippy::iter_over_hash_type, reason = "order doesn't matter")]
        for (mime, mut c) in codecs {
            if REQUIRED_CODECS.contains(&mime.as_str()) {
                target_codecs.append(&mut c);
            }
        }
    }

    (target_codecs, target_scalability_mode)
}

/// Returns [`SendEncodingParameters`] for a [`platform::Transceiver`] based on
/// the provided [`EncodingParameters`] and target [`ScalabilityMode`].
fn get_encodings_params(
    mut encodings: Vec<EncodingParameters>,
    target_sm: Option<ScalabilityMode>,
) -> Vec<SendEncodingParameters> {
    if encodings.is_empty() && target_sm.is_some() {
        encodings.push(EncodingParameters {
            rid: "0".to_owned(),
            active: true,
            max_bitrate: None,
            scale_resolution_down_by: None,
        });
    }

    encodings
        .into_iter()
        .map(|enc| {
            let mut enc = SendEncodingParameters::from(enc);
            if let Some(target_sm) = target_sm {
                enc.set_scalability_mode(target_sm);
            }
            enc
        })
        .collect()
}

/// Actual data of [`MediaConnections`] storage.
#[derive(Debug)]
struct InnerMediaConnections {
    /// Reference to the parent [`platform::RtcPeerConnection`].
    ///
    /// Used to generate transceivers for [`Sender`]s and [`Receiver`]s.
    peer: Rc<platform::RtcPeerConnection>,

    /// [`PeerEvent`]s tx.
    peer_events_sender: mpsc::UnboundedSender<PeerEvent>,

    /// [`TrackId`] to its [`sender::Component`].
    senders: HashMap<TrackId, sender::Component>,

    /// [`TrackId`] to its [`receiver::Component`].
    receivers: HashMap<TrackId, receiver::Component>,
}

impl InnerMediaConnections {
    /// Returns [`Iterator`] over [`sender::Component`]s with provided
    /// [`MediaKind`] and [`MediaSourceKind`].
    fn iter_senders_with_kind_and_source_kind(
        &self,
        kind: MediaKind,
        source_kind: Option<MediaSourceKind>,
    ) -> impl Iterator<Item = &sender::Component> {
        self.senders
            .values()
            .filter(move |sender| sender.state().kind() == kind)
            .filter(move |sender| {
                source_kind
                    .map_or(true, |sk| sender.caps().media_source_kind() == sk)
            })
    }

    /// Returns [`Iterator`] over [`receiver::Component`]s with provided
    /// [`MediaKind`] and [`MediaSourceKind`].
    fn iter_receivers_with_kind_and_source_kind(
        &self,
        kind: MediaKind,
        source_kind: Option<MediaSourceKind>,
    ) -> impl Iterator<Item = &receiver::Component> {
        self.receivers
            .values()
            .filter(move |s| s.state().kind() == kind)
            .filter(move |s| {
                source_kind
                    .map_or(true, |skind| s.state().source_kind() == skind)
            })
    }

    /// Returns all [`TransceiverSide`]s by provided [`TrackDirection`],
    /// [`MediaKind`] and [`MediaSourceKind`].
    #[expect(clippy::as_conversions, reason = "no other way")]
    fn get_transceivers_by_direction_and_kind(
        &self,
        direction: TrackDirection,
        kind: MediaKind,
        source_kind: Option<MediaSourceKind>,
    ) -> Vec<Rc<dyn TransceiverSide>> {
        match direction {
            TrackDirection::Send => self
                .iter_senders_with_kind_and_source_kind(kind, source_kind)
                .map(|tx| tx.state() as Rc<dyn TransceiverSide>)
                .collect(),
            TrackDirection::Recv => self
                .iter_receivers_with_kind_and_source_kind(kind, source_kind)
                .map(|rx| rx.state() as Rc<dyn TransceiverSide>)
                .collect(),
        }
    }

    /// Creates a [`platform::Transceiver`] and adds it to the
    /// [`platform::RtcPeerConnection`].
    ///
    /// Handles both audio and video media types, including setting up
    /// [`EncodingParameters`] and codec preferences for video.
    fn add_transceiver(
        &self,
        media_type: MediaType,
        direction: platform::TransceiverDirection,
    ) -> impl Future<Output = platform::Transceiver> + 'static {
        let peer = Rc::clone(&self.peer);

        async move {
            let kind = MediaKind::from(&media_type);

            match media_type {
                MediaType::Audio(_) => {
                    peer.add_transceiver(kind, TransceiverInit::new(direction))
                        .await
                }
                MediaType::Video(settings) => {
                    let mut init = TransceiverInit::new(direction);

                    let (target_codecs, target_scalability_mode) =
                        probe_video_codecs(&settings.svc_settings).await;

                    let encoding_params = get_encodings_params(
                        settings.encoding_parameters,
                        target_scalability_mode,
                    );
                    if !encoding_params.is_empty() {
                        init.sending_encodings(encoding_params);
                    }

                    let transceiver = peer.add_transceiver(kind, init).await;
                    if !target_codecs.is_empty() {
                        transceiver.set_codec_preferences(target_codecs);
                    }
                    transceiver
                }
            }
        }
    }

    /// Lookups a [`platform::Transceiver`] by the provided [`mid`].
    ///
    /// [`mid`]: https://w3.org/TR/webrtc#dom-rtptransceiver-mid
    fn get_transceiver_by_mid(
        &self,
        mid: String,
    ) -> impl Future<Output = Option<platform::Transceiver>> + 'static {
        self.peer.get_transceiver_by_mid(mid)
    }
}

/// Storage of [`platform::RtcPeerConnection`]'s [`sender::Component`] and
/// [`receiver::Component`].
#[derive(Debug)]
pub struct MediaConnections(RefCell<InnerMediaConnections>);

impl MediaConnections {
    /// Instantiates a new [`MediaConnections`] storage for the given
    /// [`platform::RtcPeerConnection`].
    #[must_use]
    pub fn new(
        peer: Rc<platform::RtcPeerConnection>,
        peer_events_sender: mpsc::UnboundedSender<PeerEvent>,
    ) -> Self {
        Self(RefCell::new(InnerMediaConnections {
            peer,
            peer_events_sender,
            senders: HashMap::new(),
            receivers: HashMap::new(),
        }))
    }

    /// Returns all [`Sender`]s and [`Receiver`]s from this [`MediaConnections`]
    /// with provided [`MediaKind`], [`TrackDirection`] and
    /// [`MediaSourceKind`].
    pub fn get_transceivers_sides(
        &self,
        kind: MediaKind,
        direction: TrackDirection,
        source_kind: Option<MediaSourceKind>,
    ) -> Vec<Rc<dyn TransceiverSide>> {
        self.0.borrow().get_transceivers_by_direction_and_kind(
            direction,
            kind,
            source_kind,
        )
    }

    /// Indicates whether all [`TransceiverSide`]s with provided [`MediaKind`],
    /// [`TrackDirection`] and [`MediaSourceKind`] is in the provided
    /// [`MediaExchangeState`].
    #[must_use]
    pub fn is_all_tracks_in_media_state(
        &self,
        kind: MediaKind,
        direction: TrackDirection,
        source_kind: Option<MediaSourceKind>,
        state: MediaState,
    ) -> bool {
        let transceivers =
            self.0.borrow().get_transceivers_by_direction_and_kind(
                direction,
                kind,
                source_kind,
            );
        for transceiver in transceivers {
            if !transceiver.is_transitable() {
                continue;
            }

            let not_in_state = match state {
                MediaState::Mute(mute_state) => {
                    transceiver.mute_state() != mute_state.into()
                }
                MediaState::MediaExchange(media_exchange) => {
                    transceiver.media_exchange_state() != media_exchange.into()
                }
            };
            if not_in_state {
                return false;
            }
        }

        true
    }

    /// Returns mapping from a [`proto::Track`] ID to a `mid` of this track's
    /// [`platform::Transceiver`].
    ///
    /// # Errors
    ///
    /// See [`GetMidsError`] for details.
    pub fn get_mids(
        &self,
    ) -> Result<HashMap<TrackId, String>, Traced<GetMidsError>> {
        let inner = self.0.borrow();
        let mut mids =
            HashMap::with_capacity(inner.senders.len() + inner.receivers.len());
        #[expect(clippy::iter_over_hash_type, reason = "order doesn't matter")]
        for (track_id, sender) in &inner.senders {
            drop(
                mids.insert(
                    *track_id,
                    sender
                        .mid()
                        .ok_or(GetMidsError::SendersWithoutMid)
                        .map_err(tracerr::wrap!())?,
                ),
            );
        }
        #[expect(clippy::iter_over_hash_type, reason = "order doesn't matter")]
        for (track_id, receiver) in &inner.receivers {
            drop(
                mids.insert(
                    *track_id,
                    receiver
                        .mid()
                        .ok_or(GetMidsError::ReceiversWithoutMid)
                        .map_err(tracerr::wrap!())?,
                ),
            );
        }
        Ok(mids)
    }

    /// Returns activity statuses of the all the [`Sender`]s and [`Receiver`]s
    /// from these [`MediaConnections`].
    pub fn get_transceivers_statuses(
        &self,
    ) -> impl Future<Output = HashMap<TrackId, bool>> + 'static {
        let inner = self.0.borrow();
        let transceivers = inner
            .senders
            .iter()
            .map(|(&track_id, sender)| {
                let sender = sender.obj();
                async move { (track_id, sender.is_publishing().await) }
                    .boxed_local()
            })
            .chain(inner.receivers.iter().map(|(&track_id, receiver)| {
                let receiver = receiver.obj();
                async move { (track_id, receiver.is_receiving().await) }
                    .boxed_local()
            }))
            .collect::<Vec<_>>();

        future::join_all(transceivers).map(|r| r.into_iter().collect())
    }

    /// Returns [`Rc`] to [`TransceiverSide`] with a provided [`TrackId`].
    ///
    /// Returns `None` if [`TransceiverSide`] with a provided [`TrackId`]
    /// doesn't exists in this [`MediaConnections`].
    #[expect(clippy::as_conversions, reason = "no other way")]
    pub fn get_transceiver_side_by_id(
        &self,
        track_id: TrackId,
    ) -> Option<Rc<dyn TransceiverSide>> {
        let inner = self.0.borrow();
        inner
            .senders
            .get(&track_id)
            .map(|sndr| sndr.state() as Rc<dyn TransceiverSide>)
            .or_else(|| {
                inner
                    .receivers
                    .get(&track_id)
                    .map(|rcvr| rcvr.state() as Rc<dyn TransceiverSide>)
            })
    }

    /// Inserts new [`sender::Component`] into [`MediaConnections`].
    pub fn insert_sender(&self, sender: sender::Component) {
        drop(
            self.0
                .borrow_mut()
                .senders
                .insert(sender.state().id(), sender),
        );
    }

    /// Inserts new [`receiver::Component`] into [`MediaConnections`].
    pub fn insert_receiver(&self, receiver: receiver::Component) {
        drop(
            self.0
                .borrow_mut()
                .receivers
                .insert(receiver.state().id(), receiver),
        );
    }

    /// Returns [`TracksRequest`] based on [`Sender`]s in this
    /// [`MediaConnections`]. [`Sender`]s are chosen based on provided
    /// [`LocalStreamUpdateCriteria`].
    pub fn get_tracks_request(
        &self,
        kinds: LocalStreamUpdateCriteria,
    ) -> Option<TracksRequest> {
        let mut stream_request = None;
        #[expect(clippy::iter_over_hash_type, reason = "order doesn't matter")]
        for sender in self.0.borrow().senders.values() {
            if kinds
                .has(sender.state().media_kind(), sender.state().media_source())
            {
                stream_request
                    .get_or_insert_with(TracksRequest::default)
                    .add_track_request(
                        sender.state().track_id(),
                        sender.caps().clone(),
                    );
            }
        }
        stream_request
    }

    /// Inserts provided tracks into [`Sender`]s based on track IDs.
    ///
    /// [`local::Track`]s are inserted into [`Sender`]'s
    /// [`platform::Transceiver`]s via a [`replaceTrack` method][1], changing
    /// its direction to `sendonly`.
    ///
    /// Returns [`HashMap`] with [`media_exchange_state::Stable`]s updates for
    /// the [`Sender`]s.
    ///
    /// # Errors
    ///
    /// See [`InsertLocalTracksError`] for details.
    ///
    /// [1]: https://w3.org/TR/webrtc#dom-rtcrtpsender-replacetrack
    pub async fn insert_local_tracks(
        &self,
        tracks: &HashMap<TrackId, Rc<local::Track>>,
    ) -> Result<
        HashMap<TrackId, media_exchange_state::Stable>,
        Traced<InsertLocalTracksError>,
    > {
        // Build sender to track pairs to catch errors before inserting.
        let mut sender_and_track =
            Vec::with_capacity(self.0.borrow().senders.len());
        let mut media_exchange_state_updates = HashMap::new();
        let senders = self
            .0
            .borrow()
            .senders
            .values()
            .map(|c| (c.obj(), c.state()))
            .collect::<Vec<_>>();
        for (sender, state) in senders {
            if let Some(track) = tracks.get(&state.id()).cloned() {
                if sender.caps().satisfies(track.as_ref()).await {
                    sender_and_track.push((sender, track));
                } else {
                    return Err(tracerr::new!(
                        InsertLocalTracksError::InvalidMediaTrack
                    ));
                }
            } else if sender.caps().required() {
                return Err(tracerr::new!(
                    InsertLocalTracksError::NotEnoughTracks
                ));
            } else {
                _ = media_exchange_state_updates
                    .insert(state.id(), media_exchange_state::Stable::Disabled);
            }
        }

        future::try_join_all(sender_and_track.into_iter().map(
            |(sender, track)| async move {
                Rc::clone(&sender).insert_track(track).await
            },
        ))
        .await
        .map(drop)
        .map_err(tracerr::map_from_and_wrap!())?;

        Ok(media_exchange_state_updates)
    }

    /// Adds a new track to the corresponding [`Receiver`].
    ///
    /// # Errors
    ///
    /// Errors with a transceivers `mid` if could not find [`Receiver`] by this
    /// `mid`.
    ///
    /// # Panics
    ///
    /// If the provided [`platform::Transceiver`] doesn't have a [`mid`]. Not
    /// supposed to happen, since [`platform::MediaStreamTrack`] is only fired
    /// when a [`platform::Transceiver`] is negotiated, thus have a [`mid`].
    ///
    /// [`mid`]: https://w3.org/TR/webrtc#dom-rtptransceiver-mid
    pub async fn add_remote_track(
        &self,
        track: platform::MediaStreamTrack,
        transceiver: platform::Transceiver,
    ) -> Result<(), String> {
        // Cannot fail, since transceiver is guaranteed to be negotiated at this
        // point.
        let mid = transceiver.mid().ok_or("No Transceiver::mid found")?;
        let receiver = self
            .0
            .borrow()
            .receivers
            .values()
            .find(|rcvr| rcvr.mid().as_ref() == Some(&mid))
            .map(Component::obj);

        if let Some(rcvr) = receiver {
            rcvr.set_remote_track(transceiver, track).await;
            Ok(())
        } else {
            Err(mid)
        }
    }

    /// Iterates over all [`Receiver`]s with [`mid`] and without
    /// [`platform::Transceiver`], trying to find the corresponding
    /// [`platform::Transceiver`] in the [`platform::RtcPeerConnection`] and to
    /// insert it into the [`Receiver`].
    ///
    /// [`mid`]: https://w3.org/TR/webrtc#dom-rtptransceiver-mid
    pub fn sync_receivers(&self) -> impl Future<Output = ()> + 'static {
        future::join_all({
            self.0
                .borrow()
                .receivers
                .values()
                .filter_map(|receiver| {
                    #[expect(clippy::question_mark, reason = "more readable")]
                    if receiver.transceiver().is_none() {
                        return None;
                    }
                    receiver.mid().map(|mid| {
                        let fut = {
                            self.0.borrow().peer.get_transceiver_by_mid(mid)
                        };
                        let receiver = Component::obj(receiver);
                        async move {
                            if let Some(t) = fut.await {
                                receiver.set_transceiver(t);
                            }
                        }
                    })
                })
                .collect::<Vec<_>>()
        })
        .map(drop)
    }

    /// Returns all [`Sender`]s which are matches provided
    /// [`LocalStreamUpdateCriteria`] and doesn't have [`local::Track`].
    pub fn get_senders_without_tracks_ids(
        &self,
        kinds: LocalStreamUpdateCriteria,
    ) -> Vec<TrackId> {
        self.0
            .borrow()
            .senders
            .values()
            .filter_map(|s| {
                (kinds.has(s.state().kind(), s.state().source_kind())
                    && s.state().enabled()
                    && !s.has_track())
                .then_some(s.state().id())
            })
            .collect()
    }

    /// Drops [`local::Track`]s of all [`Sender`]s which are matches provided
    /// [`LocalStreamUpdateCriteria`].
    pub async fn drop_send_tracks(&self, kinds: LocalStreamUpdateCriteria) {
        let remove_tracks_fut = future::join_all(
            self.0
                .borrow()
                .senders
                .values()
                .filter(|&s| {
                    kinds.has(s.state().kind(), s.state().source_kind())
                })
                .map(|s| {
                    let sender = s.obj();
                    async move {
                        sender.remove_track().await;
                    }
                }),
        );
        drop(remove_tracks_fut.await);
    }

    /// Removes a [`sender::Component`] or a [`receiver::Component`] with the
    /// provided [`TrackId`] from these [`MediaConnections`].
    pub fn remove_track(&self, track_id: TrackId) {
        let mut inner = self.0.borrow_mut();
        if inner.receivers.remove(&track_id).is_none() {
            drop(inner.senders.remove(&track_id));
        }
    }
}

#[cfg(feature = "mockable")]
// TODO: Try remove on next Rust version upgrade.
#[expect(clippy::allow_attributes, reason = "`#[expect]` is not considered")]
#[allow(clippy::multiple_inherent_impl, reason = "feature gated")]
impl MediaConnections {
    /// Indicates whether all [`Receiver`]s with [`MediaKind::Video`] are
    /// enabled.
    #[must_use]
    pub fn is_recv_video_enabled(&self) -> bool {
        !self
            .0
            .borrow()
            .iter_receivers_with_kind_and_source_kind(MediaKind::Video, None)
            .any(|s| !s.state().enabled_individual())
    }

    /// Indicates whether if all [`Receiver`]s with [`MediaKind::Audio`] are
    /// enabled.
    #[must_use]
    pub fn is_recv_audio_enabled(&self) -> bool {
        !self
            .0
            .borrow()
            .iter_receivers_with_kind_and_source_kind(MediaKind::Audio, None)
            .any(|s| !s.state().enabled_individual())
    }

    /// Returns [`Receiver`] with the provided [`TrackId`].
    #[must_use]
    pub fn get_receiver_by_id(&self, id: TrackId) -> Option<Rc<Receiver>> {
        self.0.borrow().receivers.get(&id).map(Component::obj)
    }

    /// Returns [`Sender`] with a provided [`TrackId`].
    #[must_use]
    pub fn get_sender_by_id(&self, id: TrackId) -> Option<Rc<Sender>> {
        self.0.borrow().senders.get(&id).map(Component::obj)
    }

    /// Indicates whether all [`Sender`]s with [`MediaKind::Audio`] are enabled.
    #[must_use]
    pub fn is_send_audio_enabled(&self) -> bool {
        self.0
            .borrow()
            .iter_senders_with_kind_and_source_kind(MediaKind::Audio, None)
            .all(|s| s.state().enabled())
    }

    /// Indicates whether all [`Sender`]s with [`MediaKind::Video`] are enabled.
    #[must_use]
    pub fn is_send_video_enabled(
        &self,
        source_kind: Option<MediaSourceKind>,
    ) -> bool {
        self.0
            .borrow()
            .iter_senders_with_kind_and_source_kind(
                MediaKind::Video,
                source_kind,
            )
            .all(|s| s.state().enabled())
    }

    /// Indicates whether all [`Sender`]'s video tracks are unmuted.
    #[must_use]
    pub fn is_send_video_unmuted(
        &self,
        source_kind: Option<MediaSourceKind>,
    ) -> bool {
        !self
            .0
            .borrow()
            .iter_senders_with_kind_and_source_kind(
                MediaKind::Video,
                source_kind,
            )
            .any(|s| s.muted())
    }

    /// Indicates whether all [`Sender`]'s audio tracks are unmuted.
    #[must_use]
    pub fn is_send_audio_unmuted(&self) -> bool {
        !self
            .0
            .borrow()
            .iter_senders_with_kind_and_source_kind(MediaKind::Audio, None)
            .any(|s| s.muted())
    }

    /// Creates a new [`sender::Component`] with the provided data.
    ///
    /// # Errors
    ///
    /// See [`sender::CreateError`] for details.
    #[expect(clippy::too_many_arguments, reason = "not a problem")]
    pub async fn create_sender(
        &self,
        id: TrackId,
        media_type: MediaType,
        media_direction: proto::MediaDirection,
        muted: bool,
        mid: Option<String>,
        receivers: Vec<MemberId>,
        send_constraints: &LocalTracksConstraints,
        connection_mode: ConnectionMode,
    ) -> Result<sender::Component, Traced<sender::CreateError>> {
        let sender_state = sender::State::new(
            id,
            mid,
            media_type,
            media_direction,
            muted,
            receivers,
            send_constraints.clone(),
            connection_mode,
        );
        let sender = Sender::new(
            &sender_state,
            self,
            send_constraints.clone(),
            mpsc::unbounded().0,
        )
        .await?;

        Ok(sender::Component::new(sender, Rc::new(sender_state)))
    }

    /// Creates a new [`receiver::Component`] with the provided data.
    #[expect(clippy::too_many_arguments, reason = "not a problem")]
    pub async fn create_receiver(
        &self,
        id: TrackId,
        media_type: MediaType,
        media_direction: proto::MediaDirection,
        muted: bool,
        mid: Option<String>,
        sender: MemberId,
        recv_constraints: &RecvConstraints,
        connection_mode: ConnectionMode,
    ) -> receiver::Component {
        let state = receiver::State::new(
            id,
            mid,
            media_type,
            media_direction,
            muted,
            sender,
            connection_mode,
        );
        let receiver = Receiver::new(
            &state,
            self,
            mpsc::unbounded().0,
            recv_constraints,
            connection_mode,
        )
        .await;

        receiver::Component::new(Rc::new(receiver), Rc::new(state))
    }

    /// Creates a new [`sender::Component`]s/[`receiver::Component`]s from the
    /// provided [`proto::Track`]s.
    ///
    /// # Errors
    ///
    /// See [`sender::CreateError`] for details.
    pub async fn create_tracks(
        &self,
        tracks: Vec<proto::Track>,
        send_constraints: &LocalTracksConstraints,
        recv_constraints: &RecvConstraints,
        connection_mode: ConnectionMode,
    ) -> Result<(), Traced<sender::CreateError>> {
        for track in tracks {
            match track.direction {
                proto::Direction::Send { mid, receivers } => {
                    let is_muted = send_constraints.muted(&track.media_type);
                    let component = self
                        .create_sender(
                            track.id,
                            track.media_type,
                            proto::MediaDirection::SendRecv,
                            is_muted,
                            mid,
                            receivers,
                            send_constraints,
                            connection_mode,
                        )
                        .await?;
                    drop(
                        self.0.borrow_mut().senders.insert(track.id, component),
                    );
                }
                proto::Direction::Recv { mid, sender } => {
                    let component = self
                        .create_receiver(
                            track.id,
                            track.media_type,
                            proto::MediaDirection::SendRecv,
                            false,
                            mid,
                            sender,
                            recv_constraints,
                            connection_mode,
                        )
                        .await;
                    drop(
                        self.0
                            .borrow_mut()
                            .receivers
                            .insert(track.id, component),
                    );
                }
            }
        }
        Ok(())
    }

    /// Returns all underlying [`Sender`]'s.
    pub fn get_senders(&self) -> Vec<Rc<Sender>> {
        self.0
            .borrow()
            .senders
            .values()
            .map(Component::obj)
            .collect()
    }

    /// Returns [`sender::State`] with the provided [`TrackId`].
    #[must_use]
    pub fn get_sender_state_by_id(
        &self,
        id: TrackId,
    ) -> Option<Rc<sender::State>> {
        self.0.borrow().senders.get(&id).map(Component::state)
    }
}