rtci 0.4.1

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
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
//! RTP Media API
//!
//! This module provides the RTCRtpTransceiver, which represents a permanent pairing
//! of an [`RTCRtpSender`](rtp_sender::RTCRtpSender) and an [`RTCRtpReceiver`](rtp_receiver::RTCRtpReceiver),
//! along with shared state.
//!
//! # Overview
//!
//! A transceiver manages bidirectional media exchange for a single media type (audio or video).
//! It combines:
//! - An RTP sender for outgoing media
//! - An RTP receiver for incoming media  
//! - Shared state including direction, mid, and codec preferences
//!
//! # Examples
//!
//! ## Adding a transceiver from a track
//!
//! ```no_run
//! # use std::time::Instant;
//! # use rtci::peer_connection::RTCPeerConnectionBuilder;
//! # use rtci::media_stream::MediaStreamTrack;
//! # use rtci::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
//! # fn example(audio_track: MediaStreamTrack) -> Result<(), Box<dyn std::error::Error>> {
//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
//!
//! // Add a transceiver for sending audio
//! let init = RTCRtpTransceiverInit {
//!     direction: RTCRtpTransceiverDirection::Sendrecv,
//!     ..Default::default()
//! };
//!
//! let sender_id = peer_connection
//!     .add_transceiver_from_track(audio_track, Some(init))?;
//!
//! println!("Added sender with ID: {:?}", sender_id);
//! # Ok(())
//! # }
//! ```
//!
//! ## Adding a transceiver by media kind
//!
//! ```no_run
//! # use std::time::Instant;
//! # use rtci::peer_connection::RTCPeerConnectionBuilder;
//! # use rtci::rtp_transceiver::rtp_sender::RtpCodecKind;
//! # use rtci::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
//!
//! // Add a video transceiver for receiving only
//! let init = RTCRtpTransceiverInit {
//!     direction: RTCRtpTransceiverDirection::Recvonly,
//!     ..Default::default()
//! };
//!
//! let receiver_id = peer_connection
//!     .add_transceiver_from_kind(RtpCodecKind::Video, Some(init))?;
//!
//! println!("Added receiver with ID: {:?}", receiver_id);
//! # Ok(())
//! # }
//! ```
//!
//! ## Controlling transceiver direction
//!
//! ```no_run
//! # use std::time::Instant;
//! # use rtci::peer_connection::RTCPeerConnectionBuilder;
//! # use rtci::rtp_transceiver::RTCRtpTransceiverDirection;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
//!
//! // Iterate through transceivers and change direction
//! for transceiver_id in peer_connection.get_transceivers() {
//!     // Access the transceiver through peer_connection's internal methods
//!     // Note: Direct transceiver access may be internal API
//!     // This demonstrates the concept - actual usage depends on your API design
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Setting codec preferences
//!
//! ```no_run
//! # use std::time::Instant;
//! # use rtci::peer_connection::RTCPeerConnectionBuilder;
//! # use rtci::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
//! # fn example(preferred_codecs: Vec<RTCRtpCodecParameters>) -> Result<(), Box<dyn std::error::Error>> {
//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
//!
//! // Codec preferences would be set through peer connection methods
//! // The exact API depends on your implementation
//! # Ok(())
//! # }
//! ```
//!
//! # Specification
//!
//! See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.

use crate::media_stream::MediaStreamId;
use crate::peer_connection::RTCPeerConnection;
use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
use crate::rtp_transceiver::rtp_sender::{RTCRtpCodecParameters, RTCRtpHeaderExtensionToNegotiate};
pub use direction::RTCRtpTransceiverDirection;
use log::trace;
use shared::error::{Error, Result};

pub(crate) mod direction;
pub(crate) mod fmtp;
pub(crate) mod header_extension_control;
pub(crate) mod internal;
pub mod rtp_receiver;
pub mod rtp_sender;
#[cfg(test)]
mod rtp_transceiver_test;
pub mod sframe_transform;

/// SSRC (Synchronization Source) identifier.
///
/// A synchronization source is a randomly chosen value meant to be globally unique
/// within a particular RTP session. It is used to identify a single stream of media.
///
/// # Specification
///
/// See [RFC 3550 Section 3](https://datatracker.ietf.org/doc/html/rfc3550#section-3).
#[allow(clippy::upper_case_acronyms)]
pub type SSRC = u32;

/// RTP payload type identifier.
///
/// Identifies the format of the RTP payload and determines its interpretation by the
/// application. Each codec in an RTP session will have a different payload type.
///
/// # Specification
///
/// See [RFC 3550 Section 3](https://datatracker.ietf.org/doc/html/rfc3550#section-3).
pub type PayloadType = u8;

/// RTP stream identifier.
///
/// Is used for unique identification of RTP stream
///
/// # Specification
///
/// See [RFC 8852 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8852#section-3.1).
pub type RtpStreamId = String;

/// Repaired RTP stream identifier.
///
/// Is used to identify which stream is to be repaired using a redundancy RTP stream
///
/// # Specification
///
/// See [RFC 8852 Section 3.2](https://datatracker.ietf.org/doc/html/rfc8852#section-3.2).
pub type RepairedStreamId = String;

/// Internal identifier for an RTP transceiver.
pub type RTCRtpTransceiverId = usize;

impl From<RTCRtpSenderId> for RTCRtpTransceiverId {
    fn from(id: RTCRtpSenderId) -> Self {
        id.0
    }
}

