diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 7f9ca0e35..f8177a423 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -123,7 +123,25 @@ Signaling signaling = message -> socket.send(message.toJson()); socket.onText(text -> peer.signal(SignalMessage.fromJson(text))); ``` -A transport class can implement both directions by overriding `Signaling.attach(Consumer)`, which the peer calls once when it is created, with the consumer to push received messages into. +A transport class can implement both directions by overriding `Signaling.attach(Consumer)`, which the peer calls once when it is created, with the consumer to push received messages into. It returns a `Subscription` that removes that consumer, and only that one: the peer closes it when it closes, after its last `send`, on its event thread. The transport itself stays open, so a WebSocket can outlive the peer and take the next one, or serve several peers at once. A transport that keeps the consumer must drop it there, or the closed peer and the runtime with it stay reachable: + +```java +@Override +public synchronized Subscription attach(Consumer inbound) { + this.inbound = inbound; + + return () -> { + synchronized (this) { + // A peer closed after the next one attached leaves that one in place. + if (this.inbound == inbound) { + this.inbound = null; + } + } + }; +} +``` + +Each end of `Signaling.loopback()` takes one peer at a time; once that peer has closed, the next one can attach, and receives what was sent to the end in between. A `SignalMessage` is a session description (`OFFER`, `ANSWER`) or an ICE candidate (`CANDIDATE`). `toJson()` writes the shapes the browser API uses, so a JavaScript peer can pass them to `setRemoteDescription` and `addIceCandidate` as they are: @@ -792,20 +810,25 @@ peer.onStats(Duration.ofSeconds(1), stats -> System.out.printf( "%s candidate, rtt %s, %d kbit/s out, %d kbit/s in, %.1f%% lost%n", stats.candidateType(), stats.roundTripTime(), stats.outgoingBitrate() / 1000, stats.incomingBitrate() / 1000, - stats.packetLoss() * 100)); + stats.recentPacketLoss() * 100)); ``` | Method | Value | |---|---| -| `candidateType()` | The type of the local candidate in use: `host`, `srflx`, `prflx` or `relay`. Null while not connected. | -| `roundTripTime()` | The current round trip time, or null while not measured. | -| `bytesSent()`, `bytesReceived()` | The bytes sent and received on the connection so far. | +| `transport()` | The transport in use, whose candidate type and round trip time the sample reports. Null while no transport has a candidate pair in use. | +| `transports()` | Every transport of the peer, ordered by id, each with its id, the id of its candidate pair in use, candidate type, round trip time and bytes. | +| `candidateType()` | The type of the local candidate in use on `transport()`: `host`, `srflx`, `prflx` or `relay`. Null while not connected. | +| `roundTripTime()` | The current round trip time on `transport()`, or null while not measured. | +| `bytesSent()`, `bytesReceived()` | The bytes sent and received on all transports so far. | | `timestamp()` | When WebRTC measured the statistics. | | `outgoingBitrate()`, `incomingBitrate()` | Bits per second between the measurement times of the previous sample and this one, or -1 when there is none to compare with: for a peer's first sample, after the clock went back, or after the byte counter started again. A report WebRTC hands out again within its short cache lifetime repeats the previous bitrates. | -| `packetLoss()` | The share of received packets lost so far, 0 to 1. | +| `packetLoss()` | The share of received packets lost so far, 0 to 1. After a long session it barely moves. | +| `recentPacketLoss()` | The share of packets lost of those expected since the previous sample, 0 to 1, and 0 if none were expected; -1 for the first sample and after the clock went back. A stream that came up or whose counters started again counts all it has. | | `outboundVideo()`, `inboundVideo()` | Codec, resolution and frame rate of each video stream, and what limits a sent one. | | `report()` | The whole `RTCStatsReport`. | +A peer bundles its media on one transport by default. When the remote side refuses to bundle, each m-line has a transport of its own. `transport()` is then the one with a candidate pair in use that carried the most bytes, sent and received, and of transports that carried as many, the one with the lowest id. Read `transports()` to watch each connection by itself. + ## Closing You close what you created, and closing an owner closes what it owns: diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/web/client/SignalingManager.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/web/client/SignalingManager.java index 892d98d00..82b76a3ca 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/web/client/SignalingManager.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/web/client/SignalingManager.java @@ -27,6 +27,7 @@ import dev.onvoid.webrtc.RTCSessionDescription; import dev.onvoid.webrtc.client.SignalMessage; import dev.onvoid.webrtc.client.Signaling; +import dev.onvoid.webrtc.client.Subscription; import dev.onvoid.webrtc.examples.web.model.*; @@ -158,10 +159,22 @@ public void send(SignalMessage message) { * the peer created last, which replaces the one before. * * @param inbound Takes the messages the browser sends. + * + * @return Lets go of the peer when it closes. The connection to the signaling + * server stays open for the next peer. */ @Override - public void attach(Consumer inbound) { + public synchronized Subscription attach(Consumer inbound) { this.inbound = inbound; + + return () -> { + synchronized (this) { + // A peer closed after its successor attached leaves that one in place. + if (this.inbound == inbound) { + this.inbound = null; + } + } + }; } /** diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index df16b7a72..88442b1f3 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -214,6 +214,14 @@ final class PeerImpl implements Peer { /** Runs once gathering is complete, or null. Called on the control executor. */ private volatile Runnable gatheredListener; + /** + * What {@link Signaling#attach} returned, or null before, and {@link + * #DETACHED} once the peer has let go of the signaling on close. + */ + private final AtomicReference signalingSubscription = new AtomicReference<>(); + + private static final Subscription DETACHED = () -> { }; + PeerImpl(WebRtc rtc, PeerOptions options, String name) { this.rtc = rtc; @@ -299,8 +307,14 @@ void open() { throw new ConfigurationException("Creating " + name + " failed: " + cause.getMessage(), cause); } - if (signaling != null) { - signaling.attach(this::signal); + if (signaling != null && !closing.get()) { + Subscription subscription = signaling.attach(this::signal); + + if (subscription != null && !signalingSubscription.compareAndSet(null, subscription)) { + // Closed while attaching: the close found nothing to let go of + // yet, so this lets go of what attach returned. + detach(subscription); + } } } @@ -1568,6 +1582,11 @@ private void send(SignalMessage message) { } events.execute(() -> { + if (signalingSubscription.get() == DETACHED) { + // The transport may take another peer by now. + return; + } + try { signaling.send(message); } @@ -1891,6 +1910,10 @@ private void finishTeardown(List ended, PeerClosedException err closedInternal.complete(null); events.execute(() -> { + // Behind the messages queued for sending, so that the transport + // hears of none once it was let go of. + detachSignaling(); + for (RemoteTrackImpl remote : ended) { remote.fireEnded(); } @@ -1907,11 +1930,34 @@ private void finishTeardown(List ended, PeerClosedException err stateHandlers.clear(); errorHandlers.clear(); }, () -> { + detachSignaling(); + connected.completeExceptionally(error); closedFuture.complete(null); }); } + /** + * Lets go of the signaling, once: a transport that outlives the peer must + * not keep it, and the runtime with it, reachable. + */ + private void detachSignaling() { + Subscription subscription = signalingSubscription.getAndSet(DETACHED); + + if (subscription != null && subscription != DETACHED) { + detach(subscription); + } + } + + private void detach(Subscription subscription) { + try { + subscription.close(); + } + catch (Throwable e) { + rtc.reportError(new WebRtcException("Detaching " + name + " from its signaling failed", e)); + } + } + // On the event executor. private void deliverState(PeerState newState) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java index 13859f5e8..755bca417 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java @@ -24,16 +24,20 @@ /** * The statistics people look for first, taken from an {@link RTCStatsReport}. - * Bitrates are computed between the measurement times of two samples, so the - * first sample a peer takes has none. + * Bitrates and the recent packet loss are computed between the measurement + * times of two samples, so the first sample a peer takes has none. + *

+ * Bytes and bitrates count all transports of the peer. The candidate type and + * the round trip time are those of one of them, the {@link #transport() + * connection in use}; {@link #transports()} has each one's. */ public final class PeerStats { private final Instant timestamp; - private final String candidateType; + private final TransportStats transport; - private final Duration roundTripTime; + private final List transports; private final long bytesSent; @@ -45,6 +49,8 @@ public final class PeerStats { private final double packetLoss; + private final double recentPacketLoss; + private final List outboundVideo; private final List inboundVideo; @@ -52,19 +58,20 @@ public final class PeerStats { private final RTCStatsReport report; - PeerStats(Instant timestamp, String candidateType, Duration roundTripTime, + PeerStats(Instant timestamp, TransportStats transport, List transports, long bytesSent, long bytesReceived, long outgoingBitrate, - long incomingBitrate, double packetLoss, + long incomingBitrate, double packetLoss, double recentPacketLoss, List outboundVideo, List inboundVideo, RTCStatsReport report) { this.timestamp = timestamp; - this.candidateType = candidateType; - this.roundTripTime = roundTripTime; + this.transport = transport; + this.transports = transports; this.bytesSent = bytesSent; this.bytesReceived = bytesReceived; this.outgoingBitrate = outgoingBitrate; this.incomingBitrate = incomingBitrate; this.packetLoss = packetLoss; + this.recentPacketLoss = recentPacketLoss; this.outboundVideo = outboundVideo; this.inboundVideo = inboundVideo; this.report = report; @@ -79,29 +86,50 @@ public Instant timestamp() { } /** - * @return the type of the local candidate in use: {@code host}, {@code - * srflx}, {@code prflx} or {@code relay}. Null while not connected. + * The transport whose candidate type and round trip time this sample + * reports. It is the only one that has a candidate pair in use, as with + * bundled media. Of several, it is the one that carried the most bytes, + * sent and received, and of those the one with the lowest id. + * + * @return the transport, or null while none has a candidate pair in use. + */ + public TransportStats transport() { + return transport; + } + + /** + * @return every transport of the peer, ordered by id. + */ + public List transports() { + return transports; + } + + /** + * @return the type of the local candidate in use on the {@link + * #transport()} transport: {@code host}, {@code srflx}, {@code prflx} or + * {@code relay}. Null while not connected. */ public String candidateType() { - return candidateType; + return transport == null ? null : transport.candidateType(); } /** - * @return the current round trip time, or null while not measured. + * @return the current round trip time on the {@link #transport()} + * transport, or null while not measured. */ public Duration roundTripTime() { - return roundTripTime; + return transport == null ? null : transport.roundTripTime(); } /** - * @return the bytes sent on the connection so far. + * @return the bytes sent on all transports so far. */ public long bytesSent() { return bytesSent; } /** - * @return the bytes received on the connection so far. + * @return the bytes received on all transports so far. */ public long bytesReceived() { return bytesReceived; @@ -126,12 +154,24 @@ public long incomingBitrate() { } /** - * @return the share of received packets lost so far, 0 to 1. + * @return the share of received packets lost so far, 0 to 1. After a long + * session it barely moves; {@link #recentPacketLoss()} shows what happens + * now. */ public double packetLoss() { return packetLoss; } + /** + * @return the share of the packets lost of those expected since the + * previous sample, 0 to 1, and 0 if none were expected. -1 when there is + * no sample to compare with: for the first one, or after the clock went + * back. A stream whose counters started again counts from zero. + */ + public double recentPacketLoss() { + return recentPacketLoss; + } + /** * @return the video streams sent. */ @@ -155,10 +195,11 @@ public RTCStatsReport report() { @Override public String toString() { - return "PeerStats[candidate=" + candidateType + ", rtt=" + roundTripTime + return "PeerStats[candidate=" + candidateType() + ", rtt=" + roundTripTime() + ", sent=" + bytesSent + " B, received=" + bytesReceived + " B, out=" + outgoingBitrate + " bps, in=" + incomingBitrate - + " bps, loss=" + packetLoss + ", outboundVideo=" + outboundVideo + + " bps, loss=" + packetLoss + ", recentLoss=" + recentPacketLoss + + ", transports=" + transports + ", outboundVideo=" + outboundVideo + ", inboundVideo=" + inboundVideo + "]"; } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Signaling.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Signaling.java index 92a6e54da..8abcde70f 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Signaling.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Signaling.java @@ -46,10 +46,20 @@ public interface Signaling { * Called once, when the peer is created. A transport that receives * messages may push them into {@code inbound} instead of calling {@link * Peer#signal(SignalMessage)}. Does nothing by default. + *

+ * The peer closes the returned subscription when it closes, after its last + * call of {@link #send(SignalMessage)}, on its event thread. Closing it + * removes this {@code inbound} and nothing else: the transport stays open, + * so it may outlive the peer and take the next one, or serve several peers + * at once. A transport that keeps {@code inbound} must let go of it there, + * or it keeps the closed peer, and the runtime with it, reachable. * * @param inbound takes the messages the remote peer sent, from any thread. + * + * @return removes {@code inbound} from the transport. */ - default void attach(Consumer inbound) { + default Subscription attach(Consumer inbound) { + return () -> { }; } /** diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingPair.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingPair.java index 51116f681..e3636b102 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingPair.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/SignalingPair.java @@ -16,6 +16,8 @@ package dev.onvoid.webrtc.client; +import static java.util.Objects.requireNonNull; + import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -23,7 +25,9 @@ /** * Two linked {@link Signaling} ends, made by {@link Signaling#loopback()}. * Messages sent through one end reach the peer attached to the other end, in - * order. Messages sent before that peer exists are held until it attaches. + * order. Messages sent while no peer is attached there, before the first one + * or after it closed, are held until the next one attaches. An end takes one + * peer at a time. */ public final class SignalingPair { @@ -68,7 +72,9 @@ public void send(SignalMessage message) { } @Override - public synchronized void attach(Consumer inbound) { + public synchronized Subscription attach(Consumer inbound) { + requireNonNull(inbound, "inbound"); + if (this.inbound != null) { throw new IllegalStateException("This end of the loopback is already attached to a peer"); } @@ -79,6 +85,16 @@ public synchronized void attach(Consumer inbound) { // A peer's inbound only queues the message. held.forEach(inbound); held.clear(); + + return () -> detach(inbound); + } + + private synchronized void detach(Consumer inbound) { + // Only the registration it was made for: closed again once the + // next peer has attached, it leaves that one alone. + if (this.inbound == inbound) { + this.inbound = null; + } } private synchronized void deliver(SignalMessage message) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsReader.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsReader.java index aef8e4966..6477b1fa4 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsReader.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/StatsReader.java @@ -21,6 +21,8 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -30,9 +32,9 @@ /** * Takes {@link PeerStats} from the reports of one peer. It keeps the previous - * sample to compute bitrates over the time between the two measurements, not - * between their arrival here, which a busy control executor may delay. Used on - * the peer's control executor. + * sample to compute bitrates and the recent packet loss over the time between + * the two measurements, not between their arrival here, which a busy control + * executor may delay. Used on the peer's control executor. */ final class StatsReader { @@ -42,20 +44,25 @@ final class StatsReader { private long lastBytesReceived; + /** The packets received and lost of each inbound stream, by id. */ + private Map lastStreams = Collections.emptyMap(); + private long lastOutgoingBitrate = -1; private long lastIncomingBitrate = -1; + private double lastRecentPacketLoss = -1; + PeerStats read(RTCStatsReport report) { Map stats = report.getStats(); long bytesSent = 0; long bytesReceived = 0; - String candidateType = null; - Duration roundTripTime = null; long packetsReceived = 0; long packetsLost = 0; + List transports = new ArrayList<>(); + Map streams = new HashMap<>(); List outbound = new ArrayList<>(); List inbound = new ArrayList<>(); @@ -63,28 +70,20 @@ PeerStats read(RTCStatsReport report) { Map values = entry.getAttributes(); if (entry.getType() == RTCStatsType.TRANSPORT) { - bytesSent += longValue(values.get("bytesSent")); - bytesReceived += longValue(values.get("bytesReceived")); - - RTCStats pair = lookup(stats, values.get("selectedCandidatePairId")); + TransportStats transport = transport(stats, entry); - if (pair != null) { - Object rtt = pair.getAttributes().get("currentRoundTripTime"); - - if (rtt instanceof Number) { - roundTripTime = Duration.ofNanos((long) (((Number) rtt).doubleValue() * 1e9)); - } - - RTCStats local = lookup(stats, pair.getAttributes().get("localCandidateId")); - - if (local != null) { - candidateType = string(local.getAttributes().get("candidateType")); - } - } + bytesSent += transport.bytesSent(); + bytesReceived += transport.bytesReceived(); + transports.add(transport); } else if (entry.getType() == RTCStatsType.INBOUND_RTP) { - packetsReceived += longValue(values.get("packetsReceived")); - packetsLost += Math.max(0, longValue(values.get("packetsLost"))); + long received = longValue(values.get("packetsReceived")); + // Negative when more arrived than were expected, as duplicates do. + long lost = Math.max(0, longValue(values.get("packetsLost"))); + + packetsReceived += received; + packetsLost += lost; + streams.put(entry.getId(), new long[] { received, lost }); if ("video".equals(values.get("kind"))) { inbound.add(video(stats, values, string(values.get("trackIdentifier")), null)); @@ -100,16 +99,23 @@ else if (entry.getType() == RTCStatsType.OUTBOUND_RTP) { } } + // The report is a map without order: sorted, the same report gives the + // same result. + transports.sort(Comparator.comparing(TransportStats::id, + Comparator.nullsFirst(Comparator.naturalOrder()))); + long micros = report.getTimestamp(); long outgoingBitrate = -1; long incomingBitrate = -1; + double recentPacketLoss = -1; if (lastMicros >= 0 && micros == lastMicros) { // WebRTC hands out a report again for a short while: the same - // measurement, with the same bitrates, measured from the same + // measurement, with the same values, measured from the same // sample. outgoingBitrate = lastOutgoingBitrate; incomingBitrate = lastIncomingBitrate; + recentPacketLoss = lastRecentPacketLoss; } else { // A clock that went back leaves no interval to measure, and the @@ -119,21 +125,107 @@ else if (entry.getType() == RTCStatsType.OUTBOUND_RTP) { outgoingBitrate = bitrate(bytesSent, lastBytesSent, seconds); incomingBitrate = bitrate(bytesReceived, lastBytesReceived, seconds); + recentPacketLoss = recentPacketLoss(streams); } lastMicros = micros; lastBytesSent = bytesSent; lastBytesReceived = bytesReceived; + lastStreams = streams; lastOutgoingBitrate = outgoingBitrate; lastIncomingBitrate = incomingBitrate; + lastRecentPacketLoss = recentPacketLoss; + } + + return new PeerStats(Instant.EPOCH.plus(micros, ChronoUnit.MICROS), inUse(transports), + Collections.unmodifiableList(transports), bytesSent, bytesReceived, + outgoingBitrate, incomingBitrate, lossRate(packetsLost, packetsReceived), + recentPacketLoss, Collections.unmodifiableList(outbound), + Collections.unmodifiableList(inbound), report); + } + + private static TransportStats transport(Map stats, RTCStats entry) { + Map values = entry.getAttributes(); + String pairId = string(values.get("selectedCandidatePairId")); + RTCStats pair = lookup(stats, pairId); + String candidateType = null; + Duration roundTripTime = null; + + if (pair != null) { + Object rtt = pair.getAttributes().get("currentRoundTripTime"); + + if (rtt instanceof Number) { + roundTripTime = Duration.ofNanos((long) (((Number) rtt).doubleValue() * 1e9)); + } + + RTCStats local = lookup(stats, pair.getAttributes().get("localCandidateId")); + + if (local != null) { + candidateType = string(local.getAttributes().get("candidateType")); + } + } + + return new TransportStats(entry.getId(), pairId, candidateType, roundTripTime, + longValue(values.get("bytesSent")), longValue(values.get("bytesReceived"))); + } + + /** + * @param transports ordered by id. + * + * @return the transport with a candidate pair in use that carried the most + * bytes, the first of those that carried as many, or null. + */ + private static TransportStats inUse(List transports) { + TransportStats inUse = null; + + for (TransportStats transport : transports) { + if (transport.selectedCandidatePairId() != null && (inUse == null + || bytes(transport) > bytes(inUse))) { + inUse = transport; + } } - long packetsExpected = packetsReceived + packetsLost; - double packetLoss = packetsExpected == 0 ? 0 : (double) packetsLost / packetsExpected; + return inUse; + } + + private static long bytes(TransportStats transport) { + return transport.bytesSent() + transport.bytesReceived(); + } + + /** + * @param streams the packets received and lost of each inbound stream now. + * + * @return the share of packets lost of those expected since the last + * sample. + */ + private double recentPacketLoss(Map streams) { + long received = 0; + long lost = 0; + + for (Map.Entry stream : streams.entrySet()) { + long[] now = stream.getValue(); + long[] before = lastStreams.get(stream.getKey()); + + if (before == null || now[0] < before[0]) { + // Came up since, or its counters started again: all it + // counted is new. + received += now[0]; + lost += now[1]; + } + else { + received += now[0] - before[0]; + // Fewer lost than before when late packets filled a gap. + lost += Math.max(0, now[1] - before[1]); + } + } + + return lossRate(lost, received); + } + + private static double lossRate(long lost, long received) { + long expected = received + lost; - return new PeerStats(Instant.EPOCH.plus(micros, ChronoUnit.MICROS), candidateType, roundTripTime, bytesSent, bytesReceived, - outgoingBitrate, incomingBitrate, packetLoss, - Collections.unmodifiableList(outbound), Collections.unmodifiableList(inbound), report); + return expected == 0 ? 0 : (double) lost / expected; } private static long bitrate(long bytes, long lastBytes, double seconds) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/TransportStats.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/TransportStats.java new file mode 100644 index 000000000..766069be9 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/TransportStats.java @@ -0,0 +1,101 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import java.time.Duration; + +/** + * The statistics of one transport of a peer, one ICE and DTLS connection. A + * peer that bundles its media, as it does by default, has one. One that does + * not, because the remote side refused to bundle, has one for each m-line. + */ +public final class TransportStats { + + private final String id; + + private final String selectedCandidatePairId; + + private final String candidateType; + + private final Duration roundTripTime; + + private final long bytesSent; + + private final long bytesReceived; + + + TransportStats(String id, String selectedCandidatePairId, String candidateType, + Duration roundTripTime, long bytesSent, long bytesReceived) { + this.id = id; + this.selectedCandidatePairId = selectedCandidatePairId; + this.candidateType = candidateType; + this.roundTripTime = roundTripTime; + this.bytesSent = bytesSent; + this.bytesReceived = bytesReceived; + } + + /** + * @return the id of the transport's entry in the report. + */ + public String id() { + return id; + } + + /** + * @return the id of the candidate pair in use, its entry in the report, or + * null while there is none. + */ + public String selectedCandidatePairId() { + return selectedCandidatePairId; + } + + /** + * @return the type of the local candidate in use: {@code host}, {@code + * srflx}, {@code prflx} or {@code relay}. Null while not connected. + */ + public String candidateType() { + return candidateType; + } + + /** + * @return the current round trip time of the candidate pair in use, or + * null while not measured. + */ + public Duration roundTripTime() { + return roundTripTime; + } + + /** + * @return the bytes sent on this transport so far. + */ + public long bytesSent() { + return bytesSent; + } + + /** + * @return the bytes received on this transport so far. + */ + public long bytesReceived() { + return bytesReceived; + } + + @Override + public String toString() { + return "TransportStats[" + id + ", candidate=" + candidateType + ", rtt=" + roundTripTime + + ", sent=" + bytesSent + " B, received=" + bytesReceived + " B]"; + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HeldSignaling.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HeldSignaling.java index 2b14ac37a..e08bb615a 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HeldSignaling.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HeldSignaling.java @@ -103,10 +103,13 @@ public void send(SignalMessage message) { } @Override - public void attach(Consumer inbound) { + public Subscription attach(Consumer inbound) { synchronized (HeldSignaling.this) { this.inbound = inbound; } + + // Kept for the test's lifetime, as is the peer. + return () -> { }; } /** Delivers what this end sent to the other end's peer. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java index 6787660fa..ad69f107c 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java @@ -48,6 +48,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; import dev.onvoid.webrtc.RTCSessionDescription; @@ -745,6 +746,78 @@ void failedAttachClosesPeer() { assertEquals(1, rtc.peers().size()); } + @Test + void closeDetachesSignaling() throws Exception { + List> attached = new CopyOnWriteArrayList<>(); + AtomicInteger detached = new AtomicInteger(); + Signaling transport = new Signaling() { + + @Override + public void send(SignalMessage message) { + } + + @Override + public Subscription attach(Consumer inbound) { + attached.add(inbound); + return detached::incrementAndGet; + } + }; + + Peer peer = rtc.createPeer(PeerOptions.builder().signaling(transport).build()); + + assertEquals(1, attached.size()); + assertEquals(0, detached.get()); + + // Once, by the time the close completes. + await(peer.closeAsync()); + await(peer.closeAsync()); + assertEquals(1, detached.get()); + } + + @Test + void closeWhileAttaching() throws Exception { + // The peer has closed, and found nothing to let go of, before attach + // returns. The subscription it then gets is closed all the same. + AtomicInteger detached = new AtomicInteger(); + Signaling transport = new Signaling() { + + @Override + public void send(SignalMessage message) { + } + + @Override + public Subscription attach(Consumer inbound) { + rtc.peers().forEach(peer -> peer.closeAsync().join()); + return detached::incrementAndGet; + } + }; + + Peer peer = rtc.createPeer(PeerOptions.builder().signaling(transport).build()); + + assertEquals(PeerState.CLOSED, peer.state()); + assertEquals(1, detached.get()); + } + + @Test + void signalingOutlivesPeer() throws Exception { + // A closed peer frees its end of the loopback for the next one, which + // connects through it. + SignalingPair link = Signaling.loopback(); + await(rtc.createPeer(PeerOptions.builder().signaling(link.first()).build()).closeAsync()); + + Peer caller = rtc.createPeer(PeerOptions.builder().signaling(link.first()).build()); + Peer callee = rtc.createPeer(PeerOptions.builder().signaling(link.second()).polite(true).build()); + CompletableFuture reply = new CompletableFuture<>(); + + callee.onChannel(channel -> channel.onMessage(message -> channel.send("pong:" + message.text()))); + + DataChannel channel = caller.createChannel("chat"); + channel.onMessage(message -> reply.complete(message.text())); + channel.send("ping"); + + assertEquals("pong:ping", await(reply)); + } + @Test void operationAfterRuntimeCloseFails() throws Exception { // The runtime's threads are gone, so the task that would fail the diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/SignalingPairTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/SignalingPairTests.java new file mode 100644 index 000000000..d193d5bf9 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/SignalingPairTests.java @@ -0,0 +1,80 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import dev.onvoid.webrtc.RTCSdpType; +import dev.onvoid.webrtc.RTCSessionDescription; + +import org.junit.jupiter.api.Test; + +class SignalingPairTests { + + private static final SignalMessage OFFER = + SignalMessage.of(new RTCSessionDescription(RTCSdpType.OFFER, "v=0\r\n")); + + private static final SignalMessage END = SignalMessage.endOfCandidates(); + + private final SignalingPair link = Signaling.loopback(); + + + @Test + void detachedEndHoldsForNextPeer() { + List closed = new ArrayList<>(); + List next = new ArrayList<>(); + + Subscription subscription = link.first().attach(closed::add); + link.second().send(OFFER); + subscription.close(); + link.second().send(END); + link.first().attach(next::add); + + assertEquals(Collections.singletonList(OFFER), closed); + assertEquals(Collections.singletonList(END), next); + } + + @Test + void staleCloseKeepsNextPeer() { + List next = new ArrayList<>(); + + Subscription stale = link.first().attach(message -> { }); + stale.close(); + link.first().attach(next::add); + + // Closed again, the first registration leaves the second in place. + stale.close(); + link.second().send(OFFER); + link.second().send(END); + + assertEquals(Arrays.asList(OFFER, END), next); + } + + @Test + void oneAttachedPeerAtATime() { + link.first().attach(message -> { }); + + assertThrows(IllegalStateException.class, () -> link.first().attach(message -> { })); + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/StatsReaderTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/StatsReaderTests.java index f6f62f8cf..ad20a2767 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/StatsReaderTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/StatsReaderTests.java @@ -17,10 +17,15 @@ package dev.onvoid.webrtc.client; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import java.time.Duration; import java.time.Instant; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; import dev.onvoid.webrtc.RTCStats; import dev.onvoid.webrtc.RTCStatsReport; @@ -106,6 +111,134 @@ void counterStartedAgain() { assertEquals(0, next.incomingBitrate()); } + @Test + void eachTransport() { + // Unbundled: a transport for each m-line. T03 carried the most, but + // has no candidate pair in use. + Map stats = new HashMap<>(); + transport(stats, "T02", 4_000, 1_000, "CP02", "relay", 0.2); + transport(stats, "T01", 1_000, 500, "CP01", "host", 0.05); + transport(stats, "T03", 9_000, 9_000, null, null, 0); + + PeerStats sample = reader.read(new RTCStatsReport(stats, START) { }); + + assertEquals(Arrays.asList("T01", "T02", "T03"), + sample.transports().stream().map(TransportStats::id).collect(Collectors.toList())); + assertEquals("host", sample.transports().get(0).candidateType()); + assertEquals(Duration.ofMillis(50), sample.transports().get(0).roundTripTime()); + assertNull(sample.transports().get(2).selectedCandidatePairId()); + + assertSame(sample.transports().get(1), sample.transport()); + assertEquals("relay", sample.candidateType()); + assertEquals(Duration.ofMillis(200), sample.roundTripTime()); + assertEquals(14_000, sample.bytesSent()); + assertEquals(10_500, sample.bytesReceived()); + } + + @Test + void equalTransportsTakeLowestId() { + Map stats = new HashMap<>(); + transport(stats, "T02", 1_000, 0, "CP02", "srflx", 0.1); + transport(stats, "T01", 0, 1_000, "CP01", "host", 0.1); + + assertEquals("T01", reader.read(new RTCStatsReport(stats, START) { }).transport().id()); + } + + @Test + void noPairInUse() { + PeerStats sample = reader.read(report(START, 1_000, 1_000)); + + assertNull(sample.transport()); + assertNull(sample.candidateType()); + assertNull(sample.roundTripTime()); + assertEquals(1, sample.transports().size()); + } + + @Test + void recentPacketLoss() { + PeerStats first = reader.read(inbound(START, 1_000, 0)); + PeerStats lossy = reader.read(inbound(START + SECOND, 1_900, 100)); + PeerStats repeated = reader.read(inbound(START + SECOND, 1_900, 100)); + PeerStats clean = reader.read(inbound(START + 2 * SECOND, 2_900, 100)); + PeerStats idle = reader.read(inbound(START + 3 * SECOND, 2_900, 100)); + + assertEquals(-1, first.recentPacketLoss()); + // 100 of the 1000 expected since the first sample. + assertEquals(0.1, lossy.recentPacketLoss(), 1e-9); + assertEquals(0.05, lossy.packetLoss(), 1e-9); + assertEquals(0.1, repeated.recentPacketLoss(), 1e-9); + assertEquals(0, clean.recentPacketLoss()); + assertEquals(0, idle.recentPacketLoss()); + } + + @Test + void recentLossOfNewAndRestartedStreams() { + Map before = new HashMap<>(); + stream(before, START, "IA", 10_000, 0); + stream(before, START, "IB", 10_000, 0); + reader.read(new RTCStatsReport(before, START) { }); + + // IA started again, IC came up: what they count is all new. IB lost + // none of its 800 since: 30 lost of 1000 expected. + Map after = new HashMap<>(); + long micros = START + SECOND; + stream(after, micros, "IA", 90, 10); + stream(after, micros, "IB", 10_800, 0); + stream(after, micros, "IC", 80, 20); + PeerStats sample = reader.read(new RTCStatsReport(after, micros) { }); + + assertEquals(30 / 1_000.0, sample.recentPacketLoss(), 1e-9); + } + + @Test + void clockWentBackLeavesNoRecentLoss() { + reader.read(inbound(START, 1_000, 0)); + PeerStats back = reader.read(inbound(START - SECOND, 1_500, 0)); + PeerStats next = reader.read(inbound(START, 1_900, 100)); + + assertEquals(-1, back.recentPacketLoss()); + assertEquals(0.2, next.recentPacketLoss(), 1e-9); + } + + private static RTCStatsReport inbound(long micros, long packetsReceived, long packetsLost) { + Map stats = new HashMap<>(); + stream(stats, micros, "IT01", packetsReceived, packetsLost); + + return new RTCStatsReport(stats, micros) { }; + } + + private static void stream(Map stats, long micros, String id, + long packetsReceived, long packetsLost) { + Map values = new HashMap<>(); + values.put("kind", "audio"); + values.put("packetsReceived", packetsReceived); + values.put("packetsLost", packetsLost); + + stats.put(id, new RTCStats(micros, RTCStatsType.INBOUND_RTP, id, values) { }); + } + + private static void transport(Map stats, String id, long bytesSent, + long bytesReceived, String pairId, String candidateType, double rttSeconds) { + Map values = new HashMap<>(); + values.put("bytesSent", bytesSent); + values.put("bytesReceived", bytesReceived); + + if (pairId != null) { + values.put("selectedCandidatePairId", pairId); + + Map pair = new HashMap<>(); + pair.put("currentRoundTripTime", rttSeconds); + pair.put("localCandidateId", "L" + id); + stats.put(pairId, new RTCStats(START, RTCStatsType.CANDIDATE_PAIR, pairId, pair) { }); + + Map local = new HashMap<>(); + local.put("candidateType", candidateType); + stats.put("L" + id, new RTCStats(START, RTCStatsType.LOCAL_CANDIDATE, "L" + id, local) { }); + } + + stats.put(id, new RTCStats(START, RTCStatsType.TRANSPORT, id, values) { }); + } + private static RTCStatsReport report(long micros, long bytesSent, long bytesReceived) { Map values = new HashMap<>(); values.put("bytesSent", bytesSent);