mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 08:42:32 -08:00
Fix VRCOSC on windows: new mdns discovery and advertise; proper handling of vrc output port; change to keep advertise of the server receiver even when manual mode is used
This commit is contained in:
1 parent
fe788ed3a7
commit
f84ce0831e
20 files changed
+901
-277
No files matched your search
@@ -0,0 +1,227 @@
|
||||
package dev.slimevr.mdns
|
||||
|
||||
import dev.slimevr.multicast.MulticastBind
|
||||
import dev.slimevr.multicast.MulticastSocket
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.channelFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
private const val MDNS_PORT = 5353
|
||||
private val MDNS_GROUP = byteArrayOf(224.toByte(), 0, 0, 251.toByte())
|
||||
private val MAX_QUERY_INTERVAL = 60.seconds
|
||||
|
||||
data class MdnsDiscoveredService(
|
||||
val name: String,
|
||||
val type: String,
|
||||
val host: String,
|
||||
val port: Int,
|
||||
val addresses: List<String>,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
|
||||
/** Advertises a [type] (e.g. "_oscjson._tcp") service named [name] until cancelled, then says goodbye. */
|
||||
typealias MdnsAdvertise = suspend (type: String, name: String, port: Int, txt: Map<String, String>) -> Nothing
|
||||
|
||||
/** Services of [type] currently on the network, kept up to date (and queried for) while collected. */
|
||||
typealias MdnsBrowse = (type: String) -> Flow<List<MdnsDiscoveredService>>
|
||||
|
||||
interface Mdns {
|
||||
val advertise: MdnsAdvertise
|
||||
val browse: MdnsBrowse
|
||||
}
|
||||
|
||||
private typealias RecordCache = Map<Any, Pair<MdnsRecord, TimeSource.Monotonic.ValueTimeMark>>
|
||||
|
||||
private fun RecordCache.unexpired() = filterValues { (_, expiry) -> !expiry.hasPassedNow() }
|
||||
|
||||
private val ticks = flow {
|
||||
while (true) {
|
||||
emit(Unit)
|
||||
delay(1.seconds)
|
||||
}
|
||||
}
|
||||
|
||||
private enum class MdnsReply { SERVICE, HOST }
|
||||
|
||||
/** What to send back for [question] about [service], null when the question is not about it. */
|
||||
private fun replyFor(question: MdnsQuestion, service: MdnsService): MdnsReply? {
|
||||
fun asks(vararg types: MdnsRecordType) = question.type == MdnsRecordType.ANY || question.type in types
|
||||
return when {
|
||||
question.name.equals(service.type, ignoreCase = true) && asks(MdnsRecordType.PTR) -> MdnsReply.SERVICE
|
||||
question.name.equals(service.instance, ignoreCase = true) && asks(MdnsRecordType.SRV, MdnsRecordType.TXT) -> MdnsReply.SERVICE
|
||||
question.name.equals(service.host, ignoreCase = true) && asks(MdnsRecordType.A) -> MdnsReply.HOST
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun repliesTo(questions: List<MdnsQuestion>, services: List<MdnsService>): List<ByteArray> = questions
|
||||
.flatMap { question -> services.mapNotNull { service -> replyFor(question, service)?.let { service to it } } }
|
||||
.toSet()
|
||||
.map { (service, reply) ->
|
||||
when (reply) {
|
||||
MdnsReply.SERVICE -> buildServiceResponse(service)
|
||||
MdnsReply.HOST -> buildHostResponse(service)
|
||||
}
|
||||
}
|
||||
|
||||
private val MdnsRecord.cacheKey: Any
|
||||
get() = when (this) {
|
||||
is MdnsRecord.Service -> "SRV" to name.lowercase()
|
||||
is MdnsRecord.Text -> "TXT" to name.lowercase()
|
||||
is MdnsRecord.Pointer, is MdnsRecord.Address -> this
|
||||
}
|
||||
|
||||
private fun servicesOf(records: Collection<MdnsRecord>, type: String): List<MdnsDiscoveredService> {
|
||||
val typeName = "$type.local"
|
||||
return records.filterIsInstance<MdnsRecord.Pointer>()
|
||||
.filter { it.name.equals(typeName, ignoreCase = true) }
|
||||
.mapNotNull { pointer ->
|
||||
val srv = records.filterIsInstance<MdnsRecord.Service>().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) }
|
||||
?: return@mapNotNull null
|
||||
MdnsDiscoveredService(
|
||||
name = pointer.target.dropLast(typeName.length + 1),
|
||||
type = type,
|
||||
host = srv.host,
|
||||
port = srv.port,
|
||||
addresses = records.filterIsInstance<MdnsRecord.Address>().filter { it.name.equals(srv.host, ignoreCase = true) }.map { it.address },
|
||||
txt = records.filterIsInstance<MdnsRecord.Text>().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) }?.entries.orEmpty(),
|
||||
)
|
||||
}
|
||||
.distinctBy { it.name }
|
||||
.sortedBy { it.name }
|
||||
}
|
||||
|
||||
/** Questions still needed to resolve [type] instances we only know by PTR, or hosts we have no address for. */
|
||||
private fun missingQuestions(records: Collection<MdnsRecord>, type: String): List<MdnsQuestion> {
|
||||
val typeName = "$type.local"
|
||||
val services = records.filterIsInstance<MdnsRecord.Service>()
|
||||
val pointers = records.filterIsInstance<MdnsRecord.Pointer>().filter { it.name.equals(typeName, ignoreCase = true) }
|
||||
val unresolved = pointers
|
||||
.filter { pointer -> services.none { it.name.equals(pointer.target, ignoreCase = true) } }
|
||||
.map { MdnsQuestion(it.target, MdnsRecordType.SRV) }
|
||||
val addressless = services
|
||||
.filter { srv -> pointers.any { it.target.equals(srv.name, ignoreCase = true) } }
|
||||
.filter { srv -> records.none { it is MdnsRecord.Address && it.name.equals(srv.host, ignoreCase = true) } }
|
||||
.map { MdnsQuestion(it.host, MdnsRecordType.A) }
|
||||
return unresolved + addressless
|
||||
}
|
||||
|
||||
/**
|
||||
* mDNS on the interface owning [address], through one multicast socket opened with [bind] while
|
||||
* anything is advertised or browsed.
|
||||
*
|
||||
* Responses are DNS-SD style: PTR as the answer, SRV/TXT/A as additional records. VRChat
|
||||
* only reads SRV/TXT/A from the additional records and drops responses carrying
|
||||
* them as answers
|
||||
*/
|
||||
fun createMdns(scope: CoroutineScope, address: String, bind: MulticastBind): Mdns {
|
||||
val published = MutableStateFlow<List<MdnsService>>(emptyList())
|
||||
val cache = MutableStateFlow<RecordCache>(emptyMap())
|
||||
|
||||
fun onPacket(opened: MulticastSocket, packet: ByteArray) {
|
||||
val (questions, records) = try {
|
||||
parseQueryQuestions(packet) to parseResponseRecords(packet)
|
||||
} catch (_: IndexOutOfBoundsException) {
|
||||
return // malformed packet from someone else on the network
|
||||
}
|
||||
if (records.isNotEmpty()) {
|
||||
cache.update { current ->
|
||||
records.fold(current.unexpired()) { acc, (record, ttl) ->
|
||||
if (ttl == Duration.ZERO) acc - record.cacheKey else acc + (record.cacheKey to (record to TimeSource.Monotonic.markNow() + ttl))
|
||||
}
|
||||
}
|
||||
}
|
||||
val replies = repliesTo(questions, published.value)
|
||||
if (replies.isNotEmpty()) scope.launch { replies.forEach { opened.send(it) } }
|
||||
}
|
||||
|
||||
val socket = channelFlow {
|
||||
val opened = try {
|
||||
bind(MDNS_GROUP, MDNS_PORT, address)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
send(Result.failure(e))
|
||||
awaitCancellation()
|
||||
}
|
||||
launch { opened.listen { packet -> onPacket(opened, packet) } }
|
||||
try {
|
||||
send(Result.success(opened))
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
withContext(NonCancellable) { opened.close() }
|
||||
cache.value = emptyMap()
|
||||
}
|
||||
}.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||
|
||||
return object : Mdns {
|
||||
override val advertise: MdnsAdvertise = { type, name, port, txt ->
|
||||
val service = MdnsService(
|
||||
type = "$type.local",
|
||||
instance = "$name.$type.local",
|
||||
host = "$name.local",
|
||||
address = address,
|
||||
port = port,
|
||||
txt = txt,
|
||||
)
|
||||
socket.collect { result ->
|
||||
val opened = result.getOrThrow()
|
||||
published.update { it + service }
|
||||
try {
|
||||
// Announce twice, one second apart (RFC 6762 8.3)
|
||||
opened.send(buildServiceResponse(service))
|
||||
delay(1.seconds)
|
||||
opened.send(buildServiceResponse(service))
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
published.update { it - service }
|
||||
withContext(NonCancellable) { opened.send(buildServiceResponse(service, ttl = Duration.ZERO)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override val browse: MdnsBrowse = { type ->
|
||||
channelFlow {
|
||||
socket.collect { result ->
|
||||
val opened = result.getOrThrow()
|
||||
coroutineScope {
|
||||
launch {
|
||||
var interval = 1.seconds
|
||||
while (true) {
|
||||
opened.send(buildQuery("$type.local", MdnsRecordType.PTR))
|
||||
delay(interval)
|
||||
interval = (interval * 2).coerceAtMost(MAX_QUERY_INTERVAL)
|
||||
}
|
||||
}
|
||||
val asked = mutableSetOf<MdnsQuestion>()
|
||||
combine(cache, ticks) { entries, _ -> entries.unexpired().values.map { (record, _) -> record } }
|
||||
.distinctUntilChanged()
|
||||
.collect { records ->
|
||||
missingQuestions(records, type)
|
||||
.filter { asked.add(it) }
|
||||
.forEach { opened.send(buildQuery(it.name, requireNotNull(it.type))) }
|
||||
send(servicesOf(records, type))
|
||||
}
|
||||
}
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package dev.slimevr.mdns
|
||||
|
||||
import kotlinx.io.Buffer
|
||||
import kotlinx.io.readByteArray
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
private const val CLASS_IN = 1
|
||||
|
||||
private val SERVICE_TTL = 75.minutes
|
||||
private val HOST_TTL = 2.minutes
|
||||
|
||||
internal enum class MdnsRecordType(val code: Int) {
|
||||
A(1),
|
||||
PTR(12),
|
||||
TXT(16),
|
||||
SRV(33),
|
||||
ANY(255),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromCode(code: Int) = entries.firstOrNull { it.code == code }
|
||||
}
|
||||
}
|
||||
|
||||
/** One of our published services, with fully qualified names ("…local"). */
|
||||
internal data class MdnsService(
|
||||
val type: String,
|
||||
val instance: String,
|
||||
val host: String,
|
||||
val address: String,
|
||||
val port: Int,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
|
||||
/** [type] is null for record types we never answer. */
|
||||
internal data class MdnsQuestion(val name: String, val type: MdnsRecordType?)
|
||||
|
||||
/** The records we read from other responders; any other type is skipped. */
|
||||
internal sealed interface MdnsRecord {
|
||||
val name: String
|
||||
|
||||
data class Pointer(override val name: String, val target: String) : MdnsRecord
|
||||
data class Service(override val name: String, val port: Int, val host: String) : MdnsRecord
|
||||
data class Text(override val name: String, val entries: Map<String, String>) : MdnsRecord
|
||||
data class Address(override val name: String, val address: String) : MdnsRecord
|
||||
}
|
||||
|
||||
/** A TTL of zero is a goodbye: the record must be forgotten. */
|
||||
internal data class ReceivedRecord(val record: MdnsRecord, val ttl: Duration)
|
||||
|
||||
internal fun buildServiceResponse(service: MdnsService, ttl: Duration = SERVICE_TTL): ByteArray = buildPacket(flags = 0x8400, answers = 1, additional = 3) {
|
||||
writeRecord(service.type, MdnsRecordType.PTR, ttl, encodeName(service.instance))
|
||||
writeRecord(service.instance, MdnsRecordType.TXT, ttl, encodeTxt(service.txt))
|
||||
writeRecord(service.instance, MdnsRecordType.SRV, ttl, encodeSrv(service.port, service.host))
|
||||
writeRecord(service.host, MdnsRecordType.A, if (ttl == Duration.ZERO) Duration.ZERO else HOST_TTL, encodeIpv4(service.address))
|
||||
}
|
||||
|
||||
internal fun buildHostResponse(service: MdnsService): ByteArray = buildPacket(flags = 0x8400, answers = 1) {
|
||||
writeRecord(service.host, MdnsRecordType.A, HOST_TTL, encodeIpv4(service.address))
|
||||
}
|
||||
|
||||
internal fun buildQuery(name: String, type: MdnsRecordType): ByteArray = buildPacket(flags = 0, questions = 1) {
|
||||
write(encodeName(name))
|
||||
writeShort(type.code.toShort())
|
||||
writeShort(CLASS_IN.toShort())
|
||||
}
|
||||
|
||||
private fun buildPacket(flags: Int, questions: Int = 0, answers: Int = 0, additional: Int = 0, body: Buffer.() -> Unit): ByteArray = Buffer().apply {
|
||||
writeShort(0) // id
|
||||
writeShort(flags.toShort())
|
||||
writeShort(questions.toShort())
|
||||
writeShort(answers.toShort())
|
||||
writeShort(0) // authority
|
||||
writeShort(additional.toShort())
|
||||
body()
|
||||
}.readByteArray()
|
||||
|
||||
private fun Buffer.writeRecord(name: String, type: MdnsRecordType, ttl: Duration, data: ByteArray) {
|
||||
write(encodeName(name))
|
||||
writeShort(type.code.toShort())
|
||||
writeShort(CLASS_IN.toShort())
|
||||
writeInt(ttl.inWholeSeconds.toInt())
|
||||
writeShort(data.size.toShort())
|
||||
write(data)
|
||||
}
|
||||
|
||||
private fun encodeName(name: String): ByteArray = Buffer().apply {
|
||||
name.split('.').filter { it.isNotEmpty() }.forEach { label ->
|
||||
val bytes = label.encodeToByteArray()
|
||||
writeByte(bytes.size.toByte())
|
||||
write(bytes)
|
||||
}
|
||||
writeByte(0)
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeTxt(txt: Map<String, String>): ByteArray = Buffer().apply {
|
||||
txt.forEach { (key, value) ->
|
||||
val bytes = "$key=$value".encodeToByteArray()
|
||||
writeByte(bytes.size.toByte())
|
||||
write(bytes)
|
||||
}
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeSrv(port: Int, host: String): ByteArray = Buffer().apply {
|
||||
writeShort(0) // priority
|
||||
writeShort(0) // weight
|
||||
writeShort(port.toShort())
|
||||
write(encodeName(host))
|
||||
}.readByteArray()
|
||||
|
||||
private fun encodeIpv4(address: String): ByteArray {
|
||||
val octets = address.split('.').map { it.toInt() }
|
||||
require(octets.size == 4 && octets.all { it in 0..255 }) { "Not an IPv4 address: $address" }
|
||||
return ByteArray(4) { octets[it].toByte() }
|
||||
}
|
||||
|
||||
private fun ByteArray.isResponse() = u16(2) and 0x8000 != 0
|
||||
|
||||
internal fun parseQueryQuestions(packet: ByteArray): List<MdnsQuestion> {
|
||||
if (packet.size < 12 || packet.isResponse()) return emptyList()
|
||||
var offset = 12
|
||||
return List(packet.u16(4)) {
|
||||
val (name, end) = readName(packet, offset)
|
||||
offset = end + 4 // type + class
|
||||
MdnsQuestion(name, MdnsRecordType.fromCode(packet.u16(end)))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseResponseRecords(packet: ByteArray): List<ReceivedRecord> {
|
||||
if (packet.size < 12 || !packet.isResponse()) return emptyList()
|
||||
var offset = 12
|
||||
repeat(packet.u16(4)) { offset = readName(packet, offset).second + 4 }
|
||||
val count = packet.u16(6) + packet.u16(8) + packet.u16(10)
|
||||
return List(count) {
|
||||
val (name, end) = readName(packet, offset)
|
||||
val type = MdnsRecordType.fromCode(packet.u16(end))
|
||||
val ttl = ((packet.u16(end + 4).toLong() shl 16) or packet.u16(end + 6).toLong()).seconds
|
||||
val length = packet.u16(end + 8)
|
||||
val data = end + 10
|
||||
offset = data + length
|
||||
if (offset > packet.size) throw IndexOutOfBoundsException("mDNS record past end of packet")
|
||||
val record = when (type) {
|
||||
MdnsRecordType.PTR -> MdnsRecord.Pointer(name, readName(packet, data).first)
|
||||
MdnsRecordType.SRV -> MdnsRecord.Service(name, port = packet.u16(data + 4), host = readName(packet, data + 6).first)
|
||||
MdnsRecordType.TXT -> MdnsRecord.Text(name, decodeTxt(packet.copyOfRange(data, offset)))
|
||||
MdnsRecordType.A -> if (length == 4) MdnsRecord.Address(name, (0..3).joinToString(".") { (packet[data + it].toInt() and 0xFF).toString() }) else null
|
||||
else -> null
|
||||
}
|
||||
record?.let { ReceivedRecord(it, ttl) }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun decodeTxt(data: ByteArray): Map<String, String> {
|
||||
val entries = mutableMapOf<String, String>()
|
||||
var offset = 0
|
||||
while (offset < data.size) {
|
||||
val length = data[offset].toInt() and 0xFF
|
||||
val entry = data.copyOfRange(offset + 1, offset + 1 + length).decodeToString()
|
||||
if (entry.isNotEmpty()) entries[entry.substringBefore('=')] = entry.substringAfter('=', "")
|
||||
offset += 1 + length
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
private fun readName(packet: ByteArray, start: Int): Pair<String, Int> {
|
||||
val labels = mutableListOf<String>()
|
||||
var offset = start
|
||||
var end = -1
|
||||
var jumps = 0
|
||||
while (true) {
|
||||
val length = packet[offset].toInt() and 0xFF
|
||||
when {
|
||||
length == 0 -> {
|
||||
if (end < 0) end = offset + 1
|
||||
return labels.joinToString(".") to end
|
||||
}
|
||||
|
||||
length and 0xC0 == 0xC0 -> {
|
||||
if (end < 0) end = offset + 2
|
||||
if (++jumps > 16) throw IndexOutOfBoundsException("mDNS name pointer loop")
|
||||
offset = ((length and 0x3F) shl 8) or (packet[offset + 1].toInt() and 0xFF)
|
||||
}
|
||||
|
||||
else -> {
|
||||
labels += packet.copyOfRange(offset + 1, offset + 1 + length).decodeToString()
|
||||
offset += 1 + length
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ByteArray.u16(offset: Int) = ((this[offset].toInt() and 0xFF) shl 8) or (this[offset + 1].toInt() and 0xFF)
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.slimevr.multicast
|
||||
|
||||
interface MulticastSocket {
|
||||
/** Calls [onPacket] for every datagram received on the group, until the socket closes. */
|
||||
suspend fun listen(onPacket: (ByteArray) -> Unit)
|
||||
|
||||
/** Sends [payload] to the group. */
|
||||
suspend fun send(payload: ByteArray)
|
||||
|
||||
suspend fun close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an IPv4 socket on [port], shared with other processes bound to it, joined to the [group]
|
||||
* multicast address on the interface owning [interfaceAddress]. Provided by each platform.
|
||||
*/
|
||||
typealias MulticastBind = suspend (group: ByteArray, port: Int, interfaceAddress: String) -> MulticastSocket
|
||||
@@ -0,0 +1,27 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.client.plugins.HttpTimeout
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
private val oscQueryHttpClient = HttpClient(CIO) {
|
||||
install(HttpTimeout) {
|
||||
connectTimeoutMillis = 2_000
|
||||
requestTimeoutMillis = 5_000
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OSC port of the OSCQuery host at [address]:[port], read from its HOST_INFO. Only OSC_PORT is read:
|
||||
* the rest varies between implementations (e.g. extension names we don't model).
|
||||
*/
|
||||
suspend fun fetchOscQueryOscPort(address: String, port: Int): Int {
|
||||
val host = if (':' in address) "[$address]" else address
|
||||
val hostInfo = oscQueryJson.parseToJsonElement(oscQueryHttpClient.get("http://$host:$port/?HOST_INFO").bodyAsText())
|
||||
return hostInfo.jsonObject.getValue("OSC_PORT").jsonPrimitive.int
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import com.appstractive.dnssd.DiscoveryEvent
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
|
||||
|
||||
class OscQueryDiscovery(
|
||||
private val discoverServicesFlow: (String) -> Flow<DiscoveryEvent>,
|
||||
private val serviceType: String = OSC_JSON_SERVICE_TYPE,
|
||||
private val serviceFilter: (String) -> Boolean = { true },
|
||||
) {
|
||||
private val mutableServices = MutableStateFlow<List<OscQueryService>>(emptyList())
|
||||
val services: StateFlow<List<OscQueryService>> = mutableServices.asStateFlow()
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
fun start(scope: CoroutineScope) {
|
||||
if (job != null) return
|
||||
job = scope.launch {
|
||||
discoverServicesFlow(serviceType).collect { event ->
|
||||
when (event) {
|
||||
is DiscoveryEvent.Discovered -> {
|
||||
if (!serviceFilter(event.service.name)) return@collect
|
||||
event.resolve()
|
||||
}
|
||||
|
||||
is DiscoveryEvent.Resolved -> onResolved(event)
|
||||
|
||||
is DiscoveryEvent.Removed -> onRemoved(event.service.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun close() {
|
||||
job?.cancelAndJoin()
|
||||
job = null
|
||||
mutableServices.value = emptyList()
|
||||
}
|
||||
|
||||
private fun onRemoved(name: String) {
|
||||
if (!serviceFilter(name)) return
|
||||
mutableServices.value = mutableServices.value.filterNot { entry -> entry.name == name }
|
||||
}
|
||||
|
||||
private suspend fun onResolved(event: DiscoveryEvent.Resolved) {
|
||||
val service = event.service
|
||||
val name = service.name
|
||||
if (!serviceFilter(name)) return
|
||||
|
||||
val resolved = OscQueryService(
|
||||
name = name,
|
||||
addresses = service.addresses,
|
||||
host = service.host,
|
||||
type = service.type,
|
||||
port = service.port,
|
||||
txt = service.txt.mapValues { (_, value) -> value?.decodeToString().orEmpty() },
|
||||
)
|
||||
AppLogger.oscQuery.info(
|
||||
"OSCQuery discovered service: name=$name address=${service.addresses.firstOrNull().orEmpty()} port=${service.port}",
|
||||
)
|
||||
mutableServices.value = mutableServices.value
|
||||
.filterNot { existing -> existing.name == name }
|
||||
.plus(resolved)
|
||||
.sortedBy { entry -> entry.name }
|
||||
}
|
||||
}
|
||||
@@ -84,12 +84,3 @@ data class OscQueryNode(
|
||||
return fullPath.substring(0, parentEnd).ifEmpty { "/" }
|
||||
}
|
||||
}
|
||||
|
||||
data class OscQueryService(
|
||||
val name: String,
|
||||
val addresses: List<String>,
|
||||
val host: String,
|
||||
val type: String,
|
||||
val port: Int,
|
||||
val txt: Map<String, String>,
|
||||
)
|
||||
@@ -1,35 +1,32 @@
|
||||
package dev.slimevr.oscquery
|
||||
|
||||
import com.appstractive.dnssd.NetService
|
||||
import dev.slimevr.mdns.MdnsAdvertise
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.random.Random
|
||||
|
||||
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
|
||||
private const val OSC_UDP_SERVICE_TYPE = "_osc._udp"
|
||||
|
||||
typealias OscQueryServiceFactory = (
|
||||
type: String,
|
||||
name: String,
|
||||
port: Int,
|
||||
priority: Int,
|
||||
weight: Int,
|
||||
addresses: List<String>?,
|
||||
txt: Map<String, String>,
|
||||
) -> NetService
|
||||
|
||||
class OscQueryServer(
|
||||
private val name: String,
|
||||
private val address: String,
|
||||
private var oscPort: UShort,
|
||||
private val serviceFactory: OscQueryServiceFactory,
|
||||
oscPort: UShort,
|
||||
private val advertise: MdnsAdvertise,
|
||||
private val tree: OscQueryTree = OscQueryTree(),
|
||||
private val transport: OscQueryTransport = OscQueryTransport.UDP,
|
||||
) {
|
||||
private val httpServer = OscQueryHttpServer(hostInfo = ::buildHostInfo, tree = tree)
|
||||
private var oscQueryService: NetService? = null
|
||||
private var oscService: NetService? = null
|
||||
private var started = false
|
||||
private val oscPort = MutableStateFlow(oscPort)
|
||||
|
||||
// mDNS instance names must be unique on the network and we don't probe for conflicts
|
||||
// the odds are very low 1 in 16.7 million, if it happens the user can restart the server
|
||||
// TODO: actually check for conflicts someday
|
||||
private val instanceName = "$name-${Random.nextInt(0x1000000).toString(16).uppercase().padStart(6, '0')}"
|
||||
|
||||
val oscQueryPort: UShort
|
||||
get() = httpServer.port
|
||||
@@ -39,65 +36,38 @@ class OscQueryServer(
|
||||
fun removeNode(path: String): Boolean = tree.remove(path)
|
||||
|
||||
suspend fun start(scope: CoroutineScope) {
|
||||
if (started) return
|
||||
val httpPort = httpServer.start(scope)
|
||||
oscQueryService = createOscQueryService(httpPort).also { it.register() }
|
||||
oscService = createOscService(oscPort).also { it.register() }
|
||||
started = true
|
||||
httpServer.start(scope)
|
||||
}
|
||||
|
||||
suspend fun updateOscPort(port: UShort) {
|
||||
if (oscPort == port) return
|
||||
oscPort = port
|
||||
if (!started) return
|
||||
withContext(NonCancellable) {
|
||||
oscService?.unregister()
|
||||
oscService = createOscService(port).also { it.register() }
|
||||
suspend fun advertise(): Nothing {
|
||||
oscPort.collectLatest { port ->
|
||||
coroutineScope {
|
||||
launch {
|
||||
advertise(
|
||||
OSC_JSON_SERVICE_TYPE,
|
||||
instanceName,
|
||||
oscQueryPort.toInt(),
|
||||
mapOf("txtvers" to "1", "osc_transport" to transport.name.lowercase(), "osc_port" to port.toString()),
|
||||
)
|
||||
}
|
||||
advertise(OSC_UDP_SERVICE_TYPE, instanceName, port.toInt(), mapOf("txtvers" to "1", "oscquery_port" to oscQueryPort.toString()))
|
||||
}
|
||||
}
|
||||
awaitCancellation()
|
||||
}
|
||||
|
||||
suspend fun close() {
|
||||
withContext(NonCancellable) {
|
||||
oscService?.unregister()
|
||||
oscService = null
|
||||
oscQueryService?.unregister()
|
||||
oscQueryService = null
|
||||
}
|
||||
fun updateOscPort(port: UShort) {
|
||||
oscPort.value = port
|
||||
}
|
||||
|
||||
fun close() {
|
||||
httpServer.close()
|
||||
started = false
|
||||
}
|
||||
|
||||
private fun createOscQueryService(httpPort: UShort) = createService(
|
||||
type = OSC_JSON_SERVICE_TYPE,
|
||||
name = "$name-$httpPort",
|
||||
port = httpPort.toInt(),
|
||||
txt = mapOf(
|
||||
"txtvers" to "1",
|
||||
"osc_transport" to transport.name.lowercase(),
|
||||
"osc_port" to oscPort.toString(),
|
||||
),
|
||||
)
|
||||
|
||||
private fun createOscService(port: UShort) = createService(
|
||||
type = OSC_UDP_SERVICE_TYPE,
|
||||
name = "$name-$oscQueryPort",
|
||||
port = port.toInt(),
|
||||
txt = mapOf(
|
||||
"txtvers" to "1",
|
||||
"oscquery_port" to oscQueryPort.toString(),
|
||||
),
|
||||
)
|
||||
|
||||
// Pin the advertised address to our resolved local IP. Otherwise dns-sd-kt
|
||||
// falls back to `getLocalAddresses().firstOrNull()` which iterates every NIC
|
||||
// and may pick a virtual / wrong-subnet adapter, making the service
|
||||
// unreachable from headsets on the actual LAN.
|
||||
private fun createService(type: String, name: String, port: Int, txt: Map<String, String>): NetService = serviceFactory(type, name, port, 0, 1, listOf(address), txt)
|
||||
|
||||
private fun buildHostInfo() = OscQueryHostInfo(
|
||||
name = name,
|
||||
oscIp = address,
|
||||
oscPort = oscPort,
|
||||
oscPort = oscPort.value,
|
||||
oscTransport = transport,
|
||||
)
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
package dev.slimevr.vrcosc
|
||||
|
||||
import com.appstractive.dnssd.DiscoveryEvent
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.EventDispatcher
|
||||
import dev.slimevr.context.Behaviour
|
||||
import dev.slimevr.context.Context
|
||||
import dev.slimevr.oscquery.OscQueryServiceFactory
|
||||
import dev.slimevr.mdns.MdnsAdvertise
|
||||
import dev.slimevr.mdns.MdnsBrowse
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.launch
|
||||
import solarxr_protocol.rpc.VRCOSCInputState
|
||||
import solarxr_protocol.rpc.VRCOSCOscQueryState
|
||||
@@ -100,8 +99,8 @@ typealias VRCOSCBehaviour = Behaviour<VRCOSCManager>
|
||||
class VRCOSCManager(
|
||||
val context: VRCOSCContext,
|
||||
val oscQueryAddress: String,
|
||||
private val discoverServicesFlow: (String) -> Flow<DiscoveryEvent>,
|
||||
private val serviceFactory: OscQueryServiceFactory,
|
||||
private val browse: MdnsBrowse,
|
||||
private val advertise: MdnsAdvertise,
|
||||
) {
|
||||
val events: EventDispatcher<VRCOSCEvent> = EventDispatcher("VRCOSC", context.scope, capacity = 32)
|
||||
|
||||
@@ -113,8 +112,8 @@ class VRCOSCManager(
|
||||
VRCOSCOscQueryBehaviour(
|
||||
settings,
|
||||
localIp = oscQueryAddress,
|
||||
discoverServicesFlow = discoverServicesFlow,
|
||||
serviceFactory = serviceFactory,
|
||||
browse = browse,
|
||||
advertise = advertise,
|
||||
),
|
||||
VRCOSCTrackingDataBehaviour(settings),
|
||||
)
|
||||
@@ -133,8 +132,8 @@ class VRCOSCManager(
|
||||
fun create(
|
||||
scope: CoroutineScope,
|
||||
oscQueryAddress: String,
|
||||
discoverServicesFlow: (String) -> Flow<DiscoveryEvent>,
|
||||
serviceFactory: OscQueryServiceFactory,
|
||||
browse: MdnsBrowse,
|
||||
advertise: MdnsAdvertise,
|
||||
): VRCOSCManager {
|
||||
val context = Context.create(
|
||||
initialState = VRCOSCState(),
|
||||
@@ -143,7 +142,7 @@ class VRCOSCManager(
|
||||
behaviours = emptyList<VRCOSCBehaviour>(),
|
||||
name = "VRCOSC",
|
||||
)
|
||||
return VRCOSCManager(context, oscQueryAddress, discoverServicesFlow, serviceFactory)
|
||||
return VRCOSCManager(context, oscQueryAddress, browse, advertise)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,43 @@
|
||||
package dev.slimevr.vrcosc
|
||||
|
||||
import com.appstractive.dnssd.DiscoveryEvent
|
||||
import dev.slimevr.config.DEFAULT_VRC_OSC_PORT_OUT
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.logging.AppLogger
|
||||
import dev.slimevr.mdns.MdnsAdvertise
|
||||
import dev.slimevr.mdns.MdnsBrowse
|
||||
import dev.slimevr.oscquery.OscQueryAccess
|
||||
import dev.slimevr.oscquery.OscQueryDiscovery
|
||||
import dev.slimevr.oscquery.OscQueryNode
|
||||
import dev.slimevr.oscquery.OscQueryServer
|
||||
import dev.slimevr.oscquery.OscQueryServiceFactory
|
||||
import dev.slimevr.oscquery.fetchOscQueryOscPort
|
||||
import dev.slimevr.util.formatExceptionMessage
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import solarxr_protocol.rpc.VRCOSCOscQueryState
|
||||
|
||||
private const val VRCHAT_SERVICE_PREFIX = "VRChat-Client"
|
||||
private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
|
||||
|
||||
class VRCOSCOscQueryBehaviour(
|
||||
private val settings: Settings,
|
||||
private val localIp: String,
|
||||
private val discoverServicesFlow: (String) -> Flow<DiscoveryEvent>,
|
||||
private val serviceFactory: OscQueryServiceFactory,
|
||||
private val browse: MdnsBrowse,
|
||||
private val advertise: MdnsAdvertise,
|
||||
) : VRCOSCBehaviour {
|
||||
private class OscQueryRuntime(
|
||||
val localIp: String,
|
||||
) {
|
||||
var server: OscQueryServer? = null
|
||||
var discovery: OscQueryDiscovery? = null
|
||||
var advertiseJob: Job? = null
|
||||
var discoveryJob: Job? = null
|
||||
}
|
||||
|
||||
@@ -52,21 +56,41 @@ class VRCOSCOscQueryBehaviour(
|
||||
::Pair,
|
||||
)
|
||||
.onEach { (settings, portIn) ->
|
||||
if (!settings.first || settings.second || portIn == null) {
|
||||
val (enabled, useManualNetwork) = settings
|
||||
if (!enabled || portIn == null) {
|
||||
stopOscQuery(receiver, runtime)
|
||||
return@onEach
|
||||
}
|
||||
|
||||
syncOscQueryServer(receiver, runtime, portIn)
|
||||
startDiscovery(receiver, runtime)
|
||||
if (useManualNetwork) {
|
||||
stopDiscovery(receiver, runtime)
|
||||
} else {
|
||||
startDiscovery(receiver, runtime)
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private suspend fun stopOscQuery(receiver: VRCOSCManager, runtime: OscQueryRuntime) {
|
||||
runtime.discoveryJob?.cancel()
|
||||
private suspend fun stopDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) {
|
||||
runtime.discoveryJob?.cancelAndJoin()
|
||||
runtime.discoveryJob = null
|
||||
runtime.discovery?.close()
|
||||
runtime.discovery = null
|
||||
val server = runtime.server ?: return
|
||||
receiver.context.dispatchAll(
|
||||
listOf(
|
||||
VRCOSCActions.SetDiscoveredTargets(emptyList()),
|
||||
VRCOSCActions.SetOscQuery(
|
||||
state = VRCOSCOscQueryState.SEARCHING,
|
||||
advertisedPort = server.oscQueryPort.toInt(),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun stopOscQuery(receiver: VRCOSCManager, runtime: OscQueryRuntime) {
|
||||
runtime.discoveryJob?.cancelAndJoin()
|
||||
runtime.discoveryJob = null
|
||||
runtime.advertiseJob?.cancelAndJoin()
|
||||
runtime.advertiseJob = null
|
||||
try {
|
||||
runtime.server?.close()
|
||||
} catch (e: Exception) {
|
||||
@@ -90,13 +114,27 @@ class VRCOSCOscQueryBehaviour(
|
||||
name = "SlimeVR-Server",
|
||||
address = runtime.localIp,
|
||||
oscPort = portIn.toUShort(),
|
||||
serviceFactory = serviceFactory,
|
||||
advertise = advertise,
|
||||
)
|
||||
arrayOf(HEAD_POSE_SUBPATH, LEFT_WRIST_POSE_SUBPATH, RIGHT_WRIST_POSE_SUBPATH).forEach {
|
||||
newServer.addNode(OscQueryNode("$TRACKING_VRSYSTEM_PATH$it", type = "ffffff", access = OscQueryAccess.WRITE))
|
||||
}
|
||||
withContext(Dispatchers.IO) { newServer.start(receiver.context.scope) }
|
||||
runtime.server = newServer
|
||||
runtime.advertiseJob = receiver.context.scope.launch {
|
||||
try {
|
||||
newServer.advertise()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
dispatchOscQueryError(
|
||||
receiver = receiver,
|
||||
message = "Failed to advertise VRChat OSCQuery",
|
||||
throwable = e,
|
||||
advertisedPort = newServer.oscQueryPort.toInt(),
|
||||
)
|
||||
}
|
||||
}
|
||||
AppLogger.vrc.info("VRChat OSCQuery started on http://${runtime.localIp}:${newServer.oscQueryPort}")
|
||||
receiver.context.dispatch(
|
||||
VRCOSCActions.SetOscQuery(
|
||||
@@ -115,66 +153,54 @@ class VRCOSCOscQueryBehaviour(
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
existing.updateOscPort(portIn.toUShort())
|
||||
} catch (e: Exception) {
|
||||
dispatchOscQueryError(
|
||||
receiver = receiver,
|
||||
message = "Failed to update VRChat OSCQuery port",
|
||||
throwable = e,
|
||||
advertisedPort = existing.oscQueryPort.toInt(),
|
||||
)
|
||||
}
|
||||
existing.updateOscPort(portIn.toUShort())
|
||||
}
|
||||
|
||||
private suspend fun startDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) {
|
||||
if (runtime.discovery != null) return
|
||||
private fun startDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) {
|
||||
if (runtime.discoveryJob != null) return
|
||||
|
||||
val discovery = OscQueryDiscovery(
|
||||
discoverServicesFlow = discoverServicesFlow,
|
||||
serviceFilter = { serviceName -> serviceName.startsWith(VRCHAT_SERVICE_PREFIX) },
|
||||
)
|
||||
runtime.discovery = discovery
|
||||
|
||||
try {
|
||||
discovery.start(receiver.context.scope)
|
||||
} catch (e: Exception) {
|
||||
discovery.close()
|
||||
runtime.discovery = null
|
||||
dispatchOscQueryError(
|
||||
receiver = receiver,
|
||||
message = "Failed to start VRChat OSCQuery discovery",
|
||||
throwable = e,
|
||||
advertisedPort = runtime.server?.oscQueryPort?.toInt(),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
runtime.discoveryJob = discovery.services
|
||||
runtime.discoveryJob = browse(OSC_JSON_SERVICE_TYPE)
|
||||
.map { services -> services.filter { it.name.startsWith(VRCHAT_SERVICE_PREFIX) && it.addresses.isNotEmpty() } }
|
||||
.distinctUntilChanged()
|
||||
.onEach { services ->
|
||||
val targets = services.mapNotNull { service ->
|
||||
val address = service.addresses.firstOrNull().orEmpty().ifEmpty { service.host }
|
||||
if (address.isBlank()) {
|
||||
null
|
||||
} else {
|
||||
VRCOSCDiscoveredTargetInfo(
|
||||
name = service.name,
|
||||
address = address,
|
||||
portOut = DEFAULT_VRC_OSC_PORT_OUT, // TODO should read VRChat's /?HOST_INFO
|
||||
)
|
||||
AppLogger.oscQuery.info("Discovered VRChat clients: ${services.map { "${it.name} ${it.addresses}:${it.port}" }}")
|
||||
val targets = services.map { service ->
|
||||
val address = service.addresses.first()
|
||||
val portOut = try {
|
||||
fetchOscQueryOscPort(address, service.port).also { port ->
|
||||
AppLogger.oscQuery.info("HOST_INFO of ${service.name} at $address:${service.port}: OSC port $port")
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
AppLogger.oscQuery.warn(e, "Could not read HOST_INFO of ${service.name} at $address:${service.port}, assuming OSC port $DEFAULT_VRC_OSC_PORT_OUT")
|
||||
DEFAULT_VRC_OSC_PORT_OUT
|
||||
}
|
||||
VRCOSCDiscoveredTargetInfo(
|
||||
name = service.name,
|
||||
address = address,
|
||||
portOut = portOut,
|
||||
)
|
||||
}
|
||||
val advertisedPort = runtime.server?.oscQueryPort?.toInt()
|
||||
receiver.context.dispatchAll(
|
||||
listOf(
|
||||
VRCOSCActions.SetDiscoveredTargets(targets),
|
||||
VRCOSCActions.SetOscQuery(
|
||||
state = if (targets.isEmpty()) VRCOSCOscQueryState.SEARCHING else VRCOSCOscQueryState.FOUND,
|
||||
advertisedPort = advertisedPort,
|
||||
advertisedPort = runtime.server?.oscQueryPort?.toInt(),
|
||||
),
|
||||
),
|
||||
)
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
.catch { e ->
|
||||
dispatchOscQueryError(
|
||||
receiver = receiver,
|
||||
message = "VRChat OSCQuery discovery failed",
|
||||
throwable = e,
|
||||
advertisedPort = runtime.server?.oscQueryPort?.toInt(),
|
||||
)
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
}
|
||||
|
||||
private suspend fun dispatchOscQueryError(
|
||||
|
||||
Reference in new issue
Block a user