impl From<RTCRtpReceiverId> for RTCRtpTransceiverId {
    fn from(id: RTCRtpReceiverId) -> Self {
        id.0
    }
}

/// Identifier for an `RTCRtpSender` within a peer connection.
///
/// Used to reference a specific RTP sender when calling methods like `remove_track`.
#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RTCRtpSenderId(pub(crate) RTCRtpTransceiverId);

impl From<RTCRtpTransceiverId> for RTCRtpSenderId {
    fn from(id: RTCRtpTransceiverId) -> Self {
        Self(id)
    }
}

/// Identifier for an `RTCRtpReceiver` within a peer connection.
///
/// Used to reference a specific RTP receiver when handling incoming media.
#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RTCRtpReceiverId(pub(crate) RTCRtpTransceiverId);

impl From<RTCRtpTransceiverId> for RTCRtpReceiverId {
    fn from(id: RTCRtpTransceiverId) -> Self {
        Self(id)
    }
}

/// The semantics of the `a=group` line that groups a media m= section with the m= section of
/// its FEC session (RFC 5109 section 14.1,
/// [`RTCPeerConnection::add_fec_session`](crate::peer_connection::RTCPeerConnection::add_fec_session)).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RTCFecGroupSemantics {
    /// `a=group:FEC-FR` (RFC 5956 section 4.1), the default: RFC 5956 section 4.4,
    /// "Sessions negotiated between two endpoints implementing this specification MUST use
    /// the "FEC-FR" semantics and not the "FEC" semantics".
    #[default]
    FecFr,
    /// `a=group:FEC` (RFC 4756), the semantics RFC 5109 sections 14.1 and 14.3 name, which
    /// RFC 5956 section 4.4 deprecates and section 4.5 keeps for a peer that only implements
    /// RFC 4756.
    Fec,
}

impl RTCFecGroupSemantics {
    /// The semantics token of the `a=group` line.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::FecFr => "FEC-FR",
            Self::Fec => "FEC",
        }
    }

    /// The semantics an `a=group` line's token names, when it is one of the two.
    pub fn from_token(token: &str) -> Option<Self> {
        match token {
            "FEC-FR" => Some(Self::FecFr),
            "FEC" => Some(Self::Fec),
            _ => None,
        }
    }
}

/// Initialization parameters for creating an `RTCRtpTransceiver`.
///
/// Used with `add_transceiver_from_track` or `add_transceiver_from_kind` to configure
/// the transceiver's initial direction and encoding parameters.
///
/// # Specification
///
/// See [RTCRtpTransceiverInit](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiverinit)
#[derive(Clone)]
pub struct RTCRtpTransceiverInit {
    /// The initial direction of the transceiver; sendrecv by default.
    pub direction: RTCRtpTransceiverDirection,
    /// The stream IDs associated with the transceiver's sender.
    pub streams: Vec<MediaStreamId>,
    /// The encoding parameters to use when sending media.
    pub send_encodings: Vec<RTCRtpEncodingParameters>,
}

impl Default for RTCRtpTransceiverInit {
    /// W3C `RTCRtpTransceiverInit`: direction "sendrecv", no streams, no send encodings.
    fn default() -> Self {
        Self::with_direction(RTCRtpTransceiverDirection::Sendrecv)
    }
}

impl RTCRtpTransceiverInit {
    /// An init with `direction`, no streams and no send encodings.
    pub fn with_direction(direction: RTCRtpTransceiverDirection) -> Self {
        Self {
            direction,
            streams: vec![],
            send_encodings: vec![],
        }
    }

    /// The init of a transceiver that offers to receive only.
    pub fn recvonly() -> Self {
        Self::with_direction(RTCRtpTransceiverDirection::Recvonly)
    }

    /// Sends `encodings` as simulcast layers: each one an RTP stream of its own, named by
    /// its rid in the description (`a=rid` and `a=simulcast`, RFC 8853).
    ///
    /// In this API several encodings *without* rids are codec alternatives of one stream
    /// (the first one the negotiation allows is sent), as upstream has them. Encodings given
    /// here are layers instead: one without a rid gets one generated, as RFC 9429 section
    /// 5.2.1 asks when the application set none ("an rid-id value MUST be generated ... it
    /// MUST NOT contain user data, ... SHOULD be no more than 3 bytes"): the smallest
    /// decimal number (`0`, `1`, ...) no other encoding uses. Rids the application set are
    /// kept.
    ///
    /// # Examples
    ///
    /// ```
    /// use rtci::rtp_transceiver::RTCRtpTransceiverInit;
    /// use rtci::rtp_transceiver::rtp_sender::RTCRtpEncodingParameters;
    ///
    /// let init = RTCRtpTransceiverInit::default()
    ///     .with_simulcast_layers(vec![RTCRtpEncodingParameters::default(); 3]);
    /// let rids: Vec<&str> = init
    ///     .send_encodings
    ///     .iter()
    ///     .map(|e| e.rtp_coding_parameters.rid.as_str())
    ///     .collect();
    /// assert_eq!(rids, ["0", "1", "2"]);
    /// ```
    pub fn with_simulcast_layers(mut self, mut encodings: Vec<RTCRtpEncodingParameters>) -> Self {
        let mut next = 0usize;
        for i in 0..encodings.len() {
            if !encodings[i].rtp_coding_parameters.rid.is_empty() {
                continue;
            }
            let rid = loop {
                let candidate = next.to_string();
                next += 1;
                if !encodings
                    .iter()
                    .any(|e| e.rtp_coding_parameters.rid == candidate)
                {
                    break candidate;
                }
            };
            encodings[i].rtp_coding_parameters.rid = rid;
        }
        self.send_encodings = encodings;
        self
    }
}

