Centricular

Expertise, Straight from the Source



« Back

Devlog

Posts tagged with #webrtc

librice


librice is a Rust library implementing RFC 8445 (Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal) that answers the question of how to efficiently discover the optimal connection between two peers. Most importantly, ICE is used by WebRTC and other media-based protocols (e.g. SIP) in order to set up the communication channel between two (or more) peers.

librice and the sans-IO counterpart rice-proto have gained a number of new features over the past year or so which includes, but is not limited to:

1. TURN support in all widely used variants. This includes

RFC 5766 - Traversal Using Relays around NAT (TURN)

RFC 5766 builds on top of the STUN RFC 5389 in order to support a server forwarding data on behalf of client. It supports the TURN server allocating a UDP socket for the client and the client can connect to the server over UDP, TCP, and TLS over TCP.

RFC 6062 - Traversal Using Relays around NAT (TURN) Extensions for TCP Allocations

Builds on top of RFC 5766 by adding functionality to support the TURN server providing a TCP allocation. The TURN client can connect over TCP or TLS over TCP when using a TCP allocation.

RFC 6156 - Traversal Using Relays around NAT (TURN) Extension for IPv6

Build on top of RFC 5766 (and optionally RFC 6062) allowing the TURN server to create an allocation with an IPv6 address.

RFC 8656 - Traversal Using Relays around NAT (TURN): Relay Extensions to Session Traversal Utilities for NAT (STUN)

Supersedes the 3 previous TURN RFCs and includes some extra functionality:

  1. DTLS over UDP between the client and server for UDP allocations
  2. Builds upon the STUN [RFC 8489] which adds support for SHA-256 integrity for increased security of STUN messages and anonymous usernames (SHA-256 hashed).
  3. Dual IPv4/IPv6 allocation support from a single control channel instead of requiring two separate client control channels.

Reusable crate

All of the above functionality specified in the above RFCs has been implemented in the Rust crate turn-client-proto. TLS backends for turn-client-proto are available from crates such as turn-client-rustls, turn-client-openssl, and turn-client-dimpl.

Thanks

Thanks to The NLnet Foundation for funding the work on TURN.

2. Improved zerocopy support for sent and received data where possible.

As of this change for UDP and this change for TCP zerocopy of data sent and received over the ICE connection does not perform and copies of the media data within rice-proto. Sending TCP still currently requires a copy to add the necessary ICE-TCP frame headers.

Thanks

Thanks to Pexip for funding the work on improved zerocopy support.

3. ICE-restart

Usually, once ICE completes and a connection is established, there is no easy way to update the currently configured connection. ICE-restart allows rerunning the connectivity checks with an optionally updated set of local and remove candidates. This can be used when e.g. the set of network interfaces or addresses associated with those network interfaces changes. This is the RFC and standard way of changing the selected pair and there is a proposal for ICE renomination but that is still in draft stage.

Thanks

Thanks to Pexip for funding the work on ICE-Restart.

4. ICE-lite support.

If the ICE agent is in an environment where the host candidate is publicly accessible, the full ICE process is not needed in order to find a viable connection with a peer. This can use the ICE-lite variant of ICE however there are some requirements before this is viable:

  1. Only single host candidate for IPv4 or a single host candidate per interface for IPv6.
  2. Connectivity checks are never initiated from any ICE-lite agent.

librice supports ICE-lite in this manner with a ICE-full peer. rice-proto can also support running multiple ICE-lite agents on the same socket in the same process through the addition of 'ignorable errors'. The idea is that each ICE-lite agent that is running on the same port attempts to handling an incoming STUN message or data message and can either handle it or produce an ignorable error. If no agents handle the incoming data, the 'ignorable error' can optionally be sent to the originating peer.

Thanks

Thanks to The NLnet Foundation for funding the work for ICE-lite.

5. Consent Freshness - RFC 7675

Once ICE has discovered a connection, there is no active keep alive mechanism with the peer. As the connection may be sent over UDP, there is no guarantee that the an agent is able to detect when a peer disappears through e.g. ICMP messages. The existing keep alive mechanism with BINDING indications are designed to keep allocations across NATs alive and no response to an indication is allowed.

