Preview of main at f2aeee3, 2026-12-05

webrtc is a header-only C++20 library of peer connections and data channels, one of the libraries of webcpp. Its types and operations carry the names and the shapes of the W3C’s WebRTC API, RTCPeerConnection and RTCDataChannel, and they are written in Asio’s model: every operation takes a completion token, runs its handler on the executor its object was made with, and fails as a value. Natively it runs over libdatachannel; in the browser, compiled with Emscripten, over the page’s own objects, so that a program is written once for both.

This page teaches webrtc section by section: two peers that talk, how a program builds with it, the runtime, signalling, the events, the data channels, the errors, cancellation and memory, what the native and the browser implementations stand on, how it differs from the W3C’s API, and what it guarantees. Every program it shows is one of the library’s examples, which the build compiles, runs and compares with the output shown. The reference lists every name the headers declare.

Overview

WebRTC connects two programs directly, through the networks between them, once each has told the other how to reach it. webrtc gives a C++ program the data-channel half of it: a peer_connection negotiates the connection with the other peer, and a data_channel carries messages over it, text or binary, reliable and ordered or not.

The names are the W3C’s, so that a reader who knows RTCPeerConnection.setLocalDescription() knows peer_connection::async_set_local_description, and the semantics are the W3C’s where a platform allows them, with every difference stated in Differences from the W3C’s API. The model is Asio’s:

  • every operation is an async_* member that takes any completion token, a callback, use_awaitable, use_future or a deferred token, and runs its handler on the object’s executor, webcpp::asio::any_io_executor unless the program chooses another;

  • what the W3C delivers as an event, a candidate, a state change, an incoming channel, a message, is a wait the program starts and starts again, as an acceptor’s async_accept (Events);

  • every failure is a value, an error_code of the category webcpp.webrtc or one of Asio’s (Errors), and every bound webcpp sets is a named option that fails as a value, never by throwing or blocking.

It runs on two targets, with exceptions on and off on both. Natively it runs over libdatachannel 0.24.6, which the superproject builds from its pinned sources (The native implementation). In the browser, compiled with Emscripten, it runs over the page’s own RTCPeerConnection and RTCDataChannel, through webcpp::asio’s bridge, in both of webcpp::asio’s suspension variants (The browser implementation). WASI has no WebRTC, neither in a guest nor from a host, so there the headers stop with an #error that says so.

Media, the tracks, codecs and transceivers of WebRTC, is not part of webrtc: it will get an interface of its own. Nor is any integration with another library: an actor of webcpp::xactor that needs a peer holds a peer_connection made on the executor its driver runs on and turns each completion into a message to itself.

Quick start

Two peers in one program open a data channel and exchange one message each way. A real program has its two peers in two processes, often on two machines, and carries what each says about itself to the other through a signalling channel of its own, a WebSocket or an HTTP request; these two hand it over directly, which is the only thing they do differently.

A program makes one runtime before any connection: natively it holds libdatachannel’s threads (The runtime). Each connection is made on an executor, whose handlers it runs; here both share one io_context. The configuration binds the connections to the loopback, so that the program needs no network:

asio::io_context io;
webrtc::runtime rt;  // libdatachannel's threads, made before any connection

// Host candidates on the loopback only, so that the example needs no network.
webrtc::configuration config;
config.bind_address = "127.0.0.1";

auto a = webrtc::peer_connection::make(rt, io.get_executor(), config).value();
auto b = webrtc::peer_connection::make(rt, io.get_executor(), config).value();

make returns a boost::system::result: a connection past the runtime’s cap, or a configuration the platform refuses, is an error, not an exception.

a creates a channel; b accepts it once the connection is up. Each side waits for what it needs, once: a waits for its channel to open and sends hello, then waits for an answer; b waits for the channel, then for a message, and answers it. Every handler runs on the io_context, and every one checks its error_code:

// a creates the channel; b accepts it once the connection is up.
auto chat = a.create_data_channel("chat").value();
std::optional<webrtc::data_channel> remote;
std::string at_a;
std::string at_b;
auto buffer_a = asio::dynamic_buffer(at_a);
auto buffer_b = asio::dynamic_buffer(at_b);

chat.async_wait_open([&](error_code ec) {
    if (ec) {
        return;
    }
    std::printf("a: the channel is open\n");
    if (const error_code sent = chat.send_text("hello"); sent) {
        std::printf("a: hello not sent: %s\n", sent.message().c_str());
        return;
    }
    chat.async_receive(buffer_a, [&](error_code ec, std::size_t, bool) {
        if (ec) {
            return;
        }
        std::printf("a received: %s\n", at_a.c_str());
        a.close();
        b.close();
    });
});
b.async_accept_data_channel([&](error_code ec, webrtc::data_channel dc) {
    if (ec) {
        return;
    }
    remote.emplace(std::move(dc));
    remote->async_receive(buffer_b, [&](error_code ec, std::size_t, bool text) {
        if (ec) {
            return;
        }
        std::printf("b received: %s (%s)\n", at_b.c_str(), text ? "text" : "binary");
        if (const error_code sent = remote->send_text("hi"); sent) {
            std::printf("b: hi not sent: %s\n", sent.message().c_str());
        }
    });
});

Then the signalling. a makes its offer, the implicit setLocalDescription() of the W3C, waits until it has gathered its candidates, the addresses b can reach it at, and gives b its local description, which by then holds them all; b answers the same way:

// a offers, b answers; each description goes over once its candidates are gathered.
void connect(webrtc::peer_connection& a, webrtc::peer_connection& b) {
    a.async_set_local_description([&](error_code ec, const webrtc::session_description&) {
        if (ec) {
            return;
        }
        gather(a, [&] {
            const auto offer = a.local_description().value();
            b.async_set_remote_description(offer.view(), [&](error_code ec) {
                if (ec) {
                    return;
                }
                b.async_set_local_description(
                    [&](error_code ec, const webrtc::session_description&) {
                        if (ec) {
                            return;
                        }
                        gather(b, [&] {
                            const auto answer = b.local_description().value();
                            a.async_set_remote_description(answer.view(), [](error_code ec) {
                                if (ec) {
                                    std::printf("a: the answer was refused: %s\n",
                                                ec.message().c_str());
                                }
                            });
                        });
                    });
            });
        });
    });
}

gather waits for candidates until the empty one, the end of gathering:

// Calls `done` once `pc` has gathered its candidates, whose end is an empty candidate: its local
// description then holds every one of them.
void gather(webrtc::peer_connection& pc, std::function<void()> done) {
    pc.async_wait_ice_candidate(
        [&pc, done = std::move(done)](error_code ec, const webrtc::ice_candidate& c) mutable {
            if (ec) {
                return;
            }
            if (c.candidate.empty()) {
                done();
            } else {
                gather(pc, std::move(done));
            }
        });
}

Waiting for every candidate before signalling is the simplest form of it. Signalling shows the other, which sends each candidate as soon as it is found, so that the connection starts sooner.

The program runs its io_context until both connections are closed, which a does once it has the answer; it gives up after thirty seconds, so that a broken network cannot hang it:

// Until both connections are closed, or the example gives up.
io.run_for(std::chrono::seconds(30));  // lint-run: the peers' events come from libdatachannel

It prints:

a: the channel is open
b received: hello (text)
a received: hi

Building a program

webrtc is header-only. A program inside a webcpp checkout names its target, /webcpp/webrtc//webrtc, which brings the headers, webcpp::config, webcpp::asio and, natively, libdatachannel:

alias webrtc : : <toolset>emscripten : : <library>headers <library>/webcpp/asio//asio ;
alias webrtc : : : : <library>headers <library>/webcpp/asio//asio
  <library>/webcpp/third_party//libdatachannel ;

Natively that target is /webcpp/third_party//libdatachannel: libdatachannel 0.24.6 with libjuice, libsrtp, usrsctp and plog, built by the superproject from the sources it pins, as static archives, with the program’s compiler and runtime settings, over the same source-built OpenSSL as webcpp::asio’s TLS. A first build makes them, and later builds reuse them. The submodule is initialized once:

git submodule update --init --recursive third_party/libs/libdatachannel
git submodule update --init third_party/libs/openssl

libdatachannel runs threads of its own, so a native program builds with threading=multi; a request for threading=single stops the build, naming the fix. webrtc works with exceptions on and off: natively it calls libdatachannel through its C API, which catches every exception libdatachannel throws and returns a code (exceptions), so a program built with exception-handling=off needs nothing more:

b2 threading=multi libs/webrtc/example
b2 threading=multi exception-handling=off libs/webrtc/example

In the browser the same target brings webcpp::asio, whose usage requirements link its browser runtime (the bridge’s export and JavaScript, which <webcpp/asio/browser/src.hpp> holds), embind and the flag of the suspension variant webcpp-suspend chooses, jspi or asyncify: a program built with b2 includes nothing more. A program built without b2 includes <webcpp/asio/browser/src.hpp> in exactly one translation unit and links with -lembind, -sJSPI (or -sASYNCIFY with JavaScript exceptions), -Wl,--export=emscripten_stack_get_current and -Wl,--export=_emscripten_stack_restore:

b2 toolset=emscripten webcpp-suspend=jspi libs/webrtc/test

The convenience header <webcpp/webrtc.hpp> includes every public header. <webcpp/webrtc/config.hpp> defines WEBCPP_WEBRTC_NO_EXCEPTIONS exactly when webcpp has no exceptions, as every webcpp library’s configuration does, and stops with #error on WASI, where no WebRTC exists.

The b2 feature webcpp-webrtc-unsupported=error|ignore, propagated, chooses what a setting a target cannot honour does: fail with operation_not_supported, the default, or be ignored where the platform does something equivalent of its own (Differences from the W3C’s API). Natively it decides a data channel’s max_packet_life_time of 0 (What the native target cannot honour), in the browser configuration::bind_address (What the browser cannot honour). On both targets the classes live in an inline namespace named after the policy, unsupported_error or unsupported_ignore, so their spelled names are the same, webcpp::webrtc::peer_connection among them, and two translation units built with different policies that pass an object between them fail to link instead of disagreeing at run time.

The runtime

Some of what WebRTC needs belongs to the whole process, or to the whole page: natively libdatachannel’s thread pool and global state, and on both targets the number of connections alive at once. webcpp keeps no global or static mutable state, so the program owns it, as a runtime:

  • it is made before any peer connection, and destroyed after the last connection and the last data channel: peer_connection::make takes it by reference, so no connection exists without one;

  • natively, making it loads libdatachannel’s global resources, with its thread pool of runtime_options::thread_pool_size threads when that is not 0, and destroying it waits until libdatachannel’s threads have stopped, for at most ten seconds, after which libdatachannel gives up and the program goes on;

  • it caps the connections alive at once at runtime_options::max_peer_connections, 256 by default, half of Chromium’s limit of 500 per page: make past the cap fails with too_many_peer_connections, and a connection’s place is given back once it is destroyed. peer_connections() says how many are alive.

Natively at most one runtime exists at a time in a process, because libdatachannel’s state is the process’s: a second runtime’s destructor would end the first one’s connections. It is a precondition, which the library does not check: a check would need a flag of the process, the static state webcpp keeps none of. A program makes its runtime in main, or in the one object that owns its connections, and passes it down; a test makes one per case, one case after another.

The connections made with one runtime may live on different executors and threads; its count is atomic. In the browser the cap counts the page’s census instead, every connection of the page until it is collected (The page’s census), and thread_pool_size means nothing.

Signalling

Two peers connect once each has the other’s session description, which says what they will exchange, and the other’s candidates, the addresses it may be reached at. Carrying them is the program’s: WebRTC leaves the signalling channel to it, a WebSocket, an HTTP request, a relay of its own. webrtc gives it the values to carry and the operations that apply them.

Descriptions

async_set_local_description() makes the local description and applies it, as the W3C’s setLocalDescription() without an argument: an offer, or an answer when a remote offer was applied. It completes with the description, a session_description whose type and sdp the program sends to the other peer, which applies it with async_set_remote_description(d.view()). The peer that offers sends first; the other answers once the offer is applied.

A description needs something to negotiate, so a peer creates its first data channel before it offers: the description then holds the connection’s data section, which every later channel shares. A channel created once the connection is up opens over it at once, on both peers, with no new offer or answer, as in a browser, where only a connection’s first channel needs negotiation. The W3C’s createOffer(), createAnswer() and negotiationneeded are not part of webrtc (Differences from the W3C’s API).

local_description() is the local description as it is now, with the candidates gathered so far; has_remote_description() says whether a remote one was applied.

Candidates

Applying a local description starts gathering candidates. async_wait_ice_candidate waits for the next one; the last, whose candidate is empty, is the end of gathering. A program either waits for the end and sends its local description, which then holds every candidate, as the quick start does, or sends each candidate as it comes, which lets the connection start sooner. The other peer adds each with async_add_ice_candidate(c.view()); an empty one ends the remote candidates and adds none.

A candidate needs the remote description first: one added before it fails with invalid_state, as in a browser. So a peer applies what it receives in the order it was sent, one operation at a time.