/// RTCRtpTransceiver represents a permanent pairing of an RTP sender and RTP receiver that share a common mid.
/// The transceiver manages the direction of media flow and codec preferences.
///
/// # Specification
///
/// See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.
pub struct RTCRtpTransceiver<'a> {
    pub(crate) id: RTCRtpTransceiverId,
    pub(crate) peer_connection: &'a mut RTCPeerConnection,
}

/// What the `b=` lines of a remote media section say (RFC 9429 section 5.10), in bits per
/// second. `None`: the section has no such line.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct RTCRemoteBandwidth {
    /// The most RTP the remote side accepts from this endpoint in the section: `b=TIAS` (RFC
    /// 3890, the bit rate without transport overhead), else the value RFC 9429 section 5.10
    /// derives from `b=AS` (kilobits per second, RFC 8866 section 5.8): "TIAS = AS * 1000 *
    /// 0.95 - (50 * 40 * 8)", which takes out RTCP's 5% and an estimate of the header
    /// overhead. The bound of the congestion controller's estimate, and what an encoder caps
    /// its target with.
    pub max_bitrate: Option<u64>,
    /// The session bandwidth of the section (RFC 3550 section 6.2), which RTCP's share is
    /// taken from: `b=TIAS`, else `b=AS` times 1000.
    pub session_bitrate: Option<u64>,
    /// `b=RS` (RFC 3556): the RTCP bandwidth allocated to active data senders.
    pub rtcp_senders_bitrate: Option<u64>,
    /// `b=RR` (RFC 3556): the RTCP bandwidth allocated to receivers; 0 turns their RTCP off.
    pub rtcp_receivers_bitrate: Option<u64>,
}