Instead, a request/response BINDING transaction is used for a liveness check in order to ensure that the peer is actively able to receive the data we send. This is also backwards compatible with agents that do not support consent freshness as all ICE agents must response to BINDING requests with the appropriate response at all times.

rice-proto supports consent freshness as outlined in RFC 7675.

Thanks

Thanks to The NLnet Foundation for funding the work for consent freshness.

6. Increased configuration options

A smaller selection of configuration that is supported by rice-proto includes.

Increased configuration options for STUN transaction retransmissions count and timeouts. i.e. reducing the number of retransmissions or delays between resends before a transaction is considered failed.

Async runtime support in librice now supports smol, tokio, and custom runtime implementations through an implementable Runtime trait.

Community use of librice

The initial user of librice has been GStreamer through the newly introduced webrtcbin2 plugin containing the webrtcsend and webrtcrecv elements. You can read more about webrtcbin2 in a previous post.

Another user was Webkit's WebRTC backend using GStreamer where the sans-IO design allows marshalling the actual IO over networks sockets to be performed in a separate process from the ICE state machine providing the required sandboxing of different resources that many modern web browsers implement.

rice-proto has also been integrated into a FreeSWITCH fork for communication with peers that commmunicate using WebRTC.

Funding

Thanks to The NLnet Foundation for funding some of the work on librice through the NGI0 Commons Fund, a fund established by NLnet with financial support from the European Commission's Next Generation Internet programme.

The NLnet Foundation supported the following functionality:

  • TURN support
  • ICE-lite
  • Consent Freshness RFC 7675

Also, thanks to Pexip for supporting work on ICE-Restart and improving the performance sending and receiving data.

Try it out

All of these improvements are in the main branch of librice and will be included in the upcoming 0.5.0 release.

If you have any network environment using WebRTC/SIP that is not currently supported by rice-proto, or would like to support ongoing maintenence and development, please get in touch.



TL;DR

There is a new webrtcbin2 rust plugin containing split webrtcsend and webrtcrecv elements for handling a WebRTC session. The highlights of webrtcbin2 are that it uses less threads per session by using rtpsend and rtprecv (also rust), implementing DTLS handling internally, using librice (ICE in rust), and handling signalling all within an async runtime. All of these components also share threads with other instances of webrtcsend and webrtcrecv allowing for an even further reduction in the amount of resources significantly improving scalability.

The landscape

When I originally wrote the webrtcbin GStreamer element almost 10 years ago, I did not completely envision the number of users that would come to use this code in some way shape or form. From HTTP based standards such as WHIP, and WHEP and the myriad of projects that use WebRTC in some way for ingest or egress. WebRTC is still one of the best ways to transport live video into a web browser for display. WebRTC's loose compatibility with the SIP ecosystem is also a driving force behind WebRTC's continued use.

Now, webrtcbin has definitely proved itself in situations that require a small number of sessions. Using webrtcbin for a mixing server (MCU) or even SFU with hundreds or even thousands of streams in a single application is still a tall ask. The biggest reason for this is the number of threads that are created for every WebRTC session.

Threads

  1. RTCP thread - rtpbin (used by webrtcbin) creates a thread per session essentially for handling timeouts required by RTCP.
  2. rtpjitterbuffer creates a thread per incoming stream in order to be able to handle timeouts and deal with late or missing RTP packets.
  3. dtlsenc - A thread whose sole purpose is for being able to handle DTLS timeouts.
  4. webrtcbin and signalling - A dedicated thread for handling signalling related changes such as SDP generation, applying remote SDPs, handling ICE candidates, etc.
  5. webrtcbin and ICE - ICE uses libnice on a dedicated ICE network thread per WebRTC session.
  6. Media streaming threads - One streaming thread for sending and receiving media data.

When an application requires many WebRTC sessions, the memory requirements and context switching overhead of having 5 extra threads per WebRTC session can limit the number of sessions that can be concurrently executed.

Pipeline loops

Another concern I had is that for the server mixing/forwarding use case, pipeline loops were almost a necessity due to the basic requirement that participants in a WebRTC call wanting to be able to see and listen to each other. The obvious answer to this problem is to split the pipeline and use some wormhole elements such as appsrc/appsink, intersink/intersrc, proxysrc/proxysink, etc.

