Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ flowchart LR
## Wire protocol

- Source of truth: `tauri-app/crates/micyou-protocol/proto/network.proto` (prost); the Android mirror is `composeApp/.../network/Protocol.kt` and must stay in sync, magics included (`0x4D696359` control, `0x4D696355` audio)
- TCP carries control frames (connect, mute, ping, pong, and desktop-to-phone stats once a second) with a 1 MiB payload cap enforced on both sides; `connect.platform` tells iOS and Android apart
- TCP carries control frames (connect, mute, ping, pong, desktop-to-phone stats once a second, phone-to-desktop battery reports) with a 1 MiB payload cap enforced on both sides; `connect.platform` tells iOS and Android apart
- UDP carries audio on TCP port + 1; Opus uses 20 ms frames with one FEC packet per group of 12
- Connection modes: **wifi** (LAN, mDNS `_micyou._tcp.`), **usb** (`adb reverse` for Android; for iOS `platform/usbmux.rs` polls usbmuxd and connects to the app listening on the phone, then splices it into the local server; either way connections arrive on loopback, so USB mode listens on 127.0.0.1 only, ignores the saved bind interface and skips mDNS), **web** (axum TLS WebSocket, feature-gated)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,13 @@ class AudioEngine constructor() {
)
val pluginMessages: SharedFlow<PluginMessage> = _pluginMessages.asSharedFlow()

// 桌面端每秒推送的链路质量(MessageWrapper 字段 8);旧桌面不发送,
// 此时保持 null,界面据此隐藏入口。
private val _linkQuality = MutableStateFlow<LinkQuality?>(null)
val linkQuality: Flow<LinkQuality?> = _linkQuality

fun currentLinkQuality(): LinkQuality? = _linkQuality.value

