From 9458ff3400a4ba82ca3413a26b2158d97fbaf4b3 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Tue, 6 Oct 2026 20:26:59 +0000 Subject: [PATCH] Add Connection Info on Android and count received voice Connection Info gains a "Voice received" section on both frontends, counting what our own playback made of a speaker's voice (everyone's, for ourselves): packets received, frames played and missed, packets out of order, dropped as too late, and discarded as copies. Android gets the window itself as a page from the client sheet. The rows and their formatting live in core, shared by both frontends; the Swing dialog keeps its tabs on one row. A minute's bandwidth now shows as the average rate it is labelled as, not the minute's bytes. Co-Authored-By: Claude Opus 5.5 --- .../com/ts3client/android/ServerController.kt | 6 + .../android/ui/ConnectionInfoScreen.kt | 68 +++++ .../com/ts3client/android/ui/ServerScreen.kt | 6 + .../java/com/ts3client/android/ui/Sheets.kt | 2 + .../ts3client/audio/StreamingVoiceOutput.java | 18 ++ .../java/com/ts3client/audio/VoiceOutput.java | 6 + .../ts3client/audio/VoiceReceiveStats.java | 29 ++ .../java/com/ts3client/audio/VoiceStream.java | 55 +++- .../com/ts3client/net/ConnectionStats.java | 8 + .../net/ConnectionStatsCollector.java | 19 +- .../ts3client/net/ConnectionStatsFormat.java | 143 ++++++++++ .../com/ts3client/audio/VoiceStreamTest.java | 15 + .../ts3client/ui/ConnectionInfoDialog.java | 258 +++++------------- ts3j | 2 +- 14 files changed, 437 insertions(+), 198 deletions(-) create mode 100644 android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt create mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java diff --git a/android/app/src/main/java/com/ts3client/android/ServerController.kt b/android/app/src/main/java/com/ts3client/android/ServerController.kt index cc83b2e..d980007 100644 --- a/android/app/src/main/java/com/ts3client/android/ServerController.kt +++ b/android/app/src/main/java/com/ts3client/android/ServerController.kt @@ -2,6 +2,7 @@ package com.ts3client.android import com.ts3client.contacts.ContactType import com.ts3client.net.ChannelNode +import com.ts3client.net.ConnectionStats import com.ts3client.net.Details import com.ts3client.net.GroupChoice import com.ts3client.net.ban.BanEntry @@ -214,6 +215,11 @@ class ServerController internal constructor( // ---- ban list ---- /** The server's bans, or why they could not be read. */ + /** One reading of a client's connection figures, or null when not connected. */ + suspend fun connectionStats(clientId: Int): ConnectionStats? = + if (!session.isConnected) null + else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } + suspend fun banList(): Result> = suspendCoroutine { done -> conn.requestBanList { bans, error -> done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error))) diff --git a/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt new file mode 100644 index 0000000..7bfb74f --- /dev/null +++ b/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt @@ -0,0 +1,68 @@ +package com.ts3client.android.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.ts3client.android.ServerController +import com.ts3client.net.ConnectionStats +import com.ts3client.net.ConnectionStatsFormat +import kotlinx.coroutines.delay + +private const val REFRESH_MS = 1000L +private const val SELF_ADDRESS = "This device" + +/** A client's connection figures, read again every second while shown, and what our playback made of their voice. */ +@Composable +fun ConnectionInfoScreen(server: ServerController, clientId: Int, nickname: String, onBack: () -> Unit) { + var stats by remember { mutableStateOf(null) } + LaunchedEffect(clientId) { + while (true) { + stats = server.connectionStats(clientId) ?: break + delay(REFRESH_MS) + } + } + val s = stats + SubScreen("Connection info", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + Text(nickname, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.titleLarge) + Figures(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)) + Section("Voice received") + Figures(ConnectionStatsFormat.voiceRows(s?.voiceReceived)) + Section("Total") + Figures(ConnectionStatsFormat.trafficRows(s, null)) + for ((kind, title) in KINDS) { + Section(title) + Figures(ConnectionStatsFormat.trafficRows(s, kind)) + } + } + } +} + +private val KINDS = listOf( + ConnectionStats.Kind.SPEECH to "Speech", + ConnectionStats.Kind.KEEPALIVE to "Keep alive", + ConnectionStats.Kind.CONTROL to "Control", +) + +@Composable +private fun Figures(rows: List) { + for (row in rows) { + Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { + Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, Modifier.weight(1f), textAlign = TextAlign.End) + } + } +} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt index b7c5be7..d70aaa7 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt @@ -129,6 +129,7 @@ fun ServerScreen( var channelSheet by remember { mutableStateOf(null) } var serverSheet by remember { mutableStateOf(false) } var banList by rememberSaveable { mutableStateOf(false) } + var connectionInfo by rememberSaveable { mutableStateOf(null) } /** The client to move, while a channel for them is being picked. */ var moving by remember { mutableStateOf(null) } val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle() @@ -207,6 +208,10 @@ fun ServerScreen( BanListScreen(server, vm.banReasons, onBack = { banList = false }) return } + connectionInfo?.let { id -> + ConnectionInfoScreen(server, id, tree.client(id)?.name ?: "", onBack = { connectionInfo = null }) + return + } BackHandler(showChat) { showChat = false } BackHandler(moving != null && !showChat) { moving = null } @@ -334,6 +339,7 @@ fun ServerScreen( onAway = { server.setAway(it); clientSheet = null }, onAddContact = { server.addContact(id, it) }, onEditContact = { clientSheet = null; onEditContact(client.uniqueId) }, + onConnectionInfo = { clientSheet = null; connectionInfo = id }, onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null, onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { { server.moveClient(id, state.channelId); clientSheet = null } diff --git a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt index 34b327f..63d3102 100644 --- a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt +++ b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt @@ -53,6 +53,7 @@ fun ClientSheet( onAway: (Boolean) -> Unit, onAddContact: (ContactType) -> Unit, onEditContact: () -> Unit, + onConnectionInfo: () -> Unit, /** Null when the client cannot be moved. */ onMove: (() -> Unit)?, /** Null when the client cannot be moved, or is in our channel already. */ @@ -87,6 +88,7 @@ fun ClientSheet( } details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) } + Action("INFO", "Connection info", onClick = onConnectionInfo) if (client.self) { Action("AWAY", if (away) "Back" else "Away") { onAway(!away) } moderation() diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java b/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java index 82be5c4..53deb65 100644 --- a/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java +++ b/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java @@ -42,6 +42,8 @@ public final class StreamingVoiceOutput implements VoiceOutput { private final Set mutedClients = ConcurrentHashMap.newKeySet(); /** Per-client gain on top of the master volume; absent means 1.0. */ private final Map clientVolumes = new ConcurrentHashMap<>(); + /** What came in from speakers who have left. */ + private volatile VoiceReceiveStats departed = VoiceReceiveStats.NONE; private volatile String outputDevice; private volatile double masterVolume = 1.0; @@ -176,6 +178,9 @@ public final class StreamingVoiceOutput implements VoiceOutput { public void removeClient(int clientId) { VoiceStream s = streams.remove(clientId); if (s != null) { + synchronized (this) { + departed = departed.plus(s.stats()); + } playout.removed(s); s.close(); } @@ -183,6 +188,19 @@ public final class StreamingVoiceOutput implements VoiceOutput { clientVolumes.remove(clientId); } + @Override + public VoiceReceiveStats receiveStats(int clientId) { + VoiceStream s = streams.get(clientId); + return s == null ? null : s.stats(); + } + + @Override + public VoiceReceiveStats receiveStats() { + VoiceReceiveStats total = departed; + for (VoiceStream s : streams.values()) total = total.plus(s.stats()); + return total; + } + @Override public void shutdown() { clock.shutdownNow(); diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java index 06c7c6d..e80be8c 100644 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java +++ b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java @@ -43,4 +43,10 @@ public interface VoiceOutput { /** Receives every speaker's voice as it is played, e.g. for recording; null detaches it. */ void setVoiceTap(VoiceTap tap); + + /** How one speaker's voice has been coming in, or {@code null} if none came yet. */ + VoiceReceiveStats receiveStats(int clientId); + + /** How everyone's voice has been coming in, those who left included. */ + VoiceReceiveStats receiveStats(); } diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java new file mode 100644 index 0000000..70a9f77 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java @@ -0,0 +1,29 @@ +package com.ts3client.audio; + +/** + * How one speaker's voice, or everyone's together, has been coming in: what arrived, and + * what playback had to do without. + * + * @param received voice packets that arrived, copies included + * @param played frames played from a packet + * @param missed frames concealed because their packet was not there when due + * @param outOfOrder packets that arrived after a later one + * @param late packets that arrived after their frame was concealed, so were dropped; + * each one is also among {@code missed} + * @param duplicates copies of a packet already received, discarded + */ +public record VoiceReceiveStats(long received, long played, long missed, long outOfOrder, long late, + long duplicates) { + + public static final VoiceReceiveStats NONE = new VoiceReceiveStats(0, 0, 0, 0, 0, 0); + + public VoiceReceiveStats plus(VoiceReceiveStats o) { + return new VoiceReceiveStats(received + o.received, played + o.played, missed + o.missed, + outOfOrder + o.outOfOrder, late + o.late, duplicates + o.duplicates); + } + + /** Frames that were due, whether played or concealed. */ + public long due() { + return played + missed; + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java index 2e7763a..be1c83b 100644 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java +++ b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java @@ -42,6 +42,8 @@ final class VoiceStream { /** Silence after which the timeline and the delay estimate are dropped, as in the official client. */ private static final long IDLE_RESET_NANOS = 5_000_000_000L; private static final int EPOCH_UNSET = Integer.MIN_VALUE; + /** How many recent sequence numbers are remembered to recognise a copy; a power of two. */ + private static final int SEEN_WINDOW = 1024; /** What a pull plays, decided under the lock and produced outside it. */ private enum Source { PACKET, CONCEAL, SILENCE, SURPLUS } @@ -67,6 +69,15 @@ final class VoiceStream { private int concealOwed; /** Set when the timeline was dropped; the decoder follows on the next pull. */ private boolean resetDecoder; + /** Recently received sequence numbers, each at {@code seq % SEEN_WINDOW}. */ + private final int[] seen = new int[SEEN_WINDOW]; + private int highestSeq; + private long received; + private long played; + private long missed; + private long outOfOrder; + private long late; + private long duplicates; /** Guards the decoder: a close from another thread may reach it mid-pull. */ private final Object decoderLock = new Object(); @@ -89,6 +100,7 @@ final class VoiceStream { this.clientId = clientId; this.opus = opus; this.talkListener = talkListener; + forgetSeen(); } void setTap(VoiceTap tap) { @@ -118,16 +130,20 @@ final class VoiceStream { epoch = EPOCH_UNSET; stopMarkCount = 0; resetDecoder = true; + forgetSeen(); } boolean fresh = epoch == EPOCH_UNSET; - int ticks = unwrap(packetId & 0xFFFF) * FRAME_TICKS; + int seq = unwrap(packetId & 0xFFFF); + int ticks = seq * FRAME_TICKS; if (end) { markStop(ticks); return false; } + boolean behind = !fresh && ticks - jitter.position() < 0; + count(seq, fresh, behind); // Playback already went past it, but the buffer still learns how late it ran, as in // the official client; that is what grows the delay to wait for redundant copies. - if (!fresh && ticks - jitter.position() < 0) { + if (behind) { jitter.put(data, ticks, FRAME_TICKS); return false; } @@ -187,8 +203,16 @@ final class VoiceStream { case OK -> { source = Source.PACKET; packet = jitter.payload(); + played++; + } + case MISSING -> { + if (isStopMark(jitter.timestamp())) { + source = Source.SILENCE; + } else { + source = Source.CONCEAL; + missed++; + } } - case MISSING -> source = isStopMark(jitter.timestamp()) ? Source.SILENCE : Source.CONCEAL; default -> { // The buffer grows its delay by inserting this many frames. source = Source.CONCEAL; @@ -327,6 +351,31 @@ final class VoiceStream { return (epoch << 16) | seq; } + /** Files an arrived packet under the counters. Call under the lock. */ + private void count(int seq, boolean fresh, boolean behind) { + received++; + int slot = seq & (SEEN_WINDOW - 1); + if (!fresh && seen[slot] == seq) { + duplicates++; + return; + } + seen[slot] = seq; + if (behind) late++; + if (fresh || seq - highestSeq > 0) highestSeq = seq; + else outOfOrder++; + } + + private void forgetSeen() { + java.util.Arrays.fill(seen, Integer.MIN_VALUE); + } + + /** How this speaker's voice has been coming in since the stream was created. */ + VoiceReceiveStats stats() { + synchronized (lock) { + return new VoiceReceiveStats(received, played, missed, outOfOrder, late, duplicates); + } + } + private void markStop(int ticks) { int position = jitter.position(); int kept = 0; diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java index 0ac767f..fb1eae4 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java @@ -1,5 +1,7 @@ package com.ts3client.net; +import com.ts3client.audio.VoiceReceiveStats; + import java.util.ArrayList; import java.util.List; @@ -50,6 +52,12 @@ public final class ConnectionStats { public long bandwidthSentLastMinute = -1; public long bandwidthReceivedLastMinute = -1; + /** + * How voice has been coming in here, measured by this client's own playback: from this + * speaker, or for ourselves from everyone. {@code null} when nothing was heard. + */ + public VoiceReceiveStats voiceReceived; + /** Per-category breakdown (one row per {@link Kind}); empty when unavailable. */ public final List perKind = new ArrayList<>(); diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java index 27aad8f..ce9225f 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java @@ -8,6 +8,7 @@ import com.github.manevolent.ts3j.protocol.ProtocolRole; import com.github.manevolent.ts3j.protocol.packet.statistics.PacketStatistics; import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; import com.github.manevolent.ts3j.util.Pair; +import com.ts3client.audio.VoiceOutput; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -42,12 +43,22 @@ final class ConnectionStatsCollector { */ void request(int clientId, Consumer callback) { if (clientId == conn.getSelfClientId()) { - new Thread(() -> callback.accept(buildLocalStats()), "ts3j-conninfo-self").start(); + new Thread(() -> callback.accept(withVoice(buildLocalStats(), clientId)), "ts3j-conninfo-self").start(); } else { - new Thread(() -> requestRemote(clientId, callback), "ts3j-conninfo").start(); + new Thread(() -> requestRemote(clientId, s -> callback.accept(withVoice(s, clientId))), + "ts3j-conninfo").start(); } } + /** Adds what our playback saw of the client's voice, or everyone's for ourselves. */ + private ConnectionStats withVoice(ConnectionStats s, int clientId) { + VoiceOutput playback = conn.getPlayback(); + if (playback != null) { + s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); + } + return s; + } + /** Matches an asynchronously arriving {@code notifyconnectioninfo} report to its request. */ void onReport(UnknownTeamspeakEvent e) { int clid = safeInt(e.get("clid")); @@ -98,8 +109,8 @@ final class ConnectionStatsCollector { ks.bytesReceived = st.getReceivedBytes(); ks.bandwidthSentLastSecond = st.getSentBytesLastSecond(); ks.bandwidthReceivedLastSecond = st.getReceivedBytesLastSecond(); - ks.bandwidthSentLastMinute = st.getSentBytesLastMinute(); - ks.bandwidthReceivedLastMinute = st.getReceivedBytesLastMinute(); + ks.bandwidthSentLastMinute = st.getSentBandwidthLastMinute(); + ks.bandwidthReceivedLastMinute = st.getReceivedBandwidthLastMinute(); s.perKind.add(ks); pSent += ks.packetsSent; diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java new file mode 100644 index 0000000..817f730 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java @@ -0,0 +1,143 @@ +package com.ts3client.net; + +import com.ts3client.audio.VoiceReceiveStats; + +import java.text.DecimalFormat; +import java.util.List; + +/** Renders {@link ConnectionStats} figures for display; an unknown value (negative) shows as a dash. */ +public final class ConnectionStatsFormat { + + public static final String UNKNOWN = "—"; + + private ConnectionStatsFormat() { + } + + public static String orDash(String s) { + return (s == null || s.isEmpty()) ? UNKNOWN : s; + } + + public static String ping(double ms, double deviationMs) { + if (ms < 0) return UNKNOWN; + String base = Math.round(ms) + " ms"; + if (deviationMs > 0) base += " (± " + Math.round(deviationMs) + " ms)"; + return base; + } + + /** A fraction 0..1 as a percentage. */ + public static String loss(double fraction) { + if (fraction < 0) return UNKNOWN; + return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; + } + + public static String count(long n) { + return n < 0 ? UNKNOWN : new DecimalFormat("#,##0").format(n); + } + + /** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */ + public static String countOf(long n, long of) { + if (n < 0) return UNKNOWN; + if (of <= 0) return count(n); + return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)"; + } + + public static String bytes(long bytes) { + if (bytes < 0) return UNKNOWN; + if (bytes < 1024) return bytes + " B"; + double kib = bytes / 1024.0; + if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB"; + double mib = kib / 1024.0; + if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB"; + return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB"; + } + + public static String rate(long bytesPerSecond) { + return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s"; + } + + /** Sent and received side by side. */ + public static String upDown(String up, String down) { + return up + " / " + down; + } + + /** A labelled figure. */ + public record Row(String label, String value) { + } + + /** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ + public static List summaryRows(ConnectionStats s, String selfAddress) { + ConnectionStats k = s == null ? new ConnectionStats() : s; + return List.of( + new Row("Address", k.self ? selfAddress : orDash(k.ip)), + new Row("Client version", orDash(k.version)), + new Row("Platform", orDash(k.platform)), + new Row("Ping", ping(k.pingMs, k.pingDeviationMs)), + new Row("Idle time", duration(k.idleTimeMs)), + new Row("Connected", duration(k.connectedTimeMs)), + new Row("Filetransfer (↑/↓)", + upDown(rate(k.filetransferBandwidthSent), rate(k.filetransferBandwidthReceived)))); + } + + /** One traffic category's figures, or the totals for a null {@code kind}. */ + public static List trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { + double loss = -1; + long packetsSent = -1, packetsReceived = -1, bytesSent = -1, bytesReceived = -1; + long secondSent = -1, secondReceived = -1, minuteSent = -1, minuteReceived = -1; + if (s != null && kind == null) { + loss = s.packetLoss; + packetsSent = s.packetsSentTotal; + packetsReceived = s.packetsReceivedTotal; + bytesSent = s.bytesSentTotal; + bytesReceived = s.bytesReceivedTotal; + secondSent = s.bandwidthSentLastSecond; + secondReceived = s.bandwidthReceivedLastSecond; + minuteSent = s.bandwidthSentLastMinute; + minuteReceived = s.bandwidthReceivedLastMinute; + } else if (s != null && s.kind(kind) != null) { + ConnectionStats.KindStats k = s.kind(kind); + loss = k.packetLoss; + packetsSent = k.packetsSent; + packetsReceived = k.packetsReceived; + bytesSent = k.bytesSent; + bytesReceived = k.bytesReceived; + secondSent = k.bandwidthSentLastSecond; + secondReceived = k.bandwidthReceivedLastSecond; + minuteSent = k.bandwidthSentLastMinute; + minuteReceived = k.bandwidthReceivedLastMinute; + } + return List.of( + new Row("Packet loss", loss(loss)), + new Row("Packets (↑/↓)", upDown(count(packetsSent), count(packetsReceived))), + new Row("Transferred (↑/↓)", upDown(bytes(bytesSent), bytes(bytesReceived))), + new Row("Bandwidth · last second (↑/↓)", upDown(rate(secondSent), rate(secondReceived))), + new Row("Bandwidth · last minute (↑/↓)", upDown(rate(minuteSent), rate(minuteReceived)))); + } + + /** The voice our playback received; every value is a dash when nothing was heard. */ + public static List voiceRows(VoiceReceiveStats v) { + VoiceReceiveStats s = v == null ? VoiceReceiveStats.NONE : v; + boolean known = v != null; + return List.of( + new Row("Received", known ? count(s.received()) : UNKNOWN), + new Row("Played", known ? countOf(s.played(), s.due()) : UNKNOWN), + new Row("Missed", known ? countOf(s.missed(), s.due()) : UNKNOWN), + new Row("Out of order", known ? countOf(s.outOfOrder(), s.received()) : UNKNOWN), + new Row("Dropped (too late)", known ? countOf(s.late(), s.received()) : UNKNOWN), + new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN)); + } + + public static String duration(long ms) { + if (ms < 0) return UNKNOWN; + long totalSeconds = ms / 1000; + long days = totalSeconds / 86400; + long hours = (totalSeconds % 86400) / 3600; + long minutes = (totalSeconds % 3600) / 60; + long seconds = totalSeconds % 60; + StringBuilder sb = new StringBuilder(); + if (days > 0) sb.append(days).append("d "); + if (days > 0 || hours > 0) sb.append(hours).append("h "); + if (days > 0 || hours > 0 || minutes > 0) sb.append(minutes).append("m "); + sb.append(seconds).append("s"); + return sb.toString(); + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java index 7e39a13..97d1eff 100644 --- a/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java +++ b/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java @@ -88,6 +88,21 @@ class VoiceStreamTest { assertEquals(List.of(true, false), talk); } + @Test + void countsWhatCameInAndWhatWasMissing() { + offer(0, 1); + offer(2, 3); + offer(1, 2); // out of order, still in time + offer(2, 3); // a copy + pull(); + pull(); + pull(); + pull(); // 3 never arrives: concealed + offer(3, 4); // too late, dropped + offer(3, 4); // a copy of that + assertEquals(new VoiceReceiveStats(6, 3, 1, 1, 1, 2), stream.stats()); + } + @Test void theTalkersStopEndsTheBurst() { offer(0, 1); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java index e3c28b5..b93d21b 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java @@ -3,6 +3,8 @@ package com.ts3client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; import com.ts3client.net.ConnectionStats; +import com.ts3client.net.ConnectionStatsFormat; +import com.ts3client.net.ConnectionStatsFormat.Row; import com.ts3client.net.TeamspeakConnection; import javax.swing.Box; @@ -22,14 +24,16 @@ import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; -import java.text.DecimalFormat; +import java.util.List; /** * Live "Client Connection Info" window, reachable from a client's right-click * menu. Mirrors the TeamSpeak 3 dialog: a summary header (address, version, * platform, idle/connected time, ping, filetransfer) above a * Total / Speech / Keep Alive / Control tab strip, each tab showing - * that category's packet loss, packet and byte totals and live bandwidth. + * that category's packet loss, packet and byte totals and live bandwidth, plus a + * Voice received tab with what our own playback made of the client's voice + * (everyone's, for ourselves): missed, out-of-order, late and duplicate packets. * *

Polls the {@link TeamspeakConnection} once a second while open; for the * local client the figures update live from local counters, for a remote client @@ -38,6 +42,9 @@ import java.text.DecimalFormat; public final class ConnectionInfoDialog extends JDialog { private static final int REFRESH_MS = 1000; + /** Wide enough for the tab strip to stay on one row. */ + private static final int MIN_WIDTH = 560; + private static final String SELF_ADDRESS = "This computer"; private final TeamspeakConnection conn; private final int clientId; @@ -45,18 +52,12 @@ public final class ConnectionInfoDialog extends JDialog { private final java.util.concurrent.atomic.AtomicBoolean inFlight = new java.util.concurrent.atomic.AtomicBoolean(); - private final JLabel addressValue = value(); - private final JLabel versionValue = value(); - private final JLabel platformValue = value(); - private final JLabel idleValue = value(); - private final JLabel connectedValue = value(); - private final JLabel pingValue = value(); - private final JLabel filetransferValue = value(); - - private final KindTab totalTab = new KindTab(); - private final KindTab speechTab = new KindTab(); - private final KindTab keepAliveTab = new KindTab(); - private final KindTab controlTab = new KindTab(); + private final Rows summary = new Rows(ConnectionStatsFormat.summaryRows(null, SELF_ADDRESS)); + private final Rows total = tab(ConnectionStatsFormat.trafficRows(null, null)); + private final Rows speech = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.SPEECH)); + private final Rows keepAlive = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.KEEPALIVE)); + private final Rows control = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.CONTROL)); + private final Rows voice = tab(ConnectionStatsFormat.voiceRows(null)); public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) { super(owner, "Connection Info — " + nickname, false); @@ -66,7 +67,7 @@ public final class ConnectionInfoDialog extends JDialog { JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(10))); content.setBackground(Theme.windowBg()); content.setBorder(new ScaledEmptyBorder(12, 14, 12, 14)); - content.add(buildSummary(), BorderLayout.NORTH); + content.add(summary, BorderLayout.NORTH); content.add(buildTabs(), BorderLayout.CENTER); content.add(buildButtons(), BorderLayout.SOUTH); setContentPane(content); @@ -74,7 +75,7 @@ public final class ConnectionInfoDialog extends JDialog { Dialogs.closeOnEscape(this); // Disposing is what stops the refresh timer, so the window button must not merely hide. setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); + fit(); setLocationRelativeTo(owner); addWindowListener(new WindowAdapter() { @@ -91,28 +92,15 @@ public final class ConnectionInfoDialog extends JDialog { // ---- construction ---- - private JPanel buildSummary() { - JPanel grid = new JPanel(new GridBagLayout()); - grid.setBackground(Theme.windowBg()); - int row = 0; - addRow(grid, row++, "Address", addressValue); - addRow(grid, row++, "Client version", versionValue); - addRow(grid, row++, "Platform", platformValue); - addRow(grid, row++, "Ping", pingValue); - addRow(grid, row++, "Idle time", idleValue); - addRow(grid, row++, "Connected", connectedValue); - addRow(grid, row, "Filetransfer (↑/↓)", filetransferValue); - return grid; - } - private JTabbedPane buildTabs() { JTabbedPane tabs = new JTabbedPane(); tabs.setFont(Theme.uiFont()); tabs.setBackground(Theme.windowBg()); - tabs.addTab("Total", totalTab); - tabs.addTab("Speech", speechTab); - tabs.addTab("Keep Alive", keepAliveTab); - tabs.addTab("Control", controlTab); + tabs.addTab("Total", total); + tabs.addTab("Speech", speech); + tabs.addTab("Keep Alive", keepAlive); + tabs.addTab("Control", control); + tabs.addTab("Voice received", voice); return tabs; } @@ -127,32 +115,10 @@ public final class ConnectionInfoDialog extends JDialog { return bar; } - private static JLabel value() { - JLabel l = new JLabel("—"); - l.setFont(Theme.uiFont()); - l.setForeground(Theme.treeText()); - return l; - } - - private static void addRow(JPanel grid, int row, String label, JLabel valueLabel) { - GridBagConstraints lc = new GridBagConstraints(); - lc.gridx = 0; - lc.gridy = row; - lc.anchor = GridBagConstraints.WEST; - lc.insets = UIScale.scale(new Insets(2, 0, 2, 16)); - JLabel key = new JLabel(label); - key.setFont(Theme.uiFont()); - key.setForeground(new Color(0x5A6B7B)); - grid.add(key, lc); - - GridBagConstraints vc = new GridBagConstraints(); - vc.gridx = 1; - vc.gridy = row; - vc.weightx = 1; - vc.anchor = GridBagConstraints.WEST; - vc.fill = GridBagConstraints.HORIZONTAL; - vc.insets = UIScale.scale(new Insets(2, 0, 2, 0)); - grid.add(valueLabel, vc); + private static Rows tab(List rows) { + Rows tab = new Rows(rows); + tab.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + return tab; } // ---- live update ---- @@ -171,21 +137,12 @@ public final class ConnectionInfoDialog extends JDialog { private void apply(ConnectionStats s) { if (!isDisplayable()) return; - - addressValue.setText(s.self ? "This computer" : orDash(s.ip)); - versionValue.setText(orDash(s.version)); - platformValue.setText(orDash(s.platform)); - pingValue.setText(formatPing(s.pingMs, s.pingDeviationMs)); - idleValue.setText(formatDuration(s.idleTimeMs)); - connectedValue.setText(formatDuration(s.connectedTimeMs)); - filetransferValue.setText(formatRate(s.filetransferBandwidthSent) - + " / " + formatRate(s.filetransferBandwidthReceived)); - - totalTab.update(totalSample(s)); - speechTab.update(kindSample(s, ConnectionStats.Kind.SPEECH)); - keepAliveTab.update(kindSample(s, ConnectionStats.Kind.KEEPALIVE)); - controlTab.update(kindSample(s, ConnectionStats.Kind.CONTROL)); - + summary.update(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)); + total.update(ConnectionStatsFormat.trafficRows(s, null)); + speech.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.SPEECH)); + keepAlive.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.KEEPALIVE)); + control.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.CONTROL)); + voice.update(ConnectionStatsFormat.voiceRows(s.voiceReceived)); growToFit(); } @@ -198,133 +155,54 @@ public final class ConnectionInfoDialog extends JDialog { Dimension pref = getContentPane().getPreferredSize(); Dimension have = getContentPane().getSize(); if (pref.width > have.width || pref.height > have.height) { - pack(); + fit(); } } - private static Sample totalSample(ConnectionStats s) { - Sample sample = new Sample(); - sample.packetLoss = s.packetLoss; - sample.packetsSent = s.packetsSentTotal; - sample.packetsReceived = s.packetsReceivedTotal; - sample.bytesSent = s.bytesSentTotal; - sample.bytesReceived = s.bytesReceivedTotal; - sample.bwSentSecond = s.bandwidthSentLastSecond; - sample.bwReceivedSecond = s.bandwidthReceivedLastSecond; - sample.bwSentMinute = s.bandwidthSentLastMinute; - sample.bwReceivedMinute = s.bandwidthReceivedLastMinute; - return sample; + private void fit() { + pack(); + setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), getHeight()); } - private static Sample kindSample(ConnectionStats s, ConnectionStats.Kind kind) { - Sample sample = new Sample(); - ConnectionStats.KindStats k = s.kind(kind); - if (k == null) return sample; // all fields stay unknown (-1) - sample.packetLoss = k.packetLoss; - sample.packetsSent = k.packetsSent; - sample.packetsReceived = k.packetsReceived; - sample.bytesSent = k.bytesSent; - sample.bytesReceived = k.bytesReceived; - sample.bwSentSecond = k.bandwidthSentLastSecond; - sample.bwReceivedSecond = k.bandwidthReceivedLastSecond; - sample.bwSentMinute = k.bandwidthSentLastMinute; - sample.bwReceivedMinute = k.bandwidthReceivedLastMinute; - return sample; - } + /** A grid of labelled figures, laid out once and refreshed in place. */ + private static final class Rows extends JPanel { + private final JLabel[] values; - // ---- one category tab ---- - - /** Numeric snapshot fed to a {@link KindTab}; -1 means "unknown". */ - private static final class Sample { - double packetLoss = -1; - long packetsSent = -1; - long packetsReceived = -1; - long bytesSent = -1; - long bytesReceived = -1; - long bwSentSecond = -1; - long bwReceivedSecond = -1; - long bwSentMinute = -1; - long bwReceivedMinute = -1; - } - - private static final class KindTab extends JPanel { - private final JLabel packetLoss = value(); - private final JLabel packets = value(); - private final JLabel bytes = value(); - private final JLabel bandwidthSecond = value(); - private final JLabel bandwidthMinute = value(); - - KindTab() { + Rows(List rows) { super(new GridBagLayout()); setBackground(Theme.windowBg()); - setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - int row = 0; - addRow(this, row++, "Packet loss", packetLoss); - addRow(this, row++, "Packets (↑/↓)", packets); - addRow(this, row++, "Transferred (↑/↓)", bytes); - addRow(this, row++, "Bandwidth · last second (↑/↓)", bandwidthSecond); - addRow(this, row, "Bandwidth · last minute (↑/↓)", bandwidthMinute); + values = new JLabel[rows.size()]; + for (int i = 0; i < values.length; i++) { + values[i] = new JLabel(rows.get(i).value()); + values[i].setFont(Theme.uiFont()); + values[i].setForeground(Theme.treeText()); + addRow(i, rows.get(i).label(), values[i]); + } } - void update(Sample s) { - packetLoss.setText(formatLoss(s.packetLoss)); - packets.setText(formatCount(s.packetsSent) + " / " + formatCount(s.packetsReceived)); - bytes.setText(formatBytes(s.bytesSent) + " / " + formatBytes(s.bytesReceived)); - bandwidthSecond.setText(formatRate(s.bwSentSecond) + " / " + formatRate(s.bwReceivedSecond)); - bandwidthMinute.setText(formatRate(s.bwSentMinute) + " / " + formatRate(s.bwReceivedMinute)); + void update(List rows) { + for (int i = 0; i < values.length; i++) values[i].setText(rows.get(i).value()); } - } - // ---- formatting ---- + private void addRow(int row, String label, JLabel valueLabel) { + GridBagConstraints lc = new GridBagConstraints(); + lc.gridx = 0; + lc.gridy = row; + lc.anchor = GridBagConstraints.WEST; + lc.insets = UIScale.scale(new Insets(2, 0, 2, 16)); + JLabel key = new JLabel(label); + key.setFont(Theme.uiFont()); + key.setForeground(new Color(0x5A6B7B)); + add(key, lc); - private static final DecimalFormat GROUPED = new DecimalFormat("#,##0"); - - private static String orDash(String s) { - return (s == null || s.isEmpty()) ? "—" : s; - } - - private static String formatPing(double ms, double deviationMs) { - if (ms < 0) return "—"; - String base = Math.round(ms) + " ms"; - if (deviationMs > 0) base += " (± " + Math.round(deviationMs) + " ms)"; - return base; - } - - private static String formatLoss(double fraction) { - if (fraction < 0) return "—"; - return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; - } - - private static String formatCount(long n) { - return n < 0 ? "—" : GROUPED.format(n); - } - - private static String formatBytes(long bytes) { - if (bytes < 0) return "—"; - if (bytes < 1024) return bytes + " B"; - double kib = bytes / 1024.0; - if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB"; - double mib = kib / 1024.0; - if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB"; - return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB"; - } - - private static String formatRate(long bytesPerSecond) { - return bytesPerSecond < 0 ? "—" : formatBytes(bytesPerSecond) + "/s"; - } - - private static String formatDuration(long ms) { - if (ms < 0) return "—"; - long totalSeconds = ms / 1000; - long days = totalSeconds / 86400; - long hours = (totalSeconds % 86400) / 3600; - long minutes = (totalSeconds % 3600) / 60; - long seconds = totalSeconds % 60; - StringBuilder sb = new StringBuilder(); - if (days > 0) sb.append(days).append("d "); - if (days > 0 || hours > 0) sb.append(hours).append("h "); - if (days > 0 || hours > 0 || minutes > 0) sb.append(minutes).append("m "); - sb.append(seconds).append("s"); - return sb.toString(); + GridBagConstraints vc = new GridBagConstraints(); + vc.gridx = 1; + vc.gridy = row; + vc.weightx = 1; + vc.anchor = GridBagConstraints.WEST; + vc.fill = GridBagConstraints.HORIZONTAL; + vc.insets = UIScale.scale(new Insets(2, 0, 2, 0)); + add(valueLabel, vc); + } } } diff --git a/ts3j b/ts3j index 90bf6e0..a4ce0fe 160000 --- a/ts3j +++ b/ts3j @@ -1 +1 @@ -Subproject commit 90bf6e030c718abf2010e851960bbaaf35483296 +Subproject commit a4ce0feb6120e1e78fd4917243ffb84d2ee6d531