feat(discovery): 被控端免填 IP,UDP 信标自动发现
- Rust: 新增 discovery::beacon(UDP 41003),被动接收 offer、用包源地址作设备 IP、单播回 host;FFI 增加 ttstd_discovery_start/devices/connect/stop(ABI 3) - Android: 新增 HostBeacon 广播自身并解析 host 应答;ReceiverSession 在 host 为空时等信标再拨号;主界面移除 IP/信令输入框,改为显示发现状态 - Flutter: discover 优先取同网段信标结果并与信令合并去重;connect 先起监听再通知设备拨号;设备卡片标注「UDP 自动发现」 - 视频诊断: 缺少 SPS/PPS 的提示改为收到关键帧后才告警,避免刚接入就误报 - 文档: DEMO 增加发现流程、防火墙与模拟器 NAT 说明及实测截图
This commit is contained in:
1 parent
df2affa9e2
commit
5442dbff2c
13 files changed
+835
-74
No files matched your search
@@ -4,58 +4,48 @@ import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.session.PairingCode
|
||||
import java.net.NetworkInterface
|
||||
|
||||
class MainActivity : Activity() {
|
||||
companion object {
|
||||
private const val REQUEST_CAPTURE = 1001
|
||||
private const val DEFAULT_HOST = "10.0.2.2"
|
||||
private const val DEFAULT_SIGNALING_URL = "http://10.0.2.2:8080"
|
||||
const val EXTRA_HOST = "com.ttstd.lancast.receiver.HOST"
|
||||
const val EXTRA_SIGNALING = "com.ttstd.lancast.receiver.SIGNALING"
|
||||
|
||||
/**
|
||||
* 调试用:`adb shell am start -n com.ttstd.lancast.receiver/.MainActivity -e host 10.0.2.2`
|
||||
* 可跳过自动发现直接指定主控端(模拟器 NAT 环境下信标回包可能到不了设备)。
|
||||
*/
|
||||
private const val EXTRA_HOST = "host"
|
||||
}
|
||||
|
||||
private lateinit var status: TextView
|
||||
private lateinit var hostInput: EditText
|
||||
private lateinit var signalingInput: EditText
|
||||
private lateinit var endpoint: TextView
|
||||
private lateinit var pairing: TextView
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var hostOverride: String = ""
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
hostOverride = intent?.getStringExtra(EXTRA_HOST)?.trim().orEmpty()
|
||||
|
||||
status = TextView(this).apply {
|
||||
text = if (MediaProjectionService.isRunning) "状态:采集中" else "状态:未开始"
|
||||
textSize = 18f
|
||||
text = "状态:未开始"
|
||||
}
|
||||
val initialHost = DEFAULT_HOST
|
||||
val initialSignaling = DEFAULT_SIGNALING_URL
|
||||
hostInput = EditText(this).apply {
|
||||
hint = "主控端 IP"
|
||||
setText(initialHost)
|
||||
isEnabled = false
|
||||
}
|
||||
signalingInput = EditText(this).apply {
|
||||
hint = "信令服务器"
|
||||
setText(initialSignaling)
|
||||
isEnabled = false
|
||||
}
|
||||
val pairing = TextView(this).apply {
|
||||
text = "配对码:生成中..."
|
||||
endpoint = TextView(this).apply {
|
||||
textSize = 13f
|
||||
text = "正在获取本机地址…"
|
||||
}
|
||||
pairing = TextView(this).apply {
|
||||
textSize = 13f
|
||||
text = "配对码:生成中..."
|
||||
}
|
||||
Thread {
|
||||
val ip = try { localIp() } catch (_: Exception) { "" }
|
||||
val text = if (ip.isEmpty()) {
|
||||
"配对码:无法获取本机 IP"
|
||||
} else {
|
||||
"配对码:\n${PairingCode.build(ip, 41001, "")}"
|
||||
}
|
||||
runOnUiThread { pairing.text = text }
|
||||
}.start()
|
||||
val start = Button(this).apply { text = "授权并开始投屏" }
|
||||
val stop = Button(this).apply { text = "停止" }
|
||||
|
||||
@@ -63,18 +53,31 @@ class MainActivity : Activity() {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(48, 64, 48, 48)
|
||||
addView(status)
|
||||
addView(hostInput)
|
||||
addView(signalingInput)
|
||||
addView(endpoint)
|
||||
addView(pairing)
|
||||
addView(start)
|
||||
addView(stop)
|
||||
})
|
||||
|
||||
start.setOnClickListener {
|
||||
if (hostInput.text.toString().trim().isEmpty()) {
|
||||
Toast.makeText(this, "请先填写主控端 IP", Toast.LENGTH_SHORT).show()
|
||||
return@setOnClickListener
|
||||
Thread {
|
||||
val ip = try { localIp() } catch (_: Exception) { "" }
|
||||
val endpointText = if (ip.isEmpty()) {
|
||||
"无法获取本机 IP,请检查网络"
|
||||
} else {
|
||||
"本机 $ip · 主控端自动发现(UDP ${HostBeacon.PORT})"
|
||||
}
|
||||
val pairingText = if (ip.isEmpty()) {
|
||||
"配对码:无法获取本机 IP"
|
||||
} else {
|
||||
"配对码:\n${PairingCode.build(ip, 41001, "")}"
|
||||
}
|
||||
runOnUiThread {
|
||||
endpoint.text = endpointText
|
||||
pairing.text = pairingText
|
||||
}
|
||||
}.start()
|
||||
|
||||
start.setOnClickListener {
|
||||
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE)
|
||||
}
|
||||
@@ -84,12 +87,35 @@ class MainActivity : Activity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
handler.post(refreshStatus)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
handler.removeCallbacks(refreshStatus)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
/** 采集过程中持续刷新「等待主控端 / 已发现主控端」。 */
|
||||
private val refreshStatus = object : Runnable {
|
||||
override fun run() {
|
||||
status.text = when {
|
||||
hostOverride.isNotEmpty() -> "状态:已指定主控端 $hostOverride"
|
||||
!MediaProjectionService.isRunning -> "状态:未开始"
|
||||
MediaProjectionService.discoveredHost.isNotEmpty() ->
|
||||
"状态:采集中 · 已发现主控端 ${MediaProjectionService.discoveredHost}"
|
||||
else -> "状态:采集中 · 等待主控端连接(无需填写 IP)"
|
||||
}
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
|
||||
val host = DEFAULT_HOST
|
||||
val signalingUrl = DEFAULT_SIGNALING_URL
|
||||
MediaProjectionService.start(this, resultCode, data, host, signalingUrl)
|
||||
// host 留空即走 UDP 信标自动发现;信令服务器未配置时传空串。
|
||||
MediaProjectionService.start(this, resultCode, data, hostOverride, "")
|
||||
status.text = "状态:连接中..."
|
||||
}
|
||||
|
||||
|
||||
+27
-1
@@ -35,6 +35,10 @@ class MediaProjectionService : Service() {
|
||||
var isRunning = false
|
||||
private set
|
||||
|
||||
/** 通过 UDP 信标自动发现的主控端地址(空串表示还没发现)。 */
|
||||
val discoveredHost: String
|
||||
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
|
||||
|
||||
fun start(context: Context, resultCode: Int, data: Intent, host: String, signalingUrl: String) {
|
||||
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
||||
action = ACTION_START
|
||||
@@ -59,6 +63,7 @@ class MediaProjectionService : Service() {
|
||||
}
|
||||
|
||||
private var session: ReceiverSession? = null
|
||||
private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -127,10 +132,11 @@ class MediaProjectionService : Service() {
|
||||
}, Handler(Looper.getMainLooper()))
|
||||
}
|
||||
|
||||
startBeacon()
|
||||
session = ReceiverSession(
|
||||
context = this,
|
||||
projection = projection,
|
||||
host = host,
|
||||
hostOverride = host,
|
||||
signalingUrl = signalingUrl,
|
||||
certificatePem = "",
|
||||
)
|
||||
@@ -155,9 +161,29 @@ class MediaProjectionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 开启 UDP 信标:一边广播自身,一边收集主控端的 host 应答。 */
|
||||
private fun startBeacon() {
|
||||
if (beacon != null) return
|
||||
val metrics = resources.displayMetrics
|
||||
val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920)
|
||||
val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080)
|
||||
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
|
||||
beacon = com.ttstd.lancast.receiver.discovery.HostBeacon(
|
||||
device = com.ttstd.lancast.receiver.discovery.HostBeacon.Offer(
|
||||
id = java.util.UUID.randomUUID().toString(),
|
||||
name = "Android Receiver",
|
||||
model = Build.MODEL ?: "Android",
|
||||
resolution = "${width}x$height",
|
||||
),
|
||||
).also { it.start() }
|
||||
}
|
||||
|
||||
private fun stopProjectionSession() {
|
||||
session?.stop()
|
||||
session = null
|
||||
beacon?.stop()
|
||||
beacon = null
|
||||
com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost()
|
||||
isRunning = false
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.ttstd.lancast.receiver.capture.AudioCapturer
|
||||
import com.ttstd.lancast.receiver.capture.ScreenCapturer
|
||||
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
|
||||
import com.ttstd.lancast.receiver.discovery.AnnouncedDevice
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.discovery.NsdAdvertiser
|
||||
import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer
|
||||
import com.ttstd.lancast.receiver.encode.OpusEncoder
|
||||
@@ -23,32 +24,26 @@ import java.util.concurrent.Executors
|
||||
class ReceiverSession(
|
||||
private val context: Context,
|
||||
private val projection: MediaProjection,
|
||||
private val host: String,
|
||||
/** 主控端地址;为空时通过 UDP 信标自动发现(推荐)。 */
|
||||
private val hostOverride: String,
|
||||
private val signalingUrl: String,
|
||||
private val certificatePem: String,
|
||||
private val preferH265: Boolean = false,
|
||||
private val bitrateMbps: Int = 8,
|
||||
) {
|
||||
private val executor = Executors.newFixedThreadPool(2)
|
||||
private val executor = Executors.newFixedThreadPool(3)
|
||||
private val clipboard = ClipboardBridge(context)
|
||||
private val injector = InputInjector(context)
|
||||
private val fileService = FileService(File(context.filesDir, "file-inbox"))
|
||||
private val opusEncoder = OpusEncoder()
|
||||
private val fingerprint: String = ""
|
||||
private val transport = ReceiverTransport(
|
||||
host,
|
||||
41001,
|
||||
41000,
|
||||
41002,
|
||||
fingerprint,
|
||||
certificatePem,
|
||||
injector,
|
||||
clipboard,
|
||||
fileService,
|
||||
)
|
||||
|
||||
@Volatile
|
||||
private var transport: ReceiverTransport? = null
|
||||
|
||||
private val encoder = VideoEncoder { buffer, info ->
|
||||
transport.sendVideo(buffer, info, preferH265)
|
||||
}
|
||||
transport?.sendVideo(buffer, info, preferH265)
|
||||
}
|
||||
|
||||
private var capturer: ScreenCapturer? = null
|
||||
private var audio: AudioCapturer? = null
|
||||
@@ -67,8 +62,7 @@ class ReceiverSession(
|
||||
encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265)
|
||||
val surface = encoder.inputSurface ?: return
|
||||
capturer = ScreenCapturer(projection, surface, metrics.densityDpi).also { it.start(width, height) }
|
||||
transport.start()
|
||||
clipboard.start { text -> transport.sendControl(ControlEvent.Clipboard(text)) }
|
||||
clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) }
|
||||
|
||||
val device = AnnouncedDevice(
|
||||
id = UUID.randomUUID().toString(),
|
||||
@@ -81,14 +75,18 @@ class ReceiverSession(
|
||||
model = Build.MODEL,
|
||||
resolution = "${width}x$height",
|
||||
)
|
||||
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
|
||||
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
|
||||
if (signalingUrl.isNotBlank()) {
|
||||
announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() }
|
||||
}
|
||||
nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() }
|
||||
|
||||
opusEncoder.start()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
audio = AudioCapturer(projection) { pcm ->
|
||||
val current = transport ?: return@AudioCapturer
|
||||
opusEncoder.encode(pcm).forEach { packet ->
|
||||
transport.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
||||
current.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000)
|
||||
}
|
||||
}.also { it.start() }
|
||||
}
|
||||
@@ -99,6 +97,35 @@ class ReceiverSession(
|
||||
Thread.sleep(4)
|
||||
}
|
||||
}
|
||||
executor.execute { connectWhenHostReady() }
|
||||
}
|
||||
|
||||
/** 等主控端地址可用(信标发现或手动覆盖)后再拨号,之后由 transport 自己重连。 */
|
||||
private fun connectWhenHostReady() {
|
||||
while (running) {
|
||||
val target = hostOverride.ifBlank { HostBeacon.lastHost }
|
||||
if (target.isNotEmpty() && transport == null) {
|
||||
val created = ReceiverTransport(
|
||||
target,
|
||||
41001,
|
||||
41000,
|
||||
41002,
|
||||
fingerprint,
|
||||
certificatePem,
|
||||
injector,
|
||||
clipboard,
|
||||
fileService,
|
||||
)
|
||||
transport = created
|
||||
created.start()
|
||||
return
|
||||
}
|
||||
try {
|
||||
Thread.sleep(500)
|
||||
} catch (_: InterruptedException) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
@@ -109,7 +136,8 @@ class ReceiverSession(
|
||||
announcer?.stop()
|
||||
nsdAdvertiser?.stop()
|
||||
opusEncoder.stop()
|
||||
transport.stop()
|
||||
transport?.stop()
|
||||
transport = null
|
||||
encoder.stop()
|
||||
executor.shutdownNow()
|
||||
}
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.ttstd.lancast.receiver.discovery
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.NetworkInterface
|
||||
|
||||
/**
|
||||
* 被控端信标(UDP 41003)。
|
||||
*
|
||||
* 工作方式:
|
||||
* 1. 每 2 秒把本机信息(名称/型号/分辨率/端口)广播到所在网段;
|
||||
* 2. 主控端只被动监听,把「数据包源地址」当作设备 IP,并单播回一条 `host` 报文;
|
||||
* 3. 收到 `host` 后本机就知道该往哪台主控端拨号,用户无需在手机上填任何 IP。
|
||||
*
|
||||
* 广播由本机发起、回包是单播,因此主控端有多块网卡也不需要扫描,Android 侧也不需要
|
||||
* `MulticastLock`(只收单播,不收组播)。
|
||||
*/
|
||||
class HostBeacon(
|
||||
private val device: Offer,
|
||||
private val controlPort: Int = 41001,
|
||||
private val mediaPort: Int = 41000,
|
||||
private val audioPort: Int = 41002,
|
||||
) {
|
||||
/** 广播用的设备自述信息。 */
|
||||
data class Offer(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val model: String,
|
||||
val resolution: String,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val PORT = 41003
|
||||
private const val PROTOCOL = "disc/1"
|
||||
private const val TAG = "HostBeacon"
|
||||
private const val OFFER_INTERVAL_MS = 2000L
|
||||
|
||||
/** 最近一次发现的主控端地址;空串表示还没发现。 */
|
||||
@Volatile
|
||||
var lastHost: String = ""
|
||||
private set
|
||||
|
||||
fun resetHost() {
|
||||
lastHost = ""
|
||||
}
|
||||
}
|
||||
|
||||
/** 发现主控端时回调:(主控端 IP, 是否要求立即连接)。 */
|
||||
@Volatile
|
||||
var onHostLocated: ((String, Boolean) -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
private var running = false
|
||||
private var socket: DatagramSocket? = null
|
||||
private val workers = mutableListOf<Thread>()
|
||||
|
||||
fun start() {
|
||||
if (running) return
|
||||
val datagram = try {
|
||||
DatagramSocket(null).apply {
|
||||
reuseAddress = true
|
||||
broadcast = true
|
||||
bind(InetSocketAddress(PORT))
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "无法监听 UDP $PORT", error)
|
||||
return
|
||||
}
|
||||
socket = datagram
|
||||
running = true
|
||||
workers.clear()
|
||||
workers += newWorker("beacon-offer") { sendLoop(datagram) }
|
||||
workers += newWorker("beacon-host") { receiveLoop(datagram) }
|
||||
Log.i(TAG, "信标已启动,本机 ${localIp()}")
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
try {
|
||||
socket?.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
socket = null
|
||||
workers.forEach { it.interrupt() }
|
||||
workers.clear()
|
||||
}
|
||||
|
||||
private fun newWorker(name: String, body: () -> Unit): Thread =
|
||||
Thread(body, name).apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
|
||||
private fun sendLoop(datagram: DatagramSocket) {
|
||||
val payload = offerPayload()
|
||||
while (running) {
|
||||
for (address in broadcastAddresses()) {
|
||||
try {
|
||||
datagram.send(DatagramPacket(payload, payload.size, address, PORT))
|
||||
} catch (_: Exception) {
|
||||
// 单个网卡发送失败(例如未连接)不影响其它网卡。
|
||||
}
|
||||
}
|
||||
try {
|
||||
Thread.sleep(OFFER_INTERVAL_MS)
|
||||
} catch (_: InterruptedException) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun receiveLoop(datagram: DatagramSocket) {
|
||||
val buffer = ByteArray(2048)
|
||||
while (running) {
|
||||
val packet = DatagramPacket(buffer, buffer.size)
|
||||
try {
|
||||
datagram.receive(packet)
|
||||
} catch (error: Exception) {
|
||||
if (!running) return
|
||||
continue
|
||||
}
|
||||
val text = String(packet.data, 0, packet.length, Charsets.UTF_8)
|
||||
val host = parseHost(text) ?: continue
|
||||
val address = packet.address?.hostAddress ?: continue
|
||||
if (address != lastHost) {
|
||||
lastHost = address
|
||||
Log.i(TAG, "发现主控端 $address")
|
||||
}
|
||||
onHostLocated?.invoke(address, host)
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 `host` 应答,返回是否要求立即连接。 */
|
||||
private fun parseHost(text: String): Boolean? {
|
||||
return try {
|
||||
val json = JSONObject(text)
|
||||
if (json.optString("ttstd") != PROTOCOL) return null
|
||||
if (json.optString("kind") != "host") return null
|
||||
json.optBoolean("connect", false)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun offerPayload(): ByteArray {
|
||||
val json = JSONObject().apply {
|
||||
put("ttstd", PROTOCOL)
|
||||
put("kind", "offer")
|
||||
put("id", device.id)
|
||||
put("name", device.name)
|
||||
put("model", device.model)
|
||||
put("res", device.resolution)
|
||||
put("ctrl", controlPort)
|
||||
put("media", mediaPort)
|
||||
put("audio", audioPort)
|
||||
put("fp", "")
|
||||
put("cap", JSONArray(listOf("h264", "opus", "uibc", "clipboard", "file")))
|
||||
}
|
||||
return json.toString().toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** 有限广播 + 每块网卡的子网广播,覆盖多网卡与 /16、/24 等不同掩码。 */
|
||||
private fun broadcastAddresses(): List<InetAddress> {
|
||||
val result = linkedSetOf<InetAddress>()
|
||||
try {
|
||||
result += InetAddress.getByName("255.255.255.255")
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
try {
|
||||
for (network in NetworkInterface.getNetworkInterfaces()) {
|
||||
if (!network.isUp || network.isLoopback) continue
|
||||
for (address in network.interfaceAddresses) {
|
||||
val broadcast = address.broadcast ?: continue
|
||||
if (broadcast is Inet4Address) result += broadcast
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "枚举网卡失败", error)
|
||||
}
|
||||
return result.toList()
|
||||
}
|
||||
|
||||
private fun localIp(): String = try {
|
||||
NetworkInterface.getNetworkInterfaces().toList()
|
||||
.flatMap { it.inetAddresses.toList() }
|
||||
.firstOrNull { !it.isLoopbackAddress && it is Inet4Address }
|
||||
?.hostAddress ?: ""
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user