diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt index 8a9de56..8439450 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt @@ -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 = "状态:连接中..." } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt index 11ed4f7..c8f1bb6 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt @@ -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 } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt index 6809d97..d4db995 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt @@ -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() } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/HostBeacon.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/HostBeacon.kt new file mode 100644 index 0000000..f7eb8f0 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/HostBeacon.kt @@ -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() + + 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 { + val result = linkedSetOf() + 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) { + "" + } +} diff --git a/docs/DEMO.md b/docs/DEMO.md index 4d228e4..c7e12af 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -10,6 +10,30 @@ 4. **libopus JNI 骨架**:`app/src/main/cpp` 预留 native 编码入口,native 库未接入源码时自动回退 Android `MediaCodec`。 5. **签名变体**:aosp/zhanxun 使用平台签名并声明 `android.uid.system`,neutral 使用 keypub 普通签名。 6. **真实视频画面**:Rust Core 把解包后的视频访问单元排队,Windows runner 内嵌插件用 Media Foundation 解码成 BGRA,经 Flutter 外部纹理渲染到 `VideoView`。 +7. **免填 IP 自动发现**:被控端周期性 UDP 广播 `offer`,主控端被动监听并用「包的源地址」作为设备 IP,再单播回 `host` 报文告知自己的端口;两端都从数据包里学到对方地址,不再需要手工填写 IP 或依赖信令服务器。 + +## 自动发现(UDP 41003,无需填写 IP) + +``` +Android(被控端) Windows(主控端) + 每 2s 广播 offer ──────────────────────────────▶ 0.0.0.0:41003 被动接收 + {id,name,model,res,ctrl,media,audio,cap} 用「源地址」当设备 IP → 设备列表 + 收到 host 记下主控端 IP ◀────────────────────── 单播回 host{ctrl,media,audio,connect} + 用户点开始投屏后自动拨 TCP 41001 ───────────────▶ demo_server 接受连接、开视频/音频 +``` + +- **为什么不扫描网卡**:广播由被控端发起,主控端只监听 + 单播应答。主控端有多块网卡(有线/无线/虚拟网卡)时接收不受影响,也不需要枚举掩码算广播地址;被控端用 `NetworkInterface` 拿到每块网卡的 `InterfaceAddress.broadcast`,再补一条 `255.255.255.255`。 +- **不用 `MulticastLock`**:被控端只发广播、收单播,属于单播接收,不受 Wi-Fi 省电过滤影响。 +- **点击「连接」时**:主控端先确保本机 41001/41000/41002 在监听,再向该设备单播一次 `host{connect:true}`,被控端立刻拨号,不必等下一次广播(最多省 2 秒)。 +- **跨网段**:UDP 广播不出路由器,跨网段仍走原有 HTTP 信令(`signaling_server`,默认 8080)。 +- **防火墙**:Windows 需放行本程序的入站 UDP 41003(与已有的 41000/TCP 41001 同属一个程序,首次允许后即可)。 + +> 模拟器(QEMU NAT,被控端地址形如 10.0.2.15)里主控端看到的源地址是 127.0.0.1,列表会显示 127.0.0.1;这是 NAT 假象,真机同一 Wi-Fi 下显示的是设备真实 IP。调试时可用 +> `adb shell am start -n com.ttstd.lancast.receiver/.MainActivity -e host 10.0.2.2` 跳过自动发现直接指定主控端。 + +实测:被控端点「授权并开始投屏」后,主控端无需任何输入,约 1 秒内出现设备,点「连接」即出图。 + +![自动发现并出图](images/auto-discovery.png) ## 视频画面链路(Windows 主控端) diff --git a/docs/images/auto-discovery.png b/docs/images/auto-discovery.png new file mode 100644 index 0000000..87848fd Binary files /dev/null and b/docs/images/auto-discovery.png differ diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart index a9904b2..62ba54d 100644 --- a/flutter_sender/lib/core/bridge.dart +++ b/flutter_sender/lib/core/bridge.dart @@ -37,14 +37,28 @@ class SenderBridge { .distinct(); } + /// 发现设备:优先用同网段 UDP 信标(被控端广播、主控端被动收集,无需填 IP), + /// 信令服务器只作为跨网段兜底。 Future> discover({String? signalingUrl}) async { + final devices = []; + final native = _native; + if (native != null) { + try { + native.startDiscovery(); + devices.addAll(DeviceInfo.listFromJson(native.discoveryDevices())); + } on Object { + // 信标不可用(端口被占用等)时退化为信令发现。 + } + } if (signalingUrl != null && signalingUrl.trim().isNotEmpty) { - final discovered = await DiscoveryClient.listDevices(signalingUrl); - if (discovered.isNotEmpty) return discovered; - } - if (_native != null) { - return const []; + for (final device in await DiscoveryClient.listDevices(signalingUrl)) { + final duplicated = devices.any( + (item) => item.ip == device.ip && item.controlPort == device.controlPort, + ); + if (!duplicated) devices.add(device); + } } + if (devices.isNotEmpty || native != null) return devices; try { final raw = await _method.invokeListMethod('discover'); if (raw == null || raw.isEmpty) return const []; @@ -92,7 +106,11 @@ class SenderBridge { Future connect(DeviceInfo device) async { final native = _native; if (native != null) { + // 先确保本机控制/媒体端口在监听,再让被控端立刻拨号(不必等它下次广播)。 native.startDemoServer(); + if (device.ip.isNotEmpty) { + native.discoveryConnect(device.ip); + } return; } await _invokeIgnoringMissing('connect', device.toJson()); diff --git a/flutter_sender/lib/core/native_core.dart b/flutter_sender/lib/core/native_core.dart index d0c1a30..1583753 100644 --- a/flutter_sender/lib/core/native_core.dart +++ b/flutter_sender/lib/core/native_core.dart @@ -97,6 +97,15 @@ class NativeCore { late final DartDemoSendControlFn _demoSendControl = _library .lookup>('ttstd_demo_send_control') .asFunction(); + late final DartDiscoveryStartFn _discoveryStart = _library + .lookup>('ttstd_discovery_start') + .asFunction(); + late final DartDiscoveryDevicesFn _discoveryDevices = _library + .lookup>('ttstd_discovery_devices') + .asFunction(); + late final DartDiscoveryConnectFn _discoveryConnect = _library + .lookup>('ttstd_discovery_connect') + .asFunction(); bool get isAvailable => !_disposed; @@ -209,6 +218,37 @@ class NativeCore { } } + /// 启动同网段自动发现(UDP 41003 信标),幂等。 + bool startDiscovery({ + int controlPort = 41001, + int mediaPort = 41000, + int audioPort = 41002, + }) { + return _discoveryStart(controlPort, mediaPort, audioPort) == ok; + } + + /// 同网段已发现的设备(字段与信令 `/list` 的 devices 一致)。 + List discoveryDevices() { + final out = calloc(65536); + try { + final written = _discoveryDevices(out, 65536); + _check(written, 'ttstd_discovery_devices'); + final decoded = jsonDecode(utf8.decode(_copy(out, written))); + if (decoded is! Map) return const []; + final devices = decoded['devices']; + return devices is List ? devices : const []; + } finally { + calloc.free(out); + } + } + + /// 通知指定设备「主控端已就绪」,让它主动拨号接入。 + bool discoveryConnect(String ip) { + final bytes = utf8.encode(ip.trim()); + if (bytes.isEmpty) return false; + return _withBytes(bytes, (ptr) => _discoveryConnect(ptr, bytes.length) == ok); + } + void dispose() => _disposed = true; void _check(int code, String symbol) { @@ -395,3 +435,9 @@ typedef NativeDemoSendControlFn = Int32 Function( typedef DartDemoSendControlFn = int Function( int, int, Pointer, int, ); +typedef NativeDiscoveryStartFn = Int32 Function(Uint16, Uint16, Uint16); +typedef DartDiscoveryStartFn = int Function(int, int, int); +typedef NativeDiscoveryDevicesFn = Int32 Function(Pointer, UintPtr); +typedef DartDiscoveryDevicesFn = int Function(Pointer, int); +typedef NativeDiscoveryConnectFn = Int32 Function(Pointer, UintPtr); +typedef DartDiscoveryConnectFn = int Function(Pointer, int); diff --git a/flutter_sender/lib/features/discovery/device_list.dart b/flutter_sender/lib/features/discovery/device_list.dart index c5081d5..bcdd457 100644 --- a/flutter_sender/lib/features/discovery/device_list.dart +++ b/flutter_sender/lib/features/discovery/device_list.dart @@ -133,8 +133,14 @@ class _DeviceCard extends StatelessWidget { ], ), const SizedBox(height: 6), - Text('指纹 ${device.shortFingerprint} · ${device.resolution}', - style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.outline)), + Text( + [ + if (device.fingerprint.isNotEmpty) '指纹 ${device.shortFingerprint}', + if (device.resolution.isNotEmpty) device.resolution, + 'UDP 自动发现', + ].join(' · '), + style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.outline), + ), ], ), ), @@ -159,7 +165,8 @@ class _EmptyState extends StatelessWidget { const Text('未发现设备'), const SizedBox(height: 4), Text( - '本机监听端点已移至设置;请确认被控端与主控端处于同一网段', + '被控端开启投屏后会自动出现(UDP 41003 自动发现,无需填写 IP)\n' + '若长时间未出现,请确认两端在同一网段且防火墙放行 UDP 41003', style: Theme.of(context).textTheme.bodySmall, textAlign: TextAlign.center, ), diff --git a/flutter_sender/windows/runner/video_texture.cpp b/flutter_sender/windows/runner/video_texture.cpp index 9a72f2a..96db538 100644 --- a/flutter_sender/windows/runner/video_texture.cpp +++ b/flutter_sender/windows/runner/video_texture.cpp @@ -880,10 +880,10 @@ class VideoTexturePlugin : public flutter::Plugin { map[flutter::EncodableValue("pts")] = flutter::EncodableValue(static_cast(frames_->pts())); std::string error = api_.error() + decoder_.error(); - if (error.empty() && !saw_codec_config_.load() && received_.load() >= 15 && + if (error.empty() && !saw_codec_config_.load() && keyframes_.load() > 0 && frames_->frames() == 0) { - // 裸流缺少 SPS/PPS 时解码器会一直「吃数据不出图」且不报错, - // 这里显式指出,避免和「没收到码流」混为一谈。 + // 关键帧都收到了却始终没有 SPS/PPS,解码器会一直「吃数据不出图」且不报错, + // 这里显式指出,避免和「还没等到关键帧」或「没收到码流」混为一谈。 error = "被控端码流缺少 SPS/PPS,请更新被控端 APK 后重连"; } map[flutter::EncodableValue("error")] = flutter::EncodableValue(error); diff --git a/rust_core/src/discovery/beacon.rs b/rust_core/src/discovery/beacon.rs new file mode 100644 index 0000000..13b759e --- /dev/null +++ b/rust_core/src/discovery/beacon.rs @@ -0,0 +1,340 @@ +//! 同网段自动发现(UDP 41003 信标)。 +//! +//! 协议只有两种报文,都是单行 JSON: +//! +//! - `offer`:被控端周期性广播的设备自述(含 id/名称/端口/型号/分辨率)。 +//! - `host`:主控端对 offer 的单播应答(含主控端控制/媒体端口,可选 `connect` 请求)。 +//! +//! 关键点:**双方都用「数据包的源地址」当作对方 IP**。 +//! 因此主控端不需要枚举/扫描本机所有网卡,被控端也不需要任何人手工填写主控端地址; +//! 一次 UDP 往返就能让两端互相认识。广播由被控端发起,主控端只被动监听 + 单播回包, +//! 所以主控端多网卡(有线 + 无线 + 虚拟网卡)时也不会漏收。 + +use std::collections::HashMap; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::thread; +use std::time::{Duration, Instant}; + +use crate::json::{self, JsonValue}; + +/// 信标 UDP 端口(与 Android 侧 `HostBeacon.PORT` 一致)。 +pub const BEACON_PORT: u16 = 41003; +/// 协议标识,出现在每个报文的 `ttstd` 字段里。 +pub const PROTOCOL: &str = "disc/1"; +/// 设备超过该时长没有任何广播即从列表剔除。 +const DEVICE_TTL: Duration = Duration::from_secs(12); +/// 单个对端的最小应答间隔,避免 offer 密集时回包风暴。 +const REPLY_INTERVAL: Duration = Duration::from_secs(1); + +/// 已发现的被控端。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BeaconDevice { + pub device_id: String, + pub name: String, + pub ip: String, + pub control_port: u16, + pub media_port: u16, + pub audio_port: u16, + pub fingerprint: String, + pub capabilities: Vec, + pub model: String, + pub resolution: String, +} + +/// 解析被控端广播;`ip` 由调用方用数据包源地址填入。 +pub fn parse_offer(text: &str, ip: &str) -> Option { + let value = json::parse(text).ok()?; + if value.get("ttstd").and_then(JsonValue::as_str) != Some(PROTOCOL) { + return None; + } + if value.get("kind").and_then(JsonValue::as_str) != Some("offer") { + return None; + } + Some(BeaconDevice { + device_id: text_field(&value, "id").unwrap_or_else(|| ip.to_string()), + name: text_field(&value, "name").unwrap_or_else(|| "Android 设备".to_string()), + ip: ip.to_string(), + control_port: port_field(&value, "ctrl").unwrap_or(41001), + media_port: port_field(&value, "media").unwrap_or(41000), + audio_port: port_field(&value, "audio").unwrap_or(41002), + fingerprint: text_field(&value, "fp").unwrap_or_default(), + capabilities: value + .get("cap") + .and_then(JsonValue::as_array) + .map(|items| { + items + .iter() + .filter_map(JsonValue::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(), + model: text_field(&value, "model").unwrap_or_default(), + resolution: text_field(&value, "res").unwrap_or_default(), + }) +} + +/// 构造主控端应答报文。 +pub fn encode_host(connect: bool, control_port: u16, media_port: u16, audio_port: u16) -> String { + let mut value = JsonValue::object(); + value.insert("ttstd", JsonValue::from(PROTOCOL)); + value.insert("kind", JsonValue::from("host")); + value.insert("ctrl", JsonValue::from(control_port as u64)); + value.insert("media", JsonValue::from(media_port as u64)); + value.insert("audio", JsonValue::from(audio_port as u64)); + value.insert("connect", JsonValue::from(connect)); + value.encode() +} + +fn text_field(value: &JsonValue, key: &str) -> Option { + value + .get(key) + .and_then(JsonValue::as_str) + .filter(|text| !text.is_empty()) + .map(str::to_string) +} + +fn port_field(value: &JsonValue, key: &str) -> Option { + let number = value.get(key).and_then(JsonValue::as_u64)?; + if number == 0 || number > u16::MAX as u64 { + return None; + } + Some(number as u16) +} + +struct Beacon { + socket: UdpSocket, + control_port: u16, + media_port: u16, + audio_port: u16, + devices: Mutex>, + replies: Mutex>, + running: AtomicBool, +} + +static BEACON: OnceLock> = OnceLock::new(); + +/// 启动信标监听(幂等)。返回是否处于运行状态。 +pub fn start(control_port: u16, media_port: u16, audio_port: u16) -> bool { + if let Some(existing) = BEACON.get() { + return existing.is_some(); + } + let created = match UdpSocket::bind(("0.0.0.0", BEACON_PORT)) { + Ok(socket) => { + let _ = socket.set_broadcast(true); + let beacon: &'static Beacon = Box::leak(Box::new(Beacon { + socket, + control_port, + media_port, + audio_port, + devices: Mutex::new(HashMap::new()), + replies: Mutex::new(HashMap::new()), + running: AtomicBool::new(true), + })); + beacon.spawn_receiver(); + Some(beacon) + } + Err(_) => None, + }; + let available = created.is_some(); + let _ = BEACON.set(created); + available +} + +/// 停止接收(释放端口,供测试与退出使用)。 +pub fn stop() { + if let Some(Some(beacon)) = BEACON.get() { + beacon.running.store(false, Ordering::Relaxed); + } +} + +/// 已发现设备列表 JSON,字段与信令 `/list` 的 devices 保持一致。 +pub fn devices_json() -> String { + let Some(Some(beacon)) = BEACON.get() else { + return "{\"devices\":[]}".to_string(); + }; + let mut root = JsonValue::object(); + let mut list = Vec::new(); + for device in beacon.snapshot() { + let mut value = JsonValue::object(); + value.insert("deviceId", JsonValue::from(device.device_id.as_str())); + value.insert("name", JsonValue::from(device.name.as_str())); + value.insert("ip", JsonValue::from(device.ip.as_str())); + value.insert("controlPort", JsonValue::from(device.control_port as u64)); + value.insert("mediaPort", JsonValue::from(device.media_port as u64)); + value.insert("audioPort", JsonValue::from(device.audio_port as u64)); + value.insert("fp", JsonValue::from(device.fingerprint.as_str())); + value.insert( + "cap", + JsonValue::Array(device.capabilities.iter().map(JsonValue::from).collect()), + ); + value.insert("model", JsonValue::from(device.model.as_str())); + value.insert("res", JsonValue::from(device.resolution.as_str())); + list.push(value); + } + root.insert("devices", JsonValue::Array(list)); + root.encode() +} + +/// 通知指定设备:主控端已就绪,请拨号接入。 +pub fn connect(ip: &str) -> bool { + let Some(Some(beacon)) = BEACON.get() else { + return false; + }; + let trimmed = ip.trim(); + if trimmed.is_empty() { + return false; + } + let Ok(mut addresses) = (trimmed, BEACON_PORT).to_socket_addrs() else { + return false; + }; + let Some(address) = addresses.next() else { + return false; + }; + // 连发三次,抵消单次丢包。 + for attempt in 0..3 { + beacon.send_host(address, true); + if attempt < 2 { + thread::sleep(Duration::from_millis(80)); + } + } + true +} + +impl Beacon { + fn spawn_receiver(self: &'static Beacon) { + thread::spawn(move || { + let mut buffer = [0u8; 4096]; + while self.running.load(Ordering::Relaxed) { + match self.socket.recv_from(&mut buffer) { + Ok((length, from)) => { + let text = String::from_utf8_lossy(&buffer[..length]).to_string(); + self.handle(&text, from); + } + Err(_) => thread::sleep(Duration::from_millis(100)), + } + } + }); + } + + fn handle(&self, text: &str, from: SocketAddr) { + let source_ip = from.ip().to_string(); + let Some(device) = parse_offer(text, &source_ip) else { + return; + }; + { + let mut devices = match self.devices.lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + devices.insert(source_ip.clone(), (device, Instant::now())); + } + // 收到 offer 立即应答,让被控端即使「先开投屏」也能马上知道主控端地址; + // 但同源 1 秒内只回一次,避免设备高频广播时互相刷包。 + let now = Instant::now(); + let allowed = { + let mut replies = match self.replies.lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + match replies.get(&source_ip) { + Some(last) if now.duration_since(*last) < REPLY_INTERVAL => false, + _ => { + replies.insert(source_ip, now); + true + } + } + }; + if allowed { + self.send_host(from, false); + } + } + + fn send_host(&self, address: SocketAddr, connect: bool) { + let payload = encode_host( + connect, + self.control_port, + self.media_port, + self.audio_port, + ); + let _ = self.socket.send_to(payload.as_bytes(), address); + } + + fn snapshot(&self) -> Vec { + let now = Instant::now(); + let mut devices = match self.devices.lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + devices.retain(|_, (_, seen)| now.duration_since(*seen) < DEVICE_TTL); + let mut list: Vec = devices.values().map(|(device, _)| device.clone()).collect(); + list.sort_by(|left, right| left.ip.cmp(&right.ip)); + list + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn offer_is_parsed_and_source_ip_wins() { + let raw = r#"{"ttstd":"disc/1","kind":"offer","id":"uuid-1","name":"客厅手机", + "model":"Pixel 8","res":"1920x1080","ctrl":41001,"media":41000,"audio":41002, + "fp":"","cap":["h264","opus"]}"#; + let device = parse_offer(raw, "192.168.1.23").expect("应当解析成功"); + assert_eq!(device.ip, "192.168.1.23"); + assert_eq!(device.name, "客厅手机"); + assert_eq!(device.control_port, 41001); + assert!(device.capabilities.contains(&"h264".to_string())); + } + + #[test] + fn foreign_packets_are_ignored() { + assert!(parse_offer(r#"{"ttstd":"disc/1","kind":"host"}"#, "1.2.3.4").is_none()); + assert!(parse_offer("not json", "1.2.3.4").is_none()); + assert!(parse_offer(r#"{"ttstd":"other","kind":"offer"}"#, "1.2.3.4").is_none()); + } + + #[test] + fn host_packet_carries_ports_and_connect_flag() { + let text = encode_host(true, 41001, 41000, 41002); + let value = json::parse(&text).expect("应当是合法 JSON"); + assert_eq!(value.get("kind").and_then(JsonValue::as_str), Some("host")); + assert_eq!(value.get("connect").and_then(JsonValue::as_bool), Some(true)); + assert_eq!(value.get("ctrl").and_then(JsonValue::as_u64), Some(41001)); + } + + /// 端到端:设备发出的 offer 应当收到带端口的 host 应答。 + #[test] + fn beacon_replies_to_offer_with_source_routing() { + if !start(41001, 41000, 41002) { + // 端口被占用(例如主程序正在运行)时跳过,避免干扰交互式调试。 + return; + } + let device = UdpSocket::bind(("127.0.0.1", 0)).expect("设备端 socket"); + device + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("设置超时"); + let offer = r#"{"ttstd":"disc/1","kind":"offer","id":"uuid-9","name":"测试机", + "ctrl":41001,"media":41000,"audio":41002,"cap":["h264"]}"#; + device + .send_to( + offer.as_bytes(), + ("127.0.0.1", BEACON_PORT), + ) + .expect("发送 offer"); + + let mut buffer = [0u8; 1024]; + let (length, _) = device.recv_from(&mut buffer).expect("应当收到 host 应答"); + let text = String::from_utf8_lossy(&buffer[..length]).to_string(); + let value = json::parse(&text).expect("应答应当是 JSON"); + assert_eq!(value.get("kind").and_then(JsonValue::as_str), Some("host")); + assert_eq!(value.get("ctrl").and_then(JsonValue::as_u64), Some(41001)); + + let listed = devices_json(); + assert!(listed.contains("uuid-9"), "设备应当出现在列表里:{listed}"); + } +} diff --git a/rust_core/src/discovery/mod.rs b/rust_core/src/discovery/mod.rs index 2ff918a..7b6cf0d 100644 --- a/rust_core/src/discovery/mod.rs +++ b/rust_core/src/discovery/mod.rs @@ -1,3 +1,4 @@ +pub mod beacon; pub mod device; pub mod mdns; pub mod signaling; diff --git a/rust_core/src/ffi.rs b/rust_core/src/ffi.rs index cbb90e0..1e284b8 100644 --- a/rust_core/src/ffi.rs +++ b/rust_core/src/ffi.rs @@ -459,8 +459,56 @@ pub unsafe extern "C" fn ttstd_video_stats(out_json: *mut u8, capacity: usize) - copy_out(json.as_bytes(), out_json, capacity) } +/// 启动同网段自动发现(UDP 41003)。幂等:已在运行时直接返回 OK。 +#[no_mangle] +pub extern "C" fn ttstd_discovery_start( + control_port: u16, + media_port: u16, + audio_port: u16, +) -> i32 { + if crate::discovery::beacon::start(control_port, media_port, audio_port) { + OK + } else { + ERR_INVALID_ARGUMENT + } +} + +/// 已发现设备列表 JSON:`{"devices":[...]}`,字段与信令 `/list` 一致。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_discovery_devices(out_json: *mut u8, capacity: usize) -> i32 { + let json = crate::discovery::beacon::devices_json(); + copy_out(json.as_bytes(), out_json, capacity) +} + +/// 通知指定 IP 的被控端「主控端已就绪」,被控端据此拨号。 +/// +/// # Safety +/// ip 必须指向长度为 len 的 UTF-8 字节。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_discovery_connect(ip: *const u8, len: usize) -> i32 { + let bytes = match read_slice(ip, len) { + Ok(bytes) => bytes, + Err(code) => return code, + }; + let text = match std::str::from_utf8(bytes) { + Ok(text) => text, + Err(_) => return ERR_INVALID_ARGUMENT, + }; + if crate::discovery::beacon::connect(text) { + OK + } else { + ERR_INVALID_ARGUMENT + } +} + +/// 停止自动发现(退出或测试用)。 +#[no_mangle] +pub extern "C" fn ttstd_discovery_stop() { + crate::discovery::beacon::stop(); +} + /// ABI 版本,便于 Dart 侧校验动态库是否匹配。 #[no_mangle] pub extern "C" fn ttstd_core_abi_revision() -> i32 { - 2 + 3 }