Skip to content

Commit 19dee3c

Browse files
committed
feat: add peer diagnostics and sanitized support reports
Expose typed audio measurements and explainable quality transitions with temporal confirmation and packet loss hysteresis. Observe existing PCM subscriptions and detect TURN on either selected candidate. Export allowlisted diagnostic snapshots with codec, platform and runtime information while excluding sensitive connection data. Document the API and demonstrate diagnosis events in the client example.
1 parent 7ba398d commit 19dee3c

19 files changed

Lines changed: 1147 additions & 11 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -860,10 +860,82 @@ peer.onStats(Duration.ofSeconds(1), stats -> System.out.printf(
860860
| `packetLoss()` | The share of received packets lost so far, 0 to 1. After a long session it barely moves. |
861861
| `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. |
862862
| `outboundVideo()`, `inboundVideo()` | Codec, resolution and frame rate of each video stream, and what limits a sent one. |
863-
| `report()` | The whole `RTCStatsReport`. |
863+
| `inboundAudio()`, `outboundAudio()` | Audio streams ordered by statistics id: codec, jitter, concealment counters, audio level and sample counters. Unavailable fields are null; received PCM callbacks are observed only while an `onAudio` sink is attached. |
864+
| `diagnostics()` | The current state and confirmed `QualityCondition` causes. |
865+
| `diagnosticReport()` | A JSON snapshot with allowlisted diagnostics, media measurements, codec names, OS/architecture, Java version, library version and processor count. |
866+
| `report()` | The whole `RTCStatsReport`, including potentially sensitive connection information. |
864867

865868
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.
866869

870+
### Diagnosis and quality events
871+
872+
```java
873+
Subscription diagnosis = peer.onDiagnostics(Duration.ofSeconds(1), status -> {
874+
System.out.println(status.state());
875+
status.conditions().forEach(cause -> System.out.println(cause.reason()));
876+
});
877+
878+
// Export on demand, for example from a support button. File I/O belongs on
879+
// an application worker, outside the peer's event executor.
880+
peer.stats().thenAccept(stats -> supportExecutor.execute(() -> {
881+
try {
882+
Files.write(Paths.get("diagnostics.json"),
883+
stats.diagnosticReport().getBytes(StandardCharsets.UTF_8));
884+
}
885+
catch (IOException error) {
886+
error.printStackTrace();
887+
}
888+
}));
889+
```
890+
891+
The export example uses `java.nio.file.Files`, `java.nio.file.Paths`,
892+
`java.nio.charset.StandardCharsets` and `java.io.IOException`; `supportExecutor`
893+
is an application-owned executor.
894+
895+
`onDiagnostics` emits the initial diagnosis and then only changes to its state or
896+
causes, including recovery. Handlers run on the peer's event executor; closing the
897+
subscription stops sampling. All `stats`, `onStats` and `onDiagnostics` calls share
898+
one history per peer. A captured `PeerStats` and its diagnosis stay immutable.
899+
900+
There is no combined score. `OBSERVING` means there is no continuous measurement
901+
interval yet (including after a clock rollback or a gap longer than five seconds).
902+
`HEALTHY` means no supported problem has been confirmed; it is not a guarantee
903+
that all media paths work. `DEGRADED` includes the following confirmed causes:
904+
905+
| Condition | Evidence |
906+
|---|---|
907+
| `VIDEO_CPU_LIMITED` | The same outgoing video RTP stream consistently reports `qualityLimitationReason=cpu`. |
908+
| `HIGH_PACKET_LOSS` | Recent inbound packet loss is at least 5%; recovery needs at most 2%. Values between those thresholds retain the current state and restart the confirmation window. |
909+
| `AUDIO_PACKETS_WITHOUT_PCM` | The same received audio RTP stream gains packets while no PCM callbacks reach its attached `onAudio` sinks. This observes sink ingress, before application queues and handlers; it does not diagnose speakers or slow application handlers. |
910+
911+
Each problem and its recovery need at least three distinct measurements spanning
912+
at least three seconds. Polling once a second is recommended; cached reports do
913+
not advance the window. A missing stream or required measurement, a changed sink
914+
set, or a reset audio counter discards that stream's evidence instead of guessing.
915+
Sampling gaps longer than five seconds and backwards timestamps discard temporal
916+
evidence. Diagnostics do not add audio sinks: without an application subscription,
917+
PCM availability is unknown. Silence (audio level zero) alone is not a fault.
918+
919+
`TURN_IN_USE` is immediate information when either selected candidate on any
920+
transport is a relay. It does not make a peer degraded. `TransportStats.relayed()`
921+
also exposes this fact, while `candidateType()` continues to describe the local
922+
candidate.
923+
924+
`AudioStats.jitter()` is a `Duration`, `audioLevel()` is linear (0 to 1), and
925+
`concealedSamples()`, `concealmentEvents()` and `totalSamplesReceived()` are
926+
cumulative counters. Outbound level is read from the media source when available;
927+
receive-only measurements on outbound audio remain null. `pcmCallbacks()` counts
928+
sink callbacks across subscriptions, so multiple subscriptions can count the same
929+
audio more than once.
930+
931+
The JSON export includes the confirmation policy and cause explanations. It uses
932+
schema version 1 and an explicit allowlist, including a
933+
bounded set of codec MIME names; unknown names become `other`. It excludes raw
934+
statistics, track/stream/transport/candidate identifiers, addresses, ports, URLs,
935+
ICE credentials, SDP, certificates and codec parameters. Missing measurements
936+
become JSON null. The raw `report()` and its string representation are not
937+
sanitized diagnostic exports.
938+
867939
## Closing
868940

869941
You close what you created, and closing an owner closes what it owns:

‎webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ClientApiExample.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ public static void main(String[] args) throws Exception {
9797

9898
receive(callee);
9999
caller.onStateChange(state -> System.out.println("Caller is " + state));
100+
caller.onDiagnostics(Duration.ofSeconds(1), diagnosis -> {
101+
System.out.println("Caller diagnosis: " + diagnosis.state());
102+
diagnosis.conditions().forEach(cause -> System.out.println(cause.reason()));
103+
});
100104

101105
// Pushed media. The same tracks could be sent on any number of peers.
102106
CustomVideo video = rtc.media().customVideo("pattern");

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

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

1919
import java.time.Duration;
2020
import java.util.function.Consumer;
21+
import java.util.concurrent.atomic.AtomicLong;
2122

2223
import dev.onvoid.webrtc.internal.Timeouts;
2324
import dev.onvoid.webrtc.media.audio.AudioTrackSink;
@@ -29,6 +30,12 @@
2930
*/
3031
final class AudioDispatcher extends Dispatcher<AudioChunk> implements AudioTrackSink {
3132

33+
private final AtomicLong pcmCallbacks = new AtomicLong();
34+
35+
long pcmCallbacks() {
36+
return pcmCallbacks.get();
37+
}
38+
3239
/**
3340
* @param buffer how much audio may wait for the handler.
3441
*/
@@ -43,6 +50,12 @@ public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels,
4350
return;
4451
}
4552

53+
if (frames > 0) {
54+
55+
pcmCallbacks.incrementAndGet();
56+
57+
}
58+
4659
// The track reuses the array for the next chunk.
4760
offer(new AudioChunk(data.clone(), sampleRate, channels, frames));
4861
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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 java.time.Duration;
20+
21+
/** Immutable statistics of one audio RTP stream. Missing measurements are null. */
22+
public final class AudioStats {
23+
private final String id;
24+
private final String trackId;
25+
private final String codec;
26+
private final Long packetsReceived;
27+
private final Duration jitter;
28+
private final Long concealedSamples;
29+
private final Long concealmentEvents;
30+
private final Double audioLevel;
31+
private final Long totalSamplesReceived;
32+
private final Long pcmCallbacks;
33+
final long pcmGeneration;
34+
35+
AudioStats(String id, String trackId, String codec, Long packetsReceived,
36+
Duration jitter, Long concealedSamples, Long concealmentEvents,
37+
Double audioLevel, Long totalSamplesReceived, Long pcmCallbacks, long pcmGeneration) {
38+
this.id = id;
39+
this.trackId = trackId;
40+
this.codec = codec;
41+
this.packetsReceived = packetsReceived;
42+
this.jitter = jitter;
43+
this.concealedSamples = concealedSamples;
44+
this.concealmentEvents = concealmentEvents;
45+
this.audioLevel = audioLevel;
46+
this.totalSamplesReceived = totalSamplesReceived;
47+
this.pcmCallbacks = pcmCallbacks;
48+
this.pcmGeneration = pcmGeneration;
49+
}
50+
51+
/** @return the RTP statistics id, for correlating successive measurements. */
52+
public String id() {
53+
return id;
54+
}
55+
56+
/** @return the track identifier, or null. */
57+
public String trackId() {
58+
return trackId;
59+
}
60+
61+
/** @return the negotiated codec MIME type, or null. */
62+
public String codec() {
63+
return codec;
64+
}
65+
66+
/** @return cumulative packets received, or null for outbound or unavailable data. */
67+
public Long packetsReceived() {
68+
return packetsReceived;
69+
}
70+
71+
/** @return interarrival jitter, or null if unavailable. */
72+
public Duration jitter() {
73+
return jitter;
74+
}
75+
76+
/** @return cumulative samples replaced by concealment, or null. */
77+
public Long concealedSamples() {
78+
return concealedSamples;
79+
}
80+
81+
/** @return cumulative concealment events, or null. */
82+
public Long concealmentEvents() {
83+
return concealmentEvents;
84+
}
85+
86+
/** @return linear audio level from 0 to 1, or null. Zero can be silence. */
87+
public Double audioLevel() {
88+
return audioLevel;
89+
}
90+
91+
/** @return cumulative received samples reported by WebRTC, or null. */
92+
public Long totalSamplesReceived() {
93+
return totalSamplesReceived;
94+
}
95+
96+
/**
97+
* @return cumulative PCM callbacks across this track's onAudio subscriptions,
98+
* or null when none is attached. Counts sink ingress, before application queues.
99+
* Several subscriptions can count the same audio more than once.
100+
*/
101+
public Long pcmCallbacks() {
102+
return pcmCallbacks;
103+
}
104+
}
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
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 java.util.Arrays;
20+
import java.util.Locale;
21+
22+
/** An explicit export schema: never serializes raw stats or arbitrary string attributes. */
23+
final class DiagnosticExport {
24+
private DiagnosticExport() { }
25+
26+
static String json(PeerStats stats) {
27+
StringBuilder out = new StringBuilder("{\"schemaVersion\":1");
28+
field(out, "timestamp", stats.timestamp().toString());
29+
field(out, "state", stats.diagnostics().state().name());
30+
field(out, "os", platform(System.getProperty("os.name", "")));
31+
field(out, "architecture", allowed(System.getProperty("os.arch", ""),
32+
"amd64", "x86_64", "aarch64", "arm", "x86", "i386"));
33+
String javaVersion = System.getProperty("java.specification.version", "");
34+
field(out, "javaVersion", javaVersion.matches("[0-9]{1,3}(\\.[0-9]{1,3})?") ? javaVersion : "other");
35+
String version = PeerStats.class.getPackage().getImplementationVersion();
36+
field(out, "libraryVersion", version != null && version.matches("[0-9]+\\.[0-9]+\\.[0-9]+(-SNAPSHOT)?")
37+
? version : "unversioned");
38+
number(out, "availableProcessors", Runtime.getRuntime().availableProcessors());
39+
number(out, "bytesSent", stats.bytesSent());
40+
number(out, "bytesReceived", stats.bytesReceived());
41+
number(out, "outgoingBitrate", stats.outgoingBitrate());
42+
number(out, "incomingBitrate", stats.incomingBitrate());
43+
number(out, "packetLoss", stats.packetLoss());
44+
number(out, "recentPacketLoss", stats.recentPacketLoss());
45+
out.append(",\"policy\":{\"confirmationSeconds\":").append(DiagnosticsReader.WINDOW.getSeconds());
46+
number(out, "minimumMeasurements", DiagnosticsReader.MIN_SAMPLES);
47+
number(out, "lossEnter", DiagnosticsReader.LOSS_ENTER);
48+
number(out, "lossExit", DiagnosticsReader.LOSS_EXIT);
49+
number(out, "maximumGapSeconds", DiagnosticsReader.MAX_GAP.getSeconds());
50+
out.append('}');
51+
out.append(",\"conditions\":[");
52+
boolean comma = false;
53+
for (QualityCondition condition : stats.diagnostics().conditions()) {
54+
if (comma) {
55+
out.append(',');
56+
}
57+
out.append("{\"cause\":");
58+
Json.writeString(out, condition.name());
59+
field(out, "reason", condition.reason());
60+
out.append(",\"problem\":").append(condition.isProblem()).append('}');
61+
comma = true;
62+
}
63+
out.append("],\"transports\":[");
64+
comma = false;
65+
for (TransportStats transport : stats.transports()) {
66+
if (comma) {
67+
out.append(',');
68+
}
69+
out.append("{\"relayed\":").append(transport.relayed());
70+
field(out, "candidateType", allowed(transport.candidateType(), "host", "srflx", "prflx", "relay"));
71+
number(out, "rttSeconds", transport.roundTripTime() == null ? null
72+
: transport.roundTripTime().toNanos() / 1e9);
73+
out.append('}');
74+
comma = true;
75+
}
76+
out.append("],\"video\":[");
77+
comma = false;
78+
for (boolean outbound : new boolean[] { false, true }) {
79+
for (VideoStats video : outbound ? stats.outboundVideo() : stats.inboundVideo()) {
80+
if (comma) {
81+
out.append(',');
82+
}
83+
out.append("{\"outbound\":").append(outbound);
84+
field(out, "codec", codec(video.codec()));
85+
number(out, "width", video.width());
86+
number(out, "height", video.height());
87+
number(out, "framesPerSecond", video.framesPerSecond());
88+
field(out, "qualityLimitation", allowed(video.qualityLimitation(), "none", "cpu", "bandwidth", "other"));
89+
out.append('}');
90+
comma = true;
91+
}
92+
}
93+
out.append("],\"audio\":[");
94+
comma = false;
95+
for (boolean outbound : new boolean[] { false, true }) {
96+
for (AudioStats audio : outbound ? stats.outboundAudio() : stats.inboundAudio()) {
97+
if (comma) {
98+
out.append(',');
99+
}
100+
out.append("{\"outbound\":").append(outbound);
101+
field(out, "codec", codec(audio.codec()));
102+
number(out, "packetsReceived", audio.packetsReceived());
103+
number(out, "jitterSeconds", audio.jitter() == null ? null : audio.jitter().toNanos() / 1e9);
104+
number(out, "concealedSamples", audio.concealedSamples());
105+
number(out, "concealmentEvents", audio.concealmentEvents());
106+
number(out, "audioLevel", audio.audioLevel());
107+
number(out, "totalSamplesReceived", audio.totalSamplesReceived());
108+
number(out, "pcmCallbacks", audio.pcmCallbacks());
109+
out.append('}');
110+
comma = true;
111+
}
112+
}
113+
return out.append("]}").toString();
114+
}
115+
116+
private static String codec(String value) {
117+
if (value == null) {
118+
return null;
119+
}
120+
return allowed(value.toLowerCase(Locale.ROOT), "audio/opus", "audio/pcmu", "audio/pcma",
121+
"audio/g722", "audio/isac", "audio/cn", "audio/telephone-event", "audio/red",
122+
"video/vp8", "video/vp9", "video/h264", "video/h265", "video/av1", "video/rtx",
123+
"video/red", "video/ulpfec", "video/flexfec-03");
124+
}
125+
126+
private static String allowed(String value, String... allowed) {
127+
return value == null ? null : Arrays.asList(allowed).contains(value) ? value : "other";
128+
}
129+
130+
private static String platform(String name) {
131+
if (name.startsWith("Windows")) {
132+
return "Windows";
133+
}
134+
if (name.equals("Mac OS X")) {
135+
return "macOS";
136+
}
137+
return name.equals("Linux") ? "Linux" : "other";
138+
}
139+
140+
private static void field(StringBuilder out, String name, String value) {
141+
out.append(',');
142+
Json.writeString(out, name);
143+
out.append(':');
144+
if (value == null) {
145+
out.append("null");
146+
}
147+
else Json.writeString(out, value);
148+
}
149+
150+
private static void number(StringBuilder out, String name, Number value) {
151+
out.append(',');
152+
Json.writeString(out, name);
153+
out.append(':');
154+
out.append(value == null || !Double.isFinite(value.doubleValue()) ? "null" : value.toString());
155+
}
156+
}

0 commit comments

Comments
 (0)