How to trickle candidates

Each peer’s end of the signalling channel is an inbox: what the other peer said, applied in order, the next operation started once the previous one has completed:

// What one peer says to the other: its description, or one of its candidates.
struct signalling_message {
    std::optional<webrtc::session_description> description;
    webrtc::ice_candidate candidate;
};

// One peer's end of the signalling channel: what the other peer said, applied in the order it was
// said, one operation at a time.
class inbox {
public:
    explicit inbox(webrtc::peer_connection& pc) : pc_(pc) {}

    // What to do once a remote description is applied.
    std::function<void()> on_description;

    // The signalling channel delivers a signal.
    void deliver(signalling_message s) {
        waiting_.push_back(std::move(s));
        if (!busy_) {
            next();
        }
    }

private:
    void next() {
        busy_ = !waiting_.empty();
        if (!busy_) {
            return;
        }
        const signalling_message s = std::move(waiting_.front());
        waiting_.pop_front();
        if (s.description) {
            pc_.async_set_remote_description(s.description->view(), [this](error_code ec) {
                if (ec) {
                    return;
                }
                on_description();
                next();
            });
        } else {
            pc_.async_add_ice_candidate(s.candidate.view(), [this](error_code ec) {
                if (!ec) {
                    next();
                }
            });
        }
    }

    webrtc::peer_connection& pc_;
    std::deque<signalling_message> waiting_;
    bool busy_ = false;
};

Each peer sends its candidates as it gathers them, the end included:

// Sends each candidate `from` gathers to `to` as soon as it is gathered, the end of gathering, an
// empty candidate, included.
void trickle(webrtc::peer_connection& from, inbox& to) {
    from.async_wait_ice_candidate([&from, &to](error_code ec, webrtc::ice_candidate c) {
        if (ec) {
            return;
        }
        const bool end = c.candidate.empty();
        to.deliver(signalling_message{.description = std::nullopt, .candidate = std::move(c)});
        if (!end) {
            trickle(from, to);
        }
    });
}

And each sends its description as soon as it has one, its candidates after it, so that the other peer’s inbox applies them in that order:

inbox at_a(a);
inbox at_b(b);
// b answers the offer once it is applied, then trickles its own candidates.
at_b.on_description = [&] {
    std::printf("b: the offer is applied\n");
    b.async_set_local_description([&](error_code ec, webrtc::session_description answer) {
        if (ec) {
            return;
        }
        at_a.deliver(signalling_message{.description = std::move(answer), .candidate = {}});
        trickle(b, at_a);
    });
};
at_a.on_description = [] { std::printf("a: the answer is applied\n"); };

// a offers, without waiting for its candidates, and trickles them after the offer.
a.async_set_local_description([&](error_code ec, webrtc::session_description offer) {
    if (ec) {
        return;
    }
    at_b.deliver(signalling_message{.description = std::move(offer), .candidate = {}});
    trickle(a, at_b);
});

The program waits until a is connected, then closes both connections. It prints:

b: the offer is applied
a: the answer is applied
a: connected

A real signalling channel carries the description’s type and sdp, and the candidate’s candidate, sdp_mid, sdp_m_line_index and username_fragment, as text or JSON of the program’s choosing; the values are the W3C’s RTCSessionDescriptionInit and RTCIceCandidateInit, so a peer in a browser reads them as they are.

Events

What the W3C delivers as an event, webrtc delivers as the completion of a wait the program starts, and starts again when it wants the next one, as an acceptor’s async_accept. Every handler then runs on the object’s executor, and nothing outlives what the program holds:

The W3C’s event The wait

icecandidate

peer_connection::async_wait_ice_candidate

connectionstatechange

peer_connection::async_wait_state_change

iceconnectionstatechange

peer_connection::async_wait_ice_connection_state_change

datachannel

peer_connection::async_accept_data_channel

open

data_channel::async_wait_open

close

data_channel::async_wait_close

bufferedamountlow

data_channel::async_wait_buffered_amount_low

message

data_channel::async_receive

While no wait is pending

An event can happen while the program has no wait of its kind pending, and each kind says what becomes of it, so that none is lost without a rule:

  • A state coalesces. A wait for a state change completes with the current state once it differs from the one the previous wait completed with, so a program that waits late sees the latest state, not every step to it.

  • Candidates queue up to options::max_queued_candidates, 64 by default, in order; past it a candidate is dropped from the queue and stays in local_description(). The end of gathering has a place of its own past the bound, so it is never dropped.

  • Incoming channels queue up to options::max_queued_channels, 16 by default; a channel past it is closed at once, as a connection past a listen backlog is refused.

  • Messages are kept from the channel’s creation until async_receive reads them (Receiving), so a channel accepted late, or handed from one owner to another, loses nothing it received before.

  • open, close and the buffered amount are states: a wait started after the channel opened, closed, or fell under its threshold completes at once, posted.

One wait of a kind at a time. A second wait of the same kind on the same object completes with already_started, and the first stays pending. A cancelled wait (Cancellation) consumes no event: the next wait gets what it would have got.

Waits and the io_context

A pending operation is outstanding work on the object’s executor and on its handler’s, as an Asio operation is: natively, run() does not return while a candidate or a state change is awaited. A program that starts its waits again after each completion keeps run() running until it closes the connection, and closing is how it ends. What arrives while no wait is pending is no work: a queued candidate or message does not keep run() alive.

Closing

peer_connection::close() is the W3C’s close(): every pending operation of the connection completes with operation_aborted, state() reads closed, and no state change is delivered for it. Its channels then close, and their pending operations complete with error::closed. A wait started on a closed connection completes with error::closed.

data_channel::close() completes the channel’s pending operations with operation_aborted, except async_wait_close, which completes once the channel is closed. When a channel closes for another reason, the peer, its connection, its transport, its pending operations complete with error::closed and async_wait_close completes without an error: that is how a program learns that the other side is gone.

Destroying a connection or a channel closes it first. Natively the destructor then waits until libdatachannel’s callbacks in flight for it have returned, so nothing of it is touched afterwards (The native implementation).

Data channels

A data_channel carries messages between two peers over their connection, each message whole, text or binary. A connection holds many of them, each with its own label and its own reliability: natively up to 1,024, the SCTP streams libdatachannel negotiates, so a negotiated channel’s id is under 1,024 there.

Making one

One peer creates a channel with create_data_channel(label, init) and the other accepts it with async_accept_data_channel once the connection is up. data_channel_init is the W3C’s RTCDataChannelInit: ordered, at most one of max_packet_life_time and max_retransmits for a channel that may drop messages, a protocol, and negotiated with an id for a channel both peers create themselves with the same id, which neither announces and neither accepts. create_data_channel returns a result: both reliability limits at once, negotiated without an id, the id 65535, or a label or protocol past 65,535 bytes fail with type_error; a closed connection with invalid_state; natively, under the default policy, a max_packet_life_time of 0 with operation_not_supported (What the native target cannot honour).

A channel is movable and not copyable; it belongs to whoever holds it, and its executor’s context outlives it. ready_state(), id() and buffered_amount() read what the W3C’s attributes of the same names read, as the channel opens, sends and closes; what it was created with never changes (A channel’s attributes). async_wait_open completes once the channel is open, at once when it already is, and with error::closed when it closed before it opened.

A channel’s attributes

label(), ordered(), max_packet_life_time(), max_retransmits(), protocol() and negotiated() read the W3C’s attributes of the same names, what the channel was created with. A channel the program created reads its data_channel_init; one it accepted reads what the peer announced when it opened the channel, so both ends read the same, but for negotiated(), false at the accepting end since a negotiated channel is never announced. Each is read once, when the channel is made, and costs nothing afterwards; label() and protocol() are views of text in the channel’s allocator, valid while the channel lives.

Here a channel’s messages may arrive out of order, each retransmitted three times at most, for a subprotocol of the program’s:

// Messages may arrive out of order, and each is retransmitted three times at most.
webrtc::data_channel_init init;
init.ordered = false;
init.max_retransmits = 3;
init.protocol = "chat.v1";
auto chat = a.create_data_channel("chat", init).value();

Each end reads it the same way:

// What one end of a channel reads of it, which never changes.
struct attributes {
    std::string label{};
    bool ordered = true;
    std::optional<std::uint16_t> max_packet_life_time{};
    std::optional<std::uint16_t> max_retransmits{};
    std::string protocol{};
    bool negotiated = false;
};

attributes attributes_of(const webrtc::data_channel& channel) {
    return {
        .label = std::string(channel.label()),
        .ordered = channel.ordered(),
        .max_packet_life_time = channel.max_packet_life_time(),
        .max_retransmits = channel.max_retransmits(),
        .protocol = std::string(channel.protocol()),
        .negotiated = channel.negotiated(),
    };
}

and the end the peer accepted reads what the creator announced:

                      created   accepted
label                 chat      chat
ordered               false     false
max_packet_life_time  none      none
max_retransmits       3         3
protocol              chat.v1   chat.v1
negotiated            false     false

Natively a channel the peer announced with a max_packet_life_time of 0 reads as one of max_retransmits 0, since libdatachannel gives it so, and one created with it under webcpp-webrtc-unsupported=ignore reads so at both ends (Differences from the W3C’s API).

Receiving

async_receive(buffer, token) appends the next message, whole, to the caller’s dynamic buffer, Asio’s first version (dynamic_buffer of a string or a vector), and completes with its size and whether it was text. The buffer outlives the operation. A message larger than the room left in the buffer (its max_size() less its size()) is not read: the operation completes with no_buffer_space and the message stays queued, for a later async_receive with a larger buffer.

Messages are kept from the moment the channel exists until they are read, in the order they came. Natively that queue is libdatachannel’s, of 1,024 messages: past it libdatachannel stops reading from the network and the peer is slowed down, a flow control that never fails. But the thread that waits for room is the one that delivers every channel of the connection, so a channel nobody reads stalls the connection’s other channels once 1,024 of its messages wait. A program reads every channel it holds, or closes it. Closing or destroying a channel discards what it holds unread, as the W3C discards what arrives once a channel left open, and releases the others; messages that arrived before the peer closed the channel are still delivered, then async_receive completes with error::closed. In the browser the queue is webrtc’s, bounded in bytes by options::max_received_bytes, since the browser has no flow control on receipt: past it the channel closes with receive_overflow (Receiving and sending).

Sending

send(buffers) and send_text(text) queue one message and return at once: nothing, or why the message was not queued, as an error_code. async_send and async_send_text do the same, and complete once the message is queued, at once, posted, for a program that composes operations. A send fails, and the channel stays open, when:

  • the channel is not open, invalid_state;

  • the message is larger than the smaller of options::max_message_size, 256 KiB by default, and the limit the peer announced, message_too_large;

  • queueing it would take the buffered amount past options::max_buffered_amount, 16 MiB by default, buffered_amount_exceeded;

  • natively, a text holds a zero byte, operation_not_supported, since libdatachannel takes a text as a zero-terminated string.

How to pace a large transfer

buffered_amount() is what the channel holds to send. async_wait_buffered_amount_low waits until it is at or under the threshold set_buffered_amount_low_threshold sets, at once when it already is. A sender keeps the buffered amount under a high-water mark of its choosing and waits for the low mark before it sends more:

// Sends `messages` messages, never more than `high_water` bytes queued at once.
class sender {
public:
    explicit sender(webrtc::data_channel& channel) : channel_(channel) {
        channel_.set_buffered_amount_low_threshold(high_water / 4);
    }

    void send() {
        while (sent_ < messages) {
            if (channel_.buffered_amount() + message_size > high_water) {
                // Too much is queued: wait until a quarter is left, then go on.
                channel_.async_wait_buffered_amount_low([this](error_code ec) {
                    if (!ec) {
                        send();
                    }
                });
                return;
            }
            if (const error_code ec = channel_.send(asio::buffer(payload_)); ec) {
                std::printf("send failed: %s\n", ec.message().c_str());
                return;
            }
            ++sent_;
        }
        std::printf("sent %zu messages, %zu bytes\n", sent_, sent_ * message_size);
    }

private:
    webrtc::data_channel& channel_;
    std::vector<char> payload_ = std::vector<char>(message_size, 'x');
    std::size_t sent_ = 0;
};

The receiver reads every message as it comes, which keeps the channel, and the connection’s other channels, moving:

// Reads every message as it comes, so that the channel never stalls.
std::function<void()> receive = [&] {
    remote->async_receive(buffer, [&](error_code ec, std::size_t n, bool) {
        if (ec) {
            return;
        }
        buffer.consume(n);
        ++received;
        bytes += n;
        if (received < messages) {
            receive();
            return;
        }
        std::printf("received %zu messages, %zu bytes\n", received, bytes);
        a.close();
        b.close();
    });
};

Four MiB go over in messages of 64 KiB, never more than one MiB queued:

sent 64 messages, 4194304 bytes
received 64 messages, 4194304 bytes

Errors

