mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-26 11:56:27 -08:00
Speeeeeeeeed
This commit is contained in:
1 parent
b0232ae783
commit
e207abbc31
14 files changed
+308
-203
No files matched your search
@@ -101,8 +101,9 @@ fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScop
|
||||
|
||||
deviceScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
// Reused across reads: parseHIDPackets is told how much of it is live
|
||||
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
|
||||
while (isActive) {
|
||||
val buffer = ByteArray(HID_READ_BUFFER_SIZE)
|
||||
val read = try {
|
||||
hidDevice.read(buffer, HID_READ_TIMEOUT_MS)
|
||||
} catch (_: Exception) {
|
||||
@@ -112,7 +113,7 @@ fun createDesktopHIDManager(appContext: AppContextProvider, scope: CoroutineScop
|
||||
// read error, device gone
|
||||
read < 0 -> return@launch
|
||||
|
||||
read > 0 -> parseHIDPackets(buffer).forEach { receiver.packetEvents.emit(it) }
|
||||
read > 0 -> parseHIDPackets(buffer, read).forEach { receiver.packetEvents.emit(it) }
|
||||
|
||||
// 0 is a timeout with no data: the read already blocked, so just go again
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ suspend fun createUnixDriverSocket(appContext: AppContextProvider) = acceptUnixC
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } },
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ suspend fun createUnixFeederSocket(appContext: AppContextProvider) = acceptUnixC
|
||||
handleDriverConnection(
|
||||
appContext = appContext,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } },
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ suspend fun createUnixSolarXRSocket(appContext: AppContextProvider) = acceptUnix
|
||||
handleSolarXRBridge(
|
||||
appContext = appContext,
|
||||
messages = readFramedMessages(channel),
|
||||
send = { bytes -> withContext(Dispatchers.IO) { writeFramed(channel, bytes) } },
|
||||
send = { bytes -> writeFramed(channel, bytes) },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,28 +7,28 @@ import com.sun.jna.platform.win32.Kernel32
|
||||
import com.sun.jna.platform.win32.WinBase
|
||||
import com.sun.jna.platform.win32.WinError
|
||||
import com.sun.jna.platform.win32.WinNT
|
||||
import com.sun.jna.ptr.IntByReference
|
||||
import com.sun.jna.win32.StdCallLibrary
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import java.io.IOException
|
||||
|
||||
private val k32 = Kernel32.INSTANCE
|
||||
private val k32io = Kernel32IO.INSTANCE
|
||||
|
||||
private const val HEADER_SIZE = 4
|
||||
private const val MAX_FRAME_SIZE = 256 * 1024
|
||||
|
||||
@Suppress("FunctionName")
|
||||
private interface Kernel32IO : StdCallLibrary {
|
||||
fun ReadFile(h: WinNT.HANDLE, buf: Pointer, len: Int, read: IntByReference?, ov: WinBase.OVERLAPPED): Boolean
|
||||
|
||||
fun WriteFile(h: WinNT.HANDLE, buf: Pointer, len: Int, written: IntByReference?, ov: WinBase.OVERLAPPED): Boolean
|
||||
|
||||
fun GetOverlappedResult(h: WinNT.HANDLE, ov: WinBase.OVERLAPPED, moved: IntByReference, wait: Boolean): Boolean
|
||||
|
||||
companion object {
|
||||
val INSTANCE: Kernel32IO = Native.load("kernel32", Kernel32IO::class.java)
|
||||
private object Kernel32IO : StdCallLibrary {
|
||||
init {
|
||||
Native.register(Kernel32IO::class.java, "kernel32")
|
||||
}
|
||||
|
||||
external fun ReadFile(handle: Pointer, buffer: Pointer, len: Int, read: Pointer?, overlapped: Pointer): Boolean
|
||||
|
||||
external fun WriteFile(handle: Pointer, buffer: Pointer, len: Int, written: Pointer?, overlapped: Pointer): Boolean
|
||||
|
||||
external fun GetOverlappedResult(handle: Pointer, overlapped: Pointer, moved: Pointer, wait: Boolean): Boolean
|
||||
|
||||
external fun WaitForSingleObject(handle: Pointer, millis: Int): Int
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,6 +48,14 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
|
||||
private val buffer = Memory(MAX_FRAME_SIZE.toLong())
|
||||
|
||||
// Resolved once. The wrappers have to stay referenced to keep the native memory alive anyway, so
|
||||
// unwrapping them per call would only re-do work. `transferred` replaces an IntByReference that
|
||||
// was allocated on every completion.
|
||||
private val handlePointer = handle.pointer
|
||||
private val eventPointer = event.pointer
|
||||
private val overlappedPointer = overlapped.pointer
|
||||
private val transferred = Memory(4)
|
||||
|
||||
fun awaitClient(): Boolean {
|
||||
// On an overlapped handle ConnectNamedPipe returns straight away, so we do the waiting
|
||||
val connected = k32.ConnectNamedPipe(handle, overlapped)
|
||||
@@ -76,12 +84,13 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
buffer.setInt(0, total)
|
||||
buffer.write(HEADER_SIZE.toLong(), payload, 0, payload.size)
|
||||
|
||||
val written = transfer { k32io.WriteFile(handle, buffer, total, null, overlapped) }
|
||||
val written = transfer { Kernel32IO.WriteFile(handlePointer, buffer, total, null, overlappedPointer) }
|
||||
if (written != total) throw IOException("Pipe write incomplete: $written of $total bytes")
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
buffer.close()
|
||||
transferred.close()
|
||||
k32.CloseHandle(event)
|
||||
}
|
||||
|
||||
@@ -90,7 +99,7 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
while (done < len) {
|
||||
val remaining = len - done
|
||||
val moved = transfer {
|
||||
k32io.ReadFile(handle, buffer.share((at + done).toLong(), remaining.toLong()), remaining, null, overlapped)
|
||||
Kernel32IO.ReadFile(handlePointer, buffer.share((at + done).toLong(), remaining.toLong()), remaining, null, overlappedPointer)
|
||||
}
|
||||
if (moved <= 0) return false
|
||||
done += moved
|
||||
@@ -114,9 +123,8 @@ internal class PipeSlot(private val handle: WinNT.HANDLE) : AutoCloseable {
|
||||
}
|
||||
|
||||
private fun awaitCompletion(): Int {
|
||||
k32.WaitForSingleObject(event, WinBase.INFINITE)
|
||||
val moved = IntByReference()
|
||||
if (!k32io.GetOverlappedResult(handle, overlapped, moved, true)) return -1
|
||||
return moved.value
|
||||
Kernel32IO.WaitForSingleObject(eventPointer, WinBase.INFINITE)
|
||||
if (!Kernel32IO.GetOverlappedResult(handlePointer, overlappedPointer, transferred, true)) return -1
|
||||
return transferred.getInt(0)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import com.squareup.wire.ProtoWriter
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.CURRENT_PLATFORM
|
||||
import dev.slimevr.Platform
|
||||
@@ -24,6 +25,7 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.Buffer
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import java.io.File
|
||||
import java.nio.file.Path
|
||||
@@ -130,8 +132,12 @@ suspend fun handleDriverConnection(
|
||||
) = coroutineScope {
|
||||
val sendMutex = Mutex()
|
||||
|
||||
val encodeBuffer = Buffer()
|
||||
val encodeWriter = ProtoWriter(encodeBuffer)
|
||||
|
||||
suspend fun sendMsg(msg: ProtobufMessage) = sendMutex.withLock {
|
||||
send(ProtobufMessage.ADAPTER.encode(msg))
|
||||
ProtobufMessage.ADAPTER.encode(encodeWriter, msg)
|
||||
send(encodeBuffer.readByteArray())
|
||||
}
|
||||
|
||||
val bridge = DriverBridge.create(
|
||||
|
||||
@@ -75,8 +75,13 @@ suspend fun handleSolarXRBridge(
|
||||
|
||||
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
|
||||
|
||||
// One builder for the life of the connection. clear() keeps the buffer it has already grown into,
|
||||
// so a datafeed frame stops re-growing from 256 bytes every time. Safe to share: this collector
|
||||
// handles one bundle at a time, and moveToByteArray copies the bytes out before send suspends.
|
||||
val fbb = FlatBufferBuilder(256)
|
||||
|
||||
bridge.outbound.on<MessageBundle> { bundle ->
|
||||
val fbb = FlatBufferBuilder(256)
|
||||
fbb.clear()
|
||||
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
|
||||
send(fbb.dataBuffer().moveToByteArray())
|
||||
}.launchIn(this)
|
||||
|
||||
@@ -84,7 +84,7 @@ private suspend fun acceptWindowsClients(
|
||||
|
||||
launch {
|
||||
try {
|
||||
handle(readFrames(pipe)) { bytes -> withContext(Dispatchers.IO) { writer.writeFrame(bytes) } }
|
||||
handle(readFrames(pipe)) { bytes -> writer.writeFrame(bytes) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -32,6 +32,10 @@ import solarxr_protocol.rpc.TrackingChecklistStep
|
||||
import solarxr_protocol.rpc.TrackingChecklistStepId
|
||||
import solarxr_protocol.rpc.TrackingChecklistStepVisibility
|
||||
import java.io.IOException
|
||||
import java.net.ConnectException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeMark
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
data class Process(val pid: ULong, val name: String)
|
||||
|
||||
@@ -80,6 +84,12 @@ private suspend fun getRunningProcesses(): List<Process> = when (CURRENT_PLATFOR
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
// Enumerating every process is orders of magnitude costlier than the loopback request it guards, so it
|
||||
// only runs to disambiguate a refused connection, and only this often.
|
||||
private val PROCESS_SCAN_INTERVAL = 10.seconds
|
||||
|
||||
private fun Throwable.isConnectionRefused(): Boolean = generateSequence(this, Throwable::cause).any { it is ConnectException }
|
||||
|
||||
data class SteamVRDriverState(val connected: Boolean = false, val installed: Boolean = true, val blocked: Boolean = false, val enabled: Boolean = true)
|
||||
|
||||
class SteamVRCheckBehaviour(private val server: VRServer) : TrackingChecklistBehaviourType {
|
||||
@@ -92,41 +102,51 @@ class SteamVRCheckBehaviour(private val server: VRServer) : TrackingChecklistBeh
|
||||
|
||||
override fun observe(receiver: TrackingChecklist) {
|
||||
receiver.context.scope.launch {
|
||||
val client = HttpClient(CIO)
|
||||
while (isActive) {
|
||||
val connected = server.context.state.value.drivers.isNotEmpty()
|
||||
val running = connected ||
|
||||
getRunningProcesses().any { proc ->
|
||||
proc.name == steamVRProcName
|
||||
}
|
||||
HttpClient(CIO).use { client ->
|
||||
var scannedRunning = false
|
||||
var lastScan: TimeMark? = null
|
||||
|
||||
val drivers = if (running) {
|
||||
try {
|
||||
while (isActive) {
|
||||
val connected = server.context.state.value.drivers.isNotEmpty()
|
||||
|
||||
val drivers = try {
|
||||
getSteamVRDriversList(client)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.checklist.warn(e, "Failed to get SteamVR drivers list")
|
||||
if (!e.isConnectionRefused()) {
|
||||
AppLogger.checklist.warn(e, "Failed to get SteamVR drivers list")
|
||||
}
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val driver = drivers?.firstOrNull {
|
||||
it.manifest.name == "slimevr"
|
||||
}
|
||||
val standableDriver = drivers?.firstOrNull {
|
||||
it.manifest.name == "standable"
|
||||
}
|
||||
val scan = lastScan
|
||||
if (drivers != null) {
|
||||
scannedRunning = false
|
||||
lastScan = null
|
||||
} else if (scan == null || scan.elapsedNow() >= PROCESS_SCAN_INTERVAL) {
|
||||
scannedRunning = getRunningProcesses().any { proc ->
|
||||
proc.name == steamVRProcName
|
||||
}
|
||||
lastScan = TimeSource.Monotonic.markNow()
|
||||
}
|
||||
|
||||
driverState.update {
|
||||
SteamVRDriverState(connected = connected, installed = !running || driver != null, driver?.blockedBySafeMode ?: false, enabled = driver?.enabled ?: true)
|
||||
val running = connected || drivers != null || scannedRunning
|
||||
|
||||
val driver = drivers?.firstOrNull {
|
||||
it.manifest.name == "slimevr"
|
||||
}
|
||||
val standableDriver = drivers?.firstOrNull {
|
||||
it.manifest.name == "standable"
|
||||
}
|
||||
|
||||
driverState.update {
|
||||
SteamVRDriverState(connected = connected, installed = !running || driver != null, driver?.blockedBySafeMode ?: false, enabled = driver?.enabled ?: true)
|
||||
}
|
||||
standableState.update {
|
||||
standableDriver != null
|
||||
}
|
||||
delay(3000)
|
||||
}
|
||||
standableState.update {
|
||||
standableDriver != null
|
||||
}
|
||||
delay(3000)
|
||||
}
|
||||
client.close()
|
||||
}
|
||||
|
||||
driverState
|
||||
|
||||
Reference in new issue
Block a user