private data class StopResources(
val sessionJob: Job?,
val recorder: AudioRecord?,
Expand Down Expand Up @@ -498,6 +505,7 @@ class AudioEngine constructor() {
lifecycleGeneration++
val sessionGeneration = lifecycleGeneration
_state.value = StreamState.Connecting
_linkQuality.value = null
val sessionJob = lifecycleScope.launch(start = CoroutineStart.LAZY) {
var recorder: AudioRecord? = null
var sessionUdpSocket: DatagramSocket? = null
Expand All @@ -520,6 +528,7 @@ class AudioEngine constructor() {
var output: ByteWriteChannel? = null
var selectorManager: SelectorManager? = null
var closeConnection: () -> Unit = {}
var batteryReporter: BatteryStatusReporter? = null
val sessionJobIdentity = requireNotNull(currentCoroutineContext()[Job])

try {
Expand Down Expand Up @@ -771,6 +780,16 @@ class AudioEngine constructor() {
Logger.d("AudioEngine", "Writer loop stopped")
}

// 电量上报:注册粘性广播时立刻拿到当前电量并发出首包,
// 之后仅在电量/充电状态变化时推送(field 9)。
ContextHelper.getContext()?.let { context ->
batteryReporter = BatteryStatusReporter(context).also { reporter ->
reporter.start { status ->
channel.trySend(MessageWrapper(clientStatus = status))
}
}
}

val readerJob = if (tcpSocket != null) {
launch {
val inChannel = input ?: throw IllegalStateException("TCP input channel unavailable for reader")
Expand Down Expand Up @@ -815,6 +834,16 @@ class AudioEngine constructor() {
wrapper.pluginMessage?.let { pm ->
_pluginMessages.tryEmit(pm)
}

// 桌面端每秒推送的链路质量(field 8)
wrapper.stats?.let { stats ->
_linkQuality.value = LinkQuality(
rttMs = stats.rttMs,
jitterMs = stats.jitterMs,
packetLoss = stats.packetLoss,
latencyMs = stats.latencyMs
)
}
} catch (e: Exception) {
Logger.e("AudioEngine", "Error decoding incoming message", e)
}
Expand Down Expand Up @@ -1048,6 +1077,9 @@ class AudioEngine constructor() {
} finally {
connectionComplete.completeExceptionally(CancellationException("Audio session ended before startup completed"))
Logger.d("AudioEngine", "Cleaning up resources for generation $sessionGeneration")
batteryReporter?.stop()
batteryReporter = null
_linkQuality.value = null
channel.close()
val recorderToRelease = recorder
val recorderStopCompletion = stopAndReleaseRecorderAsync(recorderToRelease)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* MicYou — Turns your Android device into a high-quality PC microphone.
* Copyright (C) 2026 LanRhyme <https://github.com/MicYou-Dev/MicYou>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version, with the MicYou Plugin Exception.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/

package com.lanrhyme.micyou.audio

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import com.lanrhyme.micyou.network.ClientStatusMessage
import com.lanrhyme.micyou.util.Logger

/**
* 读取本机电量并监听变化,把结果作为 `ClientStatusMessage` 上报给桌面端。
*
* 只依赖 `ACTION_BATTERY_CHANGED` 粘性广播:注册时系统立刻回调一次当前值,
* 之后每次电量/充电状态变化再回调,因此调用方无需自己轮询。
*/
class BatteryStatusReporter(private val context: Context) {

private var receiver: BroadcastReceiver? = null

/**
* 开始监听,[onChange] 会在注册时收到一次当前状态,之后仅在变化时回调。
* 该回调可能运行在主线程,实现必须是快速且非阻塞的。
*/
fun start(onChange: (ClientStatusMessage) -> Unit) {
if (receiver != null) return
val callback = object : BroadcastReceiver() {
override fun onReceive(receiverContext: Context?, intent: Intent?) {
val status = read(intent) ?: return
onChange(status)
}
}
receiver = callback
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(callback, IntentFilter(Intent.ACTION_BATTERY_CHANGED), Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("UnspecifiedRegisterReceiverFlag")
context.registerReceiver(callback, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
} catch (e: Exception) {
// 电量上报是锦上添花,注册失败不应拖垮音频会话。
Logger.w("BatteryStatusReporter", "Failed to register battery receiver: ${e.message}")
receiver = null
}
}

fun stop() {
val callback = receiver ?: return
receiver = null
try {
context.unregisterReceiver(callback)
} catch (e: Exception) {
Logger.w("BatteryStatusReporter", "Failed to unregister battery receiver: ${e.message}")
}
}

/** 粘性广播的 extras → 协议字段;读不到时返回 null。 */
private fun read(intent: Intent?): ClientStatusMessage? {
if (intent == null) return null
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
if (level < 0 || scale <= 0) return null
val percent = (level * 100 / scale).coerceIn(0, 100)
val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL
return ClientStatusMessage(batteryLevel = percent, isCharging = charging)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* MicYou — Turns your Android device into a high-quality PC microphone.
* Copyright (C) 2026 LanRhyme <https://github.com/MicYou-Dev/MicYou>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version, with the MicYou Plugin Exception.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/

package com.lanrhyme.micyou.audio

/**
* 桌面端每秒回传一次的链路质量,数据来自桌面接收侧测量
* (micyou-protocol network.proto 的 `StatsMessage`)。
*
* @property rttMs 平滑后的 ping/pong 往返时延,首个 pong 之前为 0
* @property jitterMs 音频包到达抖动(毫秒)
* @property packetLoss 丢包率,0.0 ~ 1.0
* @property latencyMs 端到端估算(接收缓冲 + RTT)
*/
data class LinkQuality(
val rttMs: Int,
val jitterMs: Float,
val packetLoss: Float,
val latencyMs: Int
)
36 changes: 34 additions & 2 deletions composeApp/src/main/kotlin/com/lanrhyme/micyou/network/Protocol.kt
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,31 @@ data class PluginMessage(
}
}

/** 桌面端每秒推送的链路质量(接收侧测量),见 micyou-protocol network.proto StatsMessage */
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class StatsMessage(
@ProtoNumber(1)
val rttMs: Int = 0,
@ProtoNumber(2)
val jitterMs: Float = 0f,
@ProtoNumber(3)
val packetLoss: Float = 0f,
@ProtoNumber(4)
val latencyMs: Int = 0
)

/** 手机上报给桌面的状态(目前只有电量),见 network.proto ClientStatusMessage */
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class ClientStatusMessage(
/** 0-100;-1 表示读不到电量 */
@ProtoNumber(1)
val batteryLevel: Int = -1,
@ProtoNumber(2)
val isCharging: Boolean = false
)

// TCP handshake strings, matching HANDSHAKE_CLIENT_STR / HANDSHAKE_SERVER_STR in micyou-protocol
const val HANDSHAKE_CLIENT = "MicYouCheck1"
const val HANDSHAKE_SERVER = "MicYouCheck2"
Expand Down Expand Up @@ -223,7 +248,8 @@ fun calculateUdpPort(tcpPort: Int): Int {

/** 判断 MessageWrapper 是否包含控制消息(应通过 TCP 发送) */
fun MessageWrapper.hasControlMessage(): Boolean {
return connect != null || mute != null || ping != null || pong != null || pluginMessage != null
return connect != null || mute != null || ping != null || pong != null ||
pluginMessage != null || clientStatus != null
}

@OptIn(ExperimentalSerializationApi::class)
Expand All @@ -242,5 +268,11 @@ data class MessageWrapper(
// Cross-device plugin messaging (micyou-protocol network.proto field 7).
// proto3 skips unknown fields, so legacy desktops simply ignore it.
@ProtoNumber(7)
val pluginMessage: PluginMessage? = null
val pluginMessage: PluginMessage? = null,
// 桌面端每秒推送的链路质量(field 8);旧版本不解析,proto3 会跳过
@ProtoNumber(8)
val stats: StatsMessage? = null,
// 手机上报的电量(field 9);旧桌面同样跳过
@ProtoNumber(9)
val clientStatus: ClientStatusMessage? = null
)
Loading
Loading