Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
* Add `webrtc.aiortc.install_alias()`, which makes `import aiortc` give the compat layer, for libraries that import aiortc themselves by [@MarshalX](https://github.com/MarshalX)
* Add aiortc's `rtp`, `jitterbuffer`, `utils` and `clock` modules and the ICE server helpers of `rtcicetransport` to the compat layer by [@MarshalX](https://github.com/MarshalX)
* Drop a compat layer track's buffered frames when its receiver's `_enabled` is set to `False`, and add the track's `_queue`, for libraries that skip stale frames by [@MarshalX](https://github.com/MarshalX)
* Fix a video frame leak in the compat layer when a sender's track is replaced or stopped by [@MarshalX](https://github.com/MarshalX)
* Add `RTCConfiguration.tcp_listen` for clients without UDP, also on `webrtc.pipecat`'s connection and request handler. See [Clients without UDP](https://wrtc.marshal.dev/guides/connections/#clients-without-udp) by [@MarshalX](https://github.com/MarshalX)
* Fix ICE and DTLS transport states changing before their events by [@MarshalX](https://github.com/MarshalX)
* Fix compat layer audio `pts` falling behind after dropped audio by [@MarshalX](https://github.com/MarshalX)
* Fix a cancelled stream read losing the next chunk by [@MarshalX](https://github.com/MarshalX)

## Version 0.1.0

Expand Down
3 changes: 2 additions & 1 deletion docs/source/guides/aiortc.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ Behaves differently:
- **Data channels.** Messages are limited to 256 KiB between Python WebRTC peers and to 64 KiB with an aiortc peer;
a larger one raises `TypeError`. A `maxPacketLifeTime` of 0 makes the channel unreliable.
- **Remote media.** `recv()` buffers about 1 s (30 video frames, 100 audio chunks) and drops the oldest after that,
where aiortc queues without limit. Remote video can arrive as `yuv420p10le` or `nv12`, besides `yuv420p`.
where aiortc queues without limit. Remote video can arrive as `yuv420p10le` or `nv12`, besides `yuv420p`. Remote
audio `recv()` returns silence while no packets arrive.
- **Track end.** Remote tracks end when the peer closes the connection or you call `close()`. A remote
`transceiver.stop()` alone doesn't end them.
- **Stats.** The ids are the engine's. `remote-inbound-rtp` and `remote-outbound-rtp` follow the engine's RTCP interval,
Expand Down
12 changes: 12 additions & 0 deletions docs/source/guides/connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ through it, like on a Mac without Local Network permission, allow it before the
webrtc.allow_loopback() # or WRTC_ALLOW_LOOPBACK=1
```

## Clients without UDP

Without UDP and TURN, a client can reach a server over TCP if the server listens. Set `tcp_listen` on the server
only:

```python
config = webrtc.RTCConfiguration(tcp_listen=True, port_range=(40000, 40099))
```

In Docker, publish `port_range` for TCP too: `-p 40000-40099:40000-40099/udp -p 40000-40099:40000-40099/tcp`.
Leave it off on clients: when both ends listen, every TCP port pairs with every remote one.

## States

The state of a connection is in {attr}`~webrtc.RTCPeerConnection.connection_state`, and each change fires
Expand Down
4 changes: 4 additions & 0 deletions docs/source/guides/pipecat.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ is a complete bot on the runner.
candidate, so there the answer waits the whole timeout.
- **Port range.** `port_range=(low, high)` keeps the bot's candidates in a range of ports. In Docker, publish the same
range, like `-p 40000-40019:40000-40019/udp`. The runner makes its own handler, so this needs a server of your own.
- **Clients without UDP.** `tcp_listen=True` lets clients behind a firewall that blocks UDP connect over TCP, without
TURN. With `port_range`, publish the range for `/tcp` too. See [Clients without UDP](connections.md#clients-without-udp).
- **Codecs.** The answer follows the client's offer. For H.264, see [H.264](h264.md).

## What differs
Expand Down Expand Up @@ -147,4 +149,6 @@ Each checked against Pipecat's transport on aiortc, with Pipecat's workaround re
- `port_range` lets Docker publish only a range of UDP ports ([#1808](https://github.com/pipecat-ai/pipecat/issues/1808), [#1570](https://github.com/pipecat-ai/pipecat/issues/1570)).
- A bot uses less CPU per session: media stays native, with no PyAV or OpenCV conversions.
- A client that vanishes is noticed sooner ([#3140](https://github.com/pipecat-ai/pipecat/issues/3140)).
- Audio resumes right after an ICE restart.
- Clients without UDP can connect over TCP, without TURN.
- A dead first TURN server falls back to the next.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ logger-objects = ["webrtc.aiortc._utils.logger"]
"python-webrtc/python/webrtc/interfaces/rtc_peer_connection.py" = ["PLR0904"] # the W3C interface
"python-webrtc/python/webrtc/pipecat/__init__.py" = ["RUF067"] # names the extra when it's missing
# the framework's signatures, with positional flags
"python-webrtc/python/webrtc/pipecat/**" = ["FBT001", "FBT002", "PLR0917"]
"python-webrtc/python/webrtc/pipecat/**" = ["FBT001", "FBT002", "PLR0913", "PLR0917"]
# aiortc's names and signatures; its docs document the API
"python-webrtc/python/webrtc/aiortc/**" = ["D1", "RUF067", "PLC0414", "N802", "N803", "FBT001", "FBT002", "PLR0913", "PLR0917"]
# user callbacks error the stream, as the specification says; handler errors go to the loop's exception handler
Expand Down
1 change: 1 addition & 0 deletions python-webrtc/cpp/NATIVE.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ Python garbage.
(`_recheck`): whichever runs last sees the other.
- An object is kept for the events still owed to it, not for the state it shows (an announced data channel reads
open before its open event).
- A `Surfaced` value is pinned before its live value moves, under the writer's lock. A `Surfaced` lock is a leaf.
- Each class's `_open()` is its delivery gate: once it's false, even queued events don't fire (a stopped track, a
detached transform, a closed connection). The base gate is "its connection isn't closed". `GATES` in
`tests/test_lifetime_model.py` lists every class's gate; a new class with events is added there.
Expand Down
5 changes: 3 additions & 2 deletions python-webrtc/cpp/src/interfaces/peer_connection_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ namespace python_webrtc {
}

std::unique_ptr<webrtc::PortAllocator>
PeerConnectionFactory::CreatePortAllocator(const webrtc::PeerConnectionInterface::RTCConfiguration &configuration) {
PeerConnectionFactory::CreatePortAllocator(const webrtc::PeerConnectionInterface::RTCConfiguration &configuration,
bool tcpListen) {
auto allocator = python_webrtc::CreatePortAllocator(webrtc::CreateEnvironment(_fieldTrials.CreateCopy()),
_networkManager, _packetSocketFactory);
_networkManager, _packetSocketFactory, tcpListen);
// as libwebrtc's factory does
allocator->SetPortRange(configuration.port_allocator_config.min_port, configuration.port_allocator_config.max_port);
allocator->set_flags(configuration.port_allocator_config.flags);
Expand Down
2 changes: 1 addition & 1 deletion python-webrtc/cpp/src/interfaces/peer_connection_factory.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ namespace python_webrtc {
[[nodiscard]] int networkIgnoreMask() const { return _networkIgnoreMask; }

std::unique_ptr<webrtc::PortAllocator>
CreatePortAllocator(const webrtc::PeerConnectionInterface::RTCConfiguration &configuration);
CreatePortAllocator(const webrtc::PeerConnectionInterface::RTCConfiguration &configuration, bool tcpListen);

[[nodiscard]] std::shared_ptr<webrtc::BasicNetworkManager> networkManager() const { return _networkManager; }
[[nodiscard]] std::shared_ptr<webrtc::BasicPacketSocketFactory> packetSocketFactory() const {
Expand Down
5 changes: 5 additions & 0 deletions python-webrtc/cpp/src/interfaces/rtc_dtls_transport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "../utils/buffer.h"
#include "../utils/gil.h"
#include "../utils/libwebrtc_thread.h"
#include "../utils/parking.h"

namespace python_webrtc {

Expand Down Expand Up @@ -96,11 +97,15 @@ namespace python_webrtc {
const std::scoped_lock lock(_mutex);
previous = _state;
changed = _state != information.state();
if (changed) {
_surfacedState.Changed(IsBound(), previous);
}
_state = information.state();
_certificates = copyCertificates(information);
}

if (changed) {
Parking::At("dtls.statechange");
if (information.state() == webrtc::DtlsTransportState::kFailed) {
// libwebrtc tells no more than that the handshake failed
webrtc::RTCError error(webrtc::RTCErrorType::OPERATION_ERROR_WITH_DATA, "The DTLS transport failed");
Expand Down
124 changes: 82 additions & 42 deletions python-webrtc/cpp/src/interfaces/rtc_ice_transport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ namespace python_webrtc {
// what libwebrtc gives a connection's allocator, on the network thread
std::unique_ptr<webrtc::PortAllocator> CreateStandalonePortAllocator(const webrtc::Environment &env,
PeerConnectionFactory &factory) {
auto allocator = CreatePortAllocator(env, factory.networkManager(), factory.packetSocketFactory());
auto allocator = CreatePortAllocator(env, factory.networkManager(), factory.packetSocketFactory(),
/*tcpListen=*/false);
allocator->Initialize();
uint32_t flags =
allocator->flags() | webrtc::PORTALLOCATOR_ENABLE_SHARED_SOCKET | webrtc::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Expand Down Expand Up @@ -83,7 +84,7 @@ namespace python_webrtc {
this, Guard([this](webrtc::IceTransportInternal *transport) { OnGatheringStateChanged(transport); }));
_subscribed = internal;
}
TakeSnapshot();
TakeSnapshot(Pin::kNone);
});
// none until its first change, unless read unbound
_surfacedPair.Changed(true, std::nullopt);
Expand Down Expand Up @@ -141,32 +142,46 @@ namespace python_webrtc {
return registry.Get();
}

RTCIceTransport::StateChange RTCIceTransport::TakeSnapshot() {
const std::scoped_lock lock(_mutex);
RTCIceTransport::StateChange RTCIceTransport::TakeSnapshot(Pin pin) {
std::unique_lock lock(_mutex);
StateChange change{.previousState = _state,
.state = _state,
.previousGatheringState = _gatheringState,
.gatheringState = _gatheringState};
if (_stopped || _connectionClosed || _dropped) {
return change;
}
auto state = webrtc::IceTransportState::kClosed;
auto gatheringState = webrtc::IceGatheringState::kIceGatheringComplete;
auto *internal = _transport->internal();
if (internal != nullptr) {
_component = internal->component() == 1 ? RTCIceComponent::kRtp : RTCIceComponent::kRtcp;
_role = internal->GetIceRole();
_state = internal->GetIceTransportState();
if (_standalone && _state == webrtc::IceTransportState::kNew && _remoteParameters && !_remoteCandidates.empty()) {
state = internal->GetIceTransportState();
if (_standalone && state == webrtc::IceTransportState::kNew && _remoteParameters && !_remoteCandidates.empty()) {
// started with remote candidates: checking, as a transport of its own is from then on, even before it
// has candidates to check them with
_state = webrtc::IceTransportState::kChecking;
state = webrtc::IceTransportState::kChecking;
}
_gatheringState = internal->gathering_state();
} else {
_state = webrtc::IceTransportState::kClosed;
_gatheringState = webrtc::IceGatheringState::kIceGatheringComplete;
gatheringState = internal->gathering_state();
}

if (pin == Pin::kState && state != _state) {
_surfacedState.Changed(IsBound(), _state);
}
if (pin == Pin::kGatheringState && gatheringState != _gatheringState) {
_surfacedGatheringState.Changed(IsBound(), _gatheringState);
}
_state = state;
_gatheringState = gatheringState;

change.state = _state;
change.gatheringState = _gatheringState;
lock.unlock();

if (pin == Pin::kGatheringState && change.gatheringState != change.previousGatheringState) {
Parking::At("ice.gatheringstatechange");
}
return change;
}

Expand All @@ -179,11 +194,15 @@ namespace python_webrtc {
if (_transport->internal() != nullptr) {
return;
}
if (previous != webrtc::IceTransportState::kClosed) {
_surfacedState.Changed(IsBound(), previous);
}
_state = webrtc::IceTransportState::kClosed;
}
if (previous != webrtc::IceTransportState::kClosed) {
// closed by a description (like the one bundling its media section on another transport), with its event;
// a closed connection mutes its transports first, which are closed right away
Parking::At("ice.closed");
EmitState(previous, webrtc::IceTransportState::kClosed);
}
}
Expand All @@ -193,10 +212,14 @@ namespace python_webrtc {
{
const std::scoped_lock lock(_mutex);
previous = _state;
if (previous != webrtc::IceTransportState::kClosed) {
_surfacedState.Changed(IsBound(), previous);
}
_state = webrtc::IceTransportState::kClosed;
_dropped = true;
}
if (previous != webrtc::IceTransportState::kClosed) {
Parking::At("ice.closed");
EmitState(previous, webrtc::IceTransportState::kClosed);
}
}
Expand All @@ -215,7 +238,7 @@ namespace python_webrtc {
}

void RTCIceTransport::OnStateChanged(webrtc::IceTransportInternal * /*unused*/) {
auto change = TakeSnapshot();
auto change = TakeSnapshot(Pin::kState);
if (change.state == change.previousState) {
return;
}
Expand Down Expand Up @@ -245,12 +268,11 @@ namespace python_webrtc {
}

void RTCIceTransport::OnGatheringStateChanged(webrtc::IceTransportInternal * /*unused*/) {
auto change = TakeSnapshot();
auto change = TakeSnapshot(Pin::kGatheringState);
auto current = change.gatheringState;
if (current == change.previousGatheringState) {
return;
}
_surfacedGatheringState.Changed(IsBound(), change.previousGatheringState);
if (_standalone) {
// a transport of its own completes by itself, its candidates end first (gather() started gathering,
// without an event)
Expand Down Expand Up @@ -321,19 +343,6 @@ namespace python_webrtc {
return _surfacedPair.ShownOr(IsBound(), [this]() { return ReadSelectedCandidatePair(); });
}

void RTCIceTransport::ResolveSignaled(CandidatePair &pair) {
auto &[local, remote, peerReflexive] = pair;
if (!peerReflexive) {
return;
}
webrtc::SdpParseError error;
auto parsed = webrtc::IceCandidate::Create(remote.sdpMid, remote.sdpMLineIndex, remote.candidate, &error);
if (auto signaled = parsed ? FindSignaledCandidate(parsed->candidate()) : std::nullopt) {
remote = *signaled;
peerReflexive = false;
}
}

std::optional<RTCIceTransport::CandidatePair> RTCIceTransport::ReadSelectedCandidatePair() {
std::optional<CandidatePair> result;
BlockingCallOn(_factory->workerThread(), [&]() {
Expand All @@ -354,17 +363,44 @@ namespace python_webrtc {
return result;
}

std::optional<IceCandidateInit> RTCIceTransport::FindSignaledCandidate(const webrtc::Candidate &candidate) {
const std::scoped_lock lock(_mutex);
for (const auto &signaled : _remoteCandidates) {
namespace {

std::optional<IceCandidateInit> findSignaled(const std::vector<IceCandidateInit> &signaled,
const webrtc::Candidate &candidate) {
for (const auto &known : signaled) {
webrtc::SdpParseError error;
auto parsed = webrtc::IceCandidate::Create(known.sdpMid, known.sdpMLineIndex, known.candidate, &error);
if (parsed && parsed->candidate().address().port() == candidate.address().port() &&
parsed->candidate().protocol() == candidate.protocol()) {
return known;
}
}
return std::nullopt;
}

void resolveSignaled(RTCIceTransport::CandidatePair &pair, const std::vector<IceCandidateInit> &signaled) {
auto &[local, remote, peerReflexive] = pair;
if (!peerReflexive) {
return;
}
webrtc::SdpParseError error;
auto parsed = webrtc::IceCandidate::Create(signaled.sdpMid, signaled.sdpMLineIndex, signaled.candidate, &error);
if (parsed && parsed->candidate().address().port() == candidate.address().port() &&
parsed->candidate().protocol() == candidate.protocol()) {
return signaled;
auto parsed = webrtc::IceCandidate::Create(remote.sdpMid, remote.sdpMLineIndex, remote.candidate, &error);
if (auto known = parsed ? findSignaled(signaled, parsed->candidate()) : std::nullopt) {
remote = *known;
peerReflexive = false;
}
}
return std::nullopt;

} // namespace

std::optional<IceCandidateInit> RTCIceTransport::FindSignaledCandidate(const webrtc::Candidate &candidate) {
const std::scoped_lock lock(_mutex);
return findSignaled(_remoteCandidates, candidate);
}

std::vector<IceCandidateInit> RTCIceTransport::SignaledCandidates() {
const std::scoped_lock lock(_mutex);
return _remoteCandidates;
}

namespace {
Expand All @@ -389,13 +425,16 @@ namespace python_webrtc {
}

void RTCIceTransport::AddRemoteCandidate(const IceCandidateInit &candidate) {
std::vector<IceCandidateInit> signaled;
{
const std::scoped_lock lock(_mutex);
addCandidate(_remoteCandidates, candidate);
signaled = _remoteCandidates;
}
_surfacedPair.Update([this](std::optional<CandidatePair> &shown) {
// copied: a Surfaced lock is a leaf
_surfacedPair.Update([&signaled](std::optional<CandidatePair> &shown) {
if (shown) {
ResolveSignaled(*shown);
resolveSignaled(*shown, signaled);
}
});
}
Expand Down Expand Up @@ -593,7 +632,7 @@ namespace python_webrtc {
}

void RTCIceTransport::SurfaceCurrent() {
BlockingCallOn(_factory->workerThread(), [this]() { TakeSnapshot(); });
BlockingCallOn(_factory->workerThread(), [this]() { TakeSnapshot(Pin::kNone); });
const std::scoped_lock lock(_mutex);
_surfacedState.Surface(_state);
_surfacedGatheringState.Surface(_gatheringState);
Expand Down Expand Up @@ -624,16 +663,17 @@ namespace python_webrtc {

void RTCIceTransport::CheckSelectedCandidatePair() {
auto pair = ReadSelectedCandidatePair();
std::optional<CandidatePair> previous;
{
const std::scoped_lock lock(_mutex);
if (keyOf(pair) == keyOf(_selectedPair)) {
return;
}
previous = std::exchange(_selectedPair, pair);
if (pair) {
_surfacedPair.Changed(IsBound(), _selectedPair);
}
_selectedPair = pair;
}
if (pair) {
_surfacedPair.Changed(IsBound(), previous);
Parking::At("ice.pairchanged");
Emit("selectedcandidatepairchange", *pair);
}
Expand All @@ -648,7 +688,7 @@ namespace python_webrtc {

void RTCIceTransport::SurfaceSelectedPair(std::optional<CandidatePair> pair) {
if (pair) {
ResolveSignaled(*pair);
resolveSignaled(*pair, SignaledCandidates());
}
_surfacedPair.Surface(std::move(pair));
}
Expand Down
Loading
Loading