mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 08:42:32 -08:00
Reduce CPU usage on UDP
This commit is contained in:
1 parent
6a82f5a54b
commit
414755fcb1
17 files changed
+296
-109
No files matched your search
@@ -42,6 +42,10 @@ object AppLogger {
|
||||
|
||||
val coroutines = noCoLogger("Coroutines")
|
||||
val console = noCoLogger("Console")
|
||||
// For the UDP receive thread, which blocks on the socket and handles each datagram inline. A
|
||||
// suspend logger would need a coroutine there, and resuming one per packet costs more than the
|
||||
// packet's own work. Same name as udp logger, so its lines read as the rest of the UDP logs
|
||||
val udpReceive = noCoLogger("UDPConnection")
|
||||
|
||||
object ShouldDebug {
|
||||
var skeletonTicks = false
|
||||
|
||||
@@ -233,7 +233,7 @@ class VRChatSettingsCheckBehaviour(
|
||||
|
||||
override fun observe(receiver: TrackingChecklist) {
|
||||
combine(
|
||||
skeleton.context.state.map { state -> state.skeletonHeight },
|
||||
skeleton.context.state.map { state -> state.skeletonHeight }.distinctUntilChanged(),
|
||||
vrcConfigManager.context.state,
|
||||
) { userHeight, vrc -> computeStep(vrc, userHeight) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
@@ -6,14 +6,12 @@ import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.device.Device
|
||||
import dev.slimevr.tracker.Tracker
|
||||
import io.ktor.network.sockets.BoundDatagramSocket
|
||||
import io.ktor.network.sockets.Datagram
|
||||
import io.ktor.network.sockets.InetSocketAddress
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.io.Buffer
|
||||
import kotlinx.io.readByteArray
|
||||
import solarxr_protocol.datatypes.MagnetometerStatus
|
||||
|
||||
data class LastPing(
|
||||
@@ -28,9 +26,6 @@ data class SensorConfigFlags(
|
||||
data class TrackerSensorIds(val trackerId: Int, val sensorId: Int)
|
||||
|
||||
data class UDPConnectionState(
|
||||
// Pre-resolved IP string. InetSocketAddress.hostname triggers a reverse DNS lookup so we
|
||||
// can't derive this on demand; it must be resolved once by the platform (see UdpServer.addressResolver)
|
||||
// and cached here. remoteAddress is kept separately on UDPConnection only for sending datagrams.
|
||||
val address: String,
|
||||
val lastPacket: Long,
|
||||
val lastPacketNum: Long,
|
||||
@@ -61,15 +56,15 @@ class UDPConnection(
|
||||
val appContext: AppContextProvider,
|
||||
val packetEvents: UDPPacketDispatcher,
|
||||
val packetChannel: Channel<PacketEvent<UDPPacket>>,
|
||||
private val socket: BoundDatagramSocket,
|
||||
private val remoteAddress: InetSocketAddress,
|
||||
private val socket: UdpSocket,
|
||||
private val peer: UdpPeer,
|
||||
private val scope: CoroutineScope,
|
||||
) {
|
||||
fun send(packet: UDPPacket) {
|
||||
scope.launch {
|
||||
val buf = Buffer()
|
||||
writePacket(buf, packet)
|
||||
socket.send(Datagram(buf, remoteAddress))
|
||||
socket.send(peer, buf.readByteArray())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,12 +83,12 @@ class UDPConnection(
|
||||
|
||||
companion object {
|
||||
fun create(
|
||||
address: String,
|
||||
socket: BoundDatagramSocket,
|
||||
remoteAddress: InetSocketAddress,
|
||||
peer: UdpPeer,
|
||||
socket: UdpSocket,
|
||||
appContext: AppContextProvider,
|
||||
scope: CoroutineScope,
|
||||
): UDPConnection {
|
||||
val address = peer.address
|
||||
val behaviours = listOf(
|
||||
PacketBehaviour(),
|
||||
PacketLossBehaviour(),
|
||||
@@ -112,7 +107,7 @@ class UDPConnection(
|
||||
)
|
||||
|
||||
val connJob = kotlinx.coroutines.SupervisorJob(scope.coroutineContext[kotlinx.coroutines.Job])
|
||||
val connScope = CoroutineScope(scope.coroutineContext + connJob + kotlinx.coroutines.Dispatchers.Default)
|
||||
val connScope = CoroutineScope(scope.coroutineContext + connJob)
|
||||
|
||||
val context = Context.create(
|
||||
initialState = UDPConnectionState(
|
||||
@@ -147,7 +142,7 @@ class UDPConnection(
|
||||
packetEvents = dispatcher,
|
||||
packetChannel = packetChannel,
|
||||
socket = socket,
|
||||
remoteAddress = remoteAddress,
|
||||
peer = peer,
|
||||
scope = connScope,
|
||||
)
|
||||
conn.startObserving()
|
||||
|
||||
@@ -4,23 +4,17 @@ import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import io.ktor.network.selector.SelectorManager
|
||||
import io.ktor.network.sockets.BoundDatagramSocket
|
||||
import io.ktor.network.sockets.InetSocketAddress
|
||||
import io.ktor.network.sockets.aSocket
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.io.Source
|
||||
import kotlin.time.measureTime
|
||||
|
||||
data class UdpServerState(
|
||||
@@ -45,7 +39,7 @@ class UdpServer(
|
||||
val context: UdpServerContext,
|
||||
// Wall-clock ms, replaceable so tests can run on virtual time
|
||||
val clock: () -> Long = System::currentTimeMillis,
|
||||
private val addressResolver: (InetSocketAddress) -> String,
|
||||
private val bind: UdpBind,
|
||||
) {
|
||||
private var receiveJob: Job? = null
|
||||
|
||||
@@ -86,66 +80,58 @@ class UdpServer(
|
||||
private fun connections() = context.state.value.connections.keys.toList()
|
||||
|
||||
private suspend fun receiveOn(port: Int, appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
val selectorManager = SelectorManager(Dispatchers.IO)
|
||||
val socket = try {
|
||||
aSocket(selectorManager).udp().bind(port = port)
|
||||
bind(port)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.udp.error(e, "Failed to bind the tracker port $port")
|
||||
release(null, selectorManager)
|
||||
return
|
||||
}
|
||||
AppLogger.udp.info("Listening for trackers on port $port")
|
||||
try {
|
||||
while (currentCoroutineContext().isActive) {
|
||||
try {
|
||||
val recvPacket = socket.receive()
|
||||
val took = measureTime {
|
||||
val src = recvPacket.packet
|
||||
val packetId = src.readInt()
|
||||
val packetNumber = src.readLong()
|
||||
val type = PacketType.fromId(packetId) ?: return@measureTime
|
||||
val packetData = readPacket(type, src)
|
||||
|
||||
val remoteAddress = recvPacket.address as? InetSocketAddress ?: return@measureTime
|
||||
val address = addressResolver(remoteAddress)
|
||||
val conn = context.state.value.connections[address]
|
||||
|
||||
val event = PacketEvent(data = packetData, packetNumber = packetNumber)
|
||||
|
||||
if (conn != null) {
|
||||
conn.packetChannel.trySend(event)
|
||||
} else {
|
||||
val newConn = UDPConnection.create(
|
||||
address = address,
|
||||
remoteAddress = remoteAddress,
|
||||
socket = socket,
|
||||
appContext = appContext,
|
||||
scope = scope,
|
||||
)
|
||||
addConnection(address, newConn)
|
||||
newConn.packetChannel.trySend(event)
|
||||
}
|
||||
}
|
||||
if (took.inWholeMilliseconds > 2) {
|
||||
AppLogger.udp.warn("Packet processing took too long (${took.inWholeMilliseconds}ms)")
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: UnsupportedOperationException) {
|
||||
AppLogger.udp.warn("Unsupported operation when processing UDP packet: ${e.message}")
|
||||
} catch (e: Exception) {
|
||||
AppLogger.udp.error(e, "Error processing UDP packet")
|
||||
}
|
||||
}
|
||||
socket.listen { from, payload -> handleDatagram(socket, from, payload, appContext, scope) }
|
||||
} finally {
|
||||
release(socket, selectorManager)
|
||||
release(socket)
|
||||
}
|
||||
}
|
||||
|
||||
// Must also run when cancelled, and the close calls can block
|
||||
private suspend fun release(socket: BoundDatagramSocket?, selectorManager: SelectorManager) = withContext(NonCancellable + Dispatchers.IO) {
|
||||
socket?.close()
|
||||
selectorManager.close()
|
||||
private fun handleDatagram(socket: UdpSocket, from: UdpPeer, src: Source, appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
try {
|
||||
val took = measureTime {
|
||||
val packetId = src.readInt()
|
||||
val packetNumber = src.readLong()
|
||||
val type = PacketType.fromId(packetId) ?: return@measureTime
|
||||
val packetData = readPacket(type, src)
|
||||
|
||||
val conn = context.state.value.connections[from.address]
|
||||
|
||||
val event = PacketEvent(data = packetData, packetNumber = packetNumber)
|
||||
|
||||
if (conn != null) {
|
||||
conn.packetChannel.trySend(event)
|
||||
} else {
|
||||
val newConn = UDPConnection.create(
|
||||
peer = from,
|
||||
socket = socket,
|
||||
appContext = appContext,
|
||||
scope = scope,
|
||||
)
|
||||
addConnection(from.address, newConn)
|
||||
newConn.packetChannel.trySend(event)
|
||||
}
|
||||
}
|
||||
if (took.inWholeMilliseconds > 2) {
|
||||
AppLogger.udpReceive.warn("Packet processing took too long (${took.inWholeMilliseconds}ms)")
|
||||
}
|
||||
} catch (e: UnsupportedOperationException) {
|
||||
AppLogger.udpReceive.warn("Unsupported operation when processing UDP packet: ${e.message}")
|
||||
} catch (e: Exception) {
|
||||
AppLogger.udpReceive.error(e, "Error processing UDP packet")
|
||||
}
|
||||
}
|
||||
|
||||
// Must also run when cancelled, and the close call can block
|
||||
private suspend fun release(socket: UdpSocket) = withContext(NonCancellable + Dispatchers.IO) {
|
||||
socket.close()
|
||||
}
|
||||
|
||||
suspend fun dispose() {
|
||||
@@ -159,7 +145,7 @@ class UdpServer(
|
||||
fun create(
|
||||
scope: CoroutineScope,
|
||||
clock: () -> Long = System::currentTimeMillis,
|
||||
addressResolver: (InetSocketAddress) -> String,
|
||||
bind: UdpBind,
|
||||
): UdpServer {
|
||||
val context = Context.create(
|
||||
initialState = INITIAL_STATE,
|
||||
@@ -168,7 +154,7 @@ class UdpServer(
|
||||
behaviours = listOf(UnknownDeviceExpiryBehaviour()),
|
||||
name = "UdpServer",
|
||||
)
|
||||
val server = UdpServer(context, clock, addressResolver)
|
||||
val server = UdpServer(context, clock, bind)
|
||||
server.startObserving()
|
||||
return server
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.slimevr.udp
|
||||
|
||||
import kotlinx.io.Source
|
||||
|
||||
data class UdpPeer(
|
||||
val address: String,
|
||||
val host: String,
|
||||
val port: Int,
|
||||
)
|
||||
|
||||
interface UdpSocket {
|
||||
/**
|
||||
* Calls [onDatagram] for every datagram, on the socket's own receive thread, until cancelled or
|
||||
* the socket closes. [onDatagram] must not block, as the next datagram waits for it.
|
||||
*/
|
||||
suspend fun listen(onDatagram: (from: UdpPeer, payload: Source) -> Unit)
|
||||
|
||||
suspend fun send(to: UdpPeer, payload: ByteArray)
|
||||
|
||||
suspend fun close()
|
||||
}
|
||||
|
||||
/** Binds the tracker port, provided by each platform. Throws when the port can't be bound */
|
||||
typealias UdpBind = suspend (port: Int) -> UdpSocket
|
||||
Reference in new issue
Block a user