Every failure is a value. An operation completes with a boost::system::error_code; make and create_data_channel return a boost::system::result; send returns an error_code. None throws, with exceptions on or off, and none waits on the network; natively async_set_local_description makes the description in the call, which waits for the connection’s DTLS certificate, milliseconds the first time.

The category webcpp.webrtc

webcpp::webrtc::error holds what has no counterpart among Asio’s codes. Its values are fixed and never reused, and five of them are the W3C’s DOMException names, so that a failure reads the same as in a browser:

Value When

invalid_state (1)

The W3C’s InvalidStateError: a candidate before a remote description, a send on a channel that is not open, an operation on a closed connection.

operation_error (2)

The W3C’s OperationError: the platform refused an operation, as a description it cannot parse.

invalid_access (3)

The W3C’s InvalidAccessError, which a browser reports; never natively.

type_error (4)

The W3C’s TypeError: an argument out of its range, as both reliability limits of one channel.

syntax_error (5)

The W3C’s SyntaxError: an ICE server URL that cannot be parsed.

closed (6)

The channel or the connection closed under a pending operation.

message_too_large (7)

A message past options::max_message_size or the peer’s limit.

buffered_amount_exceeded (8)

A send that would pass options::max_buffered_amount.

receive_overflow (9)

In the browser, unread messages past options::max_received_bytes.

too_many_peer_connections (10)

make past runtime_options::max_peer_connections.

Asio’s codes keep their meaning beside them, through webcpp::asio::error: operation_aborted for an operation cancelled or ended by close() or a destruction, already_started for a second wait of one kind, operation_not_supported for what a target cannot honour, and no_buffer_space for a message larger than the room left in the caller’s buffer.

What a program gets back

webrtc::runtime rt(webrtc::runtime_options{.max_peer_connections = 1, .thread_pool_size = 0});

// An ICE server URL that cannot be parsed: the W3C's SyntaxError.
const std::array<std::string_view, 1> urls{"stun:"};
const std::array<webrtc::ice_server, 1> servers{webrtc::ice_server{.urls = urls}};
webrtc::configuration bad;
bad.ice_servers = servers;
print("a malformed STUN URL",
      webrtc::peer_connection::make(rt, io.get_executor(), bad).error());

// The runtime's cap: one connection at a time.
auto pc = webrtc::peer_connection::make(rt, io.get_executor(), webrtc::configuration{}).value();
print("a second connection",
      webrtc::peer_connection::make(rt, io.get_executor(), webrtc::configuration{}).error());

// A candidate needs a remote description first.
pc.async_add_ice_candidate(
    webrtc::ice_candidate_view{
        .candidate = "candidate:1 1 UDP 1 "
                     "127.0.0.1 9 typ host",
    },
    [](error_code ec) { print("a candidate too early", ec); });

// Both reliability limits at once.
print("a channel with both limits",
      pc.create_data_channel(
            "x", webrtc::data_channel_init{.max_packet_life_time = 100, .max_retransmits = 3})
          .error());

// A channel is not open before the connection is.
auto channel = pc.create_data_channel("y").value();
print("a send before the channel is open", channel.send_text("too soon"));

It prints, the candidate’s line last, since an operation’s handler runs on the io_context while the other calls return their error at once:

a malformed STUN URL: webcpp.webrtc 5, Syntax error
a second connection: webcpp.webrtc 10, Too many peer connections
a channel with both limits: webcpp.webrtc 4, Argument out of its range
a send before the channel is open: webcpp.webrtc 1, Invalid state
a candidate too early: webcpp.webrtc 1, Invalid state

In the browser a failure the browser reports arrives by its DOMException name, which becomes the value of the same name (The page’s objects, through webcpp::asio’s bridge).

Natively

What the W3C checks before it calls the platform, webrtc checks too: a closed connection (invalid_state), a candidate before a remote description (invalid_state), the channel settings of making a channel (type_error), and the sends of sending. What the C API of libdatachannel then refuses comes back as a negative code, which becomes, call by call, the error a browser gives for the same call, and operation_error where nothing more precise applies:

Call RTC_ERR_INVALID RTC_ERR_FAILURE

rtcCreatePeerConnection

syntax_error: an ICE server URL

operation_error

rtcSetLocalDescription

operation_error

operation_error: nothing to negotiate

rtcSetRemoteDescription

operation_error: it cannot be parsed, as Chromium reports it

invalid_state: the signalling state refuses it

rtcAddRemoteCandidate

operation_error

operation_error

rtcCreateDataChannelEx

operation_error

operation_error

rtcSendMessage

operation_error

invalid_state: it closed meanwhile

rtcReceiveMessage

operation_error

operation_error

Cancellation

Every operation installs a handler on its completion handler’s associated cancellation slot, as Asio’s operations do, so bind_cancellation_slot, cancel_after and an awaitable operator’s cancellation reach it. Each operation states the types of cancellation it supports:

Operation Supports A cancellation

the waits of Events and async_receive

terminal, partial, total

completes it with operation_aborted; it consumes no event and no message, which the next wait gets

async_set_local_description, async_set_remote_description

terminal

completes it with operation_aborted; the description may still be applied, after the handler ran, since the platform’s own operation cannot be called back

async_send, async_send_text, and natively async_add_ice_candidate

terminal, partial, total

none in practice: each completes at once, posted

async_add_ice_candidate, in the browser

terminal

completes it with operation_aborted; the candidate may still be added, since the browser’s promise cannot be called back

A cancellation of a type an operation does not support is ignored, as Asio ignores it.

Memory

basic_peer_connection<Executor, Allocator> and basic_data_channel<Executor, Allocator> take an allocator as a standard container does; peer_connection and data_channel are the two with the default executor and std::allocator<std::byte>. make takes the allocator, and a connection’s channels use its own:

  • the object’s state is allocated through the object’s allocator, on the executor: the connection and its channels, the queues of candidates and of incoming channels, the text of a channel’s label and protocol, and that of descriptions and candidates, which the outputs carry, session_description and ice_candidate holding their strings in it;

  • an operation’s state is allocated through its completion handler’s associated allocator, as Asio’s operations are, so a program that binds an allocator to its handlers, or uses one with its coroutines, controls that memory too;

  • what runs on libdatachannel’s threads allocates through the standard allocator only: the copy an event carries to the executor, and the post that carries it. The object’s allocator may be a resource used only on the executor, and it is never touched from another thread;

  • what the platform holds is its own: natively, libdatachannel’s objects and the messages in its queues, and the copies its C API makes when a message is read (what reading a message costs).

The allocator outlives the io_context’s pending handlers, since a posted completion may hold the state until it runs. None of the types is shareable between threads: each is used on its executor.

The native implementation

libdatachannel

Natively webrtc wraps libdatachannel 0.24.6. No WebRTC exists in webcpp, in Boost, in the C++ Alliance’s libraries or in the standard library, and libdatachannel is the smallest complete implementation of it: data channels without a media engine, ICE through libjuice, SCTP through usrsctp, DTLS on the same source-built OpenSSL as webcpp::asio’s TLS. webrtc uses it as a dependency, and copies none of its files: the superproject pins it at commit 6b1e2e6, with its nested sources at the commits tools/libdatachannel/pin.json lists, and builds it from them (Building a program), with the corrections of tools/libdatachannel/patches applied to the build’s copy: two races of 0.24.6 that failed a connection whose DTLS or SCTP transport started while the answer was being applied, and two defects, of its SCTP cleanup and of the usrsctp it pins, that hung a process making a second runtime once the first was gone. Nothing of it appears in a public header: a program never names libdatachannel.

libdatachannel is distributed under the Mozilla Public License 2.0, and its nested dependencies under their own licences, which the superproject’s third-party table lists. MPL’s copyleft is per file: while libdatachannel is changed only by those patches, each under the licence of the files it changes (the MPL, or usrsctp’s BSD 3-Clause), it reaches none of webcpp’s own files, which are under the Boost Software License alone. A program that distributes a native build of webrtc distributes libdatachannel with it, and keeps its licence and notices.

Threads

libdatachannel runs its own threads, a pool whose size runtime_options::thread_pool_size sets, and libjuice’s and usrsctp’s, which is why a native program builds with threading=multi. Every callback of libdatachannel runs on one of them, and webrtc’s do one thing there: copy what the event carries and post it to the object’s executor, through a weak reference to the object’s state, so that an event posted for an object that is gone finds nothing. No handler runs there, and nothing of the program’s allocator is touched there.

Destroying a connection or a channel runs on the executor: it closes the object, then calls libdatachannel’s rtcDelete*, which waits until the callbacks in flight for it have returned and calls none afterwards, as libdatachannel documents. The execution context outlives the object, as for Asio’s I/O objects, which is what keeps a libdatachannel thread from posting to a destroyed io_context.

Exceptions

libdatachannel reports its errors by throwing, and cannot be built without exceptions: the superproject builds its archives with exceptions whatever a program asks. Its C++ API lets those exceptions reach the caller; its C API does not, since every function of it catches what libdatachannel throws and returns a negative code instead. webrtc calls the C API only, so a program built with exception-handling=off uses the native implementation as one built with exceptions does, against the same archives, and gets every error as a value (the C API’s codes). No header of webrtc throws, tries or catches.

What the native target cannot honour

A data channel’s max_packet_life_time of 0. libdatachannel’s C API takes an unreliable channel’s limit as a lifetime when it is positive and as a number of retransmissions otherwise, so a channel created with a lifetime of 0 would be announced to the peer, a browser among them, as one of 0 retransmissions. Under the default policy create_data_channel fails with operation_not_supported; under webcpp-webrtc-unsupported=ignore (Building a program) it makes that channel, the platform’s equivalent, which both of its ends read as max_retransmits() 0. A getter has no failure to give, so a channel the peer announced with a lifetime of 0 reads as max_retransmits() 0 too, whatever the policy.

What reading a message costs

The C API reads a message by copying it out of libdatachannel’s queue into the caller’s memory, rtcReceiveMessage, which the C++ API’s receive() does not need to, since it moves the message out. webrtc first asks for the message’s size, to make room for it in the caller’s buffer, then reads it: two calls, each of which copies the message twice inside libdatachannel, four allocations and four copies in all, in libdatachannel’s allocator, before the copy into the caller’s buffer that both ways make.

bench/receive_bench.cpp measures it: each round fills the receiver’s queue with 1,000 messages from a peer on the loopback, then drains them, through the function async_receive reads with, its two calls of rtcReceiveMessage, and through the C++ API’s receive() and a copy into the same buffer, and the time each round took to arrive is measured too. What async_receive adds around the read, its operation and the posted completion, is not part of either. On 2026-11-14, on macOS 27.0 on arm64 with Apple clang 21, in release, for 100,000 binary messages of each size:

Size webrtc’s read, messages a second receive(), messages a second Time Arrival on the loopback

1 KiB

4,371,163, 4 allocations each

12,758,633, none

2.9 times

71 MB/s, about 69,000 a second

64 KiB

131,446, 4 allocations each

632,404, none

4.8 times

124 MB/s, about 1,900 a second

Reading a message through the C API takes three to five times as long as receive(), and under 2% of the time the same message took to arrive: the transport, not the read, sets the pace. A later version may read into the caller’s buffer without asking for the size first, which would halve the cost. The measurement runs again with

b2 threading=multi libs/webrtc/bench//results

What webrtc quotes of libdatachannel

Some of libdatachannel’s constants shape what a program sees, and are checked again whenever the pinned commit moves: its receive queue of 1,024 messages a channel (RECV_QUEUE_LIMIT), the 1,024 SCTP streams it negotiates, so as many channels a connection (MAX_SCTP_STREAMS_COUNT), the local message size it announces by default, 256 KiB, which options::max_message_size sets, and the size it assumes of a peer that announces none, 64 KiB.

The browser implementation

The page’s objects, through webcpp::asio’s bridge

Compiled with Emscripten, webrtc runs over the page’s own RTCPeerConnection and RTCDataChannel. Each connection and each channel is one registration of webcpp::asio’s bridge, the service of the io_context through which the page’s JavaScript events reach C++: the browser’s event handlers deliver to it, it records what arrived in the object’s state and posts at most one notification for all of it, and the notification completes the waits on the executor, in the order the browser delivered what they wait for: a description’s settlement delivered before the first candidate completes async_set_local_description first, so that a program that sends each candidate as it comes sends its offer before them. No handler of the program runs inside a JavaScript event, and an event reaches the program only while it has returned to the page’s event loop or while run() is suspended, in either of webcpp::asio’s suspension variants, jspi and asyncify. When the io_context is destroyed with operations pending, its shutdown destroys their handlers without calling them, as Asio’s own operations are, even when a handler holds the last owner of the object it waits on.

Every call into the browser is a JavaScript function that catches what the browser throws before it reaches WebAssembly and reports it by its DOMException name, so the browser implementation raises nothing of its own and works with exceptions on and off, as natively. A promise, as setLocalDescription() returns, is followed through the same bridge, whose event says how it settled. The names become values of webcpp.webrtc: InvalidStateError, OperationError, InvalidAccessError, TypeError and SyntaxError the value of the same name, any other operation_error.