What if? - webrtcbin2

With the benefit of hindsight, we can definitely improve on this situation and reduce the number of threads that is required by each additional WebRTC session. Let us go through the list from above.

Pipeline loops

In order to solve the problem of loops in the pipeline, I took a leaf out of the design we made for rtpbin2 and created separate webrtcsend and webrtcrecv elements that interact with a shared WebRTC session object by having the same id. This allows data to flow essentially in one direction without requiring any kind of loop in the pipeline graph.

For some background on why rtpbin2 was created, you can have a look at a previous post I wrote.

Threads

  1. RTCP thread - Amortised over multiple instances inside rtpbin2 using a tokio scheduler.
  2. Jitter buffer per stream - rtprecv (part of rtpbin2) uses the same tokio scheduler for RTCP handling as it does for handling timeouts and packets through the jitterbuffer introducing no extra threads.
  3. dtlsenc is no longer - DTLS is performed (using OpenSSL) directly just before/after ICE processing.
  4. webrtcsend/webrtcrecv and signalling - Signalling occurs on a tokio runtime shared across all instances of webrtcsend/webrtcrecv.
  5. webrtcsend/webrtcrecv and ICE - Uses librice on the same tokio runtime as webrtcsend/webrtcrecv.
  6. Media streaming thread - Same as webrtcbin. Can be amortised by using the threadshare elements.

If we count the number of threads saved, we can see that for every WebRTC session, at least 5 threads are no longer needed in the new design. At 100 sessions, that is roughly a 500 thread saving in both memory and contention.

Features of webrtcsend/webrtcrecv

While webrtcsend and webrtcrecv are functional and can successfully communicate with a web browser such as Chrome or Firefox, there are still some missing pieces. Some of the supported features include:

  • Audio and/or Video streaming. Data channels are not currently supported.
  • BUNDLE is supported and required for multiple media.
  • rtcp-mux is required.

A non exhaustive list of not yet supported features include:

  • Retransmissions and Forward Error Correction (rtpbin2 does not support this yet).
  • Data channels
  • Renegotiation
  • Statistics
  • TURN servers (librice supports it but not yet implemented in webrtcbin2)

All of these missing features are solveable with further implementation effort.

Example

A send and receive example using webrtcbin2 is available the upstream repository and can be used with this example web page. Just make sure that data channels are not enabled as they are currently not supported.

Closing

This work will be part of the upcoming GStreamer 1.29.2 development snapshot or can be built from the main branch of gst-plugins-rs.

Writing a mature WebRTC implementation is an endeavour that requires a fair bit of implementation effort to complete. If you would like to help make a secure, mature WebRTC implementation for GStreamer please get in touch.



webrtcsink already supported instantiating a data channel for the sole purpose of carrying navigation events from the consumer to the producer, it can also now create a generic control data channel through which the consumer can send JSON requests in the form:

{
    "id": identifier used in the response message,
    "mid": optional media identifier the request applies to,
    "request": {
        "type": currently "navigationEvent" and "customUpstreamEvent" are supported,
        "type-specific-field": ...
    }
}

The producer will reply with such messages:

{
  "id": identifier of the request,
  "error": optional error message, successful if not set
}

The example frontend was also updated with a text area for sending any arbitrary request.

The use case for this work was to make it possible for a consumer to control the mix matrix used for the audio stream, with such a pipeline running on the producer side:

gst-launch-1.0 audiotestsrc ! audioconvert ! webrtcsink enable-control-data-channel=true

As audioconvert now supports setting a mix matrix through a custom upstream event, the consumer can simply input the following text in the request field of the frontend to reverse the channels of a stereo audio stream:

{
  "type": "customUpstreamEvent",
  "structureName": "GstRequestAudioMixMatrix",
  "structure": {
    "matrix": [[0.0, 1.0], [1.0, 0.0]]
  }
}


The default signaller for webrtcsink can now produce an answer when the consumer sends the offer first.

To test this with the example, you can simply follow the usual steps but also paste the following text in the text area before clicking on the producer name:

{
  "offerToReceiveAudio": 1,
  "offerToReceiveVideo": 1
}

I implemented this in order to test multiopus support with webrtcsink, as it seems to work better when munging the SDP offered by chrome.