Skip to main content

rtc/data_channel/
mod.rs

1//! Peer-to-peer Data API
2//!
3//! This module implements the RTCDataChannel interface as defined in the
4//! [W3C WebRTC specification](https://w3c.github.io/webrtc-pc/#rtcdatachannel).
5//!
6//! Data channels enable peer-to-peer exchange of arbitrary application data with low latency
7//! and optional reliability. They are useful for scenarios like gaming, real-time text chat,
8//! file transfer, and other applications that benefit from low-latency communication.
9//!
10//! # Examples
11//!
12//! ```no_run
13//! use rtc::peer_connection::RTCPeerConnectionBuilder;
14//! use rtc::data_channel::RTCDataChannelInit;
15//!
16//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
17//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
18//!
19//! let init = RTCDataChannelInit {
20//!     ordered: true,
21//!     max_retransmits: Some(3),
22//!     ..Default::default()
23//! };
24//!
25//! // Create a data channel with label "my-channel"
26//! let dc = pc.create_data_channel("my-channel", Some(init))?;
27//! # Ok(())
28//! # }
29//! ```
30//!
31//! # Specifications
32//!
33//! * [W3C WebRTC - RTCDataChannel](https://w3c.github.io/webrtc-pc/#rtcdatachannel)
34//! * [RFC 8831 - WebRTC Data Channels](https://www.rfc-editor.org/rfc/rfc8831.html)
35//! * [RFC 8832 - WebRTC Data Channel Establishment Protocol](https://www.rfc-editor.org/rfc/rfc8832.html)
36
37use crate::peer_connection::RTCPeerConnection;
38use crate::peer_connection::message::RTCMessage;
39use bytes::BytesMut;
40use interceptor::{Interceptor, NoopInterceptor};
41use sansio::Protocol;
42use shared::error::{Error, Result};
43
44pub(crate) mod init;
45pub(crate) mod internal;
46pub(crate) mod message;
47pub(crate) mod parameters;
48pub(crate) mod state;
49
50/// Identifier for a data channel within a particular peer connection.
51///
52/// Each data channel has a unique 16-bit identifier within its peer connection.
53pub type RTCDataChannelId = u16;
54
55pub use init::RTCDataChannelInit;
56
57pub use message::RTCDataChannelMessage;
58
59pub use state::RTCDataChannelState;
60
61/// Represents a WebRTC data channel for bidirectional peer-to-peer data transfer.
62///
63/// The `RTCDataChannel` interface represents a network channel which can be used for
64/// bidirectional peer-to-peer transfers of arbitrary data. Each data channel is associated
65/// with an [`RTCPeerConnection`] and provides configurable delivery semantics including
66/// ordered/unordered delivery and reliable/unreliable transport.
67///
68/// # Specifications
69///
70/// * [W3C WebRTC - RTCDataChannel](https://w3c.github.io/webrtc-pc/#dom-rtcdatachannel)
71/// * [MDN - RTCDataChannel](https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel)
72pub struct RTCDataChannel<'a, I = NoopInterceptor>
73where
74    I: Interceptor,
75{
76    pub(crate) id: RTCDataChannelId,
77    pub(crate) peer_connection: &'a mut RTCPeerConnection<I>,
78}
79
80impl<I> RTCDataChannel<'_, I>
81where
82    I: Interceptor,
83{
84    /// label represents a label that can be used to distinguish this
85    /// DataChannel object from other DataChannel objects. Scripts are
86    /// allowed to create multiple DataChannel objects with the same label.
87    pub fn label(&self) -> &str {
88        // peer_connection is mutable borrow, its data_channels won't be resized,
89        // so, unwrap() here is safe.
90        self.peer_connection
91            .data_channels
92            .get(&self.id)
93            .unwrap()
94            .label
95            .as_str()
96    }
97
98    /// Ordered returns true if the DataChannel is ordered, and false if
99    /// out-of-order delivery is allowed.
100    pub fn ordered(&self) -> bool {
101        // peer_connection is mutable borrow, its data_channels won't be resized,
102        // so, unwrap() here is safe.
103        self.peer_connection
104            .data_channels
105            .get(&self.id)
106            .unwrap()
107            .ordered
108    }
109
110    /// max_packet_lifetime represents the length of the time window (msec) during
111    /// which transmissions and retransmissions may occur in unreliable mode.
112    pub fn max_packet_life_time(&self) -> Option<u16> {
113        // peer_connection is mutable borrow, its data_channels won't be resized,
114        // so, unwrap() here is safe.
115        self.peer_connection
116            .data_channels
117            .get(&self.id)
118            .unwrap()
119            .max_packet_life_time
120    }
121
122    /// max_retransmits represents the maximum number of retransmissions that are
123    /// attempted in unreliable mode.
124    pub fn max_retransmits(&self) -> Option<u16> {
125        // peer_connection is mutable borrow, its data_channels won't be resized,
126        // so, unwrap() here is safe.
127        self.peer_connection
128            .data_channels
129            .get(&self.id)
130            .unwrap()
131            .max_retransmits
132    }
133
134    /// protocol represents the name of the sub-protocol used with this
135    /// DataChannel.
136    pub fn protocol(&self) -> &str {
137        // peer_connection is mutable borrow, its data_channels won't be resized,
138        // so, unwrap() here is safe.
139        self.peer_connection
140            .data_channels
141            .get(&self.id)
142            .unwrap()
143            .protocol
144            .as_str()
145    }
146
147    /// negotiated represents whether this DataChannel was negotiated by the
148    /// application (true), or not (false).
149    pub fn negotiated(&self) -> bool {
150        // peer_connection is mutable borrow, its data_channels won't be resized,
151        // so, unwrap() here is safe.
152        self.peer_connection
153            .data_channels
154            .get(&self.id)
155            .unwrap()
156            .negotiated
157    }
158
159    /// ID represents the ID for this DataChannel. The value is initially
160    /// null, which is what will be returned if the ID was not provided at
161    /// channel creation time, and the DTLS role of the SCTP transport has not
162    /// yet been negotiated. Otherwise, it will return the ID that was either
163    /// selected by the script or generated. After the ID is set to a non-null
164    /// value, it will not change.
165    pub fn id(&self) -> RTCDataChannelId {
166        self.id
167    }
168
169    /// ready_state represents the state of the DataChannel object.
170    pub fn ready_state(&self) -> RTCDataChannelState {
171        // peer_connection is mutable borrow, its data_channels won't be resized,
172        // so, unwrap() here is safe.
173        self.peer_connection
174            .data_channels
175            .get(&self.id)
176            .unwrap()
177            .ready_state
178    }
179
180    /// buffered_amount_high_threshold represents the threshold at which the
181    /// bufferedAmount is considered to be high. When the bufferedAmount increases
182    /// from below this threshold to equal or above it, the BufferedAmountHigh
183    /// event fires. buffered_amount_high_threshold is initially u32::MAX on each new
184    /// DataChannel, but the application may change its value at any time.
185    /// The threshold is set to u32::MAX by default.
186    pub fn buffered_amount_high_threshold(&self) -> u32 {
187        // peer_connection is mutable borrow, its data_channels won't be resized,
188        // so, unwrap() here is safe.
189        self.peer_connection
190            .data_channels
191            .get(&self.id)
192            .unwrap()
193            .buffered_amount_high_threshold
194    }
195
196    /// set_buffered_amount_high_threshold sets the threshold at which the
197    /// bufferedAmount is considered to be high.
198    pub fn set_buffered_amount_high_threshold(&mut self, threshold: u32) {
199        // peer_connection is mutable borrow, its data_channels won't be resized,
200        // so, unwrap() here is safe.
201        let dc = self
202            .peer_connection
203            .data_channels
204            .get_mut(&self.id)
205            .unwrap();
206        dc.buffered_amount_high_threshold = threshold;
207        if let Some(data_channel) = dc.data_channel.as_mut() {
208            let _ = data_channel.set_buffered_amount_high_threshold(threshold);
209        }
210    }
211
212    /// buffered_amount_low_threshold represents the threshold at which the
213    /// bufferedAmount is considered to be low. When the bufferedAmount decreases
214    /// from above this threshold to equal or below it, the BufferedAmountLow
215    /// event fires. buffered_amount_low_threshold is initially zero on each new
216    /// DataChannel, but the application may change its value at any time.
217    /// The threshold is set to 0 by default.
218    pub fn buffered_amount_low_threshold(&self) -> u32 {
219        // peer_connection is mutable borrow, its data_channels won't be resized,
220        // so, unwrap() here is safe.
221        self.peer_connection
222            .data_channels
223            .get(&self.id)
224            .unwrap()
225            .buffered_amount_low_threshold
226    }
227
228    /// set_buffered_amount_low_threshold sets the threshold at which the
229    /// bufferedAmount is considered to be low.
230    pub fn set_buffered_amount_low_threshold(&mut self, threshold: u32) {
231        // peer_connection is mutable borrow, its data_channels won't be resized,
232        // so, unwrap() here is safe.
233        let dc = self
234            .peer_connection
235            .data_channels
236            .get_mut(&self.id)
237            .unwrap();
238        dc.buffered_amount_low_threshold = threshold;
239        if let Some(data_channel) = dc.data_channel.as_mut() {
240            let _ = data_channel.set_buffered_amount_low_threshold(threshold);
241        }
242    }
243
244    /// send sends the binary message to the DataChannel peer
245    pub fn send(&mut self, data: BytesMut) -> Result<()> {
246        if self.peer_connection.data_channels.contains_key(&self.id) {
247            self.peer_connection
248                .handle_write(RTCMessage::DataChannelMessage(
249                    self.id,
250                    RTCDataChannelMessage {
251                        is_string: false,
252                        data,
253                    },
254                ))
255        } else {
256            Err(Error::ErrDataChannelClosed)
257        }
258    }
259
260    /// send_text sends the text message to the DataChannel peer
261    pub fn send_text(&mut self, s: impl Into<String>) -> Result<()> {
262        if self.peer_connection.data_channels.contains_key(&self.id) {
263            self.peer_connection
264                .handle_write(RTCMessage::DataChannelMessage(
265                    self.id,
266                    RTCDataChannelMessage {
267                        is_string: true,
268                        data: BytesMut::from(s.into().as_str()),
269                    },
270                ))
271        } else {
272            Err(Error::ErrDataChannelClosed)
273        }
274    }
275
276    pub fn close(&mut self) -> Result<()> {
277        if let Some(dc) = self.peer_connection.data_channels.get_mut(&self.id) {
278            if dc.ready_state == RTCDataChannelState::Closed {
279                return Ok(());
280            }
281            dc.ready_state = RTCDataChannelState::Closing;
282            dc.close()
283        } else {
284            Err(Error::ErrDataChannelClosed)
285        }
286    }
287}