The page’s census

The browser keeps no count of its connections that a program could read, and Chromium refuses more than 500 on a page. So the page keeps a census of its own, in JavaScript: every RTCPeerConnection webrtc makes counts from its construction until a FinalizationRegistry sees it collected. The max_peer_connections of a runtime caps that census, and peer_connections() reads it: in the browser it counts every webrtc connection of the page, whatever runtime made it, until it is garbage-collected, not only until it is destroyed. runtime_options::thread_pool_size means nothing there.

Receiving and sending

The browser delivers every message it receives at once, with no flow control, so webrtc keeps a channel’s unread messages in a queue bounded in bytes, in the channel’s allocator: options::max_received_bytes counts each message’s payload and the bookkeeping of its record, and is charged when the browser delivers the message, before the executor reads it, so that a busy or stopped io_context cannot make the page’s memory grow. Past it, or when a received message passes options::max_message_size, the channel discards what it holds unread and closes: ready_state() reads closing, then closed, and async_receive completes with receive_overflow or message_too_large.

A send is checked before the browser sees it, so a refused send leaves the channel open, as natively: the channel’s live readyState first, then the smaller of options::max_message_size and the peer’s maxMessageSize, then options::max_buffered_amount. A text must be valid UTF-8, since the browser sends a JavaScript string, or the send fails with type_error; it may hold a zero byte, which the native implementation refuses, and a leading byte order mark is part of it, sent and received as any other character.

Candidates

A local candidate carries all four of the W3C’s members, the media line’s index and the user name fragment among them. The browser ends each gathering generation with an empty candidate of its own; webrtc delivers the end of gathering once, when the browser has nothing more to gather. A remote candidate follows the browser’s own order of operations: a non-empty one follows the browser’s promise, so that one added while the remote description is still being applied is applied after it, and one added with no remote description fails with invalid_state. An empty one, the end of the remote candidates, never reaches the browser, as natively: it completes at once when a remote description is applied, after the one being applied settles, and with invalid_state when there is none.

What the browser cannot honour

configuration::bind_address names the one local address ICE binds to, which a browser cannot choose. Under the default policy make fails with operation_not_supported; under webcpp-webrtc-unsupported=ignore the address is ignored, since the browser chooses its addresses itself (Building a program).

Differences from the W3C’s API

webrtc follows the W3C’s WebRTC API where a platform allows it. Where one does not, the difference is here, with what a program gets instead.

What a target cannot honour follows one rule: by default it fails with operation_not_supported; under the b2 feature webcpp-webrtc-unsupported=ignore it is ignored, which a setting may be only where the platform does something equivalent of its own. The feature is propagated, so a whole program agrees, and setting both WEBCPP_WEBRTC_UNSUPPORTED_ERROR and WEBCPP_WEBRTC_UNSUPPORTED_IGNORE stops the build. Natively every setting is honoured, but a data channel’s max_packet_life_time of 0, which the rule decides (What the native target cannot honour); in the browser the rule decides configuration::bind_address (What the browser cannot honour). A getter has no failure to give: where a platform holds an attribute otherwise than the W3C says, the table says what the getter returns, whatever the policy.

What What a program gets

createOffer(), createAnswer()

Not offered. async_set_local_description() makes the offer or the answer and applies it, as the W3C’s setLocalDescription() without an argument does; libdatachannel cannot apply a description made apart from it.

negotiationneeded

Not offered: only a connection’s first data channel needs negotiation, and a program creates it before it offers; later channels open over the same connection without one. Natively automatic negotiation is off, so a description exists only when a program asks for one, on both targets.

configuration::bind_address

Not a W3C setting: natively, the one local address ICE binds to, which a program on the loopback needs. A browser cannot honour it: make fails with operation_not_supported, or ignores it under webcpp-webrtc-unsupported=ignore.

a stuns: ICE server URL

Natively not one: libdatachannel knows stun:, turn: and turns: alone, so make fails, the whole configuration with it, with syntax_error, as for a URL it cannot parse. In the browser a URL whose scheme the browser knows is its own to use: a browser that refuses one fails make with the error its constructor names.

a local candidate’s sdp_m_line_index and username_fragment

Natively libdatachannel gives neither: webrtc sets sdp_m_line_index to 0, the connection’s one data section, and leaves username_fragment empty; the sdp_mid is enough for a peer, a browser included. In the browser a candidate carries all four members.

a remote candidate’s username_fragment

Natively ignored, whatever the policy: libdatachannel makes one ICE session per connection and never restarts it, so every candidate belongs to it, and a candidate’s own ufrag attribute, when its text has one, still reaches it. A browser peer’s candidates carry the field, so refusing it would refuse them.

a data channel’s max_packet_life_time of 0

Natively libdatachannel’s C API takes an unreliable channel’s limit as a lifetime when it is positive and as a number of retransmissions otherwise, and gives it back the same way, so a lifetime of 0 has no form of its own. By default create_data_channel fails with operation_not_supported; under webcpp-webrtc-unsupported=ignore it makes a channel of 0 retransmissions, announced to the peer as one, which both of its ends read as max_retransmits() 0 with an empty max_packet_life_time(). A channel the peer announced with a lifetime of 0 reads so too, whatever the policy. In the browser a lifetime of 0 stays one, at both ends.

a text message holding a zero byte, or not UTF-8

Natively a zero byte is not sent, operation_not_supported whatever the policy: the C API takes a text as a zero-terminated string, and cutting the message short silently is never what a program asked for. In the browser a zero byte is sent, and a text that is not valid UTF-8 fails with type_error, since the browser sends a JavaScript string.

a received message past options::max_message_size

A peer that keeps to the size announced in the description never sends one. Natively libdatachannel truncates one that comes anyway to that size, silently, since webrtc installs no logger for it, and webrtc delivers what it kept. In the browser the channel closes, and async_receive completes with message_too_large.

unread messages

Natively they wait in libdatachannel’s queue of 1,024 messages a channel, which slows the peer down when it is full, and stalls the connection’s other channels until the channel is read or closed (Receiving). The browser has no flow control on receipt: past options::max_received_bytes the channel closes with receive_overflow (Receiving and sending).

messages sent just before a channel is closed

Natively they are delivered before the close. Chrome 156 may not deliver them at all when the sender closes the channel at once after sending them, as a page of plain JavaScript shows too; a sender that needs them read waits for the peer to say so before it closes.

runtime::peer_connections() and the cap

Natively the connections made with the runtime and not destroyed. In the browser the page’s census, every connection of the page until it is garbage-collected (The page’s census).

RTCPeerConnection and RTCDataChannel themselves

No native handle, an rtc id or a browser object, appears in a public header: what a program needs is a member, and media, for which a handle was once kept, will get an interface of its own.

Guarantees