impl RTCRtpTransceiver<'_> {
    /// The bandwidth limits the remote description states for this transceiver's media
    /// section (`b=TIAS` / `b=AS`, `b=RS`, `b=RR`); all `None` before a remote description
    /// with such lines is applied.
    pub fn remote_bandwidth(&self) -> RTCRemoteBandwidth {
        self.peer_connection.rtp_transceivers[self.id].remote_bandwidth()
    }

    /// The `xr-format`s the remote description lists in `a=rtcp-xr` for this transceiver's
    /// media section (RFC 3611 section 5.1; the media-level attribute, else the session's),
    /// such as `rcvr-rtt=all`. `None`: no such attribute. `Some` of an empty list: the remote
    /// side wants no XR blocks (RFC 3611 section 5.2).
    pub fn remote_rtcp_xr(&self) -> Option<&[String]> {
        self.peer_connection.rtp_transceivers[self.id].remote_rtcp_xr()
    }

    /// The packet times the remote description states for this transceiver's media section
    /// (`a=ptime`, `a=maxptime`, in milliseconds; RFC 8866 sections 6.4, 6.5): how much media
    /// the remote side wants in a packet, and the most it takes. For Opus they are its
    /// `ptime` and `maxptime` (RFC 7587 section 7). All `None` before a remote description
    /// states them. This endpoint's own are
    /// [`MediaEngine::set_audio_packet_time`](crate::peer_connection::configuration::media_engine::MediaEngine::set_audio_packet_time).
    pub fn remote_packet_time(
        &self,
    ) -> crate::peer_connection::configuration::media_engine::RTCPacketTime {
        self.peer_connection.rtp_transceivers[self.id].remote_packet_time()
    }

    /// The maximum video frame rate the remote description states for this transceiver's
    /// media section (`a=framerate`, RFC 8866 section 6.13: "a recommendation for the encoding
    /// of video data"), in frames per second. `None` before a remote description states one.
    /// It is reported, not applied: an application that honours it caps its encoder, or the
    /// sender's encodings with
    /// [`RTCRtpEncodingParameters::max_framerate`](crate::rtp_transceiver::rtp_sender::RTCRtpEncodingParameters::max_framerate).
    pub fn remote_framerate(&self) -> Option<f64> {
        self.peer_connection.rtp_transceivers[self.id].remote_framerate()
    }

    /// The tags of the `a=content` attribute the remote description states for this
    /// transceiver's media section (RFC 4796 section 5), in order, such as `["slides"]` or
    /// `["main"]`: what the remote side's stream shows. Any token is reported; RFC 4796 says a
    /// tag the application does not know is ignored. `None` before a remote description
    /// states one.
    pub fn remote_content(&self) -> Option<&[String]> {
        self.peer_connection.rtp_transceivers[self.id].remote_content()
    }

    /// Whether the last answer negotiated reduced-size RTCP for this transceiver's media
    /// section (`a=rtcp-rsize` in the offer and in the answer, RFC 5506 section 5).
    pub fn rtcp_reduced_size(&self) -> bool {
        self.peer_connection.rtp_transceivers[self.id].rtcp_reduced_size()
    }

    /// Returns the media stream identification tag (mid) for this transceiver.
    ///
    /// The mid uniquely identifies the media description in the SDP. `create_offer` and
    /// `create_answer` choose it (W3C `[[JsepMid]]`), but it is the transceiver's mid only
    /// once a description that has it is applied: W3C webrtc-pc 4.4.1.6, "set the
    /// transceiver's \[\[Mid\]\] slot to transceiver.\[\[JsepMid\]\]" when a local description is
    /// applied, and from the remote description's section when a remote one is. Until then,
    /// and after a rollback that disassociates it, it is `None`.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.mid](https://www.w3.org/TR/webrtc/#dom-rtptransceiver-mid).
    pub fn mid(&self) -> &Option<String> {
        static NO_MID: Option<String> = None;
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        let mid = self.peer_connection.rtp_transceivers[self.id].mid();
        match mid {
            Some(value) if self.peer_connection.applied_description_has_mid(value) => mid,
            _ => &NO_MID,
        }
    }

    /// Returns the id of this transceiver's [`RTCRtpSender`].
    ///
    /// Every transceiver has a sender from its creation, with or without a track (W3C webrtc
    /// 5.4 `[[Sender]]`); the value is always `Some`.
    ///
    /// [`RTCRtpSender`]: crate::rtp_transceiver::rtp_sender::RTCRtpSender
    pub fn sender(&self) -> Option<RTCRtpSenderId> {
        Some(RTCRtpSenderId::from(self.id))
    }

    /// Returns the id of this transceiver's [`RTCRtpReceiver`].
    ///
    /// Every transceiver has a receiver from its creation, whatever its direction (W3C webrtc
    /// 5.4 `[[Receiver]]`); the value is always `Some`.
    ///
    /// [`RTCRtpReceiver`]: crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver
    pub fn receiver(&self) -> Option<RTCRtpReceiverId> {
        Some(RTCRtpReceiverId::from(self.id))
    }

    /// Returns the preferred direction of the transceiver:
    /// [`Stopped`](RTCRtpTransceiverDirection::Stopped) once [`stop`](Self::stop) was called
    /// or the transceiver is stopped, otherwise the direction the application prefers.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
    pub fn direction(&self) -> RTCRtpTransceiverDirection {
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        let transceiver = &self.peer_connection.rtp_transceivers[self.id];
        if transceiver.stopped() {
            RTCRtpTransceiverDirection::Stopped
        } else {
            transceiver.direction()
        }
    }

    /// Whether the transceiver is stopping or stopped: [`stop`](Self::stop) was called, or a
    /// description rejected its m= section. Such a transceiver sends and receives nothing and
    /// is offered rejected; see [`is_stopped`](Self::is_stopped) for the second state alone.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.stop()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop).
    pub fn stopped(&self) -> bool {
        self.peer_connection.rtp_transceivers[self.id].stopped()
    }

    /// webrtc-encoded-transform 2.1 `[[useSFrame]]`: `None` (undefined) until a transform is
    /// set ([`set_transform_use_sframe`](Self::set_transform_use_sframe)) or the transceiver
    /// is described: by a remote description, whether its section has `a=sframe`; by a local
    /// one, false. When true the media section carries `a=sframe` (draft-ietf-avtcore-rtp-
    /// sframe-03 section 6) and the application sends and receives SFrame with
    /// `rtci::rtp::codec::sframe` and `rtci::sframe`.
    pub fn use_sframe(&self) -> Option<bool> {
        self.peer_connection.rtp_transceivers[self.id].use_sframe()
    }

    /// webrtc-encoded-transform 2.2, the `transform` setter of the transceiver's sender or
    /// receiver, for a transform whose `[[useSFrame]]` is `transform_uses_sframe`
    /// (`RTCRtpSFrameEncryptor` / `RTCRtpSFrameDecryptor`, a script transform of type
    /// "sframe": true; any other: false).
    ///
    /// # Errors
    ///
    /// InvalidModificationError when the transceiver's `[[useSFrame]]` is the other value;
    /// InvalidStateError when the connection is closed.
    pub fn set_transform_use_sframe(&mut self, transform_uses_sframe: bool) -> Result<()> {
        if self.peer_connection.is_closed() {
            return Err(Error::ErrConnectionClosed);
        }
        self.peer_connection.rtp_transceivers[self.id]
            .set_transform_use_sframe(transform_uses_sframe)
    }

    /// draft-ietf-avtcore-rtp-sframe-03 section 6: this side offered SFrame and the answer left
    /// it out: the sender's `write_rtp` is refused (`ErrSFrameRefused`) and what arrives is
    /// discarded, until an answer accepts it or the section is closed.
    pub fn sframe_refused(&self) -> bool {
        self.peer_connection.rtp_transceivers[self.id].sframe_refused()
    }

    /// W3C `[[Stopped]]`: a description rejected this transceiver's m= section (or it was
    /// created for a rejected one). [`stop`](Self::stop) alone leaves it stopping, not
    /// stopped, until the exchange that rejects the section completes.
    pub fn is_stopped(&self) -> bool {
        self.peer_connection.rtp_transceivers[self.id].is_stopped()
    }

    /// Whether a remote offer's new media section may be associated with this transceiver.
    ///
    /// See [`RTCRtpTransceiver::set_associable_with_remote_offer`].
    pub fn associable_with_remote_offer(&self) -> bool {
        self.peer_connection.rtp_transceivers[self.id].associable_with_remote_offer()
    }

    /// Sets whether a remote offer's new media section may be associated with this
    /// transceiver while it has no mid.
    ///
    /// RFC 9429, Section 5.10 gives a remote offer's new media section a transceiver that
    /// "was created by `addTrack`" (same kind, never associated, not stopped), and otherwise
    /// a new one; a transceiver the application created with `addTransceiver` is not a
    /// candidate, and is offered in a media section of its own later. This crate has one way
    /// to create a transceiver for both, so the application says which it was: `true` (the
    /// default) for `addTrack`, `false` for `addTransceiver`. Set it back to `true` when
    /// `addTrack` reuses the transceiver.
    pub fn set_associable_with_remote_offer(&mut self, associable: bool) {
        self.peer_connection.rtp_transceivers[self.id].set_associable_with_remote_offer(associable);
    }

    /// Where this transceiver's m= section goes in the BUNDLE groups of the next offers this
    /// side makes (W3C webrtc-pc has no such member; a JSEP application needs it to use RFC
    /// 9143 sections 7.5.1 and 7.5.2):
    ///
    /// - `Some(false)`: out of every group. The offer gives the section a transport of its own
    ///   (its own candidates, which the application gathers for the entry
    ///   [`ice_transport_sections`](crate::peer_connection::RTCPeerConnection::ice_transport_sections)
    ///   then lists, and its own DTLS association), leaves its tag out of the group and does
    ///   not mark it `a=bundle-only` (RFC 9143 section 7.5.2). Once the answer accepts it, the
    ///   section stays on that transport.
    /// - `Some(true)`: in the first BUNDLE group (section 7.5.1); an answer that accepts it
    ///   there closes its transport.
    /// - `None` (the default): where the most recent answer put it (RFC 9429 section 5.2.2).
    ///
    /// It takes effect at the next `create_offer`; the application starts that negotiation.
    /// Answers follow the remote offer's groups whatever this says.
    pub fn set_bundle_request(&mut self, request: Option<bool>) {
        self.peer_connection.rtp_transceivers[self.id].set_bundle_request(request);
    }

    /// What [`Self::set_bundle_request`] last set.
    pub fn bundle_request(&self) -> Option<bool> {
        self.peer_connection.rtp_transceivers[self.id].bundle_request()
    }

    /// Marks this transceiver as touched by W3C `addTrack`: a rollback of the remote offer that
    /// created it keeps it (RFC 9429, Section 5.7). For a caller that attaches the track itself,
    /// to a transceiver that already has a sender.
    pub fn keep_on_rollback(&mut self) {
        self.peer_connection.rtp_transceivers[self.id].set_created_by_remote_description(false);
    }

    /// webrtc-extensions 4.2 `getHeaderExtensionsToNegotiate()`: the header extensions this
    /// transceiver's next offers and answers negotiate, each with its direction ("stopped":
    /// not negotiated). Initially the media engine's extensions for the kind, in the
    /// direction each was registered for, or the list of the first transceiver of the same
    /// kind that is not stopping, when it has one set; after an answer, what it negotiated.
    pub fn get_header_extensions_to_negotiate(&self) -> Vec<RTCRtpHeaderExtensionToNegotiate> {
        self.peer_connection.rtp_transceivers[self.id]
            .header_extensions_to_negotiate_list(&self.peer_connection.media_engine)
    }

    /// webrtc-extensions 4.2 `setHeaderExtensionsToNegotiate(extensions)`: sets the
    /// directions the next offers and answers negotiate the header extensions in. An offer
    /// carries an `a=extmap` for each extension that is not "stopped", with its direction (a
    /// re-offer included: an extension stopped by an earlier answer comes back with the id it
    /// had, or a free one); an answer carries an offered extension only when it is not
    /// "stopped" here, in a direction within the offer's.
    ///
    /// # Errors
    ///
    /// `InvalidModificationError` when `extensions` has another size than
    /// [`Self::get_header_extensions_to_negotiate`], names another URI at an index, makes the
    /// mandatory-to-use `urn:ietf:params:rtp-hdrext:sdes:mid` anything but "sendrecv", or
    /// stops a mandatory-to-implement extension (the mid, and the RFC 6464 audio level; RFC
    /// 8834 section 5.2); a `TypeError` for an `Unspecified` direction.
    pub fn set_header_extensions_to_negotiate(
        &mut self,
        extensions: Vec<RTCRtpHeaderExtensionToNegotiate>,
    ) -> Result<()> {
        let current = self.get_header_extensions_to_negotiate();
        crate::rtp_transceiver::header_extension_control::validate(&current, &extensions)?;
        let mut extensions = extensions;
        crate::rtp_transceiver::header_extension_control::restrict_to_capabilities(
            &self.peer_connection.media_engine,
            self.peer_connection.rtp_transceivers[self.id].kind(),
            &mut extensions,
        );
        self.peer_connection.rtp_transceivers[self.id]
            .set_header_extensions_to_negotiate(extensions);
        Ok(())
    }

    /// webrtc-extensions 4.2 `getNegotiatedHeaderExtensions()`: the extensions the last
    /// applied answer negotiated for this transceiver, each with its direction from this
    /// side's point of view ("stopped" for one the answer left out). Empty until an answer.
    pub fn get_negotiated_header_extensions(&self) -> Vec<RTCRtpHeaderExtensionToNegotiate> {
        self.peer_connection.rtp_transceivers[self.id]
            .negotiated_header_extensions()
            .to_vec()
    }

    /// Sets the preferred direction of this transceiver.
    ///
    /// Changing the direction updates the negotiation-needed flag; setting the direction it
    /// already has does nothing.
    ///
    /// # Errors
    ///
    /// - [`Error::ErrConnectionClosed`] when the connection is closed and
    ///   [`Error::InvalidStateError`] when the transceiver is stopping or stopped (both W3C
    ///   `InvalidStateError`)
    /// - [`Error::ErrInvalidDirection`] for
    ///   [`Stopped`](RTCRtpTransceiverDirection::Stopped) or
    ///   [`Unspecified`](RTCRtpTransceiverDirection::Unspecified) (W3C `TypeError`)
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
    pub fn set_direction(&mut self, direction: RTCRtpTransceiverDirection) -> Result<()> {
        if self.peer_connection.is_closed() {
            return Err(Error::ErrConnectionClosed);
        }
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        if self.peer_connection.rtp_transceivers[self.id].stopped() {
            return Err(Error::InvalidStateError);
        }
        if matches!(
            direction,
            RTCRtpTransceiverDirection::Stopped | RTCRtpTransceiverDirection::Unspecified
        ) {
            return Err(Error::ErrInvalidDirection);
        }
        let previous_direction = self.peer_connection.rtp_transceivers[self.id].direction();
        if direction == previous_direction {
            return Ok(());
        }
        // A sender that is to send needs encodings (SSRCs) to describe.
        if direction.has_send() {
            self.peer_connection.ensure_send_encodings(self.id)?;
        }
        self.peer_connection.rtp_transceivers[self.id].set_direction(direction);
        trace!("Changing direction of transceiver from {previous_direction} to {direction}");
        self.peer_connection.on_transceiver_direction_changed();
        Ok(())
    }

    /// Returns the negotiated direction of the transceiver.
    ///
    /// The direction the last completed offer/answer exchange negotiated; `None` (W3C null)
    /// before the first, and [`RTCRtpTransceiverDirection::Stopped`] once the transceiver is
    /// stopped.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.currentDirection](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-currentdirection).
    pub fn current_direction(&self) -> Option<RTCRtpTransceiverDirection> {
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        let transceiver = &self.peer_connection.rtp_transceivers[self.id];
        if transceiver.is_stopped() {
            Some(RTCRtpTransceiverDirection::Stopped)
        } else {
            match transceiver.current_direction() {
                RTCRtpTransceiverDirection::Unspecified => None,
                direction => Some(direction),
            }
        }
    }

    /// Irreversibly stops the transceiver.
    ///
    /// The sender stops sending (an RTCP BYE goes out for each stream it sent), the receiver
    /// stops receiving and its track ends
    /// ([`RTCTrackEvent::OnClose`](crate::peer_connection::event::RTCTrackEvent::OnClose)),
    /// and the direction reads [`Stopped`](RTCRtpTransceiverDirection::Stopped). The
    /// transceiver is then stopping: the next offer rejects its m= section, an answer made
    /// before that still answers it (inactive), and it is stopped
    /// ([`is_stopped`](Self::is_stopped)) and removed once an exchange rejecting the section
    /// completes. Stopping a stopping transceiver does nothing.
    ///
    /// # Errors
    ///
    /// [`Error::ErrConnectionClosed`] when the connection is closed (W3C
    /// `InvalidStateError`), or an error if the sender's interceptor bindings cannot be torn
    /// down.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.stop()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop).
    pub fn stop(&mut self) -> Result<()> {
        if self.peer_connection.is_closed() {
            return Err(Error::ErrConnectionClosed);
        }
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        if self.peer_connection.rtp_transceivers[self.id].stopped() {
            return Ok(());
        }
        let ended = self.peer_connection.rtp_transceivers[self.id].stop_sending_and_receiving(
            &self.peer_connection.media_engine,
            &mut self.peer_connection.interceptor,
        )?;
        if ended {
            self.peer_connection.announce_receiver_track_ended(self.id);
        }
        // https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop, last step: update the
        // negotiation-needed flag.
        self.peer_connection
            .on_transceiver_stopped_or_streams_changed();
        Ok(())
    }

    /// Asks, in this transceiver's offers, to receive simulcast: one `a=rid:<rid> recv` line
    /// for each of `rids` and `a=simulcast:recv <rid>;...` (RFC 8853 section 5.3.1, RFC 8851
    /// section 6.1), in a section that receives. The answer's `send` streams are then received
    /// as the layers of the transceiver's receiver. At least two rids, each 1 to 255
    /// alphanumerics (RFC 8852 section 3.1), all different; an empty list asks for none (the
    /// default). Takes effect with the next offer.
    ///
    /// Not a W3C method (JSEP section 3.7: "only to receive a single encoding"): a fork
    /// addition, for an endpoint that receives simulcast (an SFU).
    pub fn set_receive_simulcast(&mut self, rids: Vec<String>) -> Result<()> {
        let valid = |rid: &String| {
            !rid.is_empty() && rid.len() <= 255 && rid.bytes().all(|b| b.is_ascii_alphanumeric())
        };
        let distinct = rids
            .iter()
            .enumerate()
            .all(|(i, rid)| !rids[..i].contains(rid));
        if !rids.is_empty() && (rids.len() < 2 || !rids.iter().all(valid) || !distinct) {
            return Err(Error::ErrRTPSenderRidInvalid);
        }
        self.peer_connection.rtp_transceivers[self.id].set_receive_simulcast(rids);
        Ok(())
    }

    /// The most this endpoint wants to receive in this transceiver's media section, in bits
    /// per second of RTP without transport overhead: written in its descriptions as
    /// `b=TIAS:<bitrate>` (RFC 3890) and, for peers that read only that modifier,
    /// `b=AS:<kilobits>` (RFC 8866 section 5.8), the value RFC 9429 section 5.10 turns back into
    /// at least `bitrate` ("TIAS = AS * 1000 * 0.95 - (50 * 40 * 8)"). The remote sender
    /// keeps under it (RFC 9429 section 5.10), and no TMMBR this endpoint sends for the
    /// section's streams exceeds it (RFC 5104 section 4.2.1.2, `ccm tmmbr`). `None` (the
    /// default) writes no `b=` line. Takes effect with the next description this endpoint
    /// creates; a change does not by itself make negotiation needed.
    ///
    /// Not a W3C method (browsers take `b=` lines from the application's SDP): a fork
    /// addition.
    pub fn set_receive_bandwidth(&mut self, bitrate: Option<u64>) {
        self.peer_connection.rtp_transceivers[self.id].set_receive_bandwidth(bitrate);
    }

    /// See [`Self::set_receive_bandwidth`].
    pub fn receive_bandwidth(&self) -> Option<u64> {
        self.peer_connection.rtp_transceivers[self.id].receive_bandwidth()
    }

    /// Sets the preferred codec list for this transceiver.
    ///
    /// This overrides the default codec preferences from the media engine. An empty list
    /// resets the transceiver to the engine's codecs; duplicates are removed, keeping the
    /// first.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidModificationError`] (W3C webrtc 5.4 `setCodecPreferences`) when a codec
    /// matches none the engine can send or receive for this kind (the codec dictionary match:
    /// MIME type, clock rate, channels and format parameters), or when the list has only
    /// retransmission, redundancy, forward error correction or comfort noise formats.
    ///
    /// # Specification
    ///
    /// See [RTCRtpTransceiver.setCodecPreferences()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences).
    pub fn set_codec_preferences(&mut self, codecs: Vec<RTCRtpCodecParameters>) -> Result<()> {
        // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
        // so, [self.id] here is safe.
        let codecs = self.peer_connection.rtp_transceivers[self.id]
            .validate_codec_preferences(codecs, &self.peer_connection.media_engine)?;
        self.peer_connection.rtp_transceivers[self.id]
            .set_application_codec_preferences(codecs, &self.peer_connection.media_engine)
    }
}

