Skip to content

Commit 23abb38

Browse files
committed
fix: compute bitrates over report times, report stats handler errors
Bitrates used the time a report was read rather than measured, so reports delayed on a busy control executor gave rates far too high. They now use the report timestamp, repeat the bitrates of a cached report, and give -1 after the clock went back or a counter started again. PeerStats.timestamp() is the report time. A throwing onStats handler now reaches the error handler.
1 parent a506122 commit 23abb38

6 files changed

Lines changed: 220 additions & 21 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,8 @@ peer.onStats(Duration.ofSeconds(1), stats -> System.out.printf(
655655
| `candidateType()` | The type of the local candidate in use: `host`, `srflx`, `prflx` or `relay`. Null while not connected. |
656656
| `roundTripTime()` | The current round trip time, or null while not measured. |
657657
| `bytesSent()`, `bytesReceived()` | The bytes sent and received on the connection so far. |
658-
| `outgoingBitrate()`, `incomingBitrate()` | Bits per second since the previous sample, or -1 for a peer's first sample. |
658+
| `timestamp()` | When WebRTC measured the statistics. |
659+
| `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. |
659660
| `packetLoss()` | The share of received packets lost so far, 0 to 1. |
660661
| `outboundVideo()`, `inboundVideo()` | Codec, resolution and frame rate of each video stream, and what limits a sent one. |
661662
| `report()` | The whole `RTCStatsReport`. |

‎webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ public Subscription onStats(Duration interval, Consumer<PeerStats> handler) {
481481
return;
482482
}
483483
if (error == null) {
484-
handler.accept(stats);
484+
call(handler, stats);
485485
}
486486
else if (!(unwrap(error) instanceof PeerClosedException)) {
487487
deliverError(asWebRtcException(error, "Reading the statistics failed"));

‎webrtc/src/main/java/dev/onvoid/webrtc/client/PeerStats.java‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@
2424

2525
/**
2626
* The statistics people look for first, taken from an {@link RTCStatsReport}.
27-
* Bitrates are computed between two samples, so the first sample a peer takes
28-
* has none.
27+
* Bitrates are computed between the measurement times of two samples, so the
28+
* first sample a peer takes has none.
2929
*/
3030
public final class PeerStats {
3131

@@ -71,7 +71,8 @@ public final class PeerStats {
7171
}
7272

7373
/**
74-
* @return when the statistics were taken.
74+
* @return when WebRTC measured the statistics, the timestamp of the
75+
* report.
7576
*/
7677
public Instant timestamp() {
7778
return timestamp;
@@ -107,16 +108,18 @@ public long bytesReceived() {
107108
}
108109

109110
/**
110-
* @return the bits sent per second since the previous sample, or -1 for
111-
* the first sample.
111+
* @return the bits sent per second since the previous sample, or -1 when
112+
* there is none to compare with: for the first sample, after the clock
113+
* went back, or after the byte counter started again.
112114
*/
113115
public long outgoingBitrate() {
114116
return outgoingBitrate;
115117
}
116118

117119
/**
118120
* @return the bits received per second since the previous sample, or -1
119-
* for the first sample.
121+
* when there is none to compare with: for the first sample, after the
122+
* clock went back, or after the byte counter started again.
120123
*/
121124
public long incomingBitrate() {
122125
return incomingBitrate;

‎webrtc/src/main/java/dev/onvoid/webrtc/client/StatsReader.java‎

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import java.time.Duration;
2020
import java.time.Instant;
21+
import java.time.temporal.ChronoUnit;
2122
import java.util.ArrayList;
2223
import java.util.Collections;
2324
import java.util.List;
@@ -29,16 +30,22 @@
2930

3031
/**
3132
* Takes {@link PeerStats} from the reports of one peer. It keeps the previous
32-
* sample to compute bitrates. Used on the peer's control executor.
33+
* sample to compute bitrates over the time between the two measurements, not
34+
* between their arrival here, which a busy control executor may delay. Used on
35+
* the peer's control executor.
3336
*/
3437
final class StatsReader {
3538

36-
private long lastNanos = -1;
39+
private long lastMicros = -1;
3740

3841
private long lastBytesSent;
3942

4043
private long lastBytesReceived;
4144

45+
private long lastOutgoingBitrate = -1;
46+
47+
private long lastIncomingBitrate = -1;
48+
4249

4350
PeerStats read(RTCStatsReport report) {
4451
Map<String, RTCStats> stats = report.getStats();
@@ -93,29 +100,49 @@ else if (entry.getType() == RTCStatsType.OUTBOUND_RTP) {
93100
}
94101
}
95102

96-
long now = System.nanoTime();
103+
long micros = report.getTimestamp();
97104
long outgoingBitrate = -1;
98105
long incomingBitrate = -1;
99106

100-
if (lastNanos >= 0 && now > lastNanos) {
101-
double seconds = (now - lastNanos) / 1e9;
102-
103-
outgoingBitrate = (long) (Math.max(0, bytesSent - lastBytesSent) * 8 / seconds);
104-
incomingBitrate = (long) (Math.max(0, bytesReceived - lastBytesReceived) * 8 / seconds);
107+
if (lastMicros >= 0 && micros == lastMicros) {
108+
// WebRTC hands out a report again for a short while: the same
109+
// measurement, with the same bitrates, measured from the same
110+
// sample.
111+
outgoingBitrate = lastOutgoingBitrate;
112+
incomingBitrate = lastIncomingBitrate;
105113
}
114+
else {
115+
// A clock that went back leaves no interval to measure, and the
116+
// next sample is measured from this one.
117+
if (lastMicros >= 0 && micros > lastMicros) {
118+
double seconds = (micros - lastMicros) / 1e6;
119+
120+
outgoingBitrate = bitrate(bytesSent, lastBytesSent, seconds);
121+
incomingBitrate = bitrate(bytesReceived, lastBytesReceived, seconds);
122+
}
106123

107-
lastNanos = now;
108-
lastBytesSent = bytesSent;
109-
lastBytesReceived = bytesReceived;
124+
lastMicros = micros;
125+
lastBytesSent = bytesSent;
126+
lastBytesReceived = bytesReceived;
127+
lastOutgoingBitrate = outgoingBitrate;
128+
lastIncomingBitrate = incomingBitrate;
129+
}
110130

111131
long packetsExpected = packetsReceived + packetsLost;
112132
double packetLoss = packetsExpected == 0 ? 0 : (double) packetsLost / packetsExpected;
113133

114-
return new PeerStats(Instant.now(), candidateType, roundTripTime, bytesSent, bytesReceived,
134+
return new PeerStats(Instant.EPOCH.plus(micros, ChronoUnit.MICROS), candidateType, roundTripTime, bytesSent, bytesReceived,
115135
outgoingBitrate, incomingBitrate, packetLoss,
116136
Collections.unmodifiableList(outbound), Collections.unmodifiableList(inbound), report);
117137
}
118138

139+
private static long bitrate(long bytes, long lastBytes, double seconds) {
140+
// Fewer bytes than before: the counter started again, such as on a
141+
// transport that replaced another, and what was sent meanwhile is
142+
// unknown.
143+
return bytes < lastBytes ? -1 : (long) ((bytes - lastBytes) * 8 / seconds);
144+
}
145+
119146
private static VideoStats video(Map<String, RTCStats> stats, Map<String, Object> values,
120147
String trackId, String qualityLimitation) {
121148
RTCStats codec = lookup(stats, values.get("codecId"));

‎webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
import static org.junit.jupiter.api.Assertions.assertTrue;
2525

2626
import java.time.Duration;
27+
import java.time.Instant;
28+
import java.time.temporal.ChronoUnit;
2729
import java.util.ArrayList;
2830
import java.util.Arrays;
2931
import java.util.Collections;
@@ -551,8 +553,54 @@ void statsAfterConnecting() throws Exception {
551553

552554
assertEquals("host", first.candidateType());
553555
assertTrue(first.bytesSent() > 10_000, () -> "Bytes sent: " + first.bytesSent());
556+
assertEquals(first.report().getTimestamp(), ChronoUnit.MICROS.between(Instant.EPOCH, first.timestamp()));
554557
assertEquals(-1, first.outgoingBitrate());
555-
assertTrue(second.outgoingBitrate() >= 0);
558+
// Asked for right after the first, the second may be the report WebRTC
559+
// still caches, which repeats the first one's bitrate.
560+
if (second.timestamp().equals(first.timestamp())) {
561+
assertEquals(-1, second.outgoingBitrate());
562+
}
563+
else {
564+
assertTrue(second.outgoingBitrate() >= 0);
565+
}
566+
}
567+
568+
@Test
569+
void statsHandlerErrorReported() throws Exception {
570+
// A stats handler that throws reaches the runtime's error handler, and
571+
// the samples after it still come.
572+
ManualTimer timer = new ManualTimer();
573+
CompletableFuture<Throwable> reported = new CompletableFuture<>();
574+
Duration interval = Duration.ofSeconds(7);
575+
576+
try (WebRtc runtime = WebRtc.builder()
577+
.audio(AudioMode.HEADLESS)
578+
.errorHandler(error -> {
579+
errors.add(error);
580+
reported.complete(error);
581+
})
582+
.timer(timer)
583+
.build()) {
584+
Peer peer = runtime.createPeer(manualOptions());
585+
AtomicInteger calls = new AtomicInteger();
586+
CompletableFuture<PeerStats> later = new CompletableFuture<>();
587+
588+
peer.onStats(interval, stats -> {
589+
if (calls.incrementAndGet() == 1) {
590+
throw new IllegalStateException("Handler failed");
591+
}
592+
later.complete(stats);
593+
});
594+
595+
assertEquals(1, timer.fire(interval));
596+
Throwable error = await(reported);
597+
598+
assertInstanceOf(IllegalStateException.class, error);
599+
errors.remove(error);
600+
601+
assertEquals(1, timer.fire(interval));
602+
await(later);
603+
}
556604
}
557605

558606
@Test
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import static org.junit.jupiter.api.Assertions.assertEquals;
20+
21+
import java.time.Instant;
22+
import java.util.HashMap;
23+
import java.util.Map;
24+
25+
import dev.onvoid.webrtc.RTCStats;
26+
import dev.onvoid.webrtc.RTCStatsReport;
27+
import dev.onvoid.webrtc.RTCStatsType;
28+
29+
import org.junit.jupiter.api.Test;
30+
31+
class StatsReaderTests {
32+
33+
private static final long START = 1_700_000_000_000_000L;
34+
35+
private static final long SECOND = 1_000_000;
36+
37+
private final StatsReader reader = new StatsReader();
38+
39+
40+
@Test
41+
void bitrateFromReportTimes() {
42+
// Read one right after the other, as a busy control executor hands
43+
// them on: the reports were measured a second apart.
44+
PeerStats first = reader.read(report(START, 5_000, 2_000));
45+
PeerStats second = reader.read(report(START + SECOND, 6_000, 2_500));
46+
47+
assertEquals(-1, first.outgoingBitrate());
48+
assertEquals(-1, first.incomingBitrate());
49+
assertEquals(8_000, second.outgoingBitrate());
50+
assertEquals(4_000, second.incomingBitrate());
51+
}
52+
53+
@Test
54+
void timestampOfReport() {
55+
PeerStats stats = reader.read(report(START + 250, 0, 0));
56+
57+
assertEquals(Instant.ofEpochSecond(1_700_000_000, 250_000), stats.timestamp());
58+
}
59+
60+
@Test
61+
void repeatedReportKeepsBitrates() {
62+
// WebRTC hands out the report it cached again. The one after it is
63+
// measured from the sample before.
64+
reader.read(report(START, 0, 0));
65+
reader.read(report(START + SECOND, 1_000, 1_000));
66+
PeerStats repeated = reader.read(report(START + SECOND, 1_000, 1_000));
67+
PeerStats next = reader.read(report(START + 2 * SECOND, 3_000, 1_000));
68+
69+
assertEquals(8_000, repeated.outgoingBitrate());
70+
assertEquals(8_000, repeated.incomingBitrate());
71+
assertEquals(16_000, next.outgoingBitrate());
72+
assertEquals(0, next.incomingBitrate());
73+
}
74+
75+
@Test
76+
void repeatedFirstReport() {
77+
reader.read(report(START, 1_000, 1_000));
78+
PeerStats repeated = reader.read(report(START, 1_000, 1_000));
79+
80+
assertEquals(-1, repeated.outgoingBitrate());
81+
assertEquals(-1, repeated.incomingBitrate());
82+
}
83+
84+
@Test
85+
void clockWentBack() {
86+
reader.read(report(START, 0, 0));
87+
PeerStats back = reader.read(report(START - SECOND, 1_000, 1_000));
88+
PeerStats next = reader.read(report(START, 2_000, 3_000));
89+
90+
assertEquals(-1, back.outgoingBitrate());
91+
assertEquals(-1, back.incomingBitrate());
92+
assertEquals(8_000, next.outgoingBitrate());
93+
assertEquals(16_000, next.incomingBitrate());
94+
}
95+
96+
@Test
97+
void counterStartedAgain() {
98+
// Fewer bytes sent than before. Received counts on.
99+
reader.read(report(START, 10_000, 1_000));
100+
PeerStats reset = reader.read(report(START + SECOND, 500, 2_000));
101+
PeerStats next = reader.read(report(START + 2 * SECOND, 1_500, 2_000));
102+
103+
assertEquals(-1, reset.outgoingBitrate());
104+
assertEquals(8_000, reset.incomingBitrate());
105+
assertEquals(8_000, next.outgoingBitrate());
106+
assertEquals(0, next.incomingBitrate());
107+
}
108+
109+
private static RTCStatsReport report(long micros, long bytesSent, long bytesReceived) {
110+
Map<String, Object> values = new HashMap<>();
111+
values.put("bytesSent", bytesSent);
112+
values.put("bytesReceived", bytesReceived);
113+
114+
Map<String, RTCStats> stats = new HashMap<>();
115+
stats.put("T01", new RTCStats(micros, RTCStatsType.TRANSPORT, "T01", values) { });
116+
117+
return new RTCStatsReport(stats, micros) { };
118+
}
119+
120+
}

0 commit comments

Comments
 (0)