This is the second post of the "WebRTC from scratch" series. Part 0 covered the motivation; this one drafts the high-level design: the components, their interfaces and how they fit together.
The more AI is involved in writing the code, the more time I find it worth spending on the design up front. A clear design keeps the generated code from becoming an opaque black box, and makes it obvious when the AI is doing something it shouldn't.
Organization of the project
WebRTC is modular by nature, and it makes a lot more sense when you structure it that way instead of hiding everything behind the usual PeerConnection API, so I will keep that modularity. The implementation will have six components: IceTransport, CryptoTransport, RtpTransport, DataChannelTransport, AudioSender and AudioReceiver.
SDP is not in the picture: it is a special case. The two audio components also deserve a discussion of their own, for the way audio enters and leaves the pipeline; how they talk to the RTP transport is covered with that component.
Handling SDP negotiation
SDP is the protocol the two peers use to negotiate the configuration of the connection.
Following the philosophy of part 0, I will implement only the parts I need. SDP can describe arbitrarily complex sessions, with several audio and video streams and a long list of settings, and it is designed for renegotiation: adding a track or restarting ICE in the middle of a call means a new offer and answer, with a state machine of its own, while the media keeps flowing. I need almost none of that. The Realtime API allows a single negotiation in which the client is the offerer; the offer carries one media line for audio and one for the data channel, and I will support Opus as the only audio codec.
That turns SDP into a simple configuration step that runs once, before the components exist, and produces the configuration of the pipeline. No persistent state, no state machine, and the rest of the library never sees an SDP string. The API will look like this:
/// What one of the two peers offers or accepts.
typedef struct {
bool is_offer;
ice_config_t ice; // ufrag, password, remote candidates
dtls_config_t dtls; // fingerprint, role
rtp_config_t rtp; // SSRCs, payload type
datachannel_config_t datachannel; // SCTP port
// Maybe more fields.
} sdp_peer_config_t;
/// The result of the negotiation. Both sides are kept, since every
/// component needs its own parameters and the remote ones.
typedef struct {
sdp_peer_config_t local;
sdp_peer_config_t remote;
} sdp_negotiated_config_t;
// The error types are left unspecified for now.
typedef struct {
int code;
} sdp_negotiation_error_t;
typedef struct {
int code;
} sdp_parsing_error_t;
/// Fills a peer configuration with defaults: fresh ICE credentials, the
/// fingerprint of the given certificate, random SSRCs. No local candidates:
/// see IceTransport.
void sdp_init_default(
arena_t* arena, bool is_offer, certificate_t* certificate,
sdp_peer_config_t* result
);
/// Checks that the two configurations are compatible and fills result.
sdp_negotiation_error_t sdp_negotiate(
arena_t* arena, const sdp_peer_config_t* local,
const sdp_peer_config_t* remote, sdp_negotiated_config_t* result
);
void sdp_to_string(const sdp_peer_config_t* config, string_builder_t* out);
sdp_parsing_error_t sdp_from_string(
arena_t* arena, const char* str, bool is_offer, sdp_peer_config_t* result
);
The usage is extremely simple. The HTTP exchange that carries the offer and the answer belongs to the application, not to the library:
void do_sdp_negotiation(void) {
// Error handling left out for clarity.
arena_t* arena = /* ... */;
string_builder_t* request_body = /* ... */;
certificate_t certificate;
// The application creates or loads its certificate here.
sdp_peer_config_t local;
sdp_peer_config_t remote;
sdp_negotiated_config_t result;
sdp_init_default(arena, true, &certificate, &local);
sdp_to_string(&local, request_body);
const char* sdp_response = do_http_request(URL, request_body);
sdp_from_string(arena, sdp_response, false, &remote);
sdp_negotiate(arena, &local, &remote, &result);
// Use result to create the components.
}WebRTC components
The six components run during the call, and they are built as described in Sans I/O in C. Each one declares the events it consumes and emits, and exposes the three functions of that post next to init and deinit. The ICE transport serves as the example:
// ---- Events ----
// Only the events the ICE transport consumes or emits are defined here.
// Consumers. Each event kind is tagged with the components that handle it.
#define TO_IO 0x0100 // the I/O layer
#define TO_APP 0x0200 // the application
#define TO_ICE 0x0400 // the ICE transport
#define TO_CRYPTO 0x0800 // the cryptographic transport
#define SEND_UDP (1 | TO_IO)
#define RECEIVE_UDP (2 | TO_ICE)
#define SEND_ENCRYPTED (3 | TO_ICE)
#define RECEIVE_ENCRYPTED (4 | TO_CRYPTO)
#define ICE_STATE (5 | TO_CRYPTO | TO_APP) // several consumers
// ---- Component ----
/// Fields omitted. The struct is complete so that it can be embedded.
typedef struct {
// ...
} ice_transport_t;
int ice_transport_init(
ice_transport_config_t config, ice_transport_t* transport
);
void ice_transport_deinit(ice_transport_t* transport);
// The three sans I/O functions.
/// Handles one event. May push new events into the buffer and change
/// the state of the transport.
void ice_transport_process_event(
ice_transport_t* transport, event_buffer_t* buffer, event_t event
);
/// Handles the passage of time: timeouts, retransmissions, keepalives.
void ice_transport_process_time(
ice_transport_t* transport, event_buffer_t* buffer, uint64_t now
);
/// The time at which process_time next has something to do, or
/// UINT64_MAX. A hint: calling process_time earlier is fine.
uint64_t ice_transport_next_deadline(const ice_transport_t* transport);
The config comes from the negotiated SDP plus the local settings: for the ICE transport, the credentials of both sides, the remote candidates and the local endpoints.
IceTransport
The ICE transport receives UDP traffic from potentially several local interfaces and establishes a route, a pair of local and remote endpoints, through which everything else reaches the other side. ICE uses packets of its own, STUN, and only asks that whatever runs on top of it can be told apart from them.
As decided in part 0, this is a lite client talking to a lite server: no STUN or TURN servers and no candidate gathering. The server never tries to reach us, so the offer carries no local candidates; the client sends a single connectivity check to the server's candidate, which also tells the server where we are.
For now, UDP only, and let's assume the network interfaces never change during the call. The Realtime API negotiates with a single HTTP request/response, so every remote candidate is known after the SDP step: the ICE transport can be created with everything it needs and only has to attempt the connection.
CryptoTransport
The protocols WebRTC runs on top of ICE are DTLS and SRTP/SRTCP, and they are related: the SRTP/SRTCP keys are derived from the DTLS connection. As a reminder:
- DTLS is TLS for datagrams.
- SRTP/SRTCP are the secure versions of RTP/RTCP.
The two protocols have different packet formats. Reading and comparing a few byte positions tells whether a packet is DTLS, SRTP or SRTCP, so they can share one packet stream. This component runs the DTLS handshake, then demultiplexes and decrypts the received traffic, and encrypts and sends the RTP, RTCP and SCTP traffic. DTLS itself carries only SCTP; RTP and RTCP use SRTP and SRTCP with the keys from the handshake.
DataChannelTransport
The data channel transport speaks SCTP plus a small protocol on top of it, DCEP, that opens and labels the channels. This implementation needs a single reliable data channel opened by the client, and that is all it will do.
RtpTransport
The idea of the RTP transport is to handle the low-level details of RTP and RTCP and offer the audio sender and receiver a protocol-agnostic, "logical" interface instead: media events that carry frames, and control events that carry stats, recovery actions and anything else that affects how the media is transferred. The sender hands over a frame with its sample position and side information such as the audio level, and the RTP transport takes care of SSRCs, payload types and header extensions; the receiver may ask for missing frames, and the RTP transport turns that into an RTCP NACK.
The hardest parts of a sender or receiver are network adaptation, efficient error recovery, and the control of the encoder and decoder. The point of the logical interface is to define exactly what information each component needs to receive and send to implement those features well.
With one sender and one receiver there is no need to worry about the general WebRTC case of several media streams: routing RTP and RTCP packets and setting up the pipeline are straightforward.
AudioSender and AudioReceiver
The sender encodes the captured audio with Opus and, as decided in part 0, sends plenty of redundancy by default instead of adapting to the network. The receiver holds the jitter buffer and decodes, building the concealment and the time stretching on the tools Opus already provides.
Both have a special requirement: interacting efficiently with the audio capture and rendering layers of the operating system. For them I make an exception to the everything-is-an-event rule of the sans I/O post, the second one after time, and add the following functions:
/// Encodes the frame and emits the resulting media events into buffer.
void audio_sender_put_10ms(
audio_sender_t* sender, event_buffer_t* buffer, const audio_frame_t* frame
);
/// Always produces a frame, whatever has or has not arrived from the network.
void audio_receiver_get_10ms(audio_receiver_t* receiver, audio_frame_t* frame);
This gives the receiver a NetEq-like interface. NetEq is the core of the audio receiver in WebRTC, and one of the pieces of WebRTC I love the most in terms of software design; mine will follow its shape with the Opus tools from part 0. At a high level, it provides the following interface:
void NetEq_insert_packet(NetEq* ne, AudioPacket* packet);
void NetEq_get_10ms_of_audio(NetEq* ne, AudioFrame* audio_out);
To use it in a pipeline you:
- Call
NetEq_insert_packeteach time an audio packet arrives from the network, which is the receiver's*_process_event. - Call
NetEq_get_10ms_of_audioeach time the audio device needs audio to play.- This is a lot like rendering in video games: you wait for the vsync signal and then render the next frame. The idea is to get a similar signal from the audio device: when it starts playing a segment, generate the next one.
NetEq_get_10ms_of_audioalways succeeds. If there are no packets to play, NetEq generates concealment audio, and it time-stretches the signal to compensate for network jitter and even for the drift between the clocks of the two systems involved in the call.
One of the great ideas of NetEq is that the get_10ms_of_audio calls are its
clock, and that clock is driven by the playback device. The device asks for
audio and must get it now, synchronously, and that same call advances the
timing of the component. A function call is the most straightforward way to
implement this behaviour.
The sender takes the same shape for symmetry, and because the alternative, copying 10 ms of PCM into an event so that the sender can read it back a moment later, buys nothing.
The peer connection
I don't like the peer connection abstraction in general, but I have to recognise that it is practical. A peer-connection-like API falls out of wiring the components into a pipeline, as the sans I/O post suggests:
typedef struct {
ice_transport_t ice_transport;
crypto_transport_t crypto_transport;
rtp_transport_t rtp_transport;
datachannel_transport_t datachannel_transport;
audio_sender_t audio_sender;
audio_receiver_t audio_receiver;
event_buffer_t buffer;
} peer_connection_t;
/// SDP stays its own thing even here: the peer connection takes the
/// negotiated result, plus the local settings.
int peer_connection_init(
const sdp_negotiated_config_t* sdp, const peer_connection_config_t* config,
peer_connection_t* pc
);
void peer_connection_deinit(peer_connection_t* pc);
/// The pipeline functions of the sans I/O post.
void peer_connection_process_event(peer_connection_t* pc, event_t event);
void peer_connection_process_time(peer_connection_t* pc, uint64_t now);
uint64_t peer_connection_next_deadline(const peer_connection_t* pc);
/// put_10ms also propagates the events it produces.
void peer_connection_put_10ms(
peer_connection_t* pc, const audio_frame_t* frame
);
void peer_connection_get_10ms(peer_connection_t* pc, audio_frame_t* frame);
/// Pushes a data channel message as an event and propagates it.
void peer_connection_send_message(
peer_connection_t* pc, const char* data, uint32_t size
);
The sans I/O post delivers the packets to send and the events for the application through two callbacks provided by the I/O layer. Whether that or its external-buffer variant is the right shape here is still open, so do not take any of this code as final.
A brief note about allocations
A good C program, as opposed to a C++ or Rust one, makes allocations explicit
and part of the design. For SDP it is already clear to me that an arena_t
is the right tool, so it appears in those signatures. The rest of the code in
this post leaves allocators out: I do not know yet how I will structure them.
Conclusion
I have spent a substantial amount of time iterating on this design and I think it is time to stop and start implementing it. Six components and an SDP step that runs once: that is the whole design. Depending on how the code turns out, some component boundaries may still move.
In the next post we will start implementing the SDP logic.