#[cfg(test)]
mod tests {
    use sansio::Protocol;
    use std::time::Instant;

    use crate::peer_connection::configuration::media_engine::MediaEngine;
    use crate::peer_connection::event::RTCPeerConnectionEvent;
    use crate::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
    use crate::rtp_transceiver::RTCRtpTransceiverDirection;
    use crate::rtp_transceiver::rtp_sender::RtpCodecKind;

    fn build_pc() -> RTCPeerConnection {
        let mut media_engine = MediaEngine::default();
        media_engine
            .register_default_codecs()
            .expect("register default codecs");
        RTCPeerConnectionBuilder::new()
            .with_media_engine(media_engine)
            .build(Instant::now())
            .expect("build peer connection")
    }

    /// Drain every queued event and count the `OnNegotiationNeededEvent`s, driving only the
    /// public sans-I/O `Protocol` API (no private negotiation state is touched).
    fn count_negotiation_needed(pc: &mut RTCPeerConnection) -> usize {
        let mut count = 0;
        while let Some(event) = pc.poll_event() {
            if matches!(event, RTCPeerConnectionEvent::OnNegotiationNeededEvent) {
                count += 1;
            }
        }
        count
    }

    /// Complete a full offer/answer exchange so `offerer` settles back into a stable, idle
    /// negotiation state.
    fn negotiate(offerer: &mut RTCPeerConnection, answerer: &mut RTCPeerConnection) {
        let offer = offerer.create_offer(None).expect("create offer");
        offerer
            .set_local_description(Instant::now(), offer.clone())
            .expect("offerer set local");
        answerer
            .set_remote_description(Instant::now(), offer)
            .expect("answerer set remote");
        let answer = answerer.create_answer(None).expect("create answer");
        answerer
            .set_local_description(Instant::now(), answer.clone())
            .expect("answerer set local");
        offerer
            .set_remote_description(Instant::now(), answer)
            .expect("offerer set remote");
    }

