rtc/rtp_transceiver/mod.rs
1//! RTP Media API
2//!
3//! This module provides the RTCRtpTransceiver, which represents a permanent pairing
4//! of an [`RTCRtpSender`](rtp_sender::RTCRtpSender) and an [`RTCRtpReceiver`](rtp_receiver::RTCRtpReceiver),
5//! along with shared state.
6//!
7//! # Overview
8//!
9//! A transceiver manages bidirectional media exchange for a single media type (audio or video).
10//! It combines:
11//! - An RTP sender for outgoing media
12//! - An RTP receiver for incoming media
13//! - Shared state including direction, mid, and codec preferences
14//!
15//! # Examples
16//!
17//! ## Adding a transceiver from a track
18//!
19//! ```no_run
20//! # use std::time::Instant;
21//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
22//! # use rtc::media_stream::MediaStreamTrack;
23//! # use rtc::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
24//! # fn example(audio_track: MediaStreamTrack) -> Result<(), Box<dyn std::error::Error>> {
25//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
26//!
27//! // Add a transceiver for sending audio
28//! let init = RTCRtpTransceiverInit {
29//! direction: RTCRtpTransceiverDirection::Sendrecv,
30//! ..Default::default()
31//! };
32//!
33//! let sender_id = peer_connection
34//! .add_transceiver_from_track(audio_track, Some(init))?;
35//!
36//! println!("Added sender with ID: {:?}", sender_id);
37//! # Ok(())
38//! # }
39//! ```
40//!
41//! ## Adding a transceiver by media kind
42//!
43//! ```no_run
44//! # use std::time::Instant;
45//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
46//! # use rtc::rtp_transceiver::rtp_sender::RtpCodecKind;
47//! # use rtc::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
48//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
49//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
50//!
51//! // Add a video transceiver for receiving only
52//! let init = RTCRtpTransceiverInit {
53//! direction: RTCRtpTransceiverDirection::Recvonly,
54//! ..Default::default()
55//! };
56//!
57//! let receiver_id = peer_connection
58//! .add_transceiver_from_kind(RtpCodecKind::Video, Some(init))?;
59//!
60//! println!("Added receiver with ID: {:?}", receiver_id);
61//! # Ok(())
62//! # }
63//! ```
64//!
65//! ## Controlling transceiver direction
66//!
67//! ```no_run
68//! # use std::time::Instant;
69//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
70//! # use rtc::rtp_transceiver::RTCRtpTransceiverDirection;
71//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
72//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
73//!
74//! // Iterate through transceivers and change direction
75//! for transceiver_id in peer_connection.get_transceivers() {
76//! // Access the transceiver through peer_connection's internal methods
77//! // Note: Direct transceiver access may be internal API
78//! // This demonstrates the concept - actual usage depends on your API design
79//! }
80//! # Ok(())
81//! # }
82//! ```
83//!
84//! ## Setting codec preferences
85//!
86//! ```no_run
87//! # use std::time::Instant;
88//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
89//! # use rtc::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
90//! # fn example(preferred_codecs: Vec<RTCRtpCodecParameters>) -> Result<(), Box<dyn std::error::Error>> {
91//! let mut peer_connection = RTCPeerConnectionBuilder::new().build(Instant::now())?;
92//!
93//! // Codec preferences would be set through peer connection methods
94//! // The exact API depends on your implementation
95//! # Ok(())
96//! # }
97//! ```
98//!
99//! # Specification
100//!
101//! See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.
102
103use crate::media_stream::MediaStreamId;
104use crate::peer_connection::RTCPeerConnection;
105use crate::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
106use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
107pub use direction::RTCRtpTransceiverDirection;
108use log::trace;
109use shared::error::Result;
110
111pub(crate) mod direction;
112pub(crate) mod fmtp;
113pub(crate) mod internal;
114pub mod rtp_receiver;
115pub mod rtp_sender;
116
117/// SSRC (Synchronization Source) identifier.
118///
119/// A synchronization source is a randomly chosen value meant to be globally unique
120/// within a particular RTP session. It is used to identify a single stream of media.
121///
122/// # Specification
123///
124/// See [RFC 3550 Section 3](https://datatracker.ietf.org/doc/html/rfc3550#section-3).
125#[allow(clippy::upper_case_acronyms)]
126pub type SSRC = u32;
127
128/// RTP payload type identifier.
129///
130/// Identifies the format of the RTP payload and determines its interpretation by the
131/// application. Each codec in an RTP session will have a different payload type.
132///
133/// # Specification
134///
135/// See [RFC 3550 Section 3](https://datatracker.ietf.org/doc/html/rfc3550#section-3).
136pub type PayloadType = u8;
137
138/// RTP stream identifier.
139///
140/// Is used for unique identification of RTP stream
141///
142/// # Specification
143///
144/// See [RFC 8852 Section 3.1](https://datatracker.ietf.org/doc/html/rfc8852#section-3.1).
145pub type RtpStreamId = String;
146
147/// Repaired RTP stream identifier.
148///
149/// Is used to identify which stream is to be repaired using a redundancy RTP stream
150///
151/// # Specification
152///
153/// See [RFC 8852 Section 3.2](https://datatracker.ietf.org/doc/html/rfc8852#section-3.2).
154pub type RepairedStreamId = String;
155
156/// Internal identifier for an RTP transceiver.
157pub type RTCRtpTransceiverId = usize;
158
159impl From<RTCRtpSenderId> for RTCRtpTransceiverId {
160 fn from(id: RTCRtpSenderId) -> Self {
161 id.0
162 }
163}
164
165impl From<RTCRtpReceiverId> for RTCRtpTransceiverId {
166 fn from(id: RTCRtpReceiverId) -> Self {
167 id.0
168 }
169}
170
171/// Identifier for an `RTCRtpSender` within a peer connection.
172///
173/// Used to reference a specific RTP sender when calling methods like `remove_track`.
174#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
175pub struct RTCRtpSenderId(pub(crate) RTCRtpTransceiverId);
176
177impl From<RTCRtpTransceiverId> for RTCRtpSenderId {
178 fn from(id: RTCRtpTransceiverId) -> Self {
179 Self(id)
180 }
181}
182
183/// Identifier for an `RTCRtpReceiver` within a peer connection.
184///
185/// Used to reference a specific RTP receiver when handling incoming media.
186#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
187pub struct RTCRtpReceiverId(pub(crate) RTCRtpTransceiverId);
188
189impl From<RTCRtpTransceiverId> for RTCRtpReceiverId {
190 fn from(id: RTCRtpTransceiverId) -> Self {
191 Self(id)
192 }
193}
194
195/// Initialization parameters for creating an `RTCRtpTransceiver`.
196///
197/// Used with `add_transceiver_from_track` or `add_transceiver_from_kind` to configure
198/// the transceiver's initial direction and encoding parameters.
199///
200/// # Specification
201///
202/// See [RTCRtpTransceiverInit](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiverinit)
203#[derive(Default, Clone)]
204pub struct RTCRtpTransceiverInit {
205 /// The initial direction of the transceiver.
206 pub direction: RTCRtpTransceiverDirection,
207 /// The stream IDs associated with the transceiver's sender.
208 pub streams: Vec<MediaStreamId>,
209 /// The encoding parameters to use when sending media.
210 pub send_encodings: Vec<RTCRtpEncodingParameters>,
211}
212
213/// RTCRtpTransceiver represents a permanent pairing of an RTP sender and RTP receiver that share a common mid.
214/// The transceiver manages the direction of media flow and codec preferences.
215///
216/// # Specification
217///
218/// See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.
219pub struct RTCRtpTransceiver<'a> {
220 pub(crate) id: RTCRtpTransceiverId,
221 pub(crate) peer_connection: &'a mut RTCPeerConnection,
222}
223
224impl RTCRtpTransceiver<'_> {
225 /// Returns the media stream identification tag (mid) for this transceiver.
226 ///
227 /// The mid uniquely identifies the media description in the SDP. When not already set,
228 /// this value will be assigned during `create_offer` or `create_answer`.
229 ///
230 /// # Specification
231 ///
232 /// See [RTCRtpTransceiver.mid](https://www.w3.org/TR/webrtc/#dom-rtptransceiver-mid).
233 pub fn mid(&self) -> &Option<String> {
234 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
235 // so, [self.id] here is safe.
236 self.peer_connection.rtp_transceivers[self.id].mid()
237 }
238
239 /// Returns the id of this transceiver's [`RTCRtpSender`], if it has one.
240 ///
241 /// [`RTCRtpSender`]: crate::rtp_transceiver::rtp_sender::RTCRtpSender
242 pub fn sender(&self) -> Option<RTCRtpSenderId> {
243 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
244 // so, [self.id] here is safe.
245 if self.peer_connection.rtp_transceivers[self.id]
246 .sender()
247 .is_some()
248 {
249 Some(RTCRtpSenderId::from(self.id))
250 } else {
251 None
252 }
253 }
254
255 /// Returns the id of this transceiver's [`RTCRtpReceiver`], if it has one.
256 ///
257 /// [`RTCRtpReceiver`]: crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver
258 pub fn receiver(&self) -> Option<RTCRtpReceiverId> {
259 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
260 // so, [self.id] here is safe.
261 if self.peer_connection.rtp_transceivers[self.id]
262 .receiver()
263 .is_some()
264 {
265 Some(RTCRtpReceiverId::from(self.id))
266 } else {
267 None
268 }
269 }
270
271 /// Returns the preferred direction of the transceiver.
272 ///
273 /// This indicates the direction that the application prefers for media flow.
274 ///
275 /// # Specification
276 ///
277 /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
278 pub fn direction(&self) -> RTCRtpTransceiverDirection {
279 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
280 // so, [self.id] here is safe.
281 self.peer_connection.rtp_transceivers[self.id].direction()
282 }
283
284 /// Sets the preferred direction of this transceiver.
285 ///
286 /// Changing the direction may trigger renegotiation to update the session description.
287 ///
288 /// # Specification
289 ///
290 /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
291 pub fn set_direction(&mut self, direction: RTCRtpTransceiverDirection) {
292 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
293 // so, [self.id] here is safe.
294 let previous_direction = self.peer_connection.rtp_transceivers[self.id].direction();
295 self.peer_connection.rtp_transceivers[self.id].set_direction(direction);
296 // Compare the effective direction after the setter (rather than the requested value) so
297 // any future normalization inside `set_direction` cannot bypass this check.
298 let current_direction = self.peer_connection.rtp_transceivers[self.id].direction();
299
300 // https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction
301 // The direction setter is a no-op when the new direction equals the current one;
302 // otherwise its final step updates the negotiation-needed flag for the connection,
303 // which may fire a `negotiationneeded` event.
304 if current_direction != previous_direction {
305 trace!(
306 "Changing direction of transceiver from {previous_direction} to {current_direction}"
307 );
308 self.peer_connection.on_transceiver_direction_changed();
309 }
310 }
311
312 /// Returns the negotiated direction of the transceiver.
313 ///
314 /// This indicates the current direction as established by the most recent session description
315 /// exchange. If this transceiver has never been negotiated or if it's stopped, this returns
316 /// [`RTCRtpTransceiverDirection::Unspecified`].
317 ///
318 /// # Specification
319 ///
320 /// See [RTCRtpTransceiver.currentDirection](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-currentdirection).
321 pub fn current_direction(&self) -> RTCRtpTransceiverDirection {
322 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
323 // so, [self.id] here is safe.
324 self.peer_connection.rtp_transceivers[self.id].current_direction()
325 }
326
327 /// Irreversibly stops the transceiver.
328 ///
329 /// After calling this method, the transceiver will no longer send or receive media.
330 /// This operation cannot be undone.
331 ///
332 /// # Errors
333 ///
334 /// Returns an error if the sender's interceptor bindings cannot be torn down.
335 ///
336 /// # Specification
337 ///
338 /// See [RTCRtpTransceiver.stop()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop).
339 pub fn stop(&mut self) -> Result<()> {
340 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
341 // so, [self.id] here is safe.
342 self.peer_connection.rtp_transceivers[self.id].stop(
343 &self.peer_connection.media_engine,
344 &mut self.peer_connection.interceptor,
345 )
346 }
347
348 /// Sets the preferred codec list for this transceiver.
349 ///
350 /// This overrides the default codec preferences from the media engine. If an empty list is
351 /// provided, the transceiver resets to use the default codecs from the media engine.
352 ///
353 /// # Errors
354 ///
355 /// Returns an error if any codec in the list is not supported by the media engine.
356 ///
357 /// # Specification
358 ///
359 /// See [RTCRtpTransceiver.setCodecPreferences()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences).
360 pub fn set_codec_preferences(&mut self, codecs: Vec<RTCRtpCodecParameters>) -> Result<()> {
361 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
362 // so, [self.id] here is safe.
363 self.peer_connection.rtp_transceivers[self.id]
364 .set_codec_preferences(codecs, &self.peer_connection.media_engine)
365 }
366}
367
368#[cfg(test)]
369mod tests {
370 use sansio::Protocol;
371 use std::time::Instant;
372
373 use crate::peer_connection::configuration::media_engine::MediaEngine;
374 use crate::peer_connection::event::RTCPeerConnectionEvent;
375 use crate::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
376 use crate::rtp_transceiver::RTCRtpTransceiverDirection;
377 use crate::rtp_transceiver::rtp_sender::RtpCodecKind;
378
379 fn build_pc() -> RTCPeerConnection {
380 let mut media_engine = MediaEngine::default();
381 media_engine
382 .register_default_codecs()
383 .expect("register default codecs");
384 RTCPeerConnectionBuilder::new()
385 .with_media_engine(media_engine)
386 .build(Instant::now())
387 .expect("build peer connection")
388 }
389
390 /// Drain every queued event and count the `OnNegotiationNeededEvent`s, driving only the
391 /// public sans-I/O `Protocol` API (no private negotiation state is touched).
392 fn count_negotiation_needed(pc: &mut RTCPeerConnection) -> usize {
393 let mut count = 0;
394 while let Some(event) = pc.poll_event() {
395 if matches!(event, RTCPeerConnectionEvent::OnNegotiationNeededEvent) {
396 count += 1;
397 }
398 }
399 count
400 }
401
402 /// Complete a full offer/answer exchange so `offerer` settles back into a stable, idle
403 /// negotiation state.
404 fn negotiate(offerer: &mut RTCPeerConnection, answerer: &mut RTCPeerConnection) {
405 let offer = offerer.create_offer(None).expect("create offer");
406 offerer
407 .set_local_description(Instant::now(), offer.clone())
408 .expect("offerer set local");
409 answerer
410 .set_remote_description(Instant::now(), offer)
411 .expect("answerer set remote");
412 let answer = answerer.create_answer(None).expect("create answer");
413 answerer
414 .set_local_description(Instant::now(), answer.clone())
415 .expect("answerer set local");
416 offerer
417 .set_remote_description(Instant::now(), answer)
418 .expect("offerer set remote");
419 }
420
421 #[test]
422 fn test_set_direction_triggers_negotiation_on_change() {
423 let mut offerer = build_pc();
424 let mut answerer = build_pc();
425
426 let tid = offerer
427 .add_transceiver_from_kind(RtpCodecKind::Video, None)
428 .expect("add offerer transceiver");
429 answerer
430 .add_transceiver_from_kind(RtpCodecKind::Video, None)
431 .expect("add answerer transceiver");
432
433 negotiate(&mut offerer, &mut answerer);
434 // Discard events produced by the initial negotiation.
435 let _ = count_negotiation_needed(&mut offerer);
436
437 // A transceiver added with `add_transceiver_from_kind(.., None)` negotiates as recvonly.
438 assert_eq!(
439 offerer.rtp_transceivers[tid].direction(),
440 RTCRtpTransceiverDirection::Recvonly,
441 );
442 offerer
443 .rtp_transceiver(tid)
444 .expect("transceiver exists")
445 .set_direction(RTCRtpTransceiverDirection::Inactive);
446
447 assert_eq!(
448 count_negotiation_needed(&mut offerer),
449 1,
450 "changing the transceiver direction must trigger negotiation-needed",
451 );
452 }
453
454 #[test]
455 fn test_set_direction_noop_when_unchanged() {
456 let mut offerer = build_pc();
457 let mut answerer = build_pc();
458
459 let tid = offerer
460 .add_transceiver_from_kind(RtpCodecKind::Video, None)
461 .expect("add offerer transceiver");
462 answerer
463 .add_transceiver_from_kind(RtpCodecKind::Video, None)
464 .expect("add answerer transceiver");
465
466 negotiate(&mut offerer, &mut answerer);
467 let _ = count_negotiation_needed(&mut offerer);
468
469 // Setting the current direction again must be a no-op.
470 let current = offerer.rtp_transceivers[tid].direction();
471 offerer
472 .rtp_transceiver(tid)
473 .expect("transceiver exists")
474 .set_direction(current);
475
476 assert_eq!(
477 count_negotiation_needed(&mut offerer),
478 0,
479 "setting the same direction must not trigger negotiation-needed",
480 );
481 }
482}