Solve regressions with KMP

This commit is contained in:
loucass003 committed 2026-05-11 13:13:57 +02:00
1 parent d8041833f1
commit f2b540d0bd
18 files changed
+537 -122

No files matched your search

@@ -39,6 +39,7 @@ interface AppContextProvider : Phase1ContextProvider {
val vmcManager: VMCManager
val vrcOscManager: VRCOSCManager
fun startObserving()
suspend fun dispose()
}
class AppContext(
@@ -69,4 +70,8 @@ class AppContext(
vmcManager.startObserving()
vrcOscManager.startObserving()
}
override suspend fun dispose() {
udpServer.dispose()
}
}
@@ -39,8 +39,13 @@ class BVHRecordingBehaviour(
.distinctUntilChanged()
.onEach { (recording, path) ->
if (recording && stream == null) {
val resolvedPath = resolveBvhPath(storage, path ?: return@onEach) ?: return@onEach
val resolvedPath = resolveBvhPath(storage, path ?: return@onEach)
if (resolvedPath == null) {
receiver.context.dispatch(BVHActions.StopRecording)
return@onEach
}
try {
AppLogger.bvh.info("Opening BVH recording at ${storage.displayPath(resolvedPath)}")
stream = BvhStream(storage.openTextFile(resolvedPath)).also {
it.writeHeader(skeleton.computed.value)
// TODO: we could write the initial T-Pose or whatever here
@@ -51,6 +56,7 @@ class BVHRecordingBehaviour(
}
} else if (!recording && stream != null) {
try {
AppLogger.bvh.info("Finalizing BVH recording")
stream?.close()
} catch (e: Exception) {
AppLogger.bvh.error("Failed to finalize BVH recording", e)
@@ -61,7 +67,12 @@ class BVHRecordingBehaviour(
}.launchIn(receiver.context.scope)
skeleton.computed.onEach { bones ->
stream?.writeFrame(bones)
try {
stream?.writeFrame(bones)
} catch (e: Exception) {
AppLogger.bvh.error("Failed to write BVH frame", e)
receiver.context.dispatch(BVHActions.StopRecording)
}
}.launchIn(receiver.context.scope)
}
}
@@ -8,6 +8,8 @@ import dev.slimevr.skeleton.DEFAULT_BONE_OFFSETS
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import solarxr_protocol.datatypes.BodyPart
private const val FRAME_COUNT_DIGITS = Long.MAX_VALUE.toString().length
@@ -17,55 +19,70 @@ private const val POSITION_SCALE = 1f
class BvhStream(
private val file: TextFileHandle,
) {
private val mutex = Mutex()
private var frameCount = 0L
private var frameCountOffset = 0L
private var frameTimeOffset = 0L
private var lastFrameTime = System.currentTimeMillis()
private val frameIntervals = mutableListOf<Float>()
private var closed = false
suspend fun writeHeader(bones: Map<BodyPart, BoneState>) {
file.write("HIERARCHY\n")
writeBone(BodyPart.HEAD, null, bones, 0)
file.write("MOTION\n")
file.write("Frames: ")
file.flush()
frameCountOffset = file.position()
frameCount = 0L
file.write(getBufferedFrameCount(0L) + "\n")
file.write("Frame Time: ")
file.flush()
frameTimeOffset = file.position()
file.write(getBufferedFrameInterval(0.01f) + "\n")
lastFrameTime = System.currentTimeMillis()
mutex.withLock {
check(!closed) { "BVH stream is closed" }
file.write("HIERARCHY\n")
writeBone(BodyPart.HEAD, null, bones, 0)
file.write("MOTION\n")
file.write("Frames: ")
file.flush()
frameCountOffset = file.position()
frameCount = 0L
file.write(getBufferedFrameCount(0L) + "\n")
file.write("Frame Time: ")
file.flush()
frameTimeOffset = file.position()
file.write(getBufferedFrameInterval(0.01f) + "\n")
lastFrameTime = System.currentTimeMillis()
}
}
suspend fun writeFrame(bones: Map<BodyPart, BoneState>) {
val now = System.currentTimeMillis()
if (frameCount > 0) {
val interval = (now - lastFrameTime) / 1000f
frameIntervals.add(interval)
}
lastFrameTime = now
mutex.withLock {
if (closed) return
val head = bones[BodyPart.HEAD]
val pos = head?.headPosition ?: Vector3.NULL
file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}")
writeRotations(BodyPart.HEAD, bones)
file.write("\n")
frameCount++
val now = System.currentTimeMillis()
if (frameCount > 0) {
val interval = (now - lastFrameTime) / 1000f
frameIntervals.add(interval)
}
lastFrameTime = now
val head = bones[BodyPart.HEAD]
val pos = head?.headPosition ?: Vector3.NULL
file.write("${pos.x * POSITION_SCALE} ${pos.y * POSITION_SCALE} ${pos.z * POSITION_SCALE}")
writeRotations(BodyPart.HEAD, bones)
file.write("\n")
frameCount++
}
}
suspend fun close() {
file.flush()
val avgInterval = if (frameIntervals.isNotEmpty()) frameIntervals.average().toFloat() else 0.01f
mutex.withLock {
if (closed) return
closed = true
file.seek(frameCountOffset)
file.write(getBufferedFrameCount(frameCount))
file.flush()
val avgInterval = if (frameIntervals.isNotEmpty()) frameIntervals.average().toFloat() else 0.01f
file.seek(frameTimeOffset)
file.write(getBufferedFrameInterval(avgInterval))
file.seek(frameCountOffset)
file.write(getBufferedFrameCount(frameCount))
file.close()
file.seek(frameTimeOffset)
file.write(getBufferedFrameInterval(avgInterval))
file.flush()
file.close()
}
}
private fun getBufferedFrameCount(frameCount: Long): String {
@@ -75,9 +75,10 @@ class Context<S, A>(
mutableStateFlow.update { currentState -> reduce(currentState, action) }
return
}
val caller = captureCallerBehaviour()
val before = mutableStateFlow.value
mutableStateFlow.update { currentState -> reduce(currentState, action) }
debugMiddleware.onDispatch(null, before, action, mutableStateFlow.value)
debugMiddleware.onDispatch(caller, before, action, mutableStateFlow.value)
}
fun dispatchAll(actions: List<A>) {
@@ -87,11 +88,12 @@ class Context<S, A>(
}
return
}
val caller = captureCallerBehaviour()
val before = mutableStateFlow.value
mutableStateFlow.update { currentState ->
actions.fold(currentState) { s, action -> reduce(s, action) }
}
debugMiddleware.onDispatchAll(null, before, actions, mutableStateFlow.value)
debugMiddleware.onDispatchAll(caller, before, actions, mutableStateFlow.value)
}
fun <C> observeAll(receiver: C) = behaviours.snapshot().forEach { behaviour ->
@@ -105,6 +107,16 @@ class Context<S, A>(
}
}
private fun captureCallerBehaviour(): String? {
val knownBehaviourClasses = behaviours.snapshot().mapTo(HashSet()) { behaviour ->
behaviour::class.qualifiedName ?: behaviour::class.simpleName.orEmpty()
}
return Throwable().stackTrace
.firstOrNull { frame -> frame.className in knownBehaviourClasses }
?.className
?.substringAfterLast('.')
}
companion object {
fun <S, A> create(
initialState: S,
@@ -114,7 +126,8 @@ class Context<S, A>(
name: String,
): Context<S, A> {
val mutableStateFlow = MutableStateFlow(initialState)
val scopeWithName = CoroutineScope(scope.coroutineContext + CoroutineName(name))
val contextJob = SupervisorJob(scope.coroutineContext[Job])
val scopeWithName = CoroutineScope(scope.coroutineContext + contextJob + CoroutineName(name))
val effectiveDebugMiddleware = if (ContextDebug.enabled) debugMiddleware else null
val context = Context(
mutableStateFlow,
@@ -10,6 +10,8 @@ import io.ktor.network.sockets.aSocket
import io.ktor.network.sockets.openReadChannel
import io.ktor.network.sockets.openWriteChannel
import io.ktor.network.sockets.port
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.ByteWriteChannel
import io.ktor.utils.io.discardExact
import io.ktor.utils.io.readRemaining
import io.ktor.utils.io.writeFully
@@ -17,16 +19,9 @@ import io.ktor.utils.io.core.buildPacket
import io.ktor.utils.io.core.readText
import io.ktor.utils.io.core.writeFully
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.datatypes.DeviceId
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.rpc.FirmwarePart
import solarxr_protocol.rpc.FirmwareUpdateStatus
import java.security.MessageDigest
@@ -87,26 +82,37 @@ private suspend fun otaUpload(
): Boolean {
val socket = withTimeout(30_000) { tcpServer.accept() }
return socket.use {
val output = socket.openWriteChannel(autoFlush = true)
val input = socket.openReadChannel()
var offset = 0
while (offset < firmware.size) {
onProgress(((offset.toDouble() / firmware.size) * 100).toInt())
val chunkLen = min(OTA_CHUNK_SIZE, firmware.size - offset)
output.writeFully(firmware, offset, offset + chunkLen)
offset += chunkLen
withTimeout(1_000) { input.discardExact(4) }
}
output.flush()
val response = withTimeout(10_000) { input.readRemaining().readByteArray().decodeToString() }
response.contains("OK")
uploadFirmware(
output = socket.openWriteChannel(autoFlush = true),
input = socket.openReadChannel(),
firmware = firmware,
onProgress = onProgress,
)
}
}
internal suspend fun uploadFirmware(
output: ByteWriteChannel,
input: ByteReadChannel,
firmware: ByteArray,
onProgress: suspend (Int) -> Unit,
): Boolean {
var offset = 0
while (offset < firmware.size) {
onProgress(((offset.toDouble() / firmware.size) * 100).toInt())
val chunkLen = min(OTA_CHUNK_SIZE, firmware.size - offset)
output.writeFully(firmware, offset, offset + chunkLen)
offset += chunkLen
withTimeout(1_000) { input.discardExact(4) }
}
output.flush()
val response = withTimeout(10_000) { input.readRemaining().readByteArray().decodeToString() }
return response.contains("OK")
}
suspend fun doOtaFlash(
deviceIp: String,
deviceId: DeviceId,
@@ -154,21 +160,7 @@ suspend fun doOtaFlash(
onStatus(FirmwareUpdateStatus.REBOOTING, 0)
// Wait for the device to come back online after reboot.
// flatMapLatest switches to the matched device's own state flow so that status changes,
// which don't emit a new VRServerState, are also observed.
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
val connected = withTimeoutOrNull(60_000) {
server.context.state
.flatMapLatest { state ->
val device = state.devices.values.find { it.context.state.value.id.toUByte() == deviceId.id }
device?.context?.state?.map { it.status != TrackerStatus.DISCONNECTED } ?: flowOf(false)
}
.filter { it }
.first()
}
if (connected == null) {
if (waitForReconnected(server, deviceId) == null) {
onStatus(FirmwareUpdateStatus.ERROR_TIMEOUT, 0)
return
}
@@ -0,0 +1,61 @@
package dev.slimevr.firmware
import dev.slimevr.VRServer
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.datatypes.DeviceId
import solarxr_protocol.datatypes.TrackerStatus
private fun isOnlineStatus(status: TrackerStatus): Boolean = when (status) {
TrackerStatus.NONE,
TrackerStatus.DISCONNECTED,
TrackerStatus.TIMED_OUT,
-> false
else -> true
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun deviceStatusFlow(
server: VRServer,
matches: (Int, String?) -> Boolean,
) = server.context.state.flatMapLatest { state ->
val device = state.devices.values.find { device ->
val deviceState = device.context.state.value
matches(deviceState.id, deviceState.macAddress)
}
device?.context?.state?.map { it.status } ?: flowOf(TrackerStatus.DISCONNECTED)
}
suspend fun waitForConnected(
server: VRServer,
macAddress: String,
timeoutMs: Long = 30_000,
): Boolean? = withTimeoutOrNull(timeoutMs) {
deviceStatusFlow(server) { _, deviceMac -> deviceMac?.uppercase() == macAddress }
.filter(::isOnlineStatus)
.first()
true
}
suspend fun waitForReconnected(
server: VRServer,
deviceId: DeviceId,
timeoutMs: Long = 60_000,
): Boolean? = withTimeoutOrNull(timeoutMs) {
val statuses = deviceStatusFlow(server) { id, _ -> id.toUByte() == deviceId.id }
.distinctUntilChanged()
if (isOnlineStatus(statuses.first())) {
statuses.first { status -> !isOnlineStatus(status) }
}
statuses.first(::isOnlineStatus)
true
}
@@ -9,17 +9,13 @@ import dev.slimevr.serial.SerialConnection
import dev.slimevr.serial.SerialServer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.rpc.FirmwarePart
import solarxr_protocol.rpc.FirmwareUpdateStatus
@@ -32,16 +28,6 @@ fun interface FirmwareFlasher {
)
}
object NoopFirmwareFlasher : FirmwareFlasher {
override suspend fun flash(
portLocation: String,
handler: FlashingHandler,
parts: List<DownloadedFirmwarePart>,
onProgress: (Int) -> Unit,
) = Unit
}
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun doSerialFlash(
portLocation: String,
parts: List<FirmwarePart>,
@@ -212,17 +198,3 @@ internal suspend fun doSerialFlashPostFlash(
onStatus(FirmwareUpdateStatus.DONE, 0)
}
suspend fun waitForConnected(server: VRServer, macAddress: String): Boolean? =
@OptIn(ExperimentalCoroutinesApi::class)
withTimeoutOrNull(30_000) {
server.context.state
.flatMapLatest { state ->
val device =
state.devices.values.find { it.context.state.value.macAddress?.uppercase() == macAddress }
device?.context?.state?.map { it.status != TrackerStatus.DISCONNECTED }
?: flowOf(false)
}
.filter { it }
.first()
}
@@ -4,12 +4,13 @@ import com.appstractive.dnssd.DiscoveryEvent
import com.appstractive.dnssd.discoverServices
import dev.slimevr.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
@@ -17,6 +18,7 @@ private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
class OscQueryDiscovery(
private val serviceType: String = OSC_JSON_SERVICE_TYPE,
private val serviceFilter: (String) -> Boolean = { true },
private val discoverServicesFlow: (String) -> Flow<DiscoveryEvent> = ::discoverServices,
) {
private val mutableServices = MutableStateFlow<List<OscQueryService>>(emptyList())
val services: StateFlow<List<OscQueryService>> = mutableServices.asStateFlow()
@@ -25,11 +27,11 @@ class OscQueryDiscovery(
fun start(scope: CoroutineScope) {
if (job != null) return
job = scope.launch(Dispatchers.Default) {
discoverServices(serviceType).collectLatest { event ->
job = scope.launch {
discoverServicesFlow(serviceType).collect { event ->
when (event) {
is DiscoveryEvent.Discovered -> {
if (!serviceFilter(event.service.name)) return@collectLatest
if (!serviceFilter(event.service.name)) return@collect
event.resolve()
}
@@ -40,8 +42,8 @@ class OscQueryDiscovery(
}
}
fun close() {
job?.cancel()
suspend fun close() {
job?.cancelAndJoin()
job = null
mutableServices.value = emptyList()
}
@@ -192,6 +192,7 @@ object HandshakeBehaviour : UDPConnectionBehaviour {
mcuType = packet.data.mcuType,
firmware = packet.data.firmware ?: firmware,
protocolVersion = packet.data.protocolVersion,
status = TrackerStatus.OK,
)
},
)
@@ -5,10 +5,13 @@ import dev.slimevr.AppLogger
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
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.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.measureTime
@@ -33,6 +36,10 @@ object UdpServerBaseBehaviour : UdpServerBehaviour {
}
class UdpServer(val context: UdpServerContext) {
private var receiveJob: Job? = null
private var socket: BoundDatagramSocket? = null
private var selectorManager: SelectorManager? = null
fun startObserving() = context.observeAll(this)
fun findConnectionForDevice(deviceId: Int): UDPConnection? = context.state.value.connections.values.find { conn ->
@@ -40,12 +47,14 @@ class UdpServer(val context: UdpServerContext) {
}
fun startReceiving(appContext: AppContextProvider, scope: CoroutineScope) {
scope.launch {
if (receiveJob != null) return
receiveJob = scope.launch {
val port = appContext.config.settings.context.state.value.data.trackerPort
val selectorManager = SelectorManager(Dispatchers.IO)
val socket = aSocket(selectorManager).udp().bind(port = port)
launch {
this@UdpServer.selectorManager = selectorManager
this@UdpServer.socket = socket
try {
while (isActive) {
val recvPacket = socket.receive()
val took = measureTime {
@@ -79,10 +88,23 @@ class UdpServer(val context: UdpServerContext) {
AppLogger.udp.warn("Packet processing took too long ${took.inWholeMilliseconds}")
}
}
} finally {
this@UdpServer.receiveJob = null
this@UdpServer.socket = null
this@UdpServer.selectorManager = null
socket.close()
selectorManager.close()
}
}
}
suspend fun dispose() {
socket?.close()
selectorManager?.close()
receiveJob?.cancelAndJoin()
receiveJob = null
}
companion object {
val INITIAL_STATE = UdpServerState(connections = emptyMap())