Reduce CPU usage on UDP

This commit is contained in:
loucass003 committed 2026-10-18 01:07:46 +02:00
1 parent 6a82f5a54b
commit 414755fcb1
17 files changed
+296 -109

No files matched your search

@@ -49,14 +49,19 @@ import dev.slimevr.tracker.behaviours.TrackerRotationRefreshBehaviour
import dev.slimevr.tracker.behaviours.TrackerStaleCalibrationBehaviour
import dev.slimevr.tracker.behaviours.TrackerTpsBehaviour
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpPeer
import dev.slimevr.udp.UdpServer
import dev.slimevr.udp.UdpSocket
import dev.slimevr.vmc.VMCManager
import dev.slimevr.vrchat.VRCConfigManager
import dev.slimevr.vrcosc.VRCOSCManager
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.io.Source
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
@@ -277,19 +282,20 @@ private fun buildTestUdpServer(): dev.slimevr.udp.UdpServer {
reducer = ::reduceUdpServer,
name = "TestUdpServer",
)
return dev.slimevr.udp.UdpServer(context) { "127.0.0.1" }.also { it.startObserving() }
return UdpServer(context, bind = ::bindFakeUdp).also { it.startObserving() }
}
class FakeDatagramSocket : io.ktor.network.sockets.BoundDatagramSocket {
override val localAddress: io.ktor.network.sockets.InetSocketAddress = io.ktor.network.sockets.InetSocketAddress("127.0.0.1", 6969)
override val socketContext: kotlinx.coroutines.Job = kotlinx.coroutines.Job()
override val incoming: kotlinx.coroutines.channels.ReceiveChannel<io.ktor.network.sockets.Datagram> = kotlinx.coroutines.channels.Channel()
override val outgoing: kotlinx.coroutines.channels.SendChannel<io.ktor.network.sockets.Datagram> = kotlinx.coroutines.channels.Channel()
override fun close() {}
override suspend fun receive(): io.ktor.network.sockets.Datagram = error("not used")
override suspend fun send(datagram: io.ktor.network.sockets.Datagram) {}
/** A socket that never receives anything and drops what it sends */
class FakeUdpSocket : UdpSocket {
override suspend fun listen(onDatagram: (from: UdpPeer, payload: Source) -> Unit) =
awaitCancellation()
override suspend fun send(to: UdpPeer, payload: ByteArray) {}
override suspend fun close() {}
}
@Suppress("RedundantSuspendModifier")
suspend fun bindFakeUdp(port: Int): UdpSocket = FakeUdpSocket()
abstract class TestAppContext : AppContextProvider {
open override val server: VRServer get() = error("not used in test")
override val featureFlags: FeatureFlags = FeatureFlags()
@@ -1,6 +1,7 @@
package dev.slimevr.firmware
import dev.slimevr.FakeSerialPortWatcher
import dev.slimevr.FakeUdpSocket
import dev.slimevr.VRServer
import dev.slimevr.VRServerActions
import dev.slimevr.buildTestAppContext
@@ -11,6 +12,7 @@ import dev.slimevr.device.Device
import dev.slimevr.device.DeviceActions
import dev.slimevr.serial.FlashingHandler
import dev.slimevr.serial.SerialPortInfo
import dev.slimevr.udp.UdpPeer
import dev.slimevr.udp.reduce
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -341,8 +343,8 @@ class DoSerialFlashTest {
appContext = appContext,
packetEvents = dev.slimevr.EventDispatcher(name = "TestEvents", scope = backgroundScope),
packetChannel = kotlinx.coroutines.channels.Channel(),
socket = dev.slimevr.FakeDatagramSocket(),
remoteAddress = io.ktor.network.sockets.InetSocketAddress("192.168.1.100", 6969),
socket = FakeUdpSocket(),
peer = UdpPeer(address = "192.168.1.100", host = "192.168.1.100", port = 6969),
scope = backgroundScope,
)
appContext.udpServer.addConnection("192.168.1.100", conn)
@@ -1,5 +1,6 @@
package dev.slimevr.provisioning
import dev.slimevr.FakeUdpSocket
import dev.slimevr.VRServer
import dev.slimevr.VRServerActions
import dev.slimevr.buildTestAppContext
@@ -10,6 +11,7 @@ import dev.slimevr.context.Context
import dev.slimevr.device.Device
import dev.slimevr.device.DeviceActions
import dev.slimevr.serial.SerialPortInfo
import dev.slimevr.udp.UdpPeer
import dev.slimevr.udp.reduce
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -82,8 +84,8 @@ private fun connectDevice(vrServer: VRServer, mac: String, scope: CoroutineScope
appContext = appContext,
packetEvents = dev.slimevr.EventDispatcher(name = "TestEvents", scope = scope),
packetChannel = kotlinx.coroutines.channels.Channel(),
socket = dev.slimevr.FakeDatagramSocket(),
remoteAddress = io.ktor.network.sockets.InetSocketAddress("192.168.1.100", 6969),
socket = FakeUdpSocket(),
peer = UdpPeer(address = "192.168.1.100", host = "192.168.1.100", port = 6969),
scope = scope,
)
appContext.udpServer.addConnection("192.168.1.100", conn)
@@ -0,0 +1,47 @@
package dev.slimevr.udp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.io.Buffer
import kotlinx.io.Source
import java.io.IOException
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.ClosedChannelException
import java.nio.channels.DatagramChannel
private fun receiveDatagrams(channel: DatagramChannel, onDatagram: (from: UdpPeer, payload: Source) -> Unit) {
val buffer = ByteBuffer.allocate(65_536)
while (channel.isOpen) {
buffer.clear()
val from = try {
channel.receive(buffer) as? InetSocketAddress ?: continue
} catch (_: ClosedChannelException) {
return
} catch (_: IOException) {
continue
}
buffer.flip()
val peer = UdpPeer(address = "${from.hostString}/${from.port}", host = from.hostString, port = from.port)
onDatagram(peer, Buffer().apply { write(ByteArray(buffer.remaining()).also { buffer.get(it) }) })
}
}
private class TestUdpSocket(val channel: DatagramChannel) : UdpSocket {
override suspend fun listen(onDatagram: (from: UdpPeer, payload: Source) -> Unit) = suspendCancellableCoroutine { continuation ->
Thread({ continuation.resumeWith(runCatching { receiveDatagrams(channel, onDatagram) }) }, "Test UDP receive").apply {
isDaemon = true
start()
}
continuation.invokeOnCancellation { channel.close() }
}
override suspend fun send(to: UdpPeer, payload: ByteArray) {
withContext(Dispatchers.IO) { channel.send(ByteBuffer.wrap(payload), InetSocketAddress(to.host, to.port)) }
}
override suspend fun close() = withContext(Dispatchers.IO) { channel.close() }
}
suspend fun bindTestUdp(port: Int): UdpSocket = withContext(Dispatchers.IO) { TestUdpSocket(DatagramChannel.open().bind(InetSocketAddress(port))) }
@@ -72,7 +72,7 @@ private fun withUdpServer(storage: MemoryStorage, block: suspend (Harness) -> Un
val appContext = object : TestAppContext() {
override val config: AppConfig = config
}
val server = UdpServer.create(scope) { "test" }
val server = UdpServer.create(scope, bind = ::bindTestUdp)
server.startReceiving(appContext, scope)
block(Harness(scope, config, server, failures))
server.dispose()
@@ -1,5 +1,6 @@
package dev.slimevr.udp
import dev.slimevr.bindFakeUdp
import dev.slimevr.solarxr.rpc.createUnknownDevice
import dev.slimevr.util.macAddressToULong
import dev.slimevr.util.udpHardwareId
@@ -66,7 +67,7 @@ class UnknownDevicesTest {
class UnknownDeviceExpiryTest {
@Test
fun `an entry expires a timeout after its last handshake`() = runTest {
val server = UdpServer.create(backgroundScope, clock = { testScheduler.currentTime }) { "test" }
val server = UdpServer.create(backgroundScope, clock = { testScheduler.currentTime }, bind = ::bindFakeUdp)
server.context.dispatch(UdpServerActions.UnknownDeviceSeen(device(lastSeen = testScheduler.currentTime)))
runCurrent()