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://www.w3.org/TR/webrtc/#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 std::time::Instant;
14//! use rtc::peer_connection::RTCPeerConnectionBuilder;
15//! use rtc::data_channel::RTCDataChannelInit;
16//!
17//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
18//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
19//!
20//! let init = RTCDataChannelInit {
21//!     ordered: true,
22//!     max_retransmits: Some(3),
23//!     ..Default::default()
24//! };
25//!
26//! // Create a data channel with label "my-channel"
27//! let dc = pc.create_data_channel("my-channel", Some(init))?;
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! # Specification
33//!
34//! * [W3C WebRTC - RTCDataChannel](https://www.w3.org/TR/webrtc/#rtcdatachannel)
35//! * [RFC 8831 - WebRTC Data Channels](https://datatracker.ietf.org/doc/html/rfc8831)
36//! * [RFC 8832 - WebRTC Data Channel Establishment Protocol](https://datatracker.ietf.org/doc/html/rfc8832)
37
38use crate::peer_connection::RTCPeerConnection;
39use crate::peer_connection::message::{RTCMessage, TaggedRTCMessage};
40use bytes::BytesMut;
41use sansio::Protocol;
42use shared::error::{Error, Result};
43use std::time::Instant;
44
45pub(crate) mod init;
46pub(crate) mod internal;
47pub(crate) mod message;
48pub(crate) mod parameters;
49pub(crate) mod registry;
50pub(crate) mod state;
51
52/// Handle identifying a data channel within a particular peer connection.
53///
54/// This is a connection-local handle, not the SCTP stream identifier the channel occupies on
55/// the wire — for that, see [`RTCDataChannel::stream_id`]. It is assigned when the channel is
56/// created, is stable for the channel's lifetime, and is never reused by a later channel.
57///
58/// The two are separate because they become known at different times. RFC 8832 §6 makes the
59/// parity of a stream identifier depend on the DTLS role — even for the client, odd for the
60/// server — and that role is not resolved until a remote description has been applied. A
61/// channel created before then has no stream id yet, but the application still needs a way to
62/// name it: to hold on to it, to match it against events, and to pass to
63/// [`RTCPeerConnection::data_channel`]. That is this handle.
64///
65/// It is a `usize`, like [`RTCRtpTransceiverId`], both to match the crate's convention for
66/// connection-local handles and so that it cannot be silently confused with a
67/// [`sctp::StreamId`], which is a `u16`.
68///
69/// [`RTCPeerConnection::data_channel`]: crate::peer_connection::RTCPeerConnection::data_channel
70/// [`RTCRtpTransceiverId`]: crate::rtp_transceiver::RTCRtpTransceiverId
71pub type RTCDataChannelId = usize;
72
73/// The SCTP stream identifier a data channel occupies on the wire.
74///
75/// Re-exported next to [`RTCDataChannelId`] because the two are easy to confuse and the
76/// distinction matters: this is the RFC 8832 §6 wire value, that is a connection-local handle.
77/// See [`RTCDataChannel::stream_id`].
78pub use sctp::StreamId;
79
80pub use init::RTCDataChannelInit;
81
82pub use message::RTCDataChannelMessage;
83
84pub use state::RTCDataChannelState;
85
86/// Represents a WebRTC data channel for bidirectional peer-to-peer data transfer.
87///
88/// The `RTCDataChannel` interface represents a network channel which can be used for
89/// bidirectional peer-to-peer transfers of arbitrary data. Each data channel is associated
90/// with an [`RTCPeerConnection`] and provides configurable delivery semantics including
91/// ordered/unordered delivery and reliable/unreliable transport.
92///
93/// # Specification
94///
95/// * [W3C WebRTC - RTCDataChannel](https://www.w3.org/TR/webrtc/#dom-rtcdatachannel)
96/// * [MDN - RTCDataChannel](https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel)
97pub struct RTCDataChannel<'a> {
98    pub(crate) id: RTCDataChannelId,
99    pub(crate) peer_connection: &'a mut RTCPeerConnection,
100}
101
102impl RTCDataChannel<'_> {
103    /// The label distinguishing this DataChannel from others on the same peer connection.
104    ///
105    /// Labels are not required to be unique: an application may create several channels with
106    /// the same label.
107    pub fn label(&self) -> &str {
108        // peer_connection is mutable borrow, its data_channels won't be resized,
109        // so, unwrap() here is safe.
110        self.peer_connection
111            .data_channels
112            .get(&self.id)
113            .unwrap()
114            .label
115            .as_str()
116    }
117
118    /// Whether the DataChannel delivers messages in order.
119    ///
120    /// `false` means out-of-order delivery is allowed.
121    pub fn ordered(&self) -> bool {
122        // peer_connection is mutable borrow, its data_channels won't be resized,
123        // so, unwrap() here is safe.
124        self.peer_connection
125            .data_channels
126            .get(&self.id)
127            .unwrap()
128            .ordered
129    }
130
131    /// The length of the time window, in milliseconds, during which transmissions and
132    /// retransmissions may occur in unreliable mode, or `None` if the channel is reliable.
133    pub fn max_packet_life_time(&self) -> Option<u16> {
134        // peer_connection is mutable borrow, its data_channels won't be resized,
135        // so, unwrap() here is safe.
136        self.peer_connection
137            .data_channels
138            .get(&self.id)
139            .unwrap()
140            .max_packet_life_time
141    }
142
143    /// The maximum number of retransmissions attempted in unreliable mode, or `None` if the
144    /// channel is reliable.
145    pub fn max_retransmits(&self) -> Option<u16> {
146        // peer_connection is mutable borrow, its data_channels won't be resized,
147        // so, unwrap() here is safe.
148        self.peer_connection
149            .data_channels
150            .get(&self.id)
151            .unwrap()
152            .max_retransmits
153    }
154
155    /// The name of the sub-protocol used with this DataChannel, or the empty string if none
156    /// was negotiated.
157    pub fn protocol(&self) -> &str {
158        // peer_connection is mutable borrow, its data_channels won't be resized,
159        // so, unwrap() here is safe.
160        self.peer_connection
161            .data_channels
162            .get(&self.id)
163            .unwrap()
164            .protocol
165            .as_str()
166    }
167
168    /// Whether this DataChannel was negotiated out-of-band by the application (`true`), or
169    /// established in-band over DCEP (`false`).
170    pub fn negotiated(&self) -> bool {
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            .negotiated
178    }
179
180    /// The handle identifying this DataChannel within its peer connection.
181    ///
182    /// Available immediately, stable for the channel's lifetime, and never reused by a later
183    /// channel. Use it to address this channel — pass it to
184    /// [`RTCPeerConnection::data_channel`], or match it against the id carried by an
185    /// [`RTCDataChannelEvent`].
186    ///
187    /// This is **not** the SCTP stream identifier: see [`Self::stream_id`], which is what
188    /// W3C's `RTCDataChannel.id` and RFC 8832 §6 refer to.
189    ///
190    /// [`RTCPeerConnection::data_channel`]: crate::peer_connection::RTCPeerConnection::data_channel
191    /// [`RTCDataChannelEvent`]: crate::peer_connection::event::RTCDataChannelEvent
192    pub fn id(&self) -> RTCDataChannelId {
193        self.id
194    }
195
196    /// The SCTP stream identifier carrying this DataChannel, or `None` if one has not been
197    /// assigned yet.
198    ///
199    /// This is W3C's `RTCDataChannel.id`: "The value is initially null, which is what will be
200    /// returned if the ID was not provided at channel creation time, and the DTLS role of the
201    /// SCTP transport has not yet been negotiated."
202    ///
203    /// It is `Some` from the outset for a channel negotiated out-of-band (created with
204    /// [`RTCDataChannelInit::negotiated`]) and for one opened by the remote peer, since both
205    /// already have a stream id. For a channel this endpoint opens in-band it stays `None`
206    /// until the SCTP connected procedure assigns one, because RFC 8832 §6 requires an even
207    /// identifier from the DTLS client and an odd one from the DTLS server, and which of those
208    /// this endpoint is may still be unknown. Once set it does not change.
209    pub fn stream_id(&self) -> Option<StreamId> {
210        // peer_connection is mutable borrow, its data_channels won't be resized,
211        // so, unwrap() here is safe.
212        self.peer_connection
213            .data_channels
214            .get(&self.id)
215            .unwrap()
216            .stream_id
217    }
218
219    /// The current state of the DataChannel.
220    pub fn ready_state(&self) -> RTCDataChannelState {
221        // peer_connection is mutable borrow, its data_channels won't be resized,
222        // so, unwrap() here is safe.
223        self.peer_connection
224            .data_channels
225            .get(&self.id)
226            .unwrap()
227            .ready_state
228    }
229
230    /// The threshold at which the buffered amount is considered high.
231    ///
232    /// When the buffered amount rises from below this threshold to at or above it, the
233    /// `BufferedAmountHigh` event fires. It is `u32::MAX` on a new DataChannel — that is,
234    /// effectively disabled — and the application may change it at any time with
235    /// [`Self::set_buffered_amount_high_threshold`].
236    pub fn buffered_amount_high_threshold(&self) -> u32 {
237        // peer_connection is mutable borrow, its data_channels won't be resized,
238        // so, unwrap() here is safe.
239        self.peer_connection
240            .data_channels
241            .get(&self.id)
242            .unwrap()
243            .buffered_amount_high_threshold
244    }
245
246    /// Sets the threshold at which the buffered amount is considered high.
247    ///
248    /// See [`Self::buffered_amount_high_threshold`].
249    pub fn set_buffered_amount_high_threshold(&mut self, threshold: u32) {
250        // peer_connection is mutable borrow, its data_channels won't be resized,
251        // so, unwrap() here is safe.
252        let dc = self
253            .peer_connection
254            .data_channels
255            .get_mut(&self.id)
256            .unwrap();
257        dc.buffered_amount_high_threshold = threshold;
258        if let Some(data_channel) = dc.data_channel.as_mut() {
259            let _ = data_channel.set_buffered_amount_high_threshold(threshold);
260        }
261    }
262
263    /// The threshold at which the buffered amount is considered low.
264    ///
265    /// When the buffered amount falls from above this threshold to at or below it, the
266    /// `BufferedAmountLow` event fires. It is `0` on a new DataChannel, and the application
267    /// may change it at any time with [`Self::set_buffered_amount_low_threshold`].
268    pub fn buffered_amount_low_threshold(&self) -> u32 {
269        // peer_connection is mutable borrow, its data_channels won't be resized,
270        // so, unwrap() here is safe.
271        self.peer_connection
272            .data_channels
273            .get(&self.id)
274            .unwrap()
275            .buffered_amount_low_threshold
276    }
277
278    /// Sets the threshold at which the buffered amount is considered low.
279    ///
280    /// See [`Self::buffered_amount_low_threshold`].
281    pub fn set_buffered_amount_low_threshold(&mut self, threshold: u32) {
282        // peer_connection is mutable borrow, its data_channels won't be resized,
283        // so, unwrap() here is safe.
284        let dc = self
285            .peer_connection
286            .data_channels
287            .get_mut(&self.id)
288            .unwrap();
289        dc.buffered_amount_low_threshold = threshold;
290        if let Some(data_channel) = dc.data_channel.as_mut() {
291            let _ = data_channel.set_buffered_amount_low_threshold(threshold);
292        }
293    }
294
295    /// Rejects a send the write path could not carry out.
296    ///
297    /// The condition mirrors what `DataChannelHandler::handle_write` requires: the channel
298    /// must be registered *and* its SCTP stream established. Checking it here, synchronously,
299    /// is what makes the failure visible — the handler runs later, on the pipeline's write
300    /// pass, where an `Err` is only logged and cannot reach the caller. The same holds for
301    /// `SctpHandler::handle_write`'s max-message-size check.
302    fn ensure_sendable(&self, data_len: usize) -> Result<()> {
303        let dc = self
304            .peer_connection
305            .data_channels
306            .get(&self.id)
307            .ok_or(Error::ErrDataChannelClosed)?;
308
309        if dc.data_channel.is_none() {
310            // No stream yet: either it is still being negotiated, or it is already gone.
311            return Err(if dc.ready_state == RTCDataChannelState::Connecting {
312                Error::ErrDataChannelNotOpen
313            } else {
314                Error::ErrDataChannelClosed
315            });
316        }
317
318        // W3C `send()`: data larger than `maxMessageSize` throws.
319        if let Some(max_message_size) = self.peer_connection.sctp_transport().max_message_size()
320            && data_len > max_message_size as usize
321        {
322            return Err(Error::ErrOutboundPacketTooLarge);
323        }
324
325        Ok(())
326    }
327
328    /// Sends a binary message to the DataChannel peer.
329    ///
330    /// # Parameters
331    ///
332    /// - `now`: The instant the send is issued; it travels with the message through the pipeline.
333    /// - `data`: The payload, taken by value so it can be enqueued without a copy.
334    ///
335    /// # Errors
336    ///
337    /// - [`Error::ErrDataChannelNotOpen`] if the channel's SCTP stream has not been established
338    ///   yet — wait for the channel's open event before sending.
339    /// - [`Error::ErrDataChannelClosed`] once the channel is gone.
340    /// - [`Error::ErrOutboundPacketTooLarge`] if `data` is larger than the negotiated
341    ///   [`max_message_size`](crate::peer_connection::transport::RTCSctpTransport::max_message_size).
342    ///
343    /// The check is made here, synchronously, rather than deeper in the pipeline where an error
344    /// could only be logged. A rejected send never charges [`Self::outstanding_bytes`].
345    pub fn send(&mut self, now: Instant, data: BytesMut) -> Result<()> {
346        let data_len = data.len();
347        self.ensure_sendable(data_len)?;
348        self.peer_connection.handle_write(TaggedRTCMessage {
349            now,
350            message: RTCMessage::DataChannelMessage(
351                self.id,
352                RTCDataChannelMessage {
353                    is_string: false,
354                    data,
355                },
356            ),
357        })?;
358        // Count only after a successful enqueue, so a failed send never leaks the
359        // counter upward (those bytes never entered the SCTP send pipeline). This
360        // is the synchronous send-boundary accounting used for back-pressure.
361        if let Some(dc) = self.peer_connection.data_channels.get_mut(&self.id) {
362            dc.outstanding_bytes += data_len;
363        }
364        Ok(())
365    }
366
367    /// Sends a text message to the DataChannel peer.
368    ///
369    /// # Errors
370    ///
371    /// Identical to [`Self::send`].
372    pub fn send_text(&mut self, now: Instant, s: impl Into<String>) -> Result<()> {
373        let s = s.into();
374        self.ensure_sendable(s.len())?;
375        let data = BytesMut::from(s.as_str());
376        let data_len = data.len();
377        self.peer_connection.handle_write(TaggedRTCMessage {
378            now,
379            message: RTCMessage::DataChannelMessage(
380                self.id,
381                RTCDataChannelMessage {
382                    is_string: true,
383                    data,
384                },
385            ),
386        })?;
387        if let Some(dc) = self.peer_connection.data_channels.get_mut(&self.id) {
388            dc.outstanding_bytes += data_len;
389        }
390        Ok(())
391    }
392
393    /// Bytes handed to [`send`](Self::send)/[`send_text`](Self::send_text) that
394    /// SCTP has not yet released (acknowledged or abandoned) — the true amount of
395    /// outstanding send-side memory for this channel, including bytes still queued
396    /// in the app→core→SCTP pipeline (the SCTP stream's own `buffered_amount`
397    /// counts only post-packetization). Used for synchronous send back-pressure.
398    pub fn outstanding_bytes(&self) -> usize {
399        self.peer_connection
400            .data_channels
401            .get(&self.id)
402            .map(|dc| dc.outstanding_bytes)
403            .unwrap_or(0)
404    }
405
406    /// Closes the data channel.
407    ///
408    /// Moves the channel to `Closing` and starts the DCEP/SCTP teardown. Closing a channel that
409    /// is already `Closed` is a no-op and succeeds.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`Error::ErrDataChannelClosed`] if no channel with this id is registered on the
414    /// peer connection any more.
415    pub fn close(&mut self) -> Result<()> {
416        if let Some(dc) = self.peer_connection.data_channels.get_mut(&self.id) {
417            if dc.ready_state == RTCDataChannelState::Closed {
418                return Ok(());
419            }
420            dc.ready_state = RTCDataChannelState::Closing;
421            dc.close()
422        } else {
423            Err(Error::ErrDataChannelClosed)
424        }
425    }
426}