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
35 changes: 29 additions & 6 deletions docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<SignalMessage>)`, 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<SignalMessage>)`, 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<SignalMessage> 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:

Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.*;

Expand Down Expand Up @@ -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<SignalMessage> inbound) {
public synchronized Subscription attach(Consumer<SignalMessage> 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;
}
}
};
}

/**
Expand Down
50 changes: 48 additions & 2 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Subscription> signalingSubscription = new AtomicReference<>();

private static final Subscription DETACHED = () -> { };


PeerImpl(WebRtc rtc, PeerOptions options, String name) {
this.rtc = rtc;
Expand Down Expand Up @@ -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);
}
}
}

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -1891,6 +1910,10 @@ private void finishTeardown(List<RemoteTrackImpl> 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();
}
Expand All @@ -1907,11 +1930,34 @@ private void finishTeardown(List<RemoteTrackImpl> 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) {
Expand Down
77 changes: 59 additions & 18 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* 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<TransportStats> transports;

private final long bytesSent;

Expand All @@ -45,26 +49,29 @@ public final class PeerStats {

private final double packetLoss;

private final double recentPacketLoss;

private final List<VideoStats> outboundVideo;

private final List<VideoStats> inboundVideo;

private final RTCStatsReport report;


PeerStats(Instant timestamp, String candidateType, Duration roundTripTime,
PeerStats(Instant timestamp, TransportStats transport, List<TransportStats> transports,
long bytesSent, long bytesReceived, long outgoingBitrate,
long incomingBitrate, double packetLoss,
long incomingBitrate, double packetLoss, double recentPacketLoss,
List<VideoStats> outboundVideo, List<VideoStats> 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;
Expand All @@ -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<TransportStats> 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;
Expand All @@ -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.
*/
Expand All @@ -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 + "]";
}
}
12 changes: 11 additions & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/client/Signaling.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* 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<SignalMessage> inbound) {
default Subscription attach(Consumer<SignalMessage> inbound) {
return () -> { };
}

/**
Expand Down
Loading
Loading