    #[test]
    fn test_set_direction_triggers_negotiation_on_change() {
        let mut offerer = build_pc();
        let mut answerer = build_pc();

        let tid = offerer
            .add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(crate::rtp_transceiver::RTCRtpTransceiverInit::recvonly()),
            )
            .expect("add offerer transceiver");
        answerer
            .add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(crate::rtp_transceiver::RTCRtpTransceiverInit::recvonly()),
            )
            .expect("add answerer transceiver");

        negotiate(&mut offerer, &mut answerer);
        // Discard events produced by the initial negotiation.
        let _ = count_negotiation_needed(&mut offerer);

        // A transceiver added with `add_transceiver_from_kind(.., None)` negotiates as recvonly.
        assert_eq!(
            offerer.rtp_transceivers[tid].direction(),
            RTCRtpTransceiverDirection::Recvonly,
        );
        offerer
            .rtp_transceiver(tid)
            .expect("transceiver exists")
            .set_direction(RTCRtpTransceiverDirection::Sendrecv)
            .expect("the change is accepted");

        assert_eq!(
            count_negotiation_needed(&mut offerer),
            1,
            "changing the transceiver direction must trigger negotiation-needed",
        );
    }

    #[test]
    fn test_set_direction_noop_when_unchanged() {
        let mut offerer = build_pc();
        let mut answerer = build_pc();

        let tid = offerer
            .add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(crate::rtp_transceiver::RTCRtpTransceiverInit::recvonly()),
            )
            .expect("add offerer transceiver");
        answerer
            .add_transceiver_from_kind(
                RtpCodecKind::Video,
                Some(crate::rtp_transceiver::RTCRtpTransceiverInit::recvonly()),
            )
            .expect("add answerer transceiver");

        negotiate(&mut offerer, &mut answerer);
        let _ = count_negotiation_needed(&mut offerer);

        // Setting the current direction again must be a no-op.
        let current = offerer.rtp_transceivers[tid].direction();
        offerer
            .rtp_transceiver(tid)
            .expect("transceiver exists")
            .set_direction(current)
            .expect("the change is accepted");

        assert_eq!(
            count_negotiation_needed(&mut offerer),
            0,
            "setting the same direction must not trigger negotiation-needed",
        );
    }

    fn audio_track(stream: &str) -> crate::media_stream::MediaStreamTrack {
        crate::media_stream::MediaStreamTrack::new(
            stream.to_string(),
            "track".to_string(),
            "label".to_string(),
            RtpCodecKind::Audio,
            vec![
                crate::rtp_transceiver::rtp_sender::RTCRtpEncodingParameters {
                    active: true,
                    ..Default::default()
                },
            ],
        )
    }

    /// The stream ids of the `a=msid` lines; each line's appdata is the track id `track`
    /// (`with_msid_appdata`, on by default).
    fn msid_lines(sdp: &str) -> Vec<&str> {
        sdp.lines()
            .filter_map(|line| line.strip_prefix("a=msid:"))
            .map(|value| {
                let (stream, appdata) = value.split_once(' ').unwrap_or((value, ""));
                assert_eq!(appdata, "track", "{value}");
                stream
            })
            .collect()
    }

    /// RFC 9429, Section 5.2.1: one `a=msid` line per MediaStream of the sender, and the
    /// stream id the track itself has (which an application sets to `-`) when it is in none.
    #[test]
    fn test_offer_has_one_msid_line_per_stream() {
        let mut pc = build_pc();
        let tid = pc
            .add_transceiver_from_track(audio_track("-"), None)
            .expect("add transceiver");

        let offer = pc.create_offer(None).expect("create offer");
        assert_eq!(msid_lines(&offer.sdp), vec!["-"]);

        pc.rtp_sender(tid.into())
            .expect("sender")
            .set_streams(vec![
                "one".to_string(),
                "two".to_string(),
                "one".to_string(),
            ])
            .expect("the change is accepted");
        let offer = pc.create_offer(None).expect("create offer");
        assert_eq!(msid_lines(&offer.sdp), vec!["one", "two"]);

        pc.rtp_sender(tid.into())
            .expect("sender")
            .set_streams(vec![])
            .expect("the change is accepted");
        let offer = pc.create_offer(None).expect("create offer");
        assert_eq!(msid_lines(&offer.sdp), vec!["-"]);
    }

    /// RFC 9429, Section 5.10: a remote offer's new media section takes a transceiver the
    /// application marked as created by `addTrack` (the default), not one it marked as created
    /// by `addTransceiver`, which keeps waiting for a media section of its own.
    #[test]
    fn test_remote_offer_skips_a_transceiver_that_is_not_associable() {
        let offer = {
            let mut offerer = build_pc();
            offerer
                .add_transceiver_from_track(audio_track("stream"), None)
                .expect("add offerer transceiver");
            offerer.create_offer(None).expect("create offer")
        };

        // The default: the answerer's own transceiver is taken.
        let mut answerer = build_pc();
        let tid = answerer
            .add_transceiver_from_track(audio_track("stream"), None)
            .expect("add answerer transceiver");
        assert!(
            answerer
                .rtp_transceiver(tid)
                .expect("transceiver")
                .associable_with_remote_offer()
        );
        answerer
            .set_remote_description(Instant::now(), offer.clone())
            .expect("set remote");
        assert_eq!(answerer.rtp_transceivers.len(), 1);
        assert!(answerer.rtp_transceivers[tid].mid().is_some());

        // Not associable: the offer gets a new transceiver, this one stays unassociated.
        let mut answerer = build_pc();
        let tid = answerer
            .add_transceiver_from_track(audio_track("stream"), None)
            .expect("add answerer transceiver");
        answerer
            .rtp_transceiver(tid)
            .expect("transceiver")
            .set_associable_with_remote_offer(false);
        answerer
            .set_remote_description(Instant::now(), offer)
            .expect("set remote");
        assert_eq!(answerer.rtp_transceivers.len(), 2);
        assert!(answerer.rtp_transceivers[tid].mid().is_none());
        assert!(answerer.rtp_transceivers[1].mid().is_some());
    }
}