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 rtc::peer_connection::RTCPeerConnectionBuilder;
21//! # use rtc::media_stream::MediaStreamTrack;
22//! # use rtc::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
23//! # fn example(audio_track: MediaStreamTrack) -> Result<(), Box<dyn std::error::Error>> {
24//! let mut peer_connection = RTCPeerConnectionBuilder::new().build()?;
25//!
26//! // Add a transceiver for sending audio
27//! let init = RTCRtpTransceiverInit {
28//! direction: RTCRtpTransceiverDirection::Sendrecv,
29//! ..Default::default()
30//! };
31//!
32//! let sender_id = peer_connection
33//! .add_transceiver_from_track(audio_track, Some(init))?;
34//!
35//! println!("Added sender with ID: {:?}", sender_id);
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! ## Adding a transceiver by media kind
41//!
42//! ```no_run
43//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
44//! # use rtc::rtp_transceiver::rtp_sender::RtpCodecKind;
45//! # use rtc::rtp_transceiver::{RTCRtpTransceiverInit, RTCRtpTransceiverDirection};
46//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
47//! let mut peer_connection = RTCPeerConnectionBuilder::new().build()?;
48//!
49//! // Add a video transceiver for receiving only
50//! let init = RTCRtpTransceiverInit {
51//! direction: RTCRtpTransceiverDirection::Recvonly,
52//! ..Default::default()
53//! };
54//!
55//! let receiver_id = peer_connection
56//! .add_transceiver_from_kind(RtpCodecKind::Video, Some(init))?;
57//!
58//! println!("Added receiver with ID: {:?}", receiver_id);
59//! # Ok(())
60//! # }
61//! ```
62//!
63//! ## Controlling transceiver direction
64//!
65//! ```no_run
66//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
67//! # use rtc::rtp_transceiver::RTCRtpTransceiverDirection;
68//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
69//! let mut peer_connection = RTCPeerConnectionBuilder::new().build()?;
70//!
71//! // Iterate through transceivers and change direction
72//! for transceiver_id in peer_connection.get_transceivers() {
73//! // Access the transceiver through peer_connection's internal methods
74//! // Note: Direct transceiver access may be internal API
75//! // This demonstrates the concept - actual usage depends on your API design
76//! }
77//! # Ok(())
78//! # }
79//! ```
80//!
81//! ## Setting codec preferences
82//!
83//! ```no_run
84//! # use rtc::peer_connection::RTCPeerConnectionBuilder;
85//! # use rtc::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
86//! # fn example(preferred_codecs: Vec<RTCRtpCodecParameters>) -> Result<(), Box<dyn std::error::Error>> {
87//! let mut peer_connection = RTCPeerConnectionBuilder::new().build()?;
88//!
89//! // Codec preferences would be set through peer connection methods
90//! // The exact API depends on your implementation
91//! # Ok(())
92//! # }
93//! ```
94//!
95//! # Specification
96//!
97//! See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.
98
99//TODO: #[cfg(test)]
100//mod rtp_transceiver_test;
101
102use crate::media_stream::MediaStreamId;
103use crate::peer_connection::RTCPeerConnection;
104use crate::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
105use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
106pub use direction::RTCRtpTransceiverDirection;
107use interceptor::{Interceptor, NoopInterceptor};
108use shared::error::Result;
109
110pub(crate) mod direction;
111pub(crate) mod fmtp;
112pub(crate) mod internal;
113pub mod rtp_receiver;
114pub mod rtp_sender;
115
116/// SSRC (Synchronization Source) identifier.
117///
118/// A synchronization source is a randomly chosen value meant to be globally unique
119/// within a particular RTP session. It is used to identify a single stream of media.
120///
121/// # Specification
122///
123/// See [RFC 3550 Section 3](https://tools.ietf.org/html/rfc3550#section-3).
124#[allow(clippy::upper_case_acronyms)]
125pub type SSRC = u32;
126
127/// RTP payload type identifier.
128///
129/// Identifies the format of the RTP payload and determines its interpretation by the
130/// application. Each codec in an RTP session will have a different payload type.
131///
132/// # Specification
133///
134/// See [RFC 3550 Section 3](https://tools.ietf.org/html/rfc3550#section-3).
135pub type PayloadType = u8;
136
137/// RTP stream identifier.
138///
139/// Is used for unique identification of RTP stream
140///
141/// # Specification
142///
143/// See [RFC 8852 Section 3.1](https://tools.ietf.org/html/rfc8852#section-3.1).
144pub type RtpStreamId = String;
145
146/// Repaired RTP stream identifier.
147///
148/// Is used to identify which stream is to be repaired using a redundancy RTP stream
149///
150/// # Specification
151///
152/// See [RFC 8852 Section 3.2](https://tools.ietf.org/html/rfc8852#section-3.2).
153pub type RepairedStreamId = String;
154
155/// Internal identifier for an RTP transceiver.
156pub type RTCRtpTransceiverId = usize;
157
158impl From<RTCRtpSenderId> for RTCRtpTransceiverId {
159 fn from(id: RTCRtpSenderId) -> Self {
160 id.0
161 }
162}
163
164impl From<RTCRtpReceiverId> for RTCRtpTransceiverId {
165 fn from(id: RTCRtpReceiverId) -> Self {
166 id.0
167 }
168}
169
170/// Identifier for an `RTCRtpSender` within a peer connection.
171///
172/// Used to reference a specific RTP sender when calling methods like `remove_track`.
173#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
174pub struct RTCRtpSenderId(pub(crate) RTCRtpTransceiverId);
175
176impl From<RTCRtpTransceiverId> for RTCRtpSenderId {
177 fn from(id: RTCRtpTransceiverId) -> Self {
178 Self(id)
179 }
180}
181
182/// Identifier for an `RTCRtpReceiver` within a peer connection.
183///
184/// Used to reference a specific RTP receiver when handling incoming media.
185#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
186pub struct RTCRtpReceiverId(pub(crate) RTCRtpTransceiverId);
187
188impl From<RTCRtpTransceiverId> for RTCRtpReceiverId {
189 fn from(id: RTCRtpTransceiverId) -> Self {
190 Self(id)
191 }
192}
193
194/// Initialization parameters for creating an `RTCRtpTransceiver`.
195///
196/// Used with `add_transceiver_from_track` or `add_transceiver_from_kind` to configure
197/// the transceiver's initial direction and encoding parameters.
198///
199/// # Specification
200///
201/// See [RTCRtpTransceiverInit](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiverinit)
202#[derive(Default, Clone)]
203pub struct RTCRtpTransceiverInit {
204 pub direction: RTCRtpTransceiverDirection,
205 pub streams: Vec<MediaStreamId>,
206 pub send_encodings: Vec<RTCRtpEncodingParameters>,
207}
208
209/// RTCRtpTransceiver represents a permanent pairing of an RTP sender and RTP receiver that share a common mid.
210/// The transceiver manages the direction of media flow and codec preferences.
211///
212/// # Specification
213///
214/// See [RTCRtpTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver) in the W3C WebRTC specification.
215pub struct RTCRtpTransceiver<'a, I = NoopInterceptor>
216where
217 I: Interceptor,
218{
219 pub(crate) id: RTCRtpTransceiverId,
220 pub(crate) peer_connection: &'a mut RTCPeerConnection<I>,
221}
222
223impl<I> RTCRtpTransceiver<'_, I>
224where
225 I: Interceptor,
226{
227 /// Returns the media stream identification tag (mid) for this transceiver.
228 ///
229 /// The mid uniquely identifies the media description in the SDP. When not already set,
230 /// this value will be assigned during `create_offer` or `create_answer`.
231 ///
232 /// # Specification
233 ///
234 /// See [RTCRtpTransceiver.mid](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-mid).
235 pub fn mid(&self) -> &Option<String> {
236 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
237 // so, [self.id] here is safe.
238 self.peer_connection.rtp_transceivers[self.id].mid()
239 }
240
241 /// sender returns the RTPTransceiver's RTPSender if it has one
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 /// receiver returns the RTPTransceiver's RTPReceiver if it has one
256 pub fn receiver(&self) -> Option<RTCRtpReceiverId> {
257 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
258 // so, [self.id] here is safe.
259 if self.peer_connection.rtp_transceivers[self.id]
260 .receiver()
261 .is_some()
262 {
263 Some(RTCRtpReceiverId::from(self.id))
264 } else {
265 None
266 }
267 }
268
269 /// Returns the preferred direction of the transceiver.
270 ///
271 /// This indicates the direction that the application prefers for media flow.
272 ///
273 /// # Specification
274 ///
275 /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
276 pub fn direction(&self) -> RTCRtpTransceiverDirection {
277 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
278 // so, [self.id] here is safe.
279 self.peer_connection.rtp_transceivers[self.id].direction()
280 }
281
282 /// Sets the preferred direction of this transceiver.
283 ///
284 /// Changing the direction may trigger renegotiation to update the session description.
285 ///
286 /// # Specification
287 ///
288 /// See [RTCRtpTransceiver.direction](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-direction).
289 pub fn set_direction(&mut self, direction: RTCRtpTransceiverDirection) {
290 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
291 // so, [self.id] here is safe.
292 self.peer_connection.rtp_transceivers[self.id].set_direction(direction);
293 }
294
295 /// Returns the negotiated direction of the transceiver.
296 ///
297 /// This indicates the current direction as established by the most recent session description
298 /// exchange. If this transceiver has never been negotiated or if it's stopped, this returns
299 /// [`RTCRtpTransceiverDirection::Unspecified`].
300 ///
301 /// # Specification
302 ///
303 /// See [RTCRtpTransceiver.currentDirection](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-currentdirection).
304 pub fn current_direction(&self) -> RTCRtpTransceiverDirection {
305 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
306 // so, [self.id] here is safe.
307 self.peer_connection.rtp_transceivers[self.id].current_direction()
308 }
309
310 /// Irreversibly stops the transceiver.
311 ///
312 /// After calling this method, the transceiver will no longer send or receive media.
313 /// This operation cannot be undone.
314 ///
315 /// # Specification
316 ///
317 /// See [RTCRtpTransceiver.stop()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop).
318 pub fn stop(&mut self) -> Result<()> {
319 // peer_connection is mutable borrow, its rtp_transceivers won't be resized,
320 // so, [self.id] here is safe.
321 self.peer_connection.rtp_transceivers[self.id].stop(
322 &self.peer_connection.media_engine,
323 &mut self.peer_connection.interceptor,
324 )
325 }
326
327 /// Sets the preferred codec list for this transceiver.
328 ///
329 /// This overrides the default codec preferences from the media engine. If an empty list is
330 /// provided, the transceiver resets to use the default codecs from the media engine.
331 ///
332 /// # Errors
333 ///
334 /// Returns an error if any codec in the list is not supported by the media engine.
335 ///
336 /// # Specification
337 ///
338 /// See [RTCRtpTransceiver.setCodecPreferences()](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences).
339 pub fn set_codec_preferences(&mut self, codecs: Vec<RTCRtpCodecParameters>) -> 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]
343 .set_codec_preferences(codecs, &self.peer_connection.media_engine)
344 }
345}