diff --git a/android_receiver/app/src/main/AndroidManifest.xml b/android_receiver/app/src/main/AndroidManifest.xml index a1d5277..737462c 100644 --- a/android_receiver/app/src/main/AndroidManifest.xml +++ b/android_receiver/app/src/main/AndroidManifest.xml @@ -10,7 +10,8 @@ + android:theme="@style/Theme.Lancast" + android:usesCleartextTraffic="true"> transport.sendVideo(buffer, info) } + private val encoder = VideoEncoder { buffer, info -> + transport.sendVideo(buffer, info, preferH265) + } private var capturer: ScreenCapturer? = null private var audio: AudioCapturer? = null @@ -107,7 +109,7 @@ class ReceiverSession( announcer?.stop() nsdAdvertiser?.stop() opusEncoder.stop() - transport.close() + transport.stop() encoder.stop() executor.shutdownNow() } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/ReceiverAnnouncer.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/ReceiverAnnouncer.kt index 4766691..25e851d 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/ReceiverAnnouncer.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/ReceiverAnnouncer.kt @@ -1,5 +1,6 @@ package com.ttstd.lancast.receiver.discovery +import android.util.Log import org.json.JSONArray import org.json.JSONObject import java.net.HttpURLConnection @@ -25,9 +26,13 @@ class ReceiverAnnouncer( future = exec.scheduleWithFixedDelay({ try { val path = if (registered) "/heartbeat" else "/register" - post(path, body()) - registered = true - } catch (_: Exception) { + registered = post(path, body()) + if (!registered) { + Log.w(TAG, "信令注册失败,将在下一轮重试") + } + } catch (error: Exception) { + registered = false + Log.w(TAG, "信令请求异常:$error") } }, 0, 15, TimeUnit.SECONDS) } @@ -53,19 +58,33 @@ class ReceiverAnnouncer( put("ttl", 30) }.toString() - private fun post(path: String, body: String) { - try { - val connection = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection - connection.requestMethod = "POST" - connection.doOutput = true - connection.setRequestProperty("Content-Type", "application/json") - connection.connectTimeout = 3000 - connection.readTimeout = 3000 - connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) } - connection.responseCode - connection.disconnect() - } catch (_: Exception) { - // 信令临时不可达不影响 mDNS 同网段直连。 + private fun post(path: String, body: String): Boolean { + var connection: HttpURLConnection? = null + return try { + val http = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection + connection = http + http.requestMethod = "POST" + http.doOutput = true + http.setRequestProperty("Content-Type", "application/json") + http.connectTimeout = 3000 + http.readTimeout = 3000 + http.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) } + val code = http.responseCode + if (code !in 200..299) { + Log.w(TAG, "信令 $path 返回 HTTP $code") + false + } else { + true + } + } catch (error: Exception) { + Log.w(TAG, "信令 $path 请求失败:$error") + false + } finally { + connection?.disconnect() } } + + private companion object { + const val TAG = "ReceiverAnnouncer" + } } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/VideoEncoder.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/VideoEncoder.kt index d354f53..86a9f70 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/VideoEncoder.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/VideoEncoder.kt @@ -12,6 +12,13 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) -> var inputSurface: Surface? = null private set + /** + * 编解码配置(SPS/PPS)。摄像头/Surface 输入的编码器不会把 SPS/PPS 放在码流里, + * 而是通过 csd-0/csd-1 或 CODEC_CONFIG 帧单独给出。缺了它的裸流解不出任何画面, + * 所以这里记录下来并随每个关键帧一起发送。 + */ + private var codecConfig: ByteArray? = null + fun start(width: Int, height: Int, fps: Int, bitrateBps: Int, preferH265: Boolean) { val mime = if (preferH265) MediaFormat.MIMETYPE_VIDEO_HEVC else MediaFormat.MIMETYPE_VIDEO_AVC val format = MediaFormat.createVideoFormat(mime, width, height).apply { @@ -31,16 +38,66 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) -> val encoder = codec ?: return val info = MediaCodec.BufferInfo() var index = encoder.dequeueOutputBuffer(info, 0) - while (index >= 0) { + while (index >= 0 || index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { + if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { + // 输出格式一旦确定就带回 csd-0/csd-1(SPS/PPS)。 + captureCodecConfig(encoder) + index = encoder.dequeueOutputBuffer(info, 0) + continue + } val buffer = encoder.getOutputBuffer(index) if (buffer != null && info.size > 0) { - onPacket(buffer, info) + if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) { + // 部分设备把 SPS/PPS 作为独立的配置帧输出。 + codecConfig = ByteArray(info.size).also { target -> + val view = buffer.duplicate() + view.position(info.offset) + view.limit(info.offset + info.size) + view.get(target) + } + } else { + emitWithConfig(buffer, info) + } } encoder.releaseOutputBuffer(index, false) index = encoder.dequeueOutputBuffer(info, 0) } } + /** 把 SPS/PPS 前置到关键帧,保证对端随时能从任意关键帧开始解码。 */ + private fun emitWithConfig(buffer: ByteBuffer, info: MediaCodec.BufferInfo) { + val config = codecConfig + val isKeyFrame = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0 + if (config == null || config.isEmpty() || !isKeyFrame) { + onPacket(buffer, info) + return + } + val payload = ByteArray(config.size + info.size) + System.arraycopy(config, 0, payload, 0, config.size) + val view = buffer.duplicate() + view.position(info.offset) + view.limit(info.offset + info.size) + view.get(payload, config.size, info.size) + val merged = MediaCodec.BufferInfo().apply { + set(0, payload.size, info.presentationTimeUs, info.flags) + } + onPacket(ByteBuffer.wrap(payload), merged) + } + + private fun captureCodecConfig(encoder: MediaCodec) { + val format = encoder.outputFormat + val chunks = ArrayList(2) + for (name in listOf("csd-0", "csd-1")) { + val csd = format.getByteBuffer(name) ?: continue + val bytes = ByteArray(csd.remaining()) + csd.duplicate().get(bytes) + chunks += bytes + } + if (chunks.isNotEmpty()) { + codecConfig = chunks.reduce { acc, item -> acc + item } + } + } + fun requestKeyFrame() { codec?.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) @@ -51,6 +108,7 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) -> codec?.stop() codec?.release() codec = null + codecConfig = null inputSurface?.release() inputSurface = null } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt index 5b1117b..5d3ae54 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt @@ -8,6 +8,13 @@ import javax.crypto.spec.SecretKeySpec object MediaPackets { const val FLAG_KEYFRAME = 1 const val FLAG_AUDIO = 2 + // 与 Rust Core 的 media::stream 保持一致的扩展标志位。 + const val FLAG_HEVC = 0x08 + const val FLAG_FRAGMENT_START = 0x10 + const val FLAG_FRAGMENT_CONTINUE = 0x20 + const val FLAG_FRAGMENT_END = 0x40 + // 单个 UDP 分片的负载上限:13 字节头 + 4 字节 MAC + 1200 负载仍远小于 MTU。 + const val FRAGMENT_PAYLOAD_SIZE = 1200 private const val HEADER_SIZE = 13 private const val MAC_SIZE = 4 diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/ReceiverTransport.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/ReceiverTransport.kt index abe42de..a664fe1 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/ReceiverTransport.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/ReceiverTransport.kt @@ -44,6 +44,8 @@ class ReceiverTransport( private var udp: DatagramSocket? = null private var keys: SessionCrypto.SessionKeys? = null @Volatile + private var active = false + @Volatile private var running = false @Volatile private var sequence = 0 @@ -51,34 +53,63 @@ class ReceiverTransport( val keyEstablished: Boolean get() = keys != null fun start() { + if (active) return + active = true executor.execute { - try { - val raw = Socket().apply { - tcpNoDelay = true - soTimeout = 5000 - connect(InetSocketAddress(host, controlPort), 5000) + while (active) { + try { + connectAndRun() + } catch (error: Exception) { + Log.e("ReceiverTransport", "Failed to connect or handshake", error) + } finally { + resetConnection() + } + if (!active) break + try { + Thread.sleep(2000) + } catch (_: InterruptedException) { + break } - socket = raw - output = DataOutputStream(raw.outputStream) - val input = DataInputStream(raw.inputStream) - - // ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。 - output?.write(crypto.publicBytes) - output?.flush() - val peerPublic = ByteArray(65) - input.readFully(peerPublic) - keys = crypto.deriveKeys(peerPublic) - - udp = DatagramSocket() - running = true - readLoop(input) - } catch (e: Exception) { - Log.e("ReceiverTransport", "Failed to connect or handshake", e) - close() } } } + private fun connectAndRun() { + val raw = Socket().apply { + tcpNoDelay = true + soTimeout = 5000 + connect(InetSocketAddress(host, controlPort), 5000) + } + socket = raw + output = DataOutputStream(raw.outputStream) + val input = DataInputStream(raw.inputStream) + + // ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。 + output?.write(crypto.publicBytes) + output?.flush() + val peerPublic = ByteArray(65) + input.readFully(peerPublic) + keys = crypto.deriveKeys(peerPublic) + + udp = DatagramSocket() + running = true + Log.i("ReceiverTransport", "Connected to $host:$controlPort") + readLoop(input) + } + + private fun resetConnection() { + running = false + try { + socket?.close() + udp?.close() + } catch (_: Exception) { + } + socket = null + output = null + udp = null + keys = null + } + fun sendControl(event: ControlEvent) { executor.execute { val key = keys?.control ?: return@execute @@ -88,7 +119,7 @@ class ReceiverTransport( } } - fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) { + fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo, hevc: Boolean = false) { val key = keys?.video ?: return if (!running) return val duplicate = buffer.duplicate().apply { @@ -97,32 +128,59 @@ class ReceiverTransport( } val payload = ByteArray(info.size) duplicate.get(payload) - val flags = if (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0) { + var flags = if (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0) { MediaPackets.FLAG_KEYFRAME } else { 0 } - val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key) - udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, mediaPort))) + if (hevc) flags = flags or MediaPackets.FLAG_HEVC + val target = InetSocketAddress(host, mediaPort) + val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE + try { + if (payload.size <= chunk) { + val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key) + udp?.send(DatagramPacket(packet, packet.size, target)) + return + } + // 大帧(尤其 I 帧)必须分片,否则超过 UDP 上限会被整帧丢弃。 + var offset = 0 + while (offset < payload.size) { + val end = minOf(offset + chunk, payload.size) + var fragmentFlags = flags + fragmentFlags = fragmentFlags or if (offset == 0) { + MediaPackets.FLAG_FRAGMENT_START + } else { + MediaPackets.FLAG_FRAGMENT_CONTINUE + } + if (end >= payload.size) { + fragmentFlags = fragmentFlags or MediaPackets.FLAG_FRAGMENT_END + } + val part = payload.copyOfRange(offset, end) + val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key) + udp?.send(DatagramPacket(packet, packet.size, target)) + offset = end + } + } catch (_: Exception) { + } } fun sendAudio(opusPacket: ByteArray, pts: Long) { val key = keys?.audio ?: return if (!running) return val packet = MediaPackets.encode(opusPacket, pts, MediaPackets.FLAG_AUDIO, key) - udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, audioPort))) + try { + udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, audioPort))) + } catch (_: Exception) { + } } fun close() { - running = false - try { - socket?.close() - udp?.close() - } catch (_: Exception) { - } - socket = null - udp = null - keys = null + active = false + resetConnection() + } + + fun stop() { + close() executor.shutdownNow() } @@ -150,8 +208,8 @@ class ReceiverTransport( } } } - } catch (_: Exception) { - // 对端断开时结束读取循环。 + } catch (error: Exception) { + Log.w("ReceiverTransport", "Control channel ended: $error") } } diff --git a/docs/DEMO.md b/docs/DEMO.md index 0c2f548..4d228e4 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -9,6 +9,87 @@ 3. **媒体包 MAC**:视频(41000)/音频(41002) UDP 包的 4 字节 HMAC 使用 ECDH 派生的 video/audio 子密钥,不再使用指纹 ASCII 串。 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`。 + +## 视频画面链路(Windows 主控端) + +``` +Android MediaCodec H.264/H.265 + │ MediaPackets.encode(13 字节头 + 负载 + 4 字节 MAC,>1200 字节自动分片) + ▼ +UDP 41000 → Rust demo_server 解包/校验/分片重组 → media::stream 队列 + ▼ +FFI:ttstd_video_next / ttstd_video_pending + ▼ +windows/runner/video_texture.cpp:Media Foundation MFT 解码(NV12/RGB32 → BGRA) + ▼ +flutter::TextureRegistrar(RegisterTexture / MarkTextureFrameAvailable) + ▼ +Dart:MethodChannel `ttstd/video` 的 `textureId` + `stats` → Texture(textureId: …) +``` + +要点: + +- **大帧必须分片**:单个 UDP 数据报上限约 64KB,1080p 的 I 帧远超该值。被控端把访问单元切成 1200 字节分片并打 `0x10/0x20/0x40` 标志,Rust 侧 `Reassembler` 按序拼回。 +- **解码在原生侧**:Rust 只做搬运与排队(容量 240,超出丢最旧),解码交给系统 Media Foundation,无需引入编解码依赖。 +- **裁剪**:解码器输出按 16 对齐(如 1080 → 1088),插件按 `MF_MT_MINIMUM_DISPLAY_APERTURE` 裁掉补齐行。 +- **低延迟**:必须开启 `CODECAPI_AVLowLatencyMode` + `MF_LOW_LATENCY`。默认模式下 Media Foundation 会为「平滑播放」攒约 36 帧输入(约 1.2 秒延迟),表现为画面明显滞后且尾部若干帧永远不出图。 +- **诊断**:`ttstd/video` 通道的 `stats` 返回 `decoded/pending/received/width/height/pts/format/auBytes/keyframes/submitHr/error`,会写入 `ttstd_connect.log`;`VideoView` 在解码失败时直接显示原因。 +- **SPS/PPS 必须随关键帧重发**:MediaCodec 只在开始时输出一次 csd,主控端晚连就只能收到 P 帧,解码器会「吃数据不出图」且不报错。被控端 `VideoEncoder` 现在把 csd 前置到每个关键帧,主控端最多等一个关键帧周期(2 秒)就能出图。 + +## 出画面排查顺序 + +| 现象 | 判定 | 处理 | +| --- | --- | --- | +| 界面停在「视频通道已建立」且日志没有 `textureId=` | 运行的是**旧构建**(runner 里没有视频插件,`ttstd/video` 通道缺失) | 重新打包或用 `dist\TTSTDConnect-Windows` 里的新程序 | +| 有纹理但画面空白,`stats.error=被控端码流缺少 SPS/PPS…` | 被控端 APK 未把 csd 随关键帧发送 | 重新编译并安装被控端 APK | +| `error` 提示 HEVC 解码器缺失 | 系统没装 HEVC 扩展 | 改装 `MediaCodec` 的 AVC 模式或安装 HEVC 视频扩展 | + +抓码流验证(无需真机日志): + +```powershell +$env:TTSTD_DUMP_VIDEO = "$env:TEMP\au.h264" # 启动主控端前设置 +.\dist\TTSTDConnect-Windows\ttstd_sender.exe +ffprobe -f h264 -count_frames -show_entries stream=width,height,nb_read_frames "$env:TEMP\au.h264" +``` + +`ffprobe` 报 `non-existing PPS 0 referenced` 即说明码流缺配置帧;能正常读出 `width/height` 则说明问题在解码/渲染侧。 + +## 无设备时验证画面 + +用 ffmpeg 生成带访问单元分隔符的测试码流,再用示例程序推进本机 demo 服务: + +```powershell +# 1. 生成 4 秒测试图案(640x360,30fps,带 AUD) +ffmpeg -y -f lavfi -i "testsrc2=size=640x360:rate=30" -t 4 ` + -c:v libx264 -preset veryfast -tune zerolatency -profile:v baseline -pix_fmt yuv420p ` + -x264-params "aud=1:keyint=30:min-keyint=30:scenecut=0:repeat-headers=1" ` + -f h264 test_pattern.h264 + +# 2. 构建并启动主控端(TTSTD_DEMO_AUTOSTART=1 让它启动即监听 41001/41000) +cd rust_core; cargo build --release --offline --example video_feed +cd ..\flutter_sender; flutter build windows --debug +$env:TTSTD_DEMO_AUTOSTART = "1" +.\build\windows\x64\runner\Debug\ttstd_sender.exe + +# 3. 另开一个终端推送码流 +cd rust_core +.\target\release\examples\video_feed.exe ..\test_pattern.h264 +``` + +成功标志:`VideoView` 出现测试图案,左上角显示 `1280x720`,右上角显示 PTS,`ttstd_connect.log` 中 `video={decoded: N, ...}` 的 `decoded` 与 `received` 相等且持续增长。 + +![主控端渲染远端视频](images/video-view.png) + +上图为 Release 版实测:1280x720 测试码流经「UDP 分片 → 重组 → Media Foundation 解码 → 外部纹理」显示在 `VideoView` 中,`decoded` 与 `received` 均为 150。 + +## 真机/模拟器实测 + +被控端(Android)点「授权并开始投屏」后,主控端启动即自动连上并出图;下方为 Android 模拟器 1920x1080 屏投到主控端的实拍: + +![主控端镜像 Android 屏](images/device-mirror.png) + +注意顺序无关:**先投屏再启动主控端**也能出图(靠关键帧携带 csd),最多等一个关键帧周期。 ## 一键验证(无需设备) diff --git a/docs/images/device-mirror.png b/docs/images/device-mirror.png new file mode 100644 index 0000000..f72bd09 Binary files /dev/null and b/docs/images/device-mirror.png differ diff --git a/docs/images/video-view.png b/docs/images/video-view.png new file mode 100644 index 0000000..9715d70 Binary files /dev/null and b/docs/images/video-view.png differ diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart index cb95055..a9904b2 100644 --- a/flutter_sender/lib/core/bridge.dart +++ b/flutter_sender/lib/core/bridge.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:flutter/services.dart'; +import 'discovery_client.dart'; import 'local_signaling.dart'; import 'models.dart'; import 'native_core.dart'; @@ -21,6 +22,9 @@ class SenderBridge { final NativeCore? _native; final LocalSignalingProcess _localSignaling = LocalSignalingProcess(); + /// 原生视频解码纹理通道(Windows runner 内嵌插件)。 + static const MethodChannel _video = MethodChannel('ttstd/video'); + NativeCore? get nativeCore => _native; bool get isLocalSignalingRunning => _localSignaling.isRunning; @@ -33,23 +37,13 @@ class SenderBridge { .distinct(); } - Future> discover() async { + Future> discover({String? signalingUrl}) async { + if (signalingUrl != null && signalingUrl.trim().isNotEmpty) { + final discovered = await DiscoveryClient.listDevices(signalingUrl); + if (discovered.isNotEmpty) return discovered; + } if (_native != null) { - final localIp = await _localIp(); - if (localIp == null) return const []; - return [ - DeviceInfo( - id: 'local-listener', - name: '本机监听端点', - ip: localIp, - mediaPort: 41000, - controlPort: 41001, - fingerprint: '', - capabilities: const [], - model: '', - resolution: '', - ), - ]; + return const []; } try { final raw = await _method.invokeListMethod('discover'); @@ -62,6 +56,22 @@ class SenderBridge { } } + Future localListener() async { + final localIp = await _localIp(); + if (localIp == null) return null; + return DeviceInfo( + id: 'local-listener', + name: '本机监听端点', + ip: localIp, + mediaPort: 41000, + controlPort: 41001, + fingerprint: '', + capabilities: const [], + model: '', + resolution: '', + ); + } + static Future _localIp() async { try { final interfaces = await NetworkInterface.list( @@ -202,6 +212,35 @@ class SenderBridge { Map demoStatus() => _native?.demoStatus() ?? {'running': false}; + /// 原生视频纹理 ID;无原生实现或纹理尚未注册时返回 null。 + Future videoTextureId() async { + try { + final id = await _video.invokeMethod('textureId'); + if (id == null || id <= 0) return null; + return id; + } on MissingPluginException { + return null; + } on PlatformException { + return null; + } + } + + /// 原生视频解码统计:textureId/decoded/pending/received/width/height/pts/error。 + Future> videoStats() async { + try { + final stats = await _video.invokeMapMethod('stats'); + return stats ?? const {}; + } on MissingPluginException { + // 老构建产物(runner 里没有视频纹理插件)会走到这里,必须显式提示, + // 否则界面只会停在「视频通道已建立」,看不出是二进制过期。 + return const { + 'error': '当前程序缺少原生视频插件(旧版构建),请重新构建/重新解压发布包', + }; + } on PlatformException { + return const {}; + } + } + Future pairingUri() async { try { final value = await _method.invokeMethod('pairingUri'); diff --git a/flutter_sender/lib/core/diagnostic_log.dart b/flutter_sender/lib/core/diagnostic_log.dart new file mode 100644 index 0000000..6f22379 --- /dev/null +++ b/flutter_sender/lib/core/diagnostic_log.dart @@ -0,0 +1,57 @@ +import 'dart:io'; + +class DiagnosticLog { + DiagnosticLog([this.fileName = 'ttstd_connect.log']); + + final String fileName; + File? _file; + + String get path => _file?.path ?? ''; + + void start() { + final directories = [ + File(Platform.resolvedExecutable).parent, + Directory.current, + Directory.systemTemp, + ]; + for (final directory in directories) { + try { + final candidate = File( + '${directory.path}${Platform.pathSeparator}$fileName', + ); + candidate.writeAsStringSync( + '=== TTSTD Connect diagnostic log ===\n' + 'started: ${DateTime.now().toIso8601String()}\n', + mode: FileMode.write, + flush: true, + ); + _file = candidate; + return; + } on Object catch (_) {} + } + } + + void write(String message) { + final file = _file; + if (file == null) return; + try { + if (file.lengthSync() > 2 * 1024 * 1024) { + file.writeAsStringSync( + '=== log rotated: ${DateTime.now().toIso8601String()} ===\n', + mode: FileMode.write, + flush: true, + ); + } + file.writeAsStringSync( + '${DateTime.now().toIso8601String()} $message\n', + mode: FileMode.append, + flush: true, + ); + } on Object catch (_) {} + } + + void dispose() { + write('=== stopped ==='); + _file = null; + } +} diff --git a/flutter_sender/lib/core/discovery_client.dart b/flutter_sender/lib/core/discovery_client.dart new file mode 100644 index 0000000..5a95354 --- /dev/null +++ b/flutter_sender/lib/core/discovery_client.dart @@ -0,0 +1,33 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'models.dart'; + +class DiscoveryClient { + static Future> listDevices( + String signalingUrl, { + Duration timeout = const Duration(seconds: 2), + }) async { + final trimmed = signalingUrl.trim(); + if (trimmed.isEmpty) return const []; + final client = HttpClient()..connectionTimeout = timeout; + try { + final base = Uri.parse(trimmed); + final path = base.path.endsWith('/') + ? '${base.path}list' + : '${base.path}/list'; + final request = await client.getUrl(base.replace(path: path)).timeout(timeout); + final response = await request.close().timeout(timeout); + final body = await utf8.decoder.bind(response).join().timeout(timeout); + if (response.statusCode != HttpStatus.ok) return const []; + final value = jsonDecode(body); + if (value is! Map) return const []; + return DeviceInfo.listFromJson(value['devices']); + } on Object { + return const []; + } finally { + client.close(force: true); + } + } +} diff --git a/flutter_sender/lib/core/native_core.dart b/flutter_sender/lib/core/native_core.dart index 2abf0a6..d0c1a30 100644 --- a/flutter_sender/lib/core/native_core.dart +++ b/flutter_sender/lib/core/native_core.dart @@ -168,7 +168,7 @@ class NativeCore { try { final written = _mediaDecode(packetPtr, packet.length, keyPtr, out, 256); _check(written, 'ttstd_media_decode'); - return jsonDecode(_copy(out, written).toString()) as Map; + return jsonDecode(utf8.decode(_copy(out, written))) as Map; } finally { calloc.free(out); } @@ -199,11 +199,11 @@ class NativeCore { void stopDemoServer() => _demoStop(); Map demoStatus() { - final out = calloc(8192); + final out = calloc(65536); try { - final written = _demoStatus(out, 8192); + final written = _demoStatus(out, 65536); _check(written, 'ttstd_demo_status'); - return jsonDecode(_copy(out, written).toString()) as Map; + return jsonDecode(utf8.decode(_copy(out, written))) as Map; } finally { calloc.free(out); } @@ -321,7 +321,7 @@ class SecureChannel { try { final written = _core._controlDecode(_handle, framePtr, frame.length, out, 256); if (written < 0) throw NativeCoreException('ttstd_control_decode', written); - return jsonDecode(NativeCore._copy(out, written).toString()) as Map; + return jsonDecode(utf8.decode(NativeCore._copy(out, written))) as Map; } finally { calloc.free(out); } diff --git a/flutter_sender/lib/core/service_check.dart b/flutter_sender/lib/core/service_check.dart new file mode 100644 index 0000000..6f13bc3 --- /dev/null +++ b/flutter_sender/lib/core/service_check.dart @@ -0,0 +1,63 @@ +import 'dart:async'; +import 'dart:io'; + +class ServiceCheckResult { + const ServiceCheckResult({ + required this.nativeCoreLoaded, + required this.localSignalingRunning, + required this.signalingReachable, + required this.listenerRunning, + required this.listenerReachable, + required this.signalingUrl, + required this.listenerHost, + required this.listenerPort, + }); + + final bool nativeCoreLoaded; + final bool localSignalingRunning; + final bool signalingReachable; + final bool listenerRunning; + final bool listenerReachable; + final String signalingUrl; + final String listenerHost; + final int listenerPort; +} + +class ServiceChecker { + static Future checkSignaling( + String url, { + Duration timeout = const Duration(seconds: 2), + }) async { + final trimmed = url.trim(); + if (trimmed.isEmpty) return false; + final client = HttpClient()..connectionTimeout = timeout; + try { + final base = Uri.parse(trimmed); + final path = base.path.endsWith('/') + ? '${base.path}healthz' + : '${base.path}/healthz'; + final request = await client.getUrl(base.replace(path: path)).timeout(timeout); + final response = await request.close().timeout(timeout); + await response.drain().timeout(timeout); + return response.statusCode == HttpStatus.ok; + } on Object { + return false; + } finally { + client.close(force: true); + } + } + + static Future checkTcp( + String host, + int port, { + Duration timeout = const Duration(seconds: 2), + }) async { + try { + final socket = await Socket.connect(host, port, timeout: timeout); + socket.destroy(); + return true; + } on Object { + return false; + } + } +} diff --git a/flutter_sender/lib/features/discovery/device_list.dart b/flutter_sender/lib/features/discovery/device_list.dart index c2f47fc..c5081d5 100644 --- a/flutter_sender/lib/features/discovery/device_list.dart +++ b/flutter_sender/lib/features/discovery/device_list.dart @@ -158,7 +158,11 @@ class _EmptyState extends StatelessWidget { const SizedBox(height: 12), const Text('未发现设备'), const SizedBox(height: 4), - Text('确认手机与主控端处于同一网段', style: Theme.of(context).textTheme.bodySmall), + Text( + '本机监听端点已移至设置;请确认被控端与主控端处于同一网段', + style: Theme.of(context).textTheme.bodySmall, + textAlign: TextAlign.center, + ), const SizedBox(height: 12), OutlinedButton.icon( onPressed: onRefresh, diff --git a/flutter_sender/lib/features/media/video_view.dart b/flutter_sender/lib/features/media/video_view.dart index f5afd27..3b196a7 100644 --- a/flutter_sender/lib/features/media/video_view.dart +++ b/flutter_sender/lib/features/media/video_view.dart @@ -7,6 +7,7 @@ class VideoView extends StatelessWidget { this.connected = false, this.resolution = '', this.pts, + this.error = '', }); final int? textureId; @@ -14,6 +15,9 @@ class VideoView extends StatelessWidget { final String resolution; final int? pts; + /// 原生解码链路的失败原因,为空表示没有错误。 + final String error; + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -46,8 +50,15 @@ class VideoView extends StatelessWidget { Text(connected ? '视频通道已建立' : '等待投屏画面', style: theme.textTheme.titleMedium), const SizedBox(height: 4), - Text('H.264/H.265 → External Texture', - style: theme.textTheme.bodySmall), + Text( + error.isNotEmpty ? error : 'H.264/H.265 → External Texture', + style: theme.textTheme.bodySmall?.copyWith( + color: error.isNotEmpty + ? theme.colorScheme.error + : theme.textTheme.bodySmall?.color, + ), + textAlign: TextAlign.center, + ), ], ), if (resolution.isNotEmpty) diff --git a/flutter_sender/lib/features/settings/settings_page.dart b/flutter_sender/lib/features/settings/settings_page.dart index f254d40..2090788 100644 --- a/flutter_sender/lib/features/settings/settings_page.dart +++ b/flutter_sender/lib/features/settings/settings_page.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../core/bridge.dart'; import '../../core/models.dart'; +import '../../core/service_check.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({ @@ -28,6 +29,10 @@ class _SettingsPageState extends State { late bool _clipboardSync; late bool _fileTransfer; late int _bitrateMbps; + DeviceInfo? _localListener; + ServiceCheckResult? _serviceResult; + bool _checkingServices = false; + bool _listenerRunning = false; @override void initState() { @@ -42,6 +47,8 @@ class _SettingsPageState extends State { _clipboardSync = widget.settings.clipboardSync; _fileTransfer = widget.settings.fileTransfer; _bitrateMbps = widget.settings.bitrateMbps; + _loadLocalListener(); + _refreshListenerState(); } @override @@ -62,6 +69,102 @@ class _SettingsPageState extends State { } } + Future _loadLocalListener() async { + final listener = await widget.bridge.localListener(); + if (!mounted) return; + setState(() => _localListener = listener); + } + + void _refreshListenerState() { + try { + final status = widget.bridge.demoStatus(); + _listenerRunning = status['running'] == true; + } on Object catch (_) { + _listenerRunning = false; + } + } + + Future _runServiceCheck() async { + setState(() => _checkingServices = true); + final url = _useLocalSignaling + ? widget.bridge.localSignalingUrl(_port) + : _signalingUrl.text.trim(); + final listener = _localListener ?? await widget.bridge.localListener(); + final host = listener?.ip ?? '127.0.0.1'; + final results = await Future.wait([ + ServiceChecker.checkSignaling(url), + ServiceChecker.checkTcp(host, 41001), + ]); + Map status = const {'running': false}; + try { + status = widget.bridge.demoStatus(); + } on Object catch (_) {} + if (!mounted) return; + setState(() { + _localListener = listener; + _listenerRunning = status['running'] == true; + _serviceResult = ServiceCheckResult( + nativeCoreLoaded: widget.bridge.nativeCore != null, + localSignalingRunning: widget.bridge.isLocalSignalingRunning, + signalingReachable: results[0], + listenerRunning: _listenerRunning, + listenerReachable: results[1], + signalingUrl: url, + listenerHost: host, + listenerPort: 41001, + ); + _checkingServices = false; + }); + } + + Future _toggleListener() async { + if (_listenerRunning) { + widget.bridge.stopDemoServer(); + if (!mounted) return; + setState(() => _listenerRunning = false); + } else { + final started = widget.bridge.startDemoServer(); + var running = started; + if (!running) { + try { + running = widget.bridge.demoStatus()['running'] == true; + } on Object catch (_) {} + } + if (!mounted) return; + setState(() => _listenerRunning = running); + if (!running) _snack('本机监听启动失败'); + } + await _runServiceCheck(); + } + + Widget _serviceRow(String label, bool? ok) { + final theme = Theme.of(context); + final icon = ok == null + ? Icons.help_outline + : ok + ? Icons.check_circle + : Icons.cancel; + final color = ok == null + ? theme.colorScheme.outline + : ok + ? theme.colorScheme.primary + : theme.colorScheme.error; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + children: [ + Icon(icon, size: 18, color: color), + const SizedBox(width: 8), + Expanded(child: Text(label, style: theme.textTheme.bodySmall)), + Text( + ok == null ? '未检测' : ok ? '正常' : '异常', + style: theme.textTheme.bodySmall?.copyWith(color: color), + ), + ], + ), + ); + } + void _setLocalServer(bool enabled) { setState(() => _localSignalingEnabled = enabled); } @@ -203,6 +306,77 @@ class _SettingsPageState extends State { ), ), ), + const SizedBox(height: 12), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.health_and_safety, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text('服务检测', style: theme.textTheme.titleMedium), + const Spacer(), + TextButton.icon( + onPressed: _checkingServices ? null : _runServiceCheck, + icon: _checkingServices + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + label: Text(_checkingServices ? '检测中' : '检测'), + ), + ], + ), + const SizedBox(height: 8), + _serviceRow('Rust Core 动态库', _serviceResult?.nativeCoreLoaded), + _serviceRow('本机信令进程', _serviceResult?.localSignalingRunning), + _serviceRow('信令 /healthz', _serviceResult?.signalingReachable), + _serviceRow('本机监听服务', _serviceResult?.listenerRunning), + _serviceRow('主控监听端口 41001', _serviceResult?.listenerReachable), + const Divider(height: 24), + Row( + children: [ + Expanded( + child: Text('本机监听端点', style: theme.textTheme.titleSmall), + ), + TextButton.icon( + onPressed: _toggleListener, + icon: Icon( + _listenerRunning ? Icons.stop : Icons.play_arrow, + size: 18, + ), + label: Text(_listenerRunning ? '停止' : '启动'), + ), + ], + ), + Text( + _localListener == null + ? '未获取到本机 IPv4 地址' + : '${_localListener!.ip}:${_localListener!.controlPort} · 媒体 ${_localListener!.mediaPort}', + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 4), + Text( + '该端点仅用于被控端接入,不再显示在主页设备列表。', + style: theme.textTheme.bodySmall, + ), + if (_serviceResult != null && _serviceResult!.signalingUrl.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + '检测地址:${_serviceResult!.signalingUrl}', + style: theme.textTheme.labelSmall, + ), + ), + ], + ), + ), + ), const Divider(height: 32), SwitchListTile( title: const Text('优先使用 H.265'), diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index a2c723a..3dc7d58 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -1,8 +1,10 @@ import 'dart:async'; +import 'dart:io'; import 'package:flutter/material.dart'; import 'core/bridge.dart'; +import 'core/diagnostic_log.dart'; import 'core/native_core.dart'; import 'core/models.dart'; import 'features/control/control_toolbar.dart'; @@ -41,7 +43,12 @@ class HomePage extends StatefulWidget { class _HomePageState extends State { NativeCore? _nativeCore; late final SenderBridge _bridge; + final DiagnosticLog _diagnosticLog = DiagnosticLog(); Timer? _demoStatusTimer; + Timer? _diagnosticTimer; + Timer? _connectWatchdog; + Timer? _discoveryTimer; + Timer? _videoStatsTimer; List _devices = const []; DeviceInfo? _selected; @@ -51,6 +58,8 @@ class _HomePageState extends State { bool _localSignalingRunning = false; bool _refreshing = false; Map _demoStatus = const {'running': false}; + Map _videoStats = const {}; + int? _textureId; String? _nativeError; @override @@ -62,7 +71,10 @@ class _HomePageState extends State { _nativeError = error.toString(); } _bridge = SenderBridge(nativeCore: _nativeCore); + _diagnosticLog.start(); + _diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}'); _bridge.watchPhase().listen((phase) { + _diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})'); if (mounted) setState(() => _phase = phase); }); _applySignalingSettings(); @@ -71,11 +83,34 @@ class _HomePageState extends State { const Duration(seconds: 1), (_) => _refreshDemoStatus(), ); + _diagnosticTimer = Timer.periodic( + const Duration(seconds: 1), + (_) => _writeDiagnosticLog(), + ); + _discoveryTimer = Timer.periodic( + const Duration(seconds: 5), + (_) => _refreshDevices(), + ); + _videoStatsTimer = Timer.periodic( + const Duration(milliseconds: 500), + (_) => _refreshVideoStats(), + ); + _refreshVideoTextureId(); + // 自测/演示用开关:TTSTD_DEMO_AUTOSTART=1 时启动即开启本机监听。 + if (Platform.environment['TTSTD_DEMO_AUTOSTART'] == '1') { + _startDemoListener(); + } + _writeDiagnosticLog(); } @override void dispose() { _demoStatusTimer?.cancel(); + _diagnosticTimer?.cancel(); + _connectWatchdog?.cancel(); + _discoveryTimer?.cancel(); + _videoStatsTimer?.cancel(); + _diagnosticLog.dispose(); _bridge.stopDemoServer(); _bridge.stopLocalSignaling(); _nativeCore?.dispose(); @@ -92,16 +127,65 @@ class _HomePageState extends State { final connected = status['peerConnected'] == true; final keyEstablished = status['keyEstablished'] == true; if (running && connected && keyEstablished) { + _connectWatchdog?.cancel(); _phase = ConnectionPhase.direct; - } else if (running && _phase != ConnectionPhase.idle) { + } else if (running && + _phase != ConnectionPhase.idle && + _phase != ConnectionPhase.failed) { _phase = ConnectionPhase.probing; } }); - } on Object catch (_) { - // 动态库不可用时忽略轮询错误。 + } on Object catch (error) { + _diagnosticLog.write('demoStatus refresh failed: $error'); } } + /// 首帧前先取一次纹理 ID,避免等待轮询。 + Future _refreshVideoTextureId() async { + final id = await _bridge.videoTextureId(); + if (!mounted || id == null || id == _textureId) return; + setState(() => _textureId = id); + } + + /// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。 + Future _refreshVideoStats() async { + if (!mounted) return; + final stats = await _bridge.videoStats(); + if (!mounted || stats.isEmpty) return; + final id = stats['textureId']; + setState(() { + _videoStats = stats; + if (_textureId == null && id is int && id > 0) { + _textureId = id; + } + }); + } + + void _writeDiagnosticLog() { + Map status; + if (_nativeCore == null) { + status = {'available': false, 'error': _nativeError ?? ''}; + } else { + try { + status = _bridge.demoStatus(); + } on Object catch (error) { + status = {'available': true, 'error': error.toString()}; + } + } + final selected = _selected; + final target = selected == null + ? '-' + : '${selected.id} ${selected.ip}:${selected.mediaPort}/${selected.controlPort}'; + _diagnosticLog.write( + 'phase=${_phase.wireName} label=${_phase.label}; ' + 'devices=${_devices.length} target=$target refreshing=$_refreshing; ' + 'signaling local=${_settings.useLocalSignaling} ' + 'running=$_localSignalingRunning url=$_effectiveSignalingUrl; ' + 'nativeError=${_nativeError ?? '-'}; textureId=${_textureId ?? '-'}; ' + 'video=$_videoStats; demoStatus=$status', + ); + } + Future _applySignalingSettings() async { if (_settings.localSignalingEnabled) { final started = await _bridge.startLocalSignaling(_settings.localSignalingPort); @@ -115,12 +199,13 @@ class _HomePageState extends State { final url = await _bridge.resolveSignalingUrl(_settings); if (!mounted) return; setState(() => _effectiveSignalingUrl = url); + unawaited(_refreshDevices()); } Future _refreshDevices() async { if (_refreshing) return; setState(() => _refreshing = true); - final devices = await _bridge.discover(); + final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl); if (!mounted) return; setState(() { _devices = devices; @@ -129,16 +214,42 @@ class _HomePageState extends State { } _refreshing = false; }); + _diagnosticLog.write('discover result: ${devices.length} devices'); } Future _connect() async { final device = _selected; if (device == null) return; + _diagnosticLog.write( + 'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}', + ); + _connectWatchdog?.cancel(); setState(() => _phase = ConnectionPhase.probing); - await _bridge.connect(device); + _connectWatchdog = Timer(const Duration(seconds: 10), () { + if (!mounted || _phase != ConnectionPhase.probing) return; + _diagnosticLog.write('connect timeout after 10s'); + _writeDiagnosticLog(); + setState(() => _phase = ConnectionPhase.failed); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('连接超时:被控端未接入,请检查 IP、端口和网络')), + ); + }); + try { + await _bridge.connect(device); + } on Object catch (error) { + _connectWatchdog?.cancel(); + _diagnosticLog.write('connect failed: $error'); + if (!mounted) return; + setState(() => _phase = ConnectionPhase.failed); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('连接失败:$error')), + ); + } } Future _disconnect() async { + _diagnosticLog.write('disconnect requested'); + _connectWatchdog?.cancel(); await _bridge.disconnect(); if (!mounted) return; setState(() => _phase = ConnectionPhase.idle); @@ -317,12 +428,88 @@ class _HomePageState extends State { (peerIp.isEmpty ? '' : ' · 对端 $peerIp'), style: Theme.of(context).textTheme.bodySmall, ), + const SizedBox(height: 6), + Text( + "诊断日志:${_diagnosticLog.path.isEmpty ? '不可写' : _diagnosticLog.path}", + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 10), + Row( + children: [ + FilledButton.tonalIcon( + onPressed: _nativeError != null || _demoRunning + ? null + : _startDemoListener, + icon: const Icon(Icons.dns_outlined, size: 18), + label: const Text('启动本机监听'), + ), + const SizedBox(width: 8), + OutlinedButton.icon( + onPressed: _demoRunning ? _stopDemoListener : null, + icon: const Icon(Icons.stop_circle_outlined, size: 18), + label: const Text('停止'), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + _demoRunning + ? 'TCP 41001 / UDP 41000 已监听,等待被控端接入' + : '监听未开启:被控端无法反连本机', + style: Theme.of(context).textTheme.bodySmall, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), ], ), ), ); } + bool get _demoRunning => _demoStatus['running'] == true; + + void _startDemoListener() { + final started = _bridge.startDemoServer(); + _diagnosticLog.write('demo listener start -> $started'); + if (!mounted) return; + setState(() { + if (started) { + _phase = ConnectionPhase.probing; + } + }); + if (!started) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('启动本机监听失败:端口可能被占用')), + ); + } + } + + void _stopDemoListener() { + _bridge.stopDemoServer(); + _diagnosticLog.write('demo listener stopped'); + if (!mounted) return; + setState(() => _phase = ConnectionPhase.idle); + } + + String get _videoResolution { + final width = _videoStats['width']; + final height = _videoStats['height']; + if (width is int && height is int && width > 0 && height > 0) { + return '${width}x$height'; + } + return _selected?.resolution ?? ''; + } + + int? get _videoPts { + final decoded = _videoStats['decoded']; + final pts = _videoStats['pts']; + if (decoded is int && decoded > 0 && pts is int) return pts; + return null; + } + + String get _videoError => (_videoStats['error'] as String? ?? '').trim(); + Widget _buildStage() { return Padding( padding: const EdgeInsets.all(16), @@ -330,9 +517,11 @@ class _HomePageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ VideoView( - textureId: null, + textureId: _textureId, connected: _phase.isConnected, - resolution: _selected?.resolution ?? '', + resolution: _videoResolution, + pts: _videoPts, + error: _videoError, ), const SizedBox(height: 16), ConnectBar( diff --git a/flutter_sender/test/discovery_client_test.dart b/flutter_sender/test/discovery_client_test.dart new file mode 100644 index 0000000..e6bcdcc --- /dev/null +++ b/flutter_sender/test/discovery_client_test.dart @@ -0,0 +1,46 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_sender/core/discovery_client.dart'; + +void main() { + test('通过信令 /list 解析在线设备', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) async { + if (request.uri.path != '/list') { + request.response.statusCode = HttpStatus.notFound; + await request.response.close(); + return; + } + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode({ + 'devices': [ + { + 'deviceId': 'android-1', + 'name': 'Android Receiver', + 'ip': '10.0.2.15', + 'mediaPort': 41000, + 'controlPort': 41001, + 'fp': '', + 'cap': ['h264', 'opus'], + 'model': 'Pixel 8', + 'res': '1080x2400', + }, + ], + })); + await request.response.close(); + }); + + final devices = await DiscoveryClient.listDevices( + 'http://127.0.0.1:${server.port}', + ); + + expect(devices, hasLength(1)); + expect(devices.first.id, 'android-1'); + expect(devices.first.name, 'Android Receiver'); + expect(devices.first.ip, '10.0.2.15'); + expect(devices.first.controlPort, 41001); + }); +} diff --git a/flutter_sender/windows/runner/CMakeLists.txt b/flutter_sender/windows/runner/CMakeLists.txt index 394917c..25cd32a 100644 --- a/flutter_sender/windows/runner/CMakeLists.txt +++ b/flutter_sender/windows/runner/CMakeLists.txt @@ -10,6 +10,7 @@ add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" + "video_texture.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" @@ -20,6 +21,9 @@ add_executable(${BINARY_NAME} WIN32 # that need different build settings. apply_standard_settings(${BINARY_NAME}) +# 源码为 UTF-8(含中文注释与提示),避免默认代码页导致的 C4819 警告被 /WX 转成错误。 +target_compile_options(${BINARY_NAME} PRIVATE "/utf-8") + # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") @@ -33,8 +37,24 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +# 内嵌的首个插件(视频纹理)需要 plugin 版 wrapper 的 PluginRegistrar/MethodChannel 实现。 +target_link_libraries(${BINARY_NAME} PRIVATE flutter_wrapper_plugin) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +# Media Foundation:H.264/HEVC 解码到 Flutter 外部纹理。 +target_link_libraries(${BINARY_NAME} PRIVATE "mfplat.lib" "mfuuid.lib" "mf.lib" "ole32.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) + +# 把 Rust Core cdylib 复制到可执行文件目录,供 dart:ffi 与视频解码插件加载。 +set(TTSTD_CORE_DLL + "${CMAKE_CURRENT_SOURCE_DIR}/../../../rust_core/target/release/ttstdconnect_core.dll") +if(EXISTS "${TTSTD_CORE_DLL}") + add_custom_command(TARGET ${BINARY_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${TTSTD_CORE_DLL}" + "$/ttstdconnect_core.dll" + COMMENT "Copying ttstdconnect_core.dll" + ) +endif() diff --git a/flutter_sender/windows/runner/flutter_window.cpp b/flutter_sender/windows/runner/flutter_window.cpp index 955ee30..fcd239c 100644 --- a/flutter_sender/windows/runner/flutter_window.cpp +++ b/flutter_sender/windows/runner/flutter_window.cpp @@ -3,6 +3,7 @@ #include #include "flutter/generated_plugin_registrant.h" +#include "video_texture.h" FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} @@ -25,6 +26,9 @@ bool FlutterWindow::OnCreate() { return false; } RegisterPlugins(flutter_controller_->engine()); + // 视频解码纹理:把 Rust Core 收到的视频帧解码后交给 Flutter 的 Texture 组件。 + RegisterVideoTexturePlugin( + flutter_controller_->engine()->GetRegistrarForPlugin("TTSTDVideoTexture")); SetChildContent(flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { diff --git a/flutter_sender/windows/runner/video_texture.cpp b/flutter_sender/windows/runner/video_texture.cpp new file mode 100644 index 0000000..9a72f2a --- /dev/null +++ b/flutter_sender/windows/runner/video_texture.cpp @@ -0,0 +1,1010 @@ +#include "video_texture.h" + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// 与 Rust Core 的 TtstdVideoFrame 内存布局保持一致(24 字节)。 +struct TtstdVideoFrame { + uint64_t seq; + uint64_t pts; + uint32_t len; + uint8_t format; + uint8_t flags; + uint16_t reserved; +}; +static_assert(sizeof(TtstdVideoFrame) == 24, + "TtstdVideoFrame 布局必须与 Rust 侧一致"); + +constexpr int32_t kErrBufferTooSmall = -1; +constexpr uint8_t kFormatH264 = 1; +constexpr uint8_t kFormatHevc = 2; +// 与 Rust 侧 media::FLAG_KEYFRAME 一致。 +constexpr uint8_t kFlagKeyframe = 0x01; +constexpr DWORD kOutputStreamId = 0; +constexpr size_t kInitialPayloadCapacity = 512 * 1024; +constexpr DWORD kIdleSleepMs = 2; +constexpr DWORD kRetrySleepMs = 1000; +constexpr DWORD kMaxOutputsPerDrain = 4; + +// 是否包含解码所需的配置 NAL:H.264 的 SPS(7),HEVC 的 VPS/SPS/PPS(32/33/34)。 +bool HasCodecConfig(const uint8_t* data, size_t len, uint8_t format) { + size_t offset = 0; + for (size_t i = 0; i + 3 < len; ++i) { + if (data[i] != 0 || data[i + 1] != 0) { + continue; + } + if (data[i + 2] == 1) { + offset = i + 3; + } else if (data[i + 2] == 0 && i + 4 < len && data[i + 3] == 1) { + offset = i + 4; + } else { + continue; + } + if (offset >= len) { + return false; + } + const uint8_t header = data[offset]; + if (format == kFormatHevc) { + const uint8_t type = static_cast((header >> 1) & 0x3F); + if (type == 32 || type == 33 || type == 34) { + return true; + } + } else if ((header & 0x1F) == 7) { + return true; + } + i = offset; + } + return false; +} + +// 极简 COM 智能指针(工程编译选项关闭了异常,避免依赖 WRL)。 +template +class ComPtr { + public: + ComPtr() = default; + ~ComPtr() { Reset(); } + + ComPtr(const ComPtr& other) : ptr_(other.ptr_) { + if (ptr_ != nullptr) { + ptr_->AddRef(); + } + } + + ComPtr(ComPtr&& other) noexcept : ptr_(other.ptr_) { other.ptr_ = nullptr; } + + ComPtr& operator=(const ComPtr& other) { + if (this != &other) { + Reset(); + ptr_ = other.ptr_; + if (ptr_ != nullptr) { + ptr_->AddRef(); + } + } + return *this; + } + + ComPtr& operator=(ComPtr&& other) noexcept { + if (this != &other) { + Reset(); + ptr_ = other.ptr_; + other.ptr_ = nullptr; + } + return *this; + } + + T* Get() const { return ptr_; } + T* operator->() const { return ptr_; } + explicit operator bool() const { return ptr_ != nullptr; } + + // 供 COM 输出参数使用:清空后返回内部指针地址。 + T** Put() { + Reset(); + return &ptr_; + } + + void Attach(T* raw) { + Reset(); + ptr_ = raw; + } + + T* Detach() { + T* raw = ptr_; + ptr_ = nullptr; + return raw; + } + + void Reset() { + if (ptr_ != nullptr) { + ptr_->Release(); + ptr_ = nullptr; + } + } + + private: + T* ptr_ = nullptr; +}; + +template +bool ResolveExport(HMODULE module, const char* name, FunctionPtr* target) { + FARPROC address = GetProcAddress(module, name); + if (address == nullptr) { + return false; + } + void* raw = nullptr; + static_assert(sizeof(raw) == sizeof(FARPROC), "FARPROC 尺寸必须与 void* 一致"); + std::memcpy(&raw, &address, sizeof(raw)); + FunctionPtr typed = nullptr; + static_assert(sizeof(typed) == sizeof(raw), "函数指针尺寸必须与 void* 一致"); + std::memcpy(&typed, &raw, sizeof(typed)); + *target = typed; + return true; +} + +// Rust Core 暴露的视频队列读取接口。 +class RustVideoApi { + public: + using NextFn = int32_t (*)(TtstdVideoFrame*, uint8_t*, size_t); + using PendingFn = uint32_t (*)(); + + bool EnsureLoaded() { + if (loaded_) { + return true; + } + HMODULE module = GetModuleHandleW(L"ttstdconnect_core.dll"); + if (module == nullptr) { + module = LoadLibraryW(L"ttstdconnect_core.dll"); + } + if (module == nullptr) { + // 兜底:从可执行文件所在目录加载(Dart 尚未调用 FFI 时)。 + wchar_t exe_path[MAX_PATH] = {}; + const DWORD length = GetModuleFileNameW(nullptr, exe_path, MAX_PATH); + if (length > 0 && length < MAX_PATH) { + std::wstring directory(exe_path, length); + const size_t slash = directory.find_last_of(L"\\/"); + if (slash != std::wstring::npos) { + directory.resize(slash + 1); + module = LoadLibraryW((directory + L"ttstdconnect_core.dll").c_str()); + } + } + } + if (module == nullptr) { + error_ = "无法加载 ttstdconnect_core.dll"; + return false; + } + if (!ResolveExport(module, "ttstd_video_next", &next_) || + !ResolveExport(module, "ttstd_video_pending", &pending_)) { + error_ = "动态库缺少视频队列导出(请重新构建 Rust Core)"; + return false; + } + loaded_ = true; + error_.clear(); + return true; + } + + const std::string& error() const { return error_; } + + uint32_t Pending() const { + return (loaded_ && pending_ != nullptr) ? pending_() : 0; + } + + int32_t Next(TtstdVideoFrame* meta, uint8_t* buffer, size_t capacity) const { + if (!loaded_ || next_ == nullptr) { + return 0; + } + return next_(meta, buffer, capacity); + } + + private: + bool loaded_ = false; + NextFn next_ = nullptr; + PendingFn pending_ = nullptr; + std::string error_; +}; + +// 最近一帧 BGRA 画面。渲染线程与解码线程共享。 +class FrameStore { + public: + void Publish(std::shared_ptr> frame, + int width, + int height, + uint64_t pts) { + std::lock_guard lock(mutex_); + // 上一帧先留作 retired_,等本次替换过去才释放, + // 避免渲染线程正在拷贝时被回收。 + retired_ = std::move(front_); + front_ = std::move(frame); + width_ = width; + height_ = height; + pts_ = pts; + ++frames_; + } + + // 渲染线程调用:返回当前帧与尺寸,无画面时返回 nullptr。 + const uint8_t* Acquire(int* width, int* height, uint64_t* pts) { + std::lock_guard lock(mutex_); + if (!front_ || front_->empty() || width_ <= 0 || height_ <= 0) { + return nullptr; + } + *width = width_; + *height = height_; + *pts = pts_; + return front_->data(); + } + + uint64_t frames() { + std::lock_guard lock(mutex_); + return frames_; + } + + uint64_t pts() { + std::lock_guard lock(mutex_); + return pts_; + } + + void size(int* width, int* height) { + std::lock_guard lock(mutex_); + *width = width_; + *height = height_; + } + + private: + std::mutex mutex_; + std::shared_ptr> front_; + std::shared_ptr> retired_; + int width_ = 0; + int height_ = 0; + uint64_t pts_ = 0; + uint64_t frames_ = 0; +}; + +void ClampToByte(int value, uint8_t* out) { + if (value < 0) { + *out = 0; + } else if (value > 255) { + *out = 255; + } else { + *out = static_cast(value); + } +} + +// BT.601 有限范围 NV12 -> BGRA(按显示区域裁剪掉解码补齐的行)。 +void ConvertNv12(const uint8_t* data, + size_t length, + int coded_width, + int coded_height, + int crop_x, + int crop_y, + int visible_width, + int visible_height, + int luma_stride, + int chroma_stride, + std::vector* out) { + const size_t y_size = static_cast(luma_stride) * coded_height; + const size_t uv_size = + static_cast(chroma_stride) * ((coded_height + 1) / 2); + if (length < y_size + uv_size || visible_width <= 0 || visible_height <= 0) { + return; + } + out->assign(static_cast(visible_width) * visible_height * 4, 0xff); + const uint8_t* uv_plane = data + y_size; + for (int row = 0; row < visible_height; ++row) { + const int source_row = crop_y + row; + if (source_row < 0 || source_row >= coded_height) { + continue; + } + const uint8_t* y_row = + data + static_cast(source_row) * luma_stride + crop_x; + const uint8_t* uv_row = + uv_plane + static_cast(source_row / 2) * chroma_stride + crop_x; + uint8_t* dst = + out->data() + static_cast(row) * visible_width * 4; + for (int column = 0; column < visible_width; ++column) { + const int c = static_cast(y_row[column]) - 16; + const int u = static_cast(uv_row[(column & ~1)]) - 128; + const int v = static_cast(uv_row[(column & ~1) + 1]) - 128; + const int scaled = c < 0 ? 0 : c; + ClampToByte((298 * scaled + 409 * v + 128) >> 8, dst); + ClampToByte((298 * scaled - 100 * u - 208 * v + 128) >> 8, dst + 1); + ClampToByte((298 * scaled + 516 * u + 128) >> 8, dst + 2); + dst[3] = 0xff; + dst += 4; + } + } +} + +// RGB32(XRGB) -> BGRA,顺带补齐 alpha 并处理自底向上的负 stride。 +void ConvertRgb32(const uint8_t* data, + size_t length, + int coded_width, + int coded_height, + int crop_x, + int crop_y, + int visible_width, + int visible_height, + int stride, + std::vector* out) { + const int row_bytes = coded_width * 4; + const int abs_stride = stride < 0 ? -stride : stride; + const int source_stride = abs_stride < row_bytes ? row_bytes : abs_stride; + if (length < static_cast(source_stride) * coded_height || + visible_width <= 0 || visible_height <= 0) { + return; + } + const int visible_bytes = visible_width * 4; + out->assign(static_cast(visible_width) * visible_height * 4, 0xff); + for (int row = 0; row < visible_height; ++row) { + const int logical_row = crop_y + row; + if (logical_row < 0 || logical_row >= coded_height) { + continue; + } + const int source_row = stride < 0 ? (coded_height - 1 - logical_row) + : logical_row; + const uint8_t* src = data + static_cast(source_row) * source_stride + + static_cast(crop_x) * 4; + uint8_t* dst = out->data() + static_cast(row) * visible_bytes; + std::memcpy(dst, src, static_cast(visible_bytes)); + for (int column = 0; column < visible_width; ++column) { + dst[column * 4 + 3] = 0xff; + } + } +} + +// Media Foundation 视频解码器封装(H.264 / HEVC)。 +class VideoDecoder { + public: + using FrameCallback = std::function>, int, int, uint64_t)>; + + VideoDecoder() = default; + ~VideoDecoder() { Close(); } + + VideoDecoder(const VideoDecoder&) = delete; + VideoDecoder& operator=(const VideoDecoder&) = delete; + + bool IsOpen() const { return transform_.Get() != nullptr; } + uint8_t format() const { return format_; } + const std::string& error() const { return error_; } + + bool Open(uint8_t format) { + Close(); + if (!mf_started_) { + const HRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE); + if (FAILED(hr)) { + error_ = "MFStartup 失败"; + return false; + } + mf_started_ = true; + } + format_ = format; + const GUID subtype = + (format == kFormatHevc) ? MFVideoFormat_HEVC : MFVideoFormat_H264; + if (!CreateTransform(subtype)) { + Close(); + return false; + } + if (!SetInputType(subtype)) { + error_ = "设置解码器输入类型失败"; + Close(); + return false; + } + // 首次协商可能失败(部分解码器要收到数据后才给出输出类型), + // 后续在 Drain 中继续尝试。 + NegotiateOutputType(); + + ConfigureLowLatency(); + + transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); + transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0); + transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0); + error_.clear(); + return true; + } + + void Close() { + if (transform_) { + transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0); + transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0); + transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); + transform_.Reset(); + } + output_type_.Reset(); + output_type_valid_ = false; + output_subtype_ = GUID{}; + output_width_ = 0; + output_height_ = 0; + } + + HRESULT Submit(const uint8_t* data, size_t length, uint64_t pts) { + if (!transform_) { + return E_FAIL; + } + ComPtr buffer; + HRESULT hr = MFCreateMemoryBuffer(static_cast(length), buffer.Put()); + if (FAILED(hr)) { + return hr; + } + BYTE* destination = nullptr; + hr = buffer->Lock(&destination, nullptr, nullptr); + if (FAILED(hr)) { + return hr; + } + std::memcpy(destination, data, length); + buffer->Unlock(); + buffer->SetCurrentLength(static_cast(length)); + + ComPtr sample; + hr = MFCreateSample(sample.Put()); + if (FAILED(hr)) { + return hr; + } + sample->AddBuffer(buffer.Get()); + // Rust 侧 pts 单位为微秒,MF 使用 100 纳秒。 + sample->SetSampleTime(static_cast(pts) * 10); + sample->SetSampleDuration(0); + last_pts_ = pts; + return transform_->ProcessInput(kOutputStreamId, sample.Get(), 0); + } + + void Drain(const FrameCallback& on_frame) { + if (!transform_) { + return; + } + if (!output_type_valid_ && FAILED(NegotiateOutputType())) { + return; + } + for (DWORD iteration = 0; iteration < kMaxOutputsPerDrain; ++iteration) { + MFT_OUTPUT_STREAM_INFO stream_info = {}; + if (FAILED(transform_->GetOutputStreamInfo(kOutputStreamId, + &stream_info))) { + return; + } + const bool decoder_allocates = + (stream_info.dwFlags & + (MFT_OUTPUT_STREAM_PROVIDES_SAMPLES | + MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES)) != 0; + + ComPtr provided; + ComPtr provided_buffer; + if (!decoder_allocates) { + if (FAILED(MFCreateSample(provided.Put()))) { + return; + } + const DWORD buffer_size = + stream_info.cbSize > 0 ? stream_info.cbSize : (1920u * 1080u * 4u); + if (FAILED(MFCreateMemoryBuffer(buffer_size, provided_buffer.Put()))) { + return; + } + if (FAILED(provided->AddBuffer(provided_buffer.Get()))) { + return; + } + } + + MFT_OUTPUT_DATA_BUFFER output = {}; + output.dwStreamID = kOutputStreamId; + output.pSample = provided.Get(); + DWORD status = 0; + const HRESULT hr = + transform_->ProcessOutput(0, 1, &output, &status); + if (output.pEvents != nullptr) { + output.pEvents->Release(); + output.pEvents = nullptr; + } + if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) { + return; + } + if (hr == MF_E_TRANSFORM_STREAM_CHANGE) { + NegotiateOutputType(); + continue; + } + if (FAILED(hr)) { + return; + } + + ComPtr produced; + if (output.pSample == provided.Get()) { + produced = provided; + } else { + produced.Attach(output.pSample); + } + if (produced) { + LONGLONG sample_time = 0; + uint64_t output_pts = last_pts_; + if (SUCCEEDED(produced->GetSampleTime(&sample_time)) && sample_time >= 0) { + output_pts = static_cast(sample_time) / 10; + } + ExtractFrame(produced.Get(), output_pts, on_frame); + } + } + } + + private: + // 远程桌面场景要求低延迟:让解码器尽快吐帧,而不是为了「平滑播放」攒缓冲。 + void ConfigureLowLatency() { + ComPtr codec_api; + if (SUCCEEDED(transform_->QueryInterface( + __uuidof(ICodecAPI), + reinterpret_cast(codec_api.Put())))) { + VARIANT value = {}; + value.vt = VT_BOOL; + value.boolVal = VARIANT_TRUE; + codec_api->SetValue(&CODECAPI_AVLowLatencyMode, &value); + } + ComPtr attributes; + if (SUCCEEDED(transform_->GetAttributes(attributes.Put()))) { + attributes->SetUINT32(MF_LOW_LATENCY, 1); + } + } + + bool CreateTransform(const GUID& subtype) { + MFT_REGISTER_TYPE_INFO input_info = {MFMediaType_Video, subtype}; + IMFActivate** activates = nullptr; + UINT32 count = 0; + const HRESULT hr = MFTEnumEx( + MFT_CATEGORY_VIDEO_DECODER, + MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_LOCALMFT | + MFT_ENUM_FLAG_SORTANDFILTER, + &input_info, nullptr, &activates, &count); + if (FAILED(hr)) { + error_ = "枚举视频解码器失败"; + return false; + } + bool activated = false; + for (UINT32 index = 0; index < count && !activated; ++index) { + if (activates[index] == nullptr) { + continue; + } + ComPtr transform; + const HRESULT activate_hr = activates[index]->ActivateObject( + __uuidof(IMFTransform), + reinterpret_cast(transform.Put())); + if (SUCCEEDED(activate_hr) && transform) { + transform_ = std::move(transform); + activated = true; + } + } + for (UINT32 index = 0; index < count; ++index) { + if (activates[index] != nullptr) { + activates[index]->Release(); + } + } + CoTaskMemFree(activates); + if (!activated) { + error_ = (subtype == MFVideoFormat_HEVC) + ? "系统没有可用的 HEVC 解码器" + : "系统没有可用的 H.264 解码器"; + return false; + } + return true; + } + + bool SetInputType(const GUID& subtype) { + ComPtr input_type; + if (FAILED(MFCreateMediaType(input_type.Put()))) { + return false; + } + input_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); + input_type->SetGUID(MF_MT_SUBTYPE, subtype); + if (SUCCEEDED(transform_->SetInputType(kOutputStreamId, input_type.Get(), + 0))) { + return true; + } + // 部分解码器要求输入类型中带上帧尺寸。 + const UINT32 candidates[][2] = {{1920, 1080}, {1280, 720}, {3840, 2160}}; + for (const auto& candidate : candidates) { + ComPtr sized_type; + if (FAILED(MFCreateMediaType(sized_type.Put()))) { + continue; + } + sized_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); + sized_type->SetGUID(MF_MT_SUBTYPE, subtype); + MFSetAttributeSize(sized_type.Get(), MF_MT_FRAME_SIZE, candidate[0], + candidate[1]); + MFSetAttributeRatio(sized_type.Get(), MF_MT_FRAME_RATE, 30, 1); + MFSetAttributeRatio(sized_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1); + if (SUCCEEDED(transform_->SetInputType(kOutputStreamId, sized_type.Get(), + 0))) { + return true; + } + } + return false; + } + + HRESULT NegotiateOutputType() { + output_type_.Reset(); + output_type_valid_ = false; + if (!transform_) { + return E_FAIL; + } + ComPtr nv12; + ComPtr rgb32; + ComPtr fallback; + for (DWORD index = 0;; ++index) { + ComPtr candidate; + const HRESULT hr = transform_->GetOutputAvailableType( + kOutputStreamId, index, candidate.Put()); + if (FAILED(hr)) { + break; + } + GUID subtype = {}; + if (FAILED(candidate->GetGUID(MF_MT_SUBTYPE, &subtype))) { + continue; + } + if (IsEqualGUID(subtype, MFVideoFormat_NV12) != 0) { + if (!nv12) { + nv12 = candidate; + } + } else if (IsEqualGUID(subtype, MFVideoFormat_RGB32) != 0 || + IsEqualGUID(subtype, MFVideoFormat_ARGB32) != 0) { + if (!rgb32) { + rgb32 = candidate; + } + } else if (!fallback) { + fallback = candidate; + } + } + ComPtr chosen; + if (nv12) { + chosen = nv12; + } else if (rgb32) { + chosen = rgb32; + } else { + chosen = fallback; + } + if (!chosen) { + return MF_E_INVALIDMEDIATYPE; + } + const HRESULT hr = + transform_->SetOutputType(kOutputStreamId, chosen.Get(), 0); + if (FAILED(hr)) { + return hr; + } + UINT32 width = 0; + UINT32 height = 0; + if (FAILED(MFGetAttributeSize(chosen.Get(), MF_MT_FRAME_SIZE, &width, + &height)) || + width == 0 || height == 0) { + return MF_E_INVALIDTYPE; + } + GUID subtype = {}; + if (FAILED(chosen->GetGUID(MF_MT_SUBTYPE, &subtype))) { + return MF_E_INVALIDTYPE; + } + output_subtype_ = subtype; + output_width_ = static_cast(width); + output_height_ = static_cast(height); + // 默认显示区域等于编码尺寸;解码器会补到 16 对齐,多余行通过 + // MF_MT_MINIMUM_DISPLAY_APERTURE 裁掉。 + crop_x_ = 0; + crop_y_ = 0; + visible_width_ = output_width_; + visible_height_ = output_height_; + MFVideoArea area = {}; + UINT32 blob_size = 0; + if (SUCCEEDED(chosen->GetBlob(MF_MT_MINIMUM_DISPLAY_APERTURE, + reinterpret_cast(&area), + sizeof(area), &blob_size)) && + blob_size == sizeof(area) && area.Area.cx > 0 && area.Area.cy > 0 && + area.OffsetX.value >= 0 && area.OffsetY.value >= 0 && + area.OffsetX.value + area.Area.cx <= output_width_ && + area.OffsetY.value + area.Area.cy <= output_height_) { + crop_x_ = area.OffsetX.value; + crop_y_ = area.OffsetY.value; + visible_width_ = static_cast(area.Area.cx); + visible_height_ = static_cast(area.Area.cy); + } + output_type_ = chosen; + output_type_valid_ = true; + return S_OK; + } + + void ExtractFrame(IMFSample* sample, + uint64_t pts, + const FrameCallback& on_frame) { + if (!output_type_valid_ || output_width_ <= 0 || output_height_ <= 0) { + return; + } + ComPtr buffer; + HRESULT hr = sample->ConvertToContiguousBuffer(buffer.Put()); + if (FAILED(hr)) { + return; + } + BYTE* data = nullptr; + DWORD length = 0; + hr = buffer->Lock(&data, nullptr, &length); + if (FAILED(hr)) { + return; + } + UINT32 raw_stride = 0; + if (FAILED(output_type_->GetUINT32(MF_MT_DEFAULT_STRIDE, &raw_stride))) { + raw_stride = 0; + } + const int stride = static_cast(raw_stride); + const bool is_nv12 = IsEqualGUID(output_subtype_, MFVideoFormat_NV12) != 0; + + auto frame = std::make_shared>(); + if (is_nv12) { + const int luma_stride = stride > 0 ? stride : output_width_; + ConvertNv12(data, static_cast(length), output_width_, + output_height_, crop_x_, crop_y_, visible_width_, + visible_height_, luma_stride, luma_stride, frame.get()); + } else if (IsEqualGUID(output_subtype_, MFVideoFormat_RGB32) != 0 || + IsEqualGUID(output_subtype_, MFVideoFormat_ARGB32) != 0) { + ConvertRgb32(data, static_cast(length), output_width_, + output_height_, crop_x_, crop_y_, visible_width_, + visible_height_, stride, frame.get()); + } else { + buffer->Unlock(); + return; + } + buffer->Unlock(); + if (frame->empty()) { + return; + } + on_frame(std::move(frame), visible_width_, visible_height_, pts); + } + + ComPtr transform_; + ComPtr output_type_; + GUID output_subtype_ = {}; + int output_width_ = 0; + int output_height_ = 0; + int crop_x_ = 0; + int crop_y_ = 0; + int visible_width_ = 0; + int visible_height_ = 0; + bool output_type_valid_ = false; + bool mf_started_ = false; + uint8_t format_ = kFormatH264; + uint64_t last_pts_ = 0; + std::string error_; +}; + +// 视频纹理插件:注册外部纹理,并把解码结果交给 Flutter 渲染。 +class VideoTexturePlugin : public flutter::Plugin { + public: + static void RegisterWith(FlutterDesktopPluginRegistrarRef registrar) { + auto* windows_registrar = + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar); + auto plugin = std::make_unique(windows_registrar); + windows_registrar->AddPlugin(std::move(plugin)); + } + + explicit VideoTexturePlugin(flutter::PluginRegistrarWindows* registrar) + : registrar_(registrar), + texture_registrar_(registrar->texture_registrar()), + frames_(std::make_shared()) { + auto shared_frames = frames_; + texture_variant_ = std::make_unique( + flutter::PixelBufferTexture([this, shared_frames](size_t width, + size_t height) { + return CopyPixelBuffer(shared_frames.get(), width, height); + })); + if (texture_registrar_ != nullptr) { + texture_id_ = + texture_registrar_->RegisterTexture(texture_variant_.get()); + } + channel_ = std::make_unique>( + registrar->messenger(), "ttstd/video", + &flutter::StandardMethodCodec::GetInstance()); + channel_->SetMethodCallHandler( + [this](const flutter::MethodCall& call, + std::unique_ptr> + result) { HandleMethodCall(call, std::move(result)); }); + + worker_ = std::thread([this, shared_frames]() { RunWorker(shared_frames); }); + } + + ~VideoTexturePlugin() override { + stop_.store(true); + if (worker_.joinable()) { + worker_.join(); + } + if (texture_registrar_ != nullptr && texture_id_ != 0) { + texture_registrar_->UnregisterTexture(texture_id_, + std::function()); + texture_id_ = 0; + } + } + + private: + const FlutterDesktopPixelBuffer* CopyPixelBuffer(FrameStore* store, + size_t /*width*/, + size_t /*height*/) { + int width = 0; + int height = 0; + uint64_t pts = 0; + const uint8_t* pixels = store->Acquire(&width, &height, &pts); + if (pixels == nullptr) { + return nullptr; + } + descriptor_.buffer = pixels; + descriptor_.width = static_cast(width); + descriptor_.height = static_cast(height); + descriptor_.release_callback = nullptr; + descriptor_.release_context = nullptr; + return &descriptor_; + } + + void HandleMethodCall( + const flutter::MethodCall& call, + std::unique_ptr> result) { + if (call.method_name() == "textureId") { + result->Success(flutter::EncodableValue( + static_cast(texture_id_))); + return; + } + if (call.method_name() == "stats") { + flutter::EncodableMap map; + int width = 0; + int height = 0; + frames_->size(&width, &height); + map[flutter::EncodableValue("textureId")] = + flutter::EncodableValue(static_cast(texture_id_)); + map[flutter::EncodableValue("decoded")] = + flutter::EncodableValue(static_cast(frames_->frames())); + map[flutter::EncodableValue("pending")] = + flutter::EncodableValue(static_cast(api_.Pending())); + map[flutter::EncodableValue("received")] = + flutter::EncodableValue(static_cast(received_)); + map[flutter::EncodableValue("width")] = + flutter::EncodableValue(static_cast(width)); + map[flutter::EncodableValue("height")] = + flutter::EncodableValue(static_cast(height)); + 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 && + frames_->frames() == 0) { + // 裸流缺少 SPS/PPS 时解码器会一直「吃数据不出图」且不报错, + // 这里显式指出,避免和「没收到码流」混为一谈。 + error = "被控端码流缺少 SPS/PPS,请更新被控端 APK 后重连"; + } + map[flutter::EncodableValue("error")] = flutter::EncodableValue(error); + map[flutter::EncodableValue("format")] = + flutter::EncodableValue(static_cast(last_format_)); + map[flutter::EncodableValue("auBytes")] = + flutter::EncodableValue(static_cast(last_bytes_)); + map[flutter::EncodableValue("keyframes")] = + flutter::EncodableValue(static_cast(keyframes_)); + map[flutter::EncodableValue("submitHr")] = + flutter::EncodableValue(static_cast(last_hr_)); + result->Success(flutter::EncodableValue(map)); + return; + } + result->NotImplemented(); + } + + void RunWorker(std::shared_ptr store) { + // Media Foundation 需要 MTA;已初始化时返回 RPC_E_CHANGED_MODE 可忽略。 + const HRESULT com_hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + + std::vector buffer(kInitialPayloadCapacity, 0); + std::vector pending; + TtstdVideoFrame pending_meta = {}; + bool has_pending = false; + + while (!stop_.load()) { + if (!has_pending) { + if (!api_.EnsureLoaded()) { + Sleep(kRetrySleepMs); + continue; + } + const int32_t written = + api_.Next(&pending_meta, buffer.data(), buffer.size()); + if (written == kErrBufferTooSmall) { + const size_t required = + pending_meta.len > buffer.size() ? pending_meta.len : buffer.size(); + buffer.resize(required + 64 * 1024); + continue; + } + if (written <= 0) { + Sleep(kIdleSleepMs); + continue; + } + pending.assign(buffer.begin(), buffer.begin() + written); + has_pending = true; + ++received_; + last_format_ = pending_meta.format; + last_bytes_ = written; + if ((pending_meta.flags & kFlagKeyframe) != 0) { + ++keyframes_; + } + if (!saw_codec_config_.load() && + HasCodecConfig(buffer.data(), static_cast(written), + pending_meta.format)) { + saw_codec_config_.store(true); + } + } + + if (!decoder_.IsOpen() || decoder_.format() != pending_meta.format) { + if (!decoder_.Open(pending_meta.format)) { + // 解码器不可用(例如缺少 HEVC 扩展):丢弃当前帧,稍后重试。 + // 失败原因通过 stats.error 暴露给 Dart 诊断日志。 + has_pending = false; + Sleep(kRetrySleepMs); + continue; + } + } + + HRESULT hr = decoder_.Submit(pending.data(), pending.size(), + pending_meta.pts); + if (hr == MF_E_NOTACCEPTING) { + decoder_.Drain(MakeFrameCallback(store)); + hr = decoder_.Submit(pending.data(), pending.size(), pending_meta.pts); + } + last_hr_ = static_cast(hr); + has_pending = false; + if (SUCCEEDED(hr)) { + decoder_.Drain(MakeFrameCallback(store)); + } + } + + decoder_.Close(); + if (SUCCEEDED(com_hr)) { + CoUninitialize(); + } + } + + // 把解码帧写进纹理并通知引擎重绘。 + std::function>, int, int, uint64_t)> + MakeFrameCallback(const std::shared_ptr& store) { + return [this, store](std::shared_ptr> frame, int width, + int height, uint64_t pts) { + store->Publish(std::move(frame), width, height, pts); + if (texture_registrar_ != nullptr && texture_id_ != 0) { + texture_registrar_->MarkTextureFrameAvailable(texture_id_); + } + }; + } + + flutter::PluginRegistrarWindows* registrar_ = nullptr; + flutter::TextureRegistrar* texture_registrar_ = nullptr; + std::unique_ptr texture_variant_; + std::unique_ptr> channel_; + FlutterDesktopPixelBuffer descriptor_ = {}; + std::shared_ptr frames_; + RustVideoApi api_; + VideoDecoder decoder_; + std::atomic stop_{false}; + std::thread worker_; + int64_t texture_id_ = 0; + std::atomic received_{0}; + std::atomic keyframes_{0}; + std::atomic saw_codec_config_{false}; + std::atomic last_bytes_{0}; + std::atomic last_hr_{0}; + std::atomic last_format_{kFormatH264}; +}; + +} // namespace + +void RegisterVideoTexturePlugin(FlutterDesktopPluginRegistrarRef registrar) { + VideoTexturePlugin::RegisterWith(registrar); +} diff --git a/flutter_sender/windows/runner/video_texture.h b/flutter_sender/windows/runner/video_texture.h new file mode 100644 index 0000000..0518547 --- /dev/null +++ b/flutter_sender/windows/runner/video_texture.h @@ -0,0 +1,12 @@ +#ifndef RUNNER_VIDEO_TEXTURE_H_ +#define RUNNER_VIDEO_TEXTURE_H_ + +#include + +// 注册视频纹理插件: +// 1. 向 Dart 暴露 "ttstd/video" 方法通道(textureId / stats); +// 2. 用 Media Foundation 解码 Rust Core 队列中的 H.264/HEVC 访问单元; +// 3. 通过 Flutter 外部纹理把 BGRA 帧交给 Texture 组件渲染。 +void RegisterVideoTexturePlugin(FlutterDesktopPluginRegistrarRef registrar); + +#endif // RUNNER_VIDEO_TEXTURE_H_ diff --git a/rust_core/examples/video_feed.rs b/rust_core/examples/video_feed.rs new file mode 100644 index 0000000..6d98fd3 --- /dev/null +++ b/rust_core/examples/video_feed.rs @@ -0,0 +1,247 @@ +//! 开发工具:把 Annex-B H.264 码流文件按访问单元推送给本机 demo 服务端。 +//! +//! 用于在没有 Android 被控端时验证桌面端「Rust 队列 -> Media Foundation 解码 -> +//! Flutter 纹理」整条画面链路。 +//! +//! 用法(先启动主控端并点击“启动本机监听”): +//! +//! ```powershell +//! cargo run --release --offline --example video_feed -- test_pattern.h264 +//! ``` +//! +//! 码流需带有访问单元分隔符(ffmpeg 的 `-x264-params aud=1`),否则整段会被当成一帧。 +//! 第 5 个参数是分片负载上限(默认 1200 字节,与 Android 被控端一致;传 0 关闭分片)。 + +use std::env; +use std::fs; +use std::io::{Read, Write}; +use std::net::{TcpStream, UdpSocket}; +use std::thread; +use std::time::Duration; + +use ttstdconnect_core::crypto::{derive_subkey, EphemeralKeyPair}; +use ttstdconnect_core::media::stream::{FLAG_FRAGMENT_CONTINUE, FLAG_FRAGMENT_END, FLAG_FRAGMENT_START}; +use ttstdconnect_core::media::{encode_media_packet, MediaPacket, FLAG_KEYFRAME}; + +const DEFAULT_CONTROL_PORT: u16 = 41001; +const DEFAULT_VIDEO_PORT: u16 = 41000; +const DEFAULT_FPS: u64 = 30; +const DEFAULT_CHUNK: usize = 1200; + +fn main() { + let mut args = env::args().skip(1); + let path = match args.next() { + Some(path) => path, + None => { + eprintln!( + "用法: video_feed [fps] [control_port] [video_port] [chunk]" + ); + std::process::exit(2); + } + }; + let fps: u64 = args + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_FPS) + .max(1); + let control_port: u16 = args + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_CONTROL_PORT); + let video_port: u16 = args + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_VIDEO_PORT); + let chunk: usize = args + .next() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_CHUNK); + + let data = match fs::read(&path) { + Ok(data) => data, + Err(error) => { + eprintln!("读取码流失败 {}: {}", path, error); + std::process::exit(1); + } + }; + let units = access_units(&data); + if units.is_empty() { + eprintln!("码流里没有找到访问单元"); + std::process::exit(1); + } + println!( + "码流 {} 字节,切出 {} 个访问单元,按 {} fps 推送", + data.len(), + units.len(), + fps + ); + + // 1. 与控制端口完成 ECDH 握手。 + let mut control = match TcpStream::connect(("127.0.0.1", control_port)) { + Ok(stream) => stream, + Err(error) => { + eprintln!("连接控制端口 {} 失败:{}(请先启动 demo 服务)", control_port, error); + std::process::exit(1); + } + }; + let _ = control.set_read_timeout(Some(Duration::from_secs(3))); + let pair = EphemeralKeyPair::generate().expect("生成 ECDH 密钥"); + let public = pair.public_bytes().to_vec(); + if let Err(error) = control.write_all(&public) { + eprintln!("发送公钥失败:{}", error); + std::process::exit(1); + } + let mut peer_public = [0u8; 65]; + if let Err(error) = control.read_exact(&mut peer_public) { + eprintln!("读取主控端公钥失败:{}", error); + std::process::exit(1); + } + let shared = match pair.into_shared_secret(&peer_public) { + Ok(secret) => secret, + Err(_) => { + eprintln!("ECDH 协商失败"); + std::process::exit(1); + } + }; + let video_key = derive_subkey(&shared, b"lancast/video/v1").expect("派生视频密钥"); + println!("握手完成,开始推送视频"); + + // 2. 逐个访问单元封装为媒体包并通过 UDP 发送。 + let socket = UdpSocket::bind("127.0.0.1:0").expect("创建 UDP socket"); + let frame_interval = Duration::from_micros(1_000_000 / fps); + for (index, unit) in units.iter().enumerate() { + let payload = &data[unit.start..unit.end]; + let mut flags = 0u8; + if contains_idr(payload) { + flags |= FLAG_KEYFRAME; + } + let pts = index as u64 * (1_000_000 / fps); + let mut failed = false; + if chunk == 0 || payload.len() <= chunk { + let packet = encode_media_packet( + &MediaPacket { + pts, + flags, + payload: payload.to_vec(), + }, + &video_key, + ); + if let Err(error) = socket.send_to(&packet, ("127.0.0.1", video_port)) { + eprintln!("发送视频包失败:{}", error); + failed = true; + } + } else { + // 与 Android 被控端一致:大帧切成 ≤chunk 字节的分片。 + let mut offset = 0usize; + while offset < payload.len() { + let end = (offset + chunk).min(payload.len()); + let mut fragment_flags = flags + | if offset == 0 { + FLAG_FRAGMENT_START + } else { + FLAG_FRAGMENT_CONTINUE + }; + if end == payload.len() { + fragment_flags |= FLAG_FRAGMENT_END; + } + let packet = encode_media_packet( + &MediaPacket { + pts, + flags: fragment_flags, + payload: payload[offset..end].to_vec(), + }, + &video_key, + ); + if let Err(error) = socket.send_to(&packet, ("127.0.0.1", video_port)) { + eprintln!("发送视频分片失败:{}", error); + failed = true; + break; + } + offset = end; + } + } + if failed { + break; + } + if index % 30 == 0 { + println!("已推送 {} 帧", index); + } + thread::sleep(frame_interval); + } + println!("推送结束,共 {} 帧", units.len()); +} + +#[derive(Debug, Clone, Copy)] +struct AccessUnit { + start: usize, + end: usize, +} + +/// 按访问单元分隔符(AUD, NAL type 9)切分 Annex-B 码流。 +fn access_units(data: &[u8]) -> Vec { + let nals = nal_units(data); + if nals.is_empty() { + return Vec::new(); + } + let mut boundaries = Vec::new(); + for nal in &nals { + if nal.nal_type == 9 { + boundaries.push(nal.start); + } + } + if boundaries.is_empty() { + // 没有 AUD:整段作为一次访问单元。 + return vec![AccessUnit { + start: nals[0].start, + end: data.len(), + }]; + } + if boundaries[0] > nals[0].start { + boundaries[0] = nals[0].start; + } + let mut units = Vec::with_capacity(boundaries.len()); + for (index, start) in boundaries.iter().enumerate() { + let end = boundaries.get(index + 1).copied().unwrap_or(data.len()); + units.push(AccessUnit { start: *start, end }); + } + units +} + +#[derive(Debug, Clone, Copy)] +struct NalUnit { + /// NAL 起始位置(包含 start code)。 + start: usize, + nal_type: u8, +} + +fn nal_units(data: &[u8]) -> Vec { + let mut nals = Vec::new(); + let mut index = 0usize; + while index + 3 < data.len() { + if data[index] != 0 || data[index + 1] != 0 { + index += 1; + continue; + } + let (start_code_len, header_index) = if data[index + 2] == 1 { + (3usize, index + 3) + } else if data[index + 2] == 0 && data[index + 3] == 1 { + (4usize, index + 4) + } else { + index += 1; + continue; + }; + if let Some(&header) = data.get(header_index) { + nals.push(NalUnit { + start: index, + nal_type: header & 0x1f, + }); + } + index += start_code_len; + } + nals +} + +fn contains_idr(unit: &[u8]) -> bool { + let nals = nal_units(unit); + nals.iter().any(|nal| nal.nal_type == 5) +} diff --git a/rust_core/src/demo_server.rs b/rust_core/src/demo_server.rs index b67b496..3c1cae1 100644 --- a/rust_core/src/demo_server.rs +++ b/rust_core/src/demo_server.rs @@ -151,40 +151,48 @@ fn server_handle() -> &'static ServerHandle { /// 启动 demo 服务端。重复调用会返回 ERR_ALREADY_RUNNING。 pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(), String> { let handle = server_handle(); - if handle.shared.running.swap(true, Ordering::SeqCst) { - return Err("demo 服务端已在运行".to_string()); + if handle.shared.running.load(Ordering::SeqCst) { + return Ok(()); } + handle.shared.running.store(true, Ordering::SeqCst); - let listener = TcpListener::bind(("0.0.0.0", control_port)) - .map_err(|error| format!("监听 TCP {} 失败:{}", control_port, error))?; - let video = UdpSocket::bind(("0.0.0.0", video_port)) - .map_err(|error| format!("监听 UDP {} 失败:{}", video_port, error))?; - let audio = UdpSocket::bind(("0.0.0.0", audio_port)) - .map_err(|error| format!("监听 UDP {} 失败:{}", audio_port, error))?; - listener - .set_nonblocking(true) - .map_err(|error| format!("设置 TCP 非阻塞失败:{}", error))?; - video - .set_read_timeout(Some(Duration::from_millis(200))) - .map_err(|error| format!("设置 UDP 超时失败:{}", error))?; - audio - .set_read_timeout(Some(Duration::from_millis(200))) - .map_err(|error| format!("设置 UDP 超时失败:{}", error))?; + let result = (|| -> Result<(), String> { + let listener = TcpListener::bind(("0.0.0.0", control_port)) + .map_err(|error| format!("监听 TCP {} 失败:{}", control_port, error))?; + let video = UdpSocket::bind(("0.0.0.0", video_port)) + .map_err(|error| format!("监听 UDP {} 失败:{}", video_port, error))?; + let audio = UdpSocket::bind(("0.0.0.0", audio_port)) + .map_err(|error| format!("监听 UDP {} 失败:{}", audio_port, error))?; + listener + .set_nonblocking(true) + .map_err(|error| format!("设置 TCP 非阻塞失败:{}", error))?; + video + .set_read_timeout(Some(Duration::from_millis(200))) + .map_err(|error| format!("设置 UDP 超时失败:{}", error))?; + audio + .set_read_timeout(Some(Duration::from_millis(200))) + .map_err(|error| format!("设置 UDP 超时失败:{}", error))?; - let shared = Arc::clone(&handle.shared); - let tcp = thread::spawn(move || run_tcp(listener, shared)); - let video_thread = { let shared = Arc::clone(&handle.shared); - thread::spawn(move || run_udp(video, shared, "video")) - }; - let audio_thread = { - let shared = Arc::clone(&handle.shared); - thread::spawn(move || run_udp(audio, shared, "audio")) - }; - if let Ok(mut threads) = handle.threads.lock() { - threads.extend([tcp, video_thread, audio_thread]); + let tcp = thread::spawn(move || run_tcp(listener, shared)); + let video_thread = { + let shared = Arc::clone(&handle.shared); + thread::spawn(move || run_udp(video, shared, "video")) + }; + let audio_thread = { + let shared = Arc::clone(&handle.shared); + thread::spawn(move || run_udp(audio, shared, "audio")) + }; + if let Ok(mut threads) = handle.threads.lock() { + threads.extend([tcp, video_thread, audio_thread]); + } + Ok(()) + })(); + + if result.is_err() { + handle.shared.running.store(false, Ordering::SeqCst); } - Ok(()) + result } /// 停止 demo 服务端。 @@ -193,6 +201,7 @@ pub fn stop() { handle.shared.running.store(false, Ordering::SeqCst); handle.shared.peer_connected.store(false, Ordering::SeqCst); handle.shared.key_established.store(false, Ordering::SeqCst); + crate::media::stream::clear(); } /// 读取当前状态快照。 @@ -286,7 +295,7 @@ fn run_tcp(listener: TcpListener, shared: Arc) { } shared.peer_connected.store(true, Ordering::Relaxed); shared.push_event(format!("peer:{}", address)); - let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); handle_peer(&mut stream, &shared); shared.peer_connected.store(false, Ordering::Relaxed); shared.key_established.store(false, Ordering::Relaxed); @@ -359,6 +368,7 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc) { } let mut buffer = Vec::new(); let mut chunk = [0u8; 4096]; + let mut keepalive_sequence = 0u16; while shared.running.load(Ordering::Relaxed) { let read = match stream.read(&mut chunk) { Ok(0) => { @@ -366,6 +376,27 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc) { break; } Ok(size) => size, + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => + { + keepalive_sequence = keepalive_sequence.wrapping_add(1); + let ping = ControlEvent::new( + keepalive_sequence, + ControlEventKind::Ping(0), + ); + let Ok(frame) = channel.encode(&ping) else { + continue; + }; + if stream.write_all(&frame).is_err() { + shared.push_event("control:keepalive-write-error".to_string()); + break; + } + let _ = stream.flush(); + continue; + } Err(error) => { shared.push_event(format!("control:read-error:{}", error)); break; @@ -409,6 +440,8 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc) { fn run_udp(socket: UdpSocket, shared: Arc, kind: &str) { let mut buffer = [0u8; MAX_FRAME]; + // 视频大帧会被发送端切成多个 UDP 分片,这里按序重组。 + let mut reassembler = crate::media::stream::Reassembler::new(); while shared.running.load(Ordering::Relaxed) { let (size, source) = match socket.recv_from(&mut buffer) { Ok(value) => value, @@ -427,14 +460,33 @@ fn run_udp(socket: UdpSocket, shared: Arc, kind: &str) { } }; match decode_media_packet(&buffer[..size], &key) { - Ok(Some((packet, _))) => shared.push_event(format!( - "{}:pts={}:flags={}:bytes={}:from={}", - kind, - packet.pts, - packet.flags, - packet.payload.len(), - source - )), + Ok(Some((packet, _))) => { + if kind == "video" { + // 视频访问单元重组后进入解码队列,由桌面端原生解码线程消费。 + if let Some((pts, flags, payload)) = + reassembler.push(packet.pts, packet.flags, &packet.payload) + { + shared.push_event(format!( + "{}:pts={}:flags={}:bytes={}:from={}", + kind, + pts, + flags, + payload.len(), + source + )); + crate::media::stream::push(pts, flags, &payload); + } + } else { + shared.push_event(format!( + "{}:pts={}:flags={}:bytes={}:from={}", + kind, + packet.pts, + packet.flags, + packet.payload.len(), + source + )); + } + } Ok(None) => shared.push_event(format!("error:{}:incomplete", kind)), Err(error) => shared.push_event(format!("error:{}:{}", kind, error)), } diff --git a/rust_core/src/ffi.rs b/rust_core/src/ffi.rs index 5a7d537..cbb90e0 100644 --- a/rust_core/src/ffi.rs +++ b/rust_core/src/ffi.rs @@ -391,8 +391,76 @@ pub unsafe extern "C" fn ttstd_demo_status(out_json: *mut u8, capacity: usize) - copy_out(json.as_bytes(), out_json, capacity) } +/// 视频访问单元元信息。字段布局需与 Windows 原生解码侧保持一致。 +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct TtstdVideoFrame { + /// 访问单元序号,单调递增。 + pub seq: u64, + /// 呈现时间戳(微秒)。 + pub pts: u64, + /// 负载字节数。 + pub len: u32, + /// 负载格式:1=H.264 Annex-B,2=HEVC Annex-B。 + pub format: u8, + /// 媒体包标志位(bit0=关键帧)。 + pub flags: u8, + /// 对齐保留字段。 + pub reserved: u16, +} + +/// 当前待解码的访问单元数量。 +#[no_mangle] +pub extern "C" fn ttstd_video_pending() -> u32 { + crate::media::stream::stats().queued as u32 +} + +/// 读取队首视频访问单元。 +/// +/// - 返回 `0`:队列为空。 +/// - 返回正数:实际写入 `out` 的字节数,该访问单元已出队。 +/// - 返回 `ERR_BUFFER_TOO_SMALL`:`out` 容量不足,`meta` 已写入所需长度,访问单元保留在队列中。 +/// +/// # Safety +/// meta 必须可写;out 可写且容量为 capacity。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_video_next( + meta: *mut TtstdVideoFrame, + out: *mut u8, + capacity: usize, +) -> i32 { + let Some(front) = crate::media::stream::peek_meta() else { + return 0; + }; + if !meta.is_null() { + *meta = TtstdVideoFrame { + seq: front.seq, + pts: front.pts, + len: front.len as u32, + format: front.format, + flags: front.flags, + reserved: 0, + }; + } + if out.is_null() || capacity < front.len { + return ERR_BUFFER_TOO_SMALL; + } + let buffer = slice::from_raw_parts_mut(out, front.len); + match crate::media::stream::pop_into(front.seq, buffer) { + Some(taken) => taken.len as i32, + None => 0, + } +} + +/// 视频队列统计 JSON(诊断用)。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_video_stats(out_json: *mut u8, capacity: usize) -> i32 { + let json = crate::media::stream::stats_json(); + copy_out(json.as_bytes(), out_json, capacity) +} + /// ABI 版本,便于 Dart 侧校验动态库是否匹配。 #[no_mangle] pub extern "C" fn ttstd_core_abi_revision() -> i32 { - 1 + 2 } diff --git a/rust_core/src/media/mod.rs b/rust_core/src/media/mod.rs index 545d528..3681099 100644 --- a/rust_core/src/media/mod.rs +++ b/rust_core/src/media/mod.rs @@ -1,5 +1,9 @@ pub mod packet; pub mod renderer; +pub mod stream; pub use packet::{decode_media_packet, encode_media_packet, MediaError, MediaPacket, FLAG_AUDIO, FLAG_KEYFRAME}; pub use renderer::{AudioSink, DecodedFrame, FrameQueue, PixelFormat, VideoRenderer}; +pub use stream::{ + AccessUnit, AccessUnitMeta, Reassembler, StreamStats, FORMAT_H264, FORMAT_HEVC, +}; diff --git a/rust_core/src/media/stream.rs b/rust_core/src/media/stream.rs new file mode 100644 index 0000000..527e55c --- /dev/null +++ b/rust_core/src/media/stream.rs @@ -0,0 +1,404 @@ +//! 视频访问单元队列。 +//! +//! UDP 接收线程把解出 MAC 的视频包(一个访问单元)推进队列, +//! 桌面端原生解码线程(Media Foundation)按序取走并解码成纹理。 +//! 队列只做搬运与限流,不做解码:解码依赖平台的硬件/系统解码器。 + +use std::collections::VecDeque; +use std::sync::{Mutex, MutexGuard, OnceLock}; + +/// 队列上限:超出后丢弃最旧的访问单元,避免内存无上限增长。 +/// 丢弃会破坏参考帧链,画面会花屏直到下一个关键帧。 +pub const MAX_QUEUED_UNITS: usize = 240; + +/// 负载格式:H.264 Annex-B 字节流。 +pub const FORMAT_H264: u8 = 1; +/// 负载格式:HEVC(H.265) Annex-B 字节流。 +pub const FORMAT_HEVC: u8 = 2; + +/// 一个待解码的视频访问单元。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccessUnit { + pub seq: u64, + pub pts: u64, + pub flags: u8, + pub format: u8, + pub data: Vec, +} + +/// 队列统计快照。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StreamStats { + pub received: u64, + pub dropped: u64, + pub dequeued: u64, + pub queued: usize, + pub bytes: u64, + pub last_pts: u64, + pub last_flags: u8, + pub last_format: u8, +} + +#[derive(Debug)] +struct StreamState { + queue: VecDeque, + next_seq: u64, + stats: StreamStats, +} + +impl StreamState { + const fn new() -> Self { + Self { + queue: VecDeque::new(), + next_seq: 1, + stats: StreamStats { + received: 0, + dropped: 0, + dequeued: 0, + queued: 0, + bytes: 0, + last_pts: 0, + last_flags: 0, + last_format: 0, + }, + } + } +} + +static STREAM: OnceLock> = OnceLock::new(); + +fn state() -> MutexGuard<'static, StreamState> { + match STREAM.get_or_init(|| Mutex::new(StreamState::new())).lock() { + Ok(guard) => guard, + // 队列锁被毒化时丢弃旧状态继续工作,避免整条视频链路僵死。 + Err(poisoned) => poisoned.into_inner(), + } +} + +/// 媒体包标志位:负载为 HEVC(由发送端设置,缺省按 H.264 处理)。 +pub const FLAG_HEVC: u8 = 0x08; +/// 分片标志:一个访问单元的第一个分片。 +pub const FLAG_FRAGMENT_START: u8 = 0x10; +/// 分片标志:中间分片。 +pub const FLAG_FRAGMENT_CONTINUE: u8 = 0x20; +/// 分片标志:最后一个分片。 +pub const FLAG_FRAGMENT_END: u8 = 0x40; + +const FRAGMENT_MASK: u8 = FLAG_FRAGMENT_START | FLAG_FRAGMENT_CONTINUE | FLAG_FRAGMENT_END; +/// 单个访问单元的重组上限(超过即视为码流异常并丢弃)。 +const MAX_ACCESS_UNIT: usize = 8 * 1024 * 1024; + +/// 由媒体包标志位推断编解码格式。 +pub fn format_from_flags(flags: u8) -> u8 { + if flags & FLAG_HEVC != 0 { + FORMAT_HEVC + } else { + FORMAT_H264 + } +} + +/// 分片重组器:把超过 MTU 的访问单元重新拼回完整帧。 +/// +/// 发送端把大帧切成 ≤1200 字节的分片,用分片标志标注首尾; +/// 未带任何分片标志的包按「单包完整访问单元」处理,兼容旧发送端。 +#[derive(Debug, Default)] +pub struct Reassembler { + buffer: Vec, + flags: u8, + pts: u64, + active: bool, +} + +impl Reassembler { + pub fn new() -> Self { + Self::default() + } + + /// 送入一个媒体包负载;凑齐整个访问单元时返回 `(pts, flags, 完整负载)`。 + pub fn push(&mut self, pts: u64, flags: u8, payload: &[u8]) -> Option<(u64, u8, Vec)> { + if flags & FRAGMENT_MASK == 0 { + self.reset(); + return Some((pts, flags, payload.to_vec())); + } + if flags & FLAG_FRAGMENT_START != 0 { + self.buffer.clear(); + self.flags = flags & !FRAGMENT_MASK; + self.pts = pts; + self.active = true; + } else if !self.active { + // 没有收到起始分片,丢弃孤儿分片。 + return None; + } + if self.buffer.len() + payload.len() > MAX_ACCESS_UNIT { + self.reset(); + return None; + } + self.buffer.extend_from_slice(payload); + if flags & FLAG_FRAGMENT_END != 0 { + let data = std::mem::take(&mut self.buffer); + let complete_flags = self.flags; + let complete_pts = self.pts; + self.active = false; + return Some((complete_pts, complete_flags, data)); + } + None + } + + pub fn reset(&mut self) { + self.buffer.clear(); + self.flags = 0; + self.pts = 0; + self.active = false; + } +} + +/// 调试开关:`TTSTD_DUMP_VIDEO=<文件路径>` 时把收到的访问单元按到达顺序 +/// 追加写入该文件(Annex-B),可直接用 ffmpeg 验证被控端码流是否可解码。 +fn dump_path() -> Option<&'static str> { + static PATH: OnceLock> = OnceLock::new(); + PATH.get_or_init(|| { + std::env::var("TTSTD_DUMP_VIDEO") + .ok() + .filter(|value| !value.is_empty()) + }) + .as_deref() +} + +fn dump_access_unit(data: &[u8]) { + use std::io::Write; + let Some(path) = dump_path() else { return }; + let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + else { + return; + }; + let _ = file.write_all(data); +} + +/// 推入一个视频访问单元,返回分配到的序号。 +pub fn push(pts: u64, flags: u8, data: &[u8]) -> u64 { + dump_access_unit(data); + let mut guard = state(); + let seq = guard.next_seq; + guard.next_seq = guard.next_seq.wrapping_add(1).max(1); + guard.stats.received += 1; + guard.stats.bytes += data.len() as u64; + guard.stats.last_pts = pts; + guard.stats.last_flags = flags; + let format = format_from_flags(flags); + guard.stats.last_format = format; + while guard.queue.len() >= MAX_QUEUED_UNITS { + guard.queue.pop_front(); + guard.stats.dropped += 1; + } + guard.queue.push_back(AccessUnit { + seq, + pts, + flags, + format, + data: data.to_vec(), + }); + guard.stats.queued = guard.queue.len(); + seq +} + +/// 访问单元元信息(不含负载)。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AccessUnitMeta { + pub seq: u64, + pub pts: u64, + pub flags: u8, + pub format: u8, + pub len: usize, +} + +impl AccessUnitMeta { + fn from_unit(unit: &AccessUnit) -> Self { + Self { + seq: unit.seq, + pts: unit.pts, + flags: unit.flags, + format: unit.format, + len: unit.data.len(), + } + } +} + +/// 查看队首访问单元的元信息(不出队)。 +pub fn peek_meta() -> Option { + state().queue.front().map(AccessUnitMeta::from_unit) +} + +/// 取出最早的一个访问单元。 +pub fn pop() -> Option { + let mut guard = state(); + let unit = guard.queue.pop_front(); + if unit.is_some() { + guard.stats.dequeued += 1; + } + guard.stats.queued = guard.queue.len(); + unit +} + +/// 把队首访问单元的负载拷贝到 `out` 并出队。 +/// +/// 序号不匹配(已被其他消费者取走)或缓冲区不足时不出队并返回 `None`。 +pub fn pop_into(expected_seq: u64, out: &mut [u8]) -> Option { + let mut guard = state(); + let front = guard.queue.front()?; + if front.seq != expected_seq || out.len() < front.data.len() { + return None; + } + let meta = AccessUnitMeta::from_unit(front); + out[..meta.len].copy_from_slice(&front.data); + guard.queue.pop_front(); + guard.stats.dequeued += 1; + guard.stats.queued = guard.queue.len(); + Some(meta) +} + +/// 队首访问单元的字节长度(无数据时为 0)。 +pub fn front_len() -> usize { + state().queue.front().map(|unit| unit.data.len()).unwrap_or(0) +} + +/// 清空队列,用于连接重置。 +pub fn clear() { + let mut guard = state(); + guard.queue.clear(); + guard.stats.queued = 0; +} + +/// 读取统计快照。 +pub fn stats() -> StreamStats { + state().stats +} + +/// 统计快照的 JSON 表示,供诊断日志使用。 +pub fn stats_json() -> String { + let snapshot = stats(); + format!( + concat!( + "{{\"received\":{},\"dropped\":{},\"dequeued\":{},\"queued\":{},", + "\"bytes\":{},\"lastPts\":{},\"lastFlags\":{},\"lastFormat\":{}}}" + ), + snapshot.received, + snapshot.dropped, + snapshot.dequeued, + snapshot.queued, + snapshot.bytes, + snapshot.last_pts, + snapshot.last_flags, + snapshot.last_format + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Mutex, MutexGuard, OnceLock}; + + const ANNEX_B_SPS: [u8; 8] = [0, 0, 0, 1, 0x67, 0x42, 0x00, 0x1f]; + const ANNEX_B_IDR: [u8; 7] = [0, 0, 0, 1, 0x65, 0x88, 0x84]; + + /// 队列是全局状态,用例之间必须串行执行。 + fn exclusive() -> MutexGuard<'static, ()> { + static GUARD: OnceLock> = OnceLock::new(); + GUARD + .get_or_init(|| Mutex::new(())) + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + #[test] + fn format_follows_packet_flag() { + assert_eq!(format_from_flags(0), FORMAT_H264); + assert_eq!(format_from_flags(crate::media::packet::FLAG_KEYFRAME), FORMAT_H264); + assert_eq!(format_from_flags(FLAG_HEVC), FORMAT_HEVC); + } + + #[test] + fn push_pop_preserves_order_and_stats() { + let _guard = exclusive(); + clear(); + let before = stats(); + let first = push(100, 1, &ANNEX_B_SPS); + let second = push(200, 0, &ANNEX_B_IDR); + assert!(second > first); + assert_eq!(stats().received - before.received, 2); + assert_eq!(stats().queued, 2); + let unit = pop().expect("应当取到第一个访问单元"); + assert_eq!(unit.pts, 100); + assert_eq!(unit.format, FORMAT_H264); + assert_eq!(unit.data, ANNEX_B_SPS); + assert_eq!(stats().dequeued - before.dequeued, 1); + assert_eq!(pop().map(|value| value.pts), Some(200)); + assert!(pop().is_none()); + assert_eq!(stats().queued, 0); + } + + #[test] + fn pop_into_copies_payload_and_guards_capacity() { + let _guard = exclusive(); + clear(); + let seq = push(7, 1, &ANNEX_B_SPS); + let meta = peek_meta().expect("应有队首元素"); + assert_eq!(meta.seq, seq); + assert_eq!(meta.len, ANNEX_B_SPS.len()); + + let mut too_small = [0u8; 2]; + assert!(pop_into(seq, &mut too_small).is_none()); + assert_eq!(stats().queued, 1, "缓冲区不足时不应出队"); + + let mut buffer = [0u8; 16]; + let taken = pop_into(seq, &mut buffer).expect("容量充足时应出队"); + assert_eq!(&buffer[..taken.len], &ANNEX_B_SPS); + assert_eq!(stats().queued, 0); + assert!(pop_into(seq, &mut buffer).is_none(), "重复出队应失败"); + } + + #[test] + fn reassembler_joins_fragments_in_order() { + let mut reassembler = Reassembler::new(); + assert_eq!( + reassembler.push(1, FLAG_FRAGMENT_START | crate::media::packet::FLAG_KEYFRAME, b"ab"), + None + ); + assert_eq!(reassembler.push(1, FLAG_FRAGMENT_CONTINUE, b"cd"), None); + let (pts, flags, data) = reassembler + .push(1, FLAG_FRAGMENT_CONTINUE | FLAG_FRAGMENT_END, b"ef") + .expect("末尾分片应当拼出完整访问单元"); + assert_eq!(pts, 1); + assert_eq!(flags, crate::media::packet::FLAG_KEYFRAME); + assert_eq!(data, b"abcdef"); + } + + #[test] + fn reassembler_passes_through_single_packet() { + let mut reassembler = Reassembler::new(); + let unit = reassembler.push(9, 0, b"whole"); + assert_eq!(unit, Some((9, 0, b"whole".to_vec()))); + } + + #[test] + fn reassembler_drops_orphan_fragment() { + let mut reassembler = Reassembler::new(); + assert_eq!(reassembler.push(3, FLAG_FRAGMENT_CONTINUE, b"x"), None); + assert_eq!(reassembler.push(3, FLAG_FRAGMENT_END, b"y"), None); + } + + #[test] + fn queue_drops_oldest_when_full() { + let _guard = exclusive(); + clear(); + let before = stats(); + for index in 0..(MAX_QUEUED_UNITS + 3) { + push(index as u64, 0, &ANNEX_B_IDR); + } + assert_eq!(stats().queued, MAX_QUEUED_UNITS); + assert_eq!(stats().dropped - before.dropped, 3); + assert_eq!(pop().map(|value| value.pts), Some(3)); + } +} diff --git a/rust_core/tests/demo_e2e.rs b/rust_core/tests/demo_e2e.rs index ed54e1f..8b0a8bb 100644 --- a/rust_core/tests/demo_e2e.rs +++ b/rust_core/tests/demo_e2e.rs @@ -75,6 +75,19 @@ fn demo_server_handshake_control_and_media_roundtrip() { assert_eq!(downlink_event.sequence(), 99); assert!(matches!(downlink_event.kind, ControlEventKind::Ping(4321))); + thread::sleep(Duration::from_secs(6)); + let idle_status = demo_server::status(); + assert!(idle_status.peer_connected, "空闲 6 秒后连接不应被读超时断开"); + assert!(idle_status.key_established, "空闲 6 秒后会话密钥应保持建立"); + + let mut keepalive = [0u8; 512]; + let keepalive_size = control.read(&mut keepalive).expect("读取保活 Ping"); + let (keepalive_event, _) = channel + .decode(&keepalive[..keepalive_size]) + .expect("解密保活帧") + .expect("完整的保活帧"); + assert!(matches!(keepalive_event.kind, ControlEventKind::Ping(_))); + let video = UdpSocket::bind("127.0.0.1:0").expect("创建视频 UDP"); let video_packet = encode_media_packet( &MediaPacket {