What webrtc promises, and the tests that hold each promise, which fail when the promise breaks. A guarantee keeps its number, and the anchor named after it, so a comment of the code or of a test cites it by that anchor: (doc: #webrtc-invariant-3) sends its reader to the third. The tests are those of Testing.

  1. Two peers connect and talk. Two native peers on the loopback exchange their descriptions and every candidate, none refused, reach connected, and carry binary and text messages both ways, each read with whether it was text; so do two peers in one page of a browser. Held by native (a_full_exchange), the browser lane (browser_test, a_full_exchange) and every example of the page.

  2. Every handler runs on the object’s executor, and never inside the call that started its operation. An operation satisfied at once is posted; nothing of libdatachannel’s threads runs a handler. Held by events (a_satisfied_wait_is_posted), native, and lifetime under ThreadSanitizer; in the browser by browser_imports (resolutions_deliver_their_outcome), whose imports never re-enter C++.

  3. No event is lost without a rule. While no wait is pending, states coalesce to the latest, candidates queue up to their bound with a place kept for the end of gathering, and incoming channels queue up to theirs; a second wait of a kind fails with already_started, and a cancelled wait consumes nothing. Held by events (states_coalesce, no_change_keeps_waiting, one_wait_of_a_kind, a_cancelled_wait_consumes_nothing, the_bound_keeps_a_place_for_the_end).

  4. A channel keeps what it received before its first read. Messages are kept from the channel’s creation until async_receive reads them, in order. Held by native (received_before_the_first_receive) and the browser lane (received_before_the_first_receive, accepted_after_its_messages).

  5. close() delivers no state change. A closed connection’s pending operations complete with operation_aborted, its channels close with error::closed, and a later wait fails with error::closed; a channel closed by its owner completes its async_wait_close. Held by native (close_fires_no_state_change, a_channel_closed_by_its_owner) and events (close_aborts_and_then_refuses).

  6. run() returns once the connections are closed. A pending operation is outstanding work, and a program that starts its waits again keeps run() running until it closes its connection. Held by native (run_returns_once_closed).

  7. Every failure is a value. Of the category webcpp.webrtc, whose ten values are fixed, or one of Asio’s; nothing throws, with exceptions on or off. Held by error, native (errors_as_values) and the example webrtc_errors.

  8. A refused send or receive leaves the channel as it was. A send past the message size or the buffered amount fails and the channel stays open; a message larger than the room left in the caller’s buffer fails with no_buffer_space and stays queued, then reads into a larger buffer. Held by native (bounds).

  9. The native implementation works without exceptions. Built with exception-handling=off, against libdatachannel’s archives built with exceptions, it behaves as with them. Held by native_no_exceptions, events_no_exceptions, and every header compiled alone without exceptions. The browser implementation works without them too: every emscripten test that runs a program, under Node in both suspension variants (its _asyncify twins), and every program of the browser lane runs again with exception-handling=off.

  10. The object’s memory is its allocator’s, on its executor. Its state, queues and outputs are allocated through it, an operation’s state through its handler’s allocator, and nothing of the object’s allocator is touched on libdatachannel’s threads. Held by allocation (state_queues_and_outputs_in_the_allocator) and events (an_operation_is_in_its_handlers_allocator).

  11. Destruction is safe while events arrive. A connection and its channels destroyed while the peer floods them touch nothing afterwards, round after round. Held by lifetime (destroyed_while_messages_arrive), 100 rounds under ThreadSanitizer.

  12. A channel never read stalls its connection’s others, and its destruction releases them. Past 1,024 unread messages, natively, a message on another channel of the connection does not arrive; destroying the flooded channel releases it, and returns in under two seconds. Held by stall and lifetime (a_flooded_channel_is_destroyed_promptly), so that a change of libdatachannel’s behaviour fails them and this page changes with it.

  13. The runtime caps the connections alive at once. make past the cap fails with too_many_peer_connections, and a connection’s place follows its moves and is given back when it is destroyed. Held by native (errors_as_values, destruction_and_moves).

  14. A negotiated channel opens on both peers with the same id, and neither accepts it. Held by native (a_negotiated_channel).

  15. In the browser, unread messages never pass their budget. A channel’s unread messages and their records stay within options::max_received_bytes, charged as the browser delivers them; past it, or past max_message_size, the channel closes and async_receive completes with receive_overflow or message_too_large. Held by browser_backend (the_budget_or_the_size) and the browser lane (unread_messages_past_the_budget, a_received_message_past_the_size).

  16. Translation units that disagree on the unsupported policy do not link together. The classes live, on both targets, in an inline namespace named after the policy, so a channel passed between two such units names two different types. Held by config_boundary, which links, and config_mismatch, which must not, natively and on emscripten.

  17. A native peer and a browser peer connect and talk. A native peer and a peer in headless Chrome, signalled through a relay as JSON of the W3C’s RTCSessionDescriptionInit and RTCIceCandidateInit, connect with either one offering and exchange messages both ways, in both suspension variants; the page’s peer passes on every candidate Chrome gathers, in order, with the end. Held by the interop lane.

Testing

Testing a program that uses webrtc

A test needs neither the network nor a second machine: two peers in one process, each made with configuration::bind_address set to "127.0.0.1" and no ICE server, connect through the loopback’s host candidate alone, as the examples of this page do. The test hands each peer’s descriptions and candidates to the other directly, in place of its signalling channel (trickling candidates), runs the io_context with a limit, so that a broken exchange fails rather than hangs, and makes one runtime per case, one case after another (The runtime).

How webrtc is tested

webrtc’s tests are under test/, each declared in test/Jamfile, and each guarantee of Guarantees names the tests that hold it. They run on two targets, 75 tests in all, 37 natively and 60 on emscripten, under Node and in headless Chrome, with every connection on the loopback and no STUN, so that a lane with no network but the loopback runs them whole. The native suite runs as the build asks and without exceptions:

webcpp.run native : native_test.cpp : <library>/webcpp/webrtc//webrtc <threading>multi : native ;
webcpp.run native_no_exceptions : native_test.cpp
  : <library>/webcpp/webrtc//webrtc <threading>multi <exception-handling>off : native ;
Test What it checks

the public headers

Each compiled alone, with libdatachannel, as the build asks and, through the lint, without exceptions.

config, config_developer_defined, config_all_off

<webcpp/webrtc/config.hpp> defines WEBCPP_WEBRTC_NO_EXCEPTIONS exactly when webcpp has no exceptions, and keeps it when a developer defines it in a build that has them.

error, types, and their _no_exceptions twins

The category’s name and fixed values, a message for each, the options’ defaults, and the value types: their defaults, a description’s and a candidate’s view, and their text in a polymorphic allocator.

events, events_no_exceptions

The event machinery both implementations share, without a platform: states coalesce, one wait of a kind, a cancelled wait consumes nothing, the bound keeps a place for the end of gathering, a satisfied wait is posted, close aborts and then refuses, and an operation lives in its handler’s allocator.

native, native_no_exceptions

Two peers on the loopback: a full exchange, messages received before the first read, a channel’s attributes as created and as announced, a negotiated channel, errors as values, the bounds, close, a channel closed by its owner, destruction and moves, and run() returning once closed.

allocation

A connection pair over a polymorphic allocator on a counting resource: the state, a channel’s protocol at both ends among it, the queues and the outputs allocate there, and nothing of it on another thread than the one that runs the io_context.

lifetime

Connections and channels destroyed while the peer floods them, repeated, and a channel flooded and never read destroyed in under two seconds.

stall

A channel past 1,024 unread messages stalls its connection’s others, and its far end’s destruction releases them.

bench

The receive benchmark’s smoke pass (what reading a message costs): a few rounds of each path, each message checked.

browser_imports, browser_runtime, browser_backend

On emscripten, under Node, which has no RTCPeerConnection: the browser calls catch what JavaScript throws and report it by name, never re-entering C++, and texts cross whole; the census and the cap, a slot freed once a connection is collected; and the browser implementation’s semantics over a fake connection and channel of the test’s own, a channel’s attributes, the order of arrivals of different kinds, cancellation, a close with a notification in flight, and the io_context destroyed while handlers own the objects. Each runs with exceptions off too, and in the asyncify variant, its _asyncify twins, which form the own lane asyncify on emscripten, as webcpp::asio’s do: a target that names <webcpp-suspend>asyncify belongs in a lane of emscripten’s, since a build with no emscripten configured cannot expand that feature.

native_policy, native_policy_ignore, and their _no_exceptions twins

A data channel’s max_packet_life_time of 0 under each policy: refused with operation_not_supported, or made with 0 retransmissions, which both of its ends read.

browser_policy, config_boundary, config_mismatch

bind_address under each policy, and two translation units with different policies that fail to link when they pass a channel between them, natively and on emscripten, with their twins likewise.

the browser lane

Two peers in one page of headless Chrome (test/browser/): every native case that applies and the browser’s own, the receive budget and the size limit, refused sends, the close paths, allocation through a counting resource and bind_address, each program in both suspension variants and with exceptions off.

the interop lane

A native peer and a peer in headless Chrome (test/interop/), the same code against the public API, signalled through a relay over webcpp::beast’s WebSocket on 127.0.0.1: each offers in turn, sends ping and gets pong, in both suspension variants; natively, two peers through the same relay.

From the root of a webcpp checkout, the first two of these build and run the tests and the examples natively, as the build asks and without exceptions, and the third runs the tests under AddressSanitizer and UndefinedBehaviorSanitizer:

b2 threading=multi libs/webrtc/test libs/webrtc/example
b2 threading=multi exception-handling=off libs/webrtc/test libs/webrtc/example
b2 threading=multi address-sanitizer=norecover undefined-sanitizer=norecover libs/webrtc/test

On emscripten the tests run under Node, and the browser and interop lanes in headless Chrome, which CHROME names, else Playwright’s cached Chromium on macOS. Both start Chrome with --disable-features=WebRtcHideLocalIpsWithMdns, so that a page’s host candidates are its addresses; the browser lane checks first, with two peers of plain JavaScript, that the browser connects at all. Chrome 156 offers a page with no media permission only its default-route address, so the interop driver grants the page’s origin the microphone, which starts no capture, and the page then offers 127.0.0.1 too, where the native peer listens. The lanes run by name:

b2 toolset=emscripten webcpp-suspend=jspi libs/webrtc/test
b2 toolset=emscripten webcpp-suspend=asyncify libs/webrtc/test
b2 toolset=emscripten libs/webrtc/test/browser//browser
b2 threading=multi libs/webrtc/test/interop//interop
b2 toolset=emscripten libs/webrtc/test/interop//interop

The lifetime and native tests run under ThreadSanitizer too, the lifetime test for 100 rounds, which checks webrtc’s side of every hand-off between libdatachannel’s threads and the executor; libdatachannel’s archives are not instrumented:

b2 threading=multi thread-sanitizer=on define=WEBCPP_TEST_WEBRTC_REPEAT=100 libs/webrtc/test//lifetime libs/webrtc/test//native

b2 compares timestamps, so a result that counts is built from scratch, with b2 -a. The CI runs the tests on every native compiler of webcpp’s lanes, GCC, Clang on libstdc++, Apple Clang and MSVC, and on emscripten, the browser lane with its pinned Chrome, and the test matrix of every run is at https://webcpporg.github.io/report/.

Reference

Every name webrtc declares, in the namespace webcpp::webrtc and those nested in it, from the Doc Comments of its headers: each class, function, type and enumerator with its declaration, what it does, what it asks of its caller and how it fails. The other sections teach the library; this one is where a name is looked up.

Macros

Name Description

WEBCPP_WEBRTC_NO_EXCEPTIONS

Defined when webrtc is built without exceptions: when webcpp has none, or when the developer defines it.

WEBCPP_WEBRTC_UNSUPPORTED_ERROR

Makes what a target cannot honour fail with operation_not_supported, the default.

WEBCPP_WEBRTC_UNSUPPORTED_ERROR

Makes what a target cannot honour fail with operation_not_supported, the default.

WEBCPP_WEBRTC_UNSUPPORTED_IGNORE

Makes what a target cannot honour, and where it may be ignored, ignored.

webcpp::webrtc

Types

Name Description

basic_data_channel

A data channel, the W3C’s RTCDataChannel, whose events are operations the caller re-arms.

basic_ice_candidate

An ICE candidate a peer connection gathered, owned, its text in the connection’s allocator.

basic_peer_connection

A peer connection, the W3C’s RTCPeerConnection, whose operations follow Asio’s model and whose events are operations the caller re-arms, as an acceptor’s async_accept.

basic_session_description

A session description a peer connection produced, owned, its text in the connection’s allocator.

configuration

How a peer connection gathers candidates, the W3C’s RTCConfiguration, read during make.

data_channel_init

How a data channel is created, the W3C’s RTCDataChannelInit.

ice_candidate_view

An ICE candidate given to a call, the W3C’s RTCIceCandidateInit.

ice_server

A STUN or TURN server, the W3C’s RTCIceServer, read during the call that takes it.

options

webcpp’s own bounds on a peer connection and its channels, past which an object fails as a value.

runtime

What the platform holds for the whole process, or the whole page, which the program owns: natively libdatachannel’s threads and global state, and on both targets the cap of peer connections.

runtime_options

What the platform holds for the whole process or page, given to runtime.

session_description_view

A session description given to a call, the W3C’s RTCSessionDescriptionInit.

Type Aliases

Name Description

data_channel

A data channel on Asio’s type-erased executor, in the standard allocator.

ice_candidate

An ICE candidate in the standard allocator.

peer_connection

A peer connection on Asio’s type-erased executor, in the standard allocator.

session_description

A session description in the standard allocator.

Enums

Name Description

data_channel_state

The state of a data channel, the W3C’s RTCDataChannelState.

error

The failures of webcpp::webrtc that have no counterpart among Asio’s codes.

ice_connection_state

The state of a peer connection’s ICE agent, the W3C’s RTCIceConnectionState.

ice_transport_policy

Which candidates ICE may use, the W3C’s RTCIceTransportPolicy.

peer_connection_state

The state of a peer connection, the W3C’s RTCPeerConnectionState.

sdp_type

The type of a session description, the W3C’s RTCSdpType.

Functions

Name Description

make_error_code

Makes the error code of a value of error.

webrtc_category

The category of webcpp::webrtc’s errors, named webcpp.webrtc.

webcpp::webrtc::data_channel

A data channel on Asio’s type-erased executor, in the standard allocator.

Synopsis

using data_channel = basic_data_channel<>;

webcpp::webrtc::ice_candidate

An ICE candidate in the standard allocator.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

webcpp::webrtc::peer_connection

A peer connection on Asio’s type-erased executor, in the standard allocator.

Synopsis

using peer_connection = basic_peer_connection<>;

webcpp::webrtc::session_description

A session description in the standard allocator.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

webcpp::webrtc::basic_data_channel

A data channel, the W3C’s RTCDataChannel, whose events are operations the caller re-arms.

Synopsis

template<
    class Executor = webcpp::asio::any_io_executor,
    class Allocator = std::allocator<std::byte>>
class basic_data_channel;

Description

Messages are kept from the channel’s creation until async_receive reads them: natively in libdatachannel’s own bounded queue, which slows the peer when it is full; in the browser in a queue of the object’s allocator bounded by options::max_received_bytes. A channel is made by its connection’s create_data_channel or async_accept_data_channel; it is movable, not copyable, and its executor’s context outlives it.

Type Aliases

Name Description

allocator_type

The allocator of its state.

executor_type

The executor its handlers run on.

Member Functions

Name Description

basic_data_channel [constructor]

Constructors

~basic_data_channel [destructor]

Closes the channel and completes every pending operation with operation_aborted.

operator=

Assignment operators

async_receive

Appends the next message, whole, to buffer.

async_send

Sends a binary message, completing once it is queued, at once, posted.

async_send_text

Sends a text message, completing once it is queued, at once, posted.

async_wait_buffered_amount_low

Waits for buffered_amount() to be at or below the threshold; at once, posted, when it is.

async_wait_close

Waits for the channel to close; completes at once, posted, when it is closed.

async_wait_open

Waits for the channel to open; completes at once, posted, when it is open.

buffered_amount

The bytes queued to send, the W3C’s bufferedAmount.

close

Closes the channel: its pending operations complete with operation_aborted, but async_wait_close, which completes once it is closed; unread messages are discarded.

get_allocator

The allocator of its state.

get_executor

The executor its handlers run on.

id

The channel’s SCTP stream id, the W3C’s id.

label

The channel’s label.

max_packet_life_time

How long the channel retransmits a message, in milliseconds, the W3C’s maxPacketLifeTime.

max_retransmits

How many times the channel retransmits a message, the W3C’s maxRetransmits.

negotiated

Whether the program negotiated the channel itself, the W3C’s negotiated.

ordered

Whether the channel delivers its messages in the order they were sent, the W3C’s ordered.

protocol

The channel’s subprotocol, the W3C’s protocol.

ready_state

The channel’s state, the W3C’s readyState.

send

Sends a binary message: queues it, or fails.

send_text

Sends a text message: queues it, or fails as send does.

set_buffered_amount_low_threshold

Sets the threshold async_wait_buffered_amount_low waits for.

Friends

Name Description

webcpp::webrtc::basic_peer_connection

A peer connection, the W3C’s RTCPeerConnection, whose operations follow Asio’s model and whose events are operations the caller re-arms, as an acceptor’s async_accept.

Template Parameters

Name Description

Executor

The executor its handlers run on.

Allocator

The allocator of its state, its queues, its label and its protocol.

webcpp::webrtc::basic_data_channel::allocator_type

The allocator of its state.

Synopsis

using allocator_type = Allocator;

webcpp::webrtc::basic_data_channel::executor_type

The executor its handlers run on.

Synopsis

using executor_type = Executor;

webcpp::webrtc::basic_data_channel::basic_data_channel

Constructors

Synopses

Not copyable: a channel has one owner, who reads it.

Moves the channel, its pending operations included; the source holds none.

basic_data_channel(basic_data_channel&& other) noexcept = default;

Parameters

Name Description

other

The channel moved from.

webcpp::webrtc::basic_data_channel::basic_data_channel

Not copyable: a channel has one owner, who reads it.

Synopsis

basic_data_channel(basic_data_channel const&) = delete;

webcpp::webrtc::basic_data_channel::basic_data_channel

Moves the channel, its pending operations included; the source holds none.

Synopsis

basic_data_channel(basic_data_channel&& other) noexcept = default;

Parameters

Name Description

other

The channel moved from.

webcpp::webrtc::basic_data_channel::~basic_data_channel

Closes the channel and completes every pending operation with operation_aborted.

Synopsis

~basic_data_channel();

webcpp::webrtc::basic_data_channel::operator=

Assignment operators

Synopses

Not copy-assignable: a channel has one owner, who reads it.

Moves the channel, closing the one this held.

Return Value

This channel.

Parameters

Name Description

other

The channel moved from.

webcpp::webrtc::basic_data_channel::operator=

Not copy-assignable: a channel has one owner, who reads it.

Synopsis

basic_data_channel&
operator=(basic_data_channel const&) = delete;

webcpp::webrtc::basic_data_channel::operator=

Moves the channel, closing the one this held.

Synopsis

basic_data_channel&
operator=(basic_data_channel&& other) noexcept;

Return Value

This channel.

Parameters

Name Description

other

The channel moved from.

webcpp::webrtc::basic_data_channel::async_receive

Appends the next message, whole, to buffer.

Synopsis

template<
    class DynamicBuffer,
    class CompletionToken>
auto
async_receive(
    DynamicBuffer& buffer,
    CompletionToken&& token);

Description

A message larger than the room left in buffer stays queued, and the operation completes with no_buffer_space. Once the peer closed the channel, the messages it sent before are still delivered, then the operation completes with error::closed. In the browser, once the unread messages passed options::max_received_bytes, or a message options::max_message_size, the channel closed, what it held is discarded, and the operation completes with error::receive_overflow or error::message_too_large.

Return Value

What the token makes of the operation.

Template Parameters

Name Description

DynamicBuffer

A dynamic buffer of Asio’s first version.

CompletionToken

The completion token.

Parameters

Name Description

buffer

A dynamic buffer (Asio’s first version, as beast::flat_buffer), which outlives the operation.

token

The completion token, of signature void(error_code, std::size_t, bool): the message’s size and whether it was text.

webcpp::webrtc::basic_data_channel::async_send

Sends a binary message, completing once it is queued, at once, posted.

Synopsis

template<
    class ConstBufferSequence,
    class CompletionToken>
auto
async_send(
    ConstBufferSequence const& buffers,
    CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

ConstBufferSequence

A sequence of constant buffers.

CompletionToken

The completion token.

Parameters

Name Description

buffers

The message, read during the call.

token

The completion token, of signature void(error_code).

webcpp::webrtc::basic_data_channel::async_send_text

Sends a text message, completing once it is queued, at once, posted.

Synopsis

template<class CompletionToken>
auto
async_send_text(
    std::string_view text,
    CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

text

The message, UTF-8, read during the call.

token

The completion token, of signature void(error_code).

webcpp::webrtc::basic_data_channel::async_wait_buffered_amount_low

Waits for buffered_amount() to be at or below the threshold; at once, posted, when it is.

Synopsis

template<class CompletionToken>
auto
async_wait_buffered_amount_low(CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code).

webcpp::webrtc::basic_data_channel::async_wait_close

Waits for the channel to close; completes at once, posted, when it is closed.

Synopsis

template<class CompletionToken>
auto
async_wait_close(CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code).

webcpp::webrtc::basic_data_channel::async_wait_open

Waits for the channel to open; completes at once, posted, when it is open.

Synopsis

template<class CompletionToken>
auto
async_wait_open(CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code); error::closed when the channel closed first.

webcpp::webrtc::basic_data_channel::buffered_amount

The bytes queued to send, the W3C’s bufferedAmount.

Synopsis

[[nodiscard]]
std::size_t
buffered_amount() const;

Return Value

The bytes.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::close

Closes the channel: its pending operations complete with operation_aborted, but async_wait_close, which completes once it is closed; unread messages are discarded.

Synopsis

void
close();

webcpp::webrtc::basic_data_channel::get_allocator

The allocator of its state.

Synopsis

[[nodiscard]]
allocator_type
get_allocator() const noexcept;

Return Value

The allocator.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::get_executor

The executor its handlers run on.

Synopsis

[[nodiscard]]
executor_type
get_executor() const noexcept;

Return Value

The executor.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::id

The channel’s SCTP stream id, the W3C’s id.

Synopsis

[[nodiscard]]
std::optional<uint16_t>
id() const;

Return Value

The id, or nothing before the transport gave it one.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::label

The channel’s label.

Synopsis

[[nodiscard]]
std::string_view
label() const noexcept;

Return Value

A view of the label, in the object’s allocator, valid while the channel lives.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::max_packet_life_time

How long the channel retransmits a message, in milliseconds, the W3C’s maxPacketLifeTime.

Synopsis

[[nodiscard]]
std::optional<uint16_t>
max_packet_life_time() const noexcept;

Return Value

The limit the channel was created with, by this program or by the peer, or nothing for a channel without one. Natively a limit of 0 reads as max_retransmits() 0, as libdatachannel gives it (the table of differences), and a peer’s limit past 65,535 reads as 65,535.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::max_retransmits

How many times the channel retransmits a message, the W3C’s maxRetransmits.

Synopsis

[[nodiscard]]
std::optional<uint16_t>
max_retransmits() const noexcept;

Return Value

The limit the channel was created with, by this program or by the peer, or nothing for a channel without one. Natively a peer’s limit past 65,535 reads as 65,535.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::negotiated

Whether the program negotiated the channel itself, the W3C’s negotiated.

Synopsis

[[nodiscard]]
bool
negotiated() const noexcept;

Return Value

True for a channel created with data_channel_init::negotiated, which both peers create with one id; false for any other, and for every channel accepted from the peer, since a negotiated channel is never announced.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::ordered

Whether the channel delivers its messages in the order they were sent, the W3C’s ordered.

Synopsis

[[nodiscard]]
bool
ordered() const noexcept;

Return Value

What data_channel_init::ordered said when the channel was created, by this program or, for a channel it accepted, by the peer, which announced it.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::protocol

The channel’s subprotocol, the W3C’s protocol.

Synopsis

[[nodiscard]]
std::string_view
protocol() const noexcept;

Return Value

A view of the name the channel was created with, by this program or by the peer, in the object’s allocator, valid while the channel lives; empty for none.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::ready_state

The channel’s state, the W3C’s readyState.

Synopsis

[[nodiscard]]
data_channel_state
ready_state() const noexcept;

Return Value

The state.

Note

The return value should not be discarded.

webcpp::webrtc::basic_data_channel::send

Sends a binary message: queues it, or fails.

Synopsis

template<class ConstBufferSequence>
boost::system::error_code
send(ConstBufferSequence const& buffers);

Return Value

error::invalid_state when the channel is not open, error::message_too_large past the smaller of options::max_message_size and the peer’s limit, error::buffered_amount_exceeded past options::max_buffered_amount; nothing once queued.

Template Parameters

Name Description

ConstBufferSequence

A sequence of constant buffers.

Parameters

Name Description

buffers

The message, read during the call.

webcpp::webrtc::basic_data_channel::send_text

Sends a text message: queues it, or fails as send does.

Synopsis

boost::system::error_code
send_text(std::string_view text);

Return Value

The failure, or nothing once queued.

Parameters

Name Description

text

The message, UTF-8, read during the call. Natively a text holding a zero fails with operation_not_supported; in the browser a text that is not valid UTF-8 fails with error::type_error (the table of differences).

webcpp::webrtc::basic_data_channel::set_buffered_amount_low_threshold

Sets the threshold async_wait_buffered_amount_low waits for.

Synopsis

void
set_buffered_amount_low_threshold(std::size_t threshold);

Parameters

Name Description

threshold

The threshold, in bytes; 0 at first.

webcpp::webrtc::basic_ice_candidate

An ICE candidate a peer connection gathered, owned, its text in the connection’s allocator.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

template<class Allocator>
struct basic_ice_candidate;

Description

An empty candidate is the end of gathering, the W3C’s own form of it.

Member Functions

Name Description

view

The view of this candidate, to give to the other peer’s async_add_ice_candidate.

Data Members

Name Description

candidate

The candidate’s attribute line, candidate:..., or empty at the end of gathering.

sdp_m_line_index

The index of the m-line it belongs to; natively always 0 (the table of differences).

sdp_mid

The media stream identification it belongs to; empty when unknown.

username_fragment

Its ICE user name fragment; natively empty (the table of differences).

Template Parameters

Name Description

Allocator

The allocator of its text.

webcpp::webrtc::basic_ice_candidate::view

The view of this candidate, to give to the other peer’s async_add_ice_candidate.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

[[nodiscard]]
ice_candidate_view
view() const noexcept;

Return Value

A view valid while this candidate is unchanged; an empty sdp_mid is no mid.

Note

The return value should not be discarded.

webcpp::webrtc::basic_ice_candidate::candidate

The candidate’s attribute line, candidate:..., or empty at the end of gathering.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

/* implementation-defined */ candidate = {};

webcpp::webrtc::basic_ice_candidate::sdp_m_line_index

The index of the m-line it belongs to; natively always 0 (the table of differences).

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<uint16_t> sdp_m_line_index = {};

webcpp::webrtc::basic_ice_candidate::sdp_mid

The media stream identification it belongs to; empty when unknown.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

/* implementation-defined */ sdp_mid = {};

webcpp::webrtc::basic_ice_candidate::username_fragment

Its ICE user name fragment; natively empty (the table of differences).

Synopsis

Declared in <webcpp/webrtc/types.hpp>

/* implementation-defined */ username_fragment = {};

webcpp::webrtc::basic_peer_connection

A peer connection, the W3C’s RTCPeerConnection, whose operations follow Asio’s model and whose events are operations the caller re-arms, as an acceptor’s async_accept.

Synopsis

template<
    class Executor = webcpp::asio::any_io_executor,
    class Allocator = std::allocator<std::byte>>
class basic_peer_connection;

Description

Its operations run on its executor, which is not thread safe: a program calls them, and emits their cancellations, on that executor. Its executor’s context, its runtime and its allocator outlive it.

Type Aliases

Name Description

allocator_type

The allocator of its state and outputs.

data_channel

One of its channels.

executor_type

The executor its handlers run on.

ice_candidate

A candidate it gathered.

session_description

A description it produced.

Member Functions

Name Description

basic_peer_connection [constructor]

Constructors

~basic_peer_connection [destructor]

Closes the connection and completes every pending operation with operation_aborted.

operator=

Assignment operators

async_accept_data_channel

Waits for the next channel the peer opened.

async_add_ice_candidate

Adds a remote candidate; an empty candidate ends the remote gathering and adds none.

async_set_local_description

Creates and applies the implicit local description: an offer, or an answer to the remote offer, the W3C’s setLocalDescription() without an argument.

async_set_remote_description

Applies the remote peer’s description.

async_wait_ice_candidate

Waits for the next local candidate; one whose candidate is empty is the end of gathering.

async_wait_ice_connection_state_change

Waits for the ICE state to differ from the one the previous wait completed with.

async_wait_state_change

Waits for the connection’s state to differ from the one the previous wait completed with.

close

Closes the connection, as the W3C’s close(): no state change is delivered, its pending operations complete with operation_aborted, its channels close with error::closed, and a wait started afterwards completes with error::closed.

create_data_channel

Creates a data channel, the W3C’s createDataChannel; adding one does not negotiate.

get_allocator

The allocator of its state and outputs.

get_executor

The executor its handlers run on.

has_remote_description

Whether a remote description was applied, which a candidate needs.

ice_state

The ICE state, the W3C’s iceConnectionState.

local_description

The local description, the W3C’s localDescription, with the candidates gathered so far.

state

The connection’s state, the W3C’s connectionState.

Static Member Functions

Name Description

make

Makes a peer connection.

Template Parameters

Name Description

Executor

The executor its handlers run on.

Allocator

The allocator of its state, its queues and its outputs.

webcpp::webrtc::basic_peer_connection::allocator_type

The allocator of its state and outputs.

Synopsis

using allocator_type = Allocator;

webcpp::webrtc::basic_peer_connection::data_channel

One of its channels.

Synopsis

webcpp::webrtc::basic_peer_connection::executor_type

The executor its handlers run on.

Synopsis

using executor_type = Executor;

webcpp::webrtc::basic_peer_connection::ice_candidate

A candidate it gathered.

Synopsis

using ice_candidate = basic_ice_candidate<Allocator>;

webcpp::webrtc::basic_peer_connection::session_description

A description it produced.

Synopsis

using session_description = basic_session_description<Allocator>;

webcpp::webrtc::basic_peer_connection::basic_peer_connection

Constructors

Synopses

Not copyable: a connection has one owner.

Moves the connection, its pending operations included; the source holds none.

basic_peer_connection(basic_peer_connection&& other) noexcept = default;

Parameters

Name Description

other

The connection moved from.

webcpp::webrtc::basic_peer_connection::basic_peer_connection

Not copyable: a connection has one owner.

Synopsis

basic_peer_connection(basic_peer_connection const&) = delete;

webcpp::webrtc::basic_peer_connection::basic_peer_connection

Moves the connection, its pending operations included; the source holds none.

Synopsis

basic_peer_connection(basic_peer_connection&& other) noexcept = default;

Parameters

Name Description

other

The connection moved from.

webcpp::webrtc::basic_peer_connection::~basic_peer_connection

Closes the connection and completes every pending operation with operation_aborted.

Synopsis

~basic_peer_connection();

webcpp::webrtc::basic_peer_connection::operator=

Assignment operators

Synopses

Not copy-assignable: a connection has one owner.

Moves the connection, closing the one this held.

Return Value

This connection.

Parameters

Name Description

other

The connection moved from.

webcpp::webrtc::basic_peer_connection::operator=

Not copy-assignable: a connection has one owner.

Synopsis

basic_peer_connection&
operator=(basic_peer_connection const&) = delete;

webcpp::webrtc::basic_peer_connection::operator=

Moves the connection, closing the one this held.

Synopsis

basic_peer_connection&
operator=(basic_peer_connection&& other) noexcept;

Return Value

This connection.

Parameters

Name Description

other

The connection moved from.

webcpp::webrtc::basic_peer_connection::async_accept_data_channel

Waits for the next channel the peer opened.

Synopsis

template<class CompletionToken>
auto
async_accept_data_channel(CompletionToken&& token);

Description

While none is pending, channels are kept up to options::max_queued_channels; one past it is closed at once, as a connection past a listen backlog is refused.

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code, data_channel).

webcpp::webrtc::basic_peer_connection::async_add_ice_candidate

Adds a remote candidate; an empty candidate ends the remote gathering and adds none.

Synopsis

template<class CompletionToken>
auto
async_add_ice_candidate(
    ice_candidate_view candidate,
    CompletionToken&& token);

Description

In the browser the operation follows the browser’s promise, in the browser’s order of operations, and its cancellation is terminal only: the candidate may still be added after the handler ran with operation_aborted.

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

candidate

The candidate, read during the call.

token

The completion token, of signature void(error_code); error::invalid_state before a remote description.

webcpp::webrtc::basic_peer_connection::async_set_local_description

Creates and applies the implicit local description: an offer, or an answer to the remote offer, the W3C’s setLocalDescription() without an argument.

Synopsis

template<class CompletionToken>
auto
async_set_local_description(CompletionToken&& token);

Description

A cancellation is terminal only: the description may still be applied after the handler ran with operation_aborted.

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code, session_description).

webcpp::webrtc::basic_peer_connection::async_set_remote_description

Applies the remote peer’s description.

Synopsis

template<class CompletionToken>
auto
async_set_remote_description(
    session_description_view description,
    CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

description

The description, read during the call.

token

The completion token, of signature void(error_code).

webcpp::webrtc::basic_peer_connection::async_wait_ice_candidate

Waits for the next local candidate; one whose candidate is empty is the end of gathering.

Synopsis

template<class CompletionToken>
auto
async_wait_ice_candidate(CompletionToken&& token);

Description

While no wait is pending, candidates are kept up to options::max_queued_candidates; one past it is dropped here and stays in local_description().

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code, ice_candidate).

webcpp::webrtc::basic_peer_connection::async_wait_ice_connection_state_change

Waits for the ICE state to differ from the one the previous wait completed with.

Synopsis

template<class CompletionToken>
auto
async_wait_ice_connection_state_change(CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code, ice_connection_state).

webcpp::webrtc::basic_peer_connection::async_wait_state_change

Waits for the connection’s state to differ from the one the previous wait completed with.

Synopsis

template<class CompletionToken>
auto
async_wait_state_change(CompletionToken&& token);

Return Value

What the token makes of the operation.

Template Parameters

Name Description

CompletionToken

The completion token.

Parameters

Name Description

token

The completion token, of signature void(error_code, peer_connection_state).

webcpp::webrtc::basic_peer_connection::close

Closes the connection, as the W3C’s close(): no state change is delivered, its pending operations complete with operation_aborted, its channels close with error::closed, and a wait started afterwards completes with error::closed.

Synopsis

void
close();

webcpp::webrtc::basic_peer_connection::create_data_channel

Creates a data channel, the W3C’s createDataChannel; adding one does not negotiate.

Synopsis

[[nodiscard]]
boost::system::result<data_channel>
create_data_channel(
    std::string_view label,
    data_channel_init const& init = {});

Return Value

The channel; or error::type_error for both reliability limits, negotiated without an id, an id of 65535 or a label or protocol past 65,535 bytes; error::invalid_state on a closed connection; natively operation_not_supported for a max_packet_life_time of 0 under the default policy (the table of differences).

Note

The return value should not be discarded.

Parameters

Name Description

label

The channel’s label, read during the call.

init

How it is created.

webcpp::webrtc::basic_peer_connection::get_allocator

The allocator of its state and outputs.

Synopsis

[[nodiscard]]
allocator_type
get_allocator() const noexcept;

Return Value

The allocator.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::get_executor

The executor its handlers run on.

Synopsis

[[nodiscard]]
executor_type
get_executor() const noexcept;

Return Value

The executor.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::has_remote_description

Whether a remote description was applied, which a candidate needs.

Synopsis

[[nodiscard]]
bool
has_remote_description() const;

Return Value

Whether there is one.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::ice_state

The ICE state, the W3C’s iceConnectionState.

Synopsis

[[nodiscard]]
ice_connection_state
ice_state() const noexcept;

Return Value

The state.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::local_description

The local description, the W3C’s localDescription, with the candidates gathered so far.

Synopsis

[[nodiscard]]
std::optional<session_description>
local_description() const;

Return Value

The description, or nothing before one was set.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::state

The connection’s state, the W3C’s connectionState.

Synopsis

[[nodiscard]]
peer_connection_state
state() const noexcept;

Return Value

The state.

Note

The return value should not be discarded.

webcpp::webrtc::basic_peer_connection::make

Makes a peer connection.

Synopsis

[[nodiscard]]
static
boost::system::result<basic_peer_connection>
make(
    runtime& rt,
    Executor const& executor,
    configuration const& config,
    options const& opts = options(),
    Allocator const& allocator = Allocator());

Return Value

The connection; or error::too_many_peer_connections past the runtime’s cap, error::syntax_error for an ICE server URL that cannot be parsed, error::type_error for a bound out of the platform’s range, error::operation_error for another refusal; in the browser, operation_not_supported for a configuration::bind_address, which it cannot honour, under the default policy.

Note

The return value should not be discarded.

Parameters

Name Description

rt

The runtime, which counts it and outlives it.

executor

The executor its handlers run on.

config

How it gathers candidates, read during the call.

opts

Its bounds.

allocator

The allocator of its state and outputs.

webcpp::webrtc::basic_session_description

A session description a peer connection produced, owned, its text in the connection’s allocator.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

template<class Allocator>
struct basic_session_description;

Member Functions

Name Description

view

The view of this description, to give to the other peer’s async_set_remote_description.

Data Members

Name Description

sdp

Its SDP.

type

Its type.

Template Parameters

Name Description

Allocator

The allocator of its text.

webcpp::webrtc::basic_session_description::view

The view of this description, to give to the other peer’s async_set_remote_description.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

[[nodiscard]]
session_description_view
view() const noexcept;

Return Value

A view valid while this description is unchanged.

Note

The return value should not be discarded.

webcpp::webrtc::basic_session_description::sdp

Its SDP.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

/* implementation-defined */ sdp = {};

webcpp::webrtc::basic_session_description::type

Its type.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

sdp_type type = sdp_type::offer;

webcpp::webrtc::configuration

How a peer connection gathers candidates, the W3C’s RTCConfiguration, read during make.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

struct configuration;

Data Members

Name Description

bind_address

The local address ICE binds to, natively; empty for every interface but the loopback.

ice_servers

The servers ICE gathers through; empty for host candidates only.

policy

Which candidates ICE may use.

webcpp::webrtc::configuration::bind_address

The local address ICE binds to, natively; empty for every interface but the loopback.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view bind_address = {};

Description

A loopback candidate needs "127.0.0.1". The browser cannot honour it (the table of differences).

webcpp::webrtc::configuration::ice_servers

The servers ICE gathers through; empty for host candidates only.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::span<ice_server const> ice_servers = {};

webcpp::webrtc::configuration::policy

Which candidates ICE may use.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

ice_transport_policy policy = ice_transport_policy::all;

webcpp::webrtc::data_channel_init

How a data channel is created, the W3C’s RTCDataChannelInit.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

struct data_channel_init;

Data Members

Name Description

id

The SCTP stream id, required when negotiated; chosen by the platform otherwise.

max_packet_life_time

How long a message may be retransmitted, in milliseconds; exclusive with max_retransmits.

max_retransmits

How many times a message may be retransmitted; exclusive with max_packet_life_time.

negotiated

Whether both peers create the channel themselves, with the same id, without announcing it.

ordered

Whether messages arrive in order.

protocol

The subprotocol name.

webcpp::webrtc::data_channel_init::id

The SCTP stream id, required when negotiated; chosen by the platform otherwise.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<uint16_t> id = {};

webcpp::webrtc::data_channel_init::max_packet_life_time

How long a message may be retransmitted, in milliseconds; exclusive with max_retransmits.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<uint16_t> max_packet_life_time = {};

Description

Natively 0 cannot be honoured: create_data_channel fails with operation_not_supported, or under webcpp-webrtc-unsupported=ignore makes a channel of 0 retransmissions, as libdatachannel takes it (the table of differences).

webcpp::webrtc::data_channel_init::max_retransmits

How many times a message may be retransmitted; exclusive with max_packet_life_time.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<uint16_t> max_retransmits = {};

webcpp::webrtc::data_channel_init::negotiated

Whether both peers create the channel themselves, with the same id, without announcing it.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

bool negotiated = false;

webcpp::webrtc::data_channel_init::ordered

Whether messages arrive in order.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

bool ordered = true;

webcpp::webrtc::data_channel_init::protocol

The subprotocol name.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view protocol = {};

webcpp::webrtc::ice_candidate_view

An ICE candidate given to a call, the W3C’s RTCIceCandidateInit.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

struct ice_candidate_view;

Description

An empty candidate ends the remote peer’s candidates, and adds none.

Data Members

Name Description

candidate

The candidate’s attribute line, candidate:..., or empty.

sdp_m_line_index

The index of the m-line it belongs to, when known.

sdp_mid

The media stream identification it belongs to, when known.

username_fragment

Its ICE user name fragment; natively ignored (the table of differences).

webcpp::webrtc::ice_candidate_view::candidate

The candidate’s attribute line, candidate:..., or empty.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view candidate = {};

webcpp::webrtc::ice_candidate_view::sdp_m_line_index

The index of the m-line it belongs to, when known.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<uint16_t> sdp_m_line_index = {};

webcpp::webrtc::ice_candidate_view::sdp_mid

The media stream identification it belongs to, when known.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::optional<std::string_view> sdp_mid = {};

webcpp::webrtc::ice_candidate_view::username_fragment

Its ICE user name fragment; natively ignored (the table of differences).

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view username_fragment = {};

webcpp::webrtc::ice_server

A STUN or TURN server, the W3C’s RTCIceServer, read during the call that takes it.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

struct ice_server;

Data Members

Name Description

credential

The TURN credential, empty for STUN.

urls

Its URLs, stun:host:port or turn:host:port?transport=udp.

username

The TURN user name, empty for STUN.

webcpp::webrtc::ice_server::credential

The TURN credential, empty for STUN.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view credential = {};

webcpp::webrtc::ice_server::urls

Its URLs, stun:host:port or turn:host:port?transport=udp.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::span<std::string_view const> urls = {};

Description

Natively stuns: is not one: libdatachannel knows stun:, turn: and turns: alone, and make fails with error::syntax_error (the table of differences).

webcpp::webrtc::ice_server::username

The TURN user name, empty for STUN.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view username = {};

webcpp::webrtc::options

webcpp’s own bounds on a peer connection and its channels, past which an object fails as a value.

Synopsis

struct options;

Description

None of them throws or blocks: each is a code of error.

Data Members

Name Description

max_buffered_amount

The most bytes a channel may hold to send; a send past it fails with buffered_amount_exceeded.

max_message_size

The largest message sent or received, announced natively in the SDP.

max_queued_candidates

Local candidates kept while no async_wait_ice_candidate is pending; the end of gathering has a place of its own.

max_queued_channels

Incoming channels kept while no async_accept_data_channel is pending; one past it is closed at once.

max_received_bytes

In the browser, the most bytes of unread messages and their records; past it the channel closes.

webcpp::webrtc::options::max_buffered_amount

The most bytes a channel may hold to send; a send past it fails with buffered_amount_exceeded.

Synopsis

std::size_t max_buffered_amount = std::size_t{16} * 1024 * 1024;

webcpp::webrtc::options::max_message_size

The largest message sent or received, announced natively in the SDP.

Synopsis

std::size_t max_message_size = std::size_t{256} * 1024;

webcpp::webrtc::options::max_queued_candidates

Local candidates kept while no async_wait_ice_candidate is pending; the end of gathering has a place of its own.

Synopsis

std::size_t max_queued_candidates = 64;

webcpp::webrtc::options::max_queued_channels

Incoming channels kept while no async_accept_data_channel is pending; one past it is closed at once.

Synopsis

std::size_t max_queued_channels = 16;

webcpp::webrtc::options::max_received_bytes

In the browser, the most bytes of unread messages and their records; past it the channel closes.

Synopsis

std::size_t max_received_bytes = std::size_t{16} * 1024 * 1024;

webcpp::webrtc::runtime

What the platform holds for the whole process, or the whole page, which the program owns: natively libdatachannel’s threads and global state, and on both targets the cap of peer connections.

Synopsis

class runtime;

Description

A program makes one before any peer connection and destroys it after the last, and after the last data channel; make takes it by reference, so no connection exists without one.

Natively at most one exists at a time in a process, because libdatachannel’s state is the process’s: a second one’s destructor would end the first one’s connections. That is a precondition: webrtc keeps no static state to check it with. A native runtime counts the connections made with it.

In the browser the count is the page’s, kept in JavaScript, so that every runtime and every module of the page counts in one place, as Chromium counts its own limit: a connection counts from its construction until the garbage collector frees it, a closed one included.

Member Functions

Name Description

runtime [constructor]

Constructors

~runtime [destructor]

Destroys the runtime.

operator=

Assignment operators

get_options

The options it was made with.

peer_connections

The peer connections alive that count against the cap: natively those made with it; in the browser the page’s, made by webcpp::webrtc with any runtime and not yet freed by the garbage collector.

See Also

"The runtime", in the guide.

webcpp::webrtc::runtime::runtime

Constructors

Synopses

Not copyable: its connections hold it by reference, and natively it is the process’s.

runtime(runtime const&) = delete;

Not movable: its connections hold it by reference.

runtime(runtime&&) = delete;

Makes the runtime.

explicit
runtime(runtime_options const& opts = {});

Parameters

Name Description

opts

The cap of peer connections and, natively, the thread pool’s size.

webcpp::webrtc::runtime::runtime

Not copyable: its connections hold it by reference, and natively it is the process’s.

Synopsis

runtime(runtime const&) = delete;

webcpp::webrtc::runtime::runtime

Not movable: its connections hold it by reference.

Synopsis

runtime(runtime&&) = delete;

webcpp::webrtc::runtime::runtime

Makes the runtime.

Synopsis

explicit
runtime(runtime_options const& opts = {});

Description

Natively it loads libdatachannel’s global resources (rtcPreload), with its thread pool sized as opts says; in the browser, whose threads are its own, thread_pool_size changes nothing.

Parameters

Name Description

opts

The cap of peer connections and, natively, the thread pool’s size.

webcpp::webrtc::runtime::~runtime

Destroys the runtime.

Synopsis

~runtime();

Description

Natively it unloads libdatachannel’s global resources (rtcCleanup), waiting until its threads have stopped, for at most ten seconds, after which libdatachannel gives up; in the browser it holds nothing of the page.

webcpp::webrtc::runtime::operator=

Assignment operators

Synopses

Not copy-assignable: its connections hold it by reference, and natively it is the process’s.

runtime&
operator=(runtime const&) = delete;

Not move-assignable: its connections hold it by reference.

runtime&
operator=(runtime&&) = delete;

webcpp::webrtc::runtime::operator=

Not copy-assignable: its connections hold it by reference, and natively it is the process’s.

Synopsis

runtime&
operator=(runtime const&) = delete;

webcpp::webrtc::runtime::operator=

Not move-assignable: its connections hold it by reference.

Synopsis

runtime&
operator=(runtime&&) = delete;

webcpp::webrtc::runtime::get_options

The options it was made with.

Synopsis

[[nodiscard]]
runtime_options const&
get_options() const noexcept;

Return Value

The options.

Note

The return value should not be discarded.

webcpp::webrtc::runtime::peer_connections

The peer connections alive that count against the cap: natively those made with it; in the browser the page’s, made by webcpp::webrtc with any runtime and not yet freed by the garbage collector.

Synopsis

[[nodiscard]]
std::size_t
peer_connections() const noexcept;

Return Value

Their number.

Note

The return value should not be discarded.

webcpp::webrtc::runtime_options

What the platform holds for the whole process or page, given to runtime.

Synopsis

struct runtime_options;

Data Members

Name Description

max_peer_connections

The most peer connections alive at once; 256 is half of Chromium’s 500 per page.

thread_pool_size

Natively, libdatachannel’s threads; 0 for its own default.

webcpp::webrtc::runtime_options::max_peer_connections

The most peer connections alive at once; 256 is half of Chromium’s 500 per page.

Synopsis

std::size_t max_peer_connections = 256;

webcpp::webrtc::runtime_options::thread_pool_size

Natively, libdatachannel’s threads; 0 for its own default.

Synopsis

uint32_t thread_pool_size = 0;

webcpp::webrtc::session_description_view

A session description given to a call, the W3C’s RTCSessionDescriptionInit.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

struct session_description_view;

Data Members

Name Description

sdp

Its SDP.

type

Its type.

webcpp::webrtc::session_description_view::sdp

Its SDP.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

std::string_view sdp = {};

webcpp::webrtc::session_description_view::type

Its type.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

sdp_type type = sdp_type::offer;

webcpp::webrtc::data_channel_state

The state of a data channel, the W3C’s RTCDataChannelState.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

enum class data_channel_state : int;

Members

Name Description

connecting

"connecting".

open

"open".

closing

"closing".

closed

"closed".

webcpp::webrtc::data_channel_state::connecting

"connecting".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

connecting

webcpp::webrtc::data_channel_state::open

"open".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

open

webcpp::webrtc::data_channel_state::closing

"closing".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

closing

webcpp::webrtc::data_channel_state::closed

"closed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

closed

webcpp::webrtc::error

The failures of webcpp::webrtc that have no counterpart among Asio’s codes.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

enum class error : int;

Description

Their values are fixed and never reused. Asio’s codes keep their own meaning beside them: operation_aborted for an operation cancelled or ended by close() or destruction, already_started for a second wait of one kind, operation_not_supported for what a target cannot honour, no_buffer_space for a message larger than the room left in the caller’s buffer.

Members

Name Description

invalid_state

The W3C’s InvalidStateError: a candidate before a remote description, a send on a channel that is not open.

operation_error

The W3C’s OperationError: the platform refused an operation, as a description it cannot parse.

invalid_access

The W3C’s InvalidAccessError.

type_error

The W3C’s TypeError: an argument out of its range, as both reliability limits of a channel.

syntax_error

The W3C’s SyntaxError: an ICE server URL that cannot be parsed.

closed

The channel or the connection closed under a pending operation.

message_too_large

A message past options::max_message_size or the peer’s limit, sent or received.

buffered_amount_exceeded

A send that would pass options::max_buffered_amount.

receive_overflow

The browser’s unread messages past options::max_received_bytes.

too_many_peer_connections

make past runtime_options::max_peer_connections.

webcpp::webrtc::error::invalid_state

The W3C’s InvalidStateError: a candidate before a remote description, a send on a channel that is not open.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

invalid_state = 1

webcpp::webrtc::error::operation_error

The W3C’s OperationError: the platform refused an operation, as a description it cannot parse.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

operation_error = 2

webcpp::webrtc::error::invalid_access

The W3C’s InvalidAccessError.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

invalid_access = 3

webcpp::webrtc::error::type_error

The W3C’s TypeError: an argument out of its range, as both reliability limits of a channel.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

type_error = 4

webcpp::webrtc::error::syntax_error

The W3C’s SyntaxError: an ICE server URL that cannot be parsed.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

syntax_error = 5

webcpp::webrtc::error::closed

The channel or the connection closed under a pending operation.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

closed = 6

webcpp::webrtc::error::message_too_large

A message past options::max_message_size or the peer’s limit, sent or received.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

message_too_large = 7

webcpp::webrtc::error::buffered_amount_exceeded

A send that would pass options::max_buffered_amount.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

buffered_amount_exceeded = 8

webcpp::webrtc::error::receive_overflow

The browser’s unread messages past options::max_received_bytes.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

receive_overflow = 9

webcpp::webrtc::error::too_many_peer_connections

make past runtime_options::max_peer_connections.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

too_many_peer_connections = 10

webcpp::webrtc::ice_connection_state

The state of a peer connection’s ICE agent, the W3C’s RTCIceConnectionState.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

enum class ice_connection_state : int;

Members

Name Description

new_

"new", spelled new_ since new is a keyword.

checking

"checking".

connected

"connected".

completed

"completed".

disconnected

"disconnected".

failed

"failed".

closed

"closed".

webcpp::webrtc::ice_connection_state::new_

"new", spelled new_ since new is a keyword.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

new_

webcpp::webrtc::ice_connection_state::checking

"checking".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

checking

webcpp::webrtc::ice_connection_state::connected

"connected".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

connected

webcpp::webrtc::ice_connection_state::completed

"completed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

completed

webcpp::webrtc::ice_connection_state::disconnected

"disconnected".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

disconnected

webcpp::webrtc::ice_connection_state::failed

"failed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

failed

webcpp::webrtc::ice_connection_state::closed

"closed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

closed

webcpp::webrtc::ice_transport_policy

Which candidates ICE may use, the W3C’s RTCIceTransportPolicy.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

enum class ice_transport_policy : int;

Members

Name Description

all

"all".

relay

"relay": TURN only.

webcpp::webrtc::ice_transport_policy::all

"all".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

all

webcpp::webrtc::ice_transport_policy::relay

"relay": TURN only.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

relay

webcpp::webrtc::peer_connection_state

The state of a peer connection, the W3C’s RTCPeerConnectionState.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

enum class peer_connection_state : int;

Members

Name Description

new_

"new", spelled new_ since new is a keyword.

connecting

"connecting".

connected

"connected".

disconnected

"disconnected".

failed

"failed".

closed

"closed".

webcpp::webrtc::peer_connection_state::new_

"new", spelled new_ since new is a keyword.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

new_

webcpp::webrtc::peer_connection_state::connecting

"connecting".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

connecting

webcpp::webrtc::peer_connection_state::connected

"connected".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

connected

webcpp::webrtc::peer_connection_state::disconnected

"disconnected".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

disconnected

webcpp::webrtc::peer_connection_state::failed

"failed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

failed

webcpp::webrtc::peer_connection_state::closed

"closed".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

closed

webcpp::webrtc::sdp_type

The type of a session description, the W3C’s RTCSdpType.

Synopsis

Declared in <webcpp/webrtc/types.hpp>

enum class sdp_type : int;

Members

Name Description

offer

"offer".

answer

"answer".

pranswer

"pranswer".

rollback

"rollback".

webcpp::webrtc::sdp_type::offer

"offer".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

offer

webcpp::webrtc::sdp_type::answer

"answer".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

answer

webcpp::webrtc::sdp_type::pranswer

"pranswer".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

pranswer

webcpp::webrtc::sdp_type::rollback

"rollback".

Synopsis

Declared in <webcpp/webrtc/types.hpp>

rollback

webcpp::webrtc::make_error_code

Makes the error code of a value of error.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

boost::system::error_code
make_error_code(error e) noexcept;

Return Value

The code, of the category webcpp.webrtc.

Parameters

Name Description

e

The error.

webcpp::webrtc::webrtc_category

The category of webcpp::webrtc’s errors, named webcpp.webrtc.

Synopsis

Declared in <webcpp/webrtc/error.hpp>

boost::system::error_category const&
webrtc_category() noexcept;

Return Value

The category, alive for the whole program.

WEBCPP_WEBRTC_NO_EXCEPTIONS

Defined when webrtc is built without exceptions: when webcpp has none, or when the developer defines it.

Synopsis

Declared in <webcpp/webrtc/config.hpp>

#define WEBCPP_WEBRTC_NO_EXCEPTIONS

Description

webrtc raises no exception of its own, so the macro changes nothing in its behaviour.

WEBCPP_WEBRTC_UNSUPPORTED_ERROR

Makes what a target cannot honour fail with operation_not_supported, the default.

Synopsis

Declared in <webcpp/webrtc/config.hpp>

#define WEBCPP_WEBRTC_UNSUPPORTED_ERROR

WEBCPP_WEBRTC_UNSUPPORTED_ERROR

Makes what a target cannot honour fail with operation_not_supported, the default.

Synopsis

Declared in <webcpp/webrtc/config.hpp>

#define WEBCPP_WEBRTC_UNSUPPORTED_ERROR

WEBCPP_WEBRTC_UNSUPPORTED_IGNORE

Makes what a target cannot honour, and where it may be ignored, ignored.

Synopsis

Declared in <webcpp/webrtc/config.hpp>

#define WEBCPP_WEBRTC_UNSUPPORTED_IGNORE

Appendix A: Changelog

What changed in webrtc in each version of webcpp, newest first, one line per change. "Unreleased" is what the next version brings. The release notes of every version are on webcpp’s index page.

Unreleased

  • Added peer connections and data channels with the W3C’s names, in Asio’s model.

  • Added the native implementation over libdatachannel’s C API, with exceptions on and off.

  • Added the browser implementation over the page’s own RTCPeerConnection.

  • Added a data channel’s ordered, max_packet_life_time, max_retransmits, protocol and negotiated.

  • Added the unsupported policy natively; by default it refuses a max_packet_life_time of 0.

  • Added a runtime that holds libdatachannel’s threads and caps connections.

  • Added errors as values, in the category webcpp.webrtc and Asio’s codes, and [[nodiscard]] on every function that returns a boost::system::result.

  • Added the library’s page, with its examples, guarantees and differences.