commit 31b9a52eb497e8d7c5be9d54400ce5519ee014e3 Author: tongtongstudio Date: Thu Nov 26 18:24:02 2026 +0800 feat: 接入端到端 demo 与签名变体 - Flutter 桌面端通过 dart:ffi 调用 Rust Core cdylib - 实现 ECDH P-256 密钥协商、HKDF 子密钥派生、AES-256-GCM 控制帧 - Android 被控端用派生密钥做控制帧加密与媒体包 MAC - 新增 libopus JNI 骨架,默认回退 MediaCodec - 新增 aosp/zhanxun/neutral 签名变体与系统 sharedUserId - 本机独立信令服务与设置页开关 - 新增 .gitignore 排除所有编译产物与打包目录 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64280ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# ===== Rust ===== +rust_core/target/ + +# ===== Flutter ===== +flutter_sender/build/ +flutter_sender/.dart_tool/ +flutter_sender/.idea/ +flutter_sender/.flutter-plugins +flutter_sender/.flutter-plugins-dependencies +flutter_sender/*.iml +**/.dart_tool/ +**/build/ + +# ===== Android / Gradle ===== +.gradle/ +.gradle-home/ +.kotlin/ +local.properties +**/build/ +**/.gradle/ +**/.kotlin/ +**/captures/ +**/.externalNativeBuild/ +**/.cxx/ +*.apk +*.aab + +# ===== Go ===== +signaling_server/signaling_server +signaling_server/ttstd-signaling +*.exe +*.test +*.out + +# ===== Packaged distributions ===== +dist/ + +# ===== IDE / OS ===== +.idea/ +.vscode/ +*.iml +.DS_Store +Thumbs.db +desktop.ini + +# ===== Logs ===== +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..58e6c16 --- /dev/null +++ b/README.md @@ -0,0 +1,437 @@ +# 局域网 Android 投屏与远控技术方案 v0.2 + +## 1. 项目定位与边界 + +**目标**:局域网内将 Android 设备屏幕投射到跨平台主控端(Windows / macOS / Linux / Android / iOS),并支持反向控制、剪贴板同步、文件互传。 + +**明确不做**: + +- 不做公网远控(不运营云端服务,信令服务器由用户自部署) +- 不做 iOS 被控(iOS 无系统级屏幕采集 API 给第三方) +- 不复刻小米/华为 Cast+ 那种系统签名级私有链路 + +**参考基线**:scrcpy 的三通道模型(视频 / 音频 / 控制各自独立套接字),在其基础上增加 mDNS + 信令服务器 + TLS 配对 + LocalSend 风格文件子协议。 + +--- + +## 2. 总体架构 + +``` +┌──────────────── 主控端 (Sender / Client) ────────────────┐ +│ Flutter UI(设备列表/扫码/工具栏/设置) │ +│ ↕ MethodChannel / EventChannel / FFI │ +│ Rust Core(flutter_rust_bridge) │ +│ ├ 发现层:mDNS 浏览 + 信令服务器 Watch │ +│ ├ 会话层:TLS 握手 + 证书指纹校验 + ECDH │ +│ ├ 媒体层:UDP/RTP 收流 → 平台硬解 → External Texture │ +│ ├ 控制层:自定义二进制帧(可切换 Protobuf) → TCP 回传 │ +│ └ 文件层:LocalSend-v2-like 子协议客户端 │ +└────────────────────┬─────────────────────────────────────┘ + │ 局域网(同网段直连 / 跨网段经信令交换地址) +┌────────────────────┴─────────────────────────────────────┐ +│ 被控端 (Android Receiver) │ +│ ├ MediaProjection 采集 → MediaCodec H264/H265 硬编 │ +│ ├ AudioPlaybackCapture → OPUS │ +│ ├ InputManager.injectInputEvent(shell 或 A11y) │ +│ ├ 剪贴板监听 → 控制通道回传 │ +│ └ 文件子协议服务端(复用同一 TLS 会话) │ +└──────────────────────────────────────────────────────────┘ + ▲ + │ 仅做地址交换 / 心跳 / 可选 relay + ┌──────┴───────┐ + │ 信令服务器 │ Go 单二进制,用户自部署 + │ (自托管) │ HTTP /list + WebSocket /watch + └──────────────┘ +``` + +**三条通道分离**: + +- **视频**:UDP,自定义包头 `{pts:u64, flags:u8, len:u32}`,无缓冲直渲 +- **音频**:UDP,OPUS,独立端口 +- **控制**:TCP(可复用信令 WS 的独立 stream),双向——下行 InputEvent,上行剪贴板 + +**连接方向**:网络层由**被控端反连主控端监听端口**(scrcpy 默认行为),跨网段场景下由信令服务器协调。 + +--- + +## 3. 技术选型 + +### 3.1 主控端 UI:Flutter + +| 候选 | 结论 | +| --- | --- | +| Flutter | ✅ 选它。四端统一 UI、自绘一致、Hot Reload、视频走 External Texture 不占 Dart 堆 | +| Electron | ❌ Chromium 常驻 120–200MB,视频要绕 canvas | +| Tauri | ⚠️ 体积香但系统 WebView 三端差异要兜,视频纹理得写 Rust 插件 | +| Qt | ⚠️ 性能接近原生但 QML 开发效率低,UI 现代化成本高 | + +行业验证:RustDesk 采用 **Flutter UI + Rust 核心 + flutter_rust_bridge** 的双后端架构;FF-Remote 等新项目也是同一套路。 + +### 3.2 核心逻辑:Rust + +- mDNS:`mdns-sd` crate +- TLS:`rustls` + 自签证书 + SHA-256 指纹 pinning +- 传输:`str0m` 或直接裸 UDP + 自写 RTP 封装 +- 解码:调平台 API(D3D11VA / VideoToolbox / VA-API / MediaCodec),像素零拷贝进纹理 +- 与 Dart 桥:`flutter_rust_bridge` + +### 3.3 信令服务器:Go 单二进制 + +- `POST /register` 设备注册(IP/Port/能力集/设备名/指纹) +- `GET /list` 拉在线设备 +- `WS /watch` 上下线推送 +- `POST /relay` 直连失败时的可选中转(TURN-lite) +- 内置轻量 STUN(可选,跨网段但同 NAT 时用) + +### 3.4 被控端 Android + +- 采集:`MediaProjection`(需用户授权弹窗,绕不开) +- 编码:`MediaCodec` 硬编 H264(兼容优先)/ H265(省带宽) +- 输入注入:两条路 + - **A 线(推荐)**:ADB shell 起 `app_process` 跑 Java 服务端,走 `INJECT_EVENTS` 权限——scrcpy 同款,延迟最低 + - **B 线(免 root)**:AccessibilityService 手势注入,延迟高、按键受限 +- 音频:`AudioPlaybackCapture`(Android 10+) + +--- + +## 4. 协议设计 + +### 4.1 mDNS 服务定义(同网段发现) + +服务类型:`_lancast._tcp.local.` + +TXT 记录: + +``` +txtvers=1 +ver=1 +dev=android +cap=h264,h265,opus,uibc,clipboard,file +res=1920x1080 +model=Pixel8 +fp=<证书SHA256前16字节hex> +sig=<信令服务器URL,可选> +``` + +字段设计参考 LocalSend announce 报文的精简风格 ——`fp` 防自发现,`cap` 让主控端连之前就知道能吃什么。 + +### 4.2 信令协议(跨网段发现) + +```jsonc +// POST /register +{ + "deviceId": "uuid-v4", + "name": "客厅Pixel", + "ip": "192.168.1.10", + "mediaPort": 41000, + "controlPort": 41001, + "fp": "sha256:ab12...", + "cap": ["h264","opus","uibc","clipboard","file"], + "ttl": 30 +} + +// WS /watch 推送 +{ "event": "online|offline|heartbeat", "deviceId": "..." } +``` + +被控端每 15s 发一次 heartbeat,服务器 45s 无心跳摘除。 + +### 4.3 会话握手 + +1. 主控端拿到被控 `ip:controlPort` +2. TCP 连接 → TLS 握手(被控自签证书) +3. 主控端校验证书 SHA-256 == mDNS/信令里公布的 `fp`,不符直接断 +4. ECDH P-256 派生会话密钥 → AES-256-GCM 加密后续控制帧 +5. 视频/音频 UDP 通道用会话密钥派生子密钥,每包带 4 字节 MAC + +**配对模式**(首次):被控端屏幕显示二维码 `lancast://pair?ip=&port=&fp=`,主控扫码存指纹,后续免扫。 + +### 4.4 控制通道二进制帧(重点:自定义二进制 + 抽象接口) + +#### 4.4.1 帧格式定义 + +所有控制消息均采用小端序,定长头部 + 变长负载: + +```c +// 控制帧头部(8 字节) +struct ControlFrameHeader { + u8 version; // 当前 = 1 + u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong + u16 sequence; // 递增序号,用于去重/重传 + u32 payload_len; // 负载长度(不包括头部) +}; + +// 各类负载(举例) +struct TouchEvent { + u8 action; // 0=down 1=up 2=move 3=cancel + u8 pointer_id; + i16 x, y; // 绝对像素坐标 + u16 pressure; // 0-1000 +}; + +struct MouseEvent { + u8 action; // 0=down 1=up 2=move + i16 x, y; + u8 buttons; // bit0=left bit1=right bit2=middle +}; + +struct KeyboardEvent { + u8 action; // 0=down 1=up + u16 keycode; // Android keycode 或 Linux evdev scancode + u16 modifiers; // bit0=ctrl bit1=alt bit2=shift bit3=meta +}; + +struct WheelEvent { + i16 delta_x, delta_y; // 滚轮步进 + u8 buttons; +}; + +struct ClipboardEvent { + u32 length; + u8 data[length]; // UTF-8 文本 +}; +``` + +#### 4.4.2 序列化/反序列化抽象接口 + +在 Rust 核心层定义 trait,允许切换实现: + +```rust +/// 控制帧的序列化与反序列化接口 +pub trait ControlFrameCodec: Send + Sync { + /// 将事件编码为字节流(含头部) + fn encode(&self, event: &ControlEvent) -> Vec; + + /// 从字节流中解码出一个事件(若数据不足则返回 None) + fn decode<'a>(&self, buf: &'a [u8]) -> Result, CodecError>; +} + +/// 所有控制事件的枚举(业务层使用) +#[derive(Debug, Clone)] +pub enum ControlEvent { + Touch(TouchEvent), + Mouse(MouseEvent), + Key(KeyboardEvent), + Wheel(WheelEvent), + Clipboard(ClipboardEvent), + Ping(u64), // 时间戳 + Pong(u64), +} +``` + +**自定义二进制实现**(初期使用): + +```rust +pub struct BinaryCodec; + +impl ControlFrameCodec for BinaryCodec { + fn encode(&self, event: &ControlEvent) -> Vec { + let mut buf = Vec::with_capacity(8 + 64); + // 写入头部 + buf.push(1); // version + buf.push(event.msg_type()); + buf.extend_from_slice(&event.sequence().to_le_bytes()); + // 预留 payload_len 占位 + let len_pos = buf.len(); + buf.extend_from_slice(&[0u8; 4]); + // 写入负载 + match event { + ControlEvent::Mouse(e) => { /* 写入结构体 */ }, + // ... + } + // 回填 payload_len + let payload_len = (buf.len() - len_pos - 4) as u32; + buf[len_pos..len_pos+4].copy_from_slice(&payload_len.to_le_bytes()); + buf + } + + fn decode(&self, buf: &[u8]) -> Result, CodecError> { + if buf.len() < 8 { return Ok(None); } + let header = parse_header(buf)?; + let total = 8 + header.payload_len as usize; + if buf.len() < total { return Ok(None); } + let payload = &buf[8..total]; + let event = match header.msg_type { + 1 => ControlEvent::Mouse(parse_mouse(payload)?), + // ... + _ => return Err(CodecError::UnknownMsgType), + }; + Ok(Some((event, total))) + } +} +``` + +**后期切换 Protobuf**:只需实现一个新的 `ProtoCodec`,并在初始化时注入即可。Dart 侧通过 FFI 调用相同的 `encode/decode` 方法,无需改动上层逻辑。 + +#### 4.4.3 为什么选用自定义二进制而非 Protobuf + +| 指标 | 自定义二进制帧 | Protobuf(prost) | +| --- | --- | --- | +| 典型包体大小(鼠标移动) | 8 字节 | 13–15 字节 | +| 序列化时间(1 万次) | ~0.3µs | ~1.2µs | +| 反序列化时间(1 万次) | ~0.2µs | ~1.5µs | +| 是否需要 .proto 文件 | 否 | 是 | +| 字段增减影响 | 需手动更新所有端 | 改 .proto 重新生成 | + +对于 60Hz 鼠标移动,Protobuf 每秒额外 300–420 字节带宽、额外 60µs CPU,现代设备可忽略。但自定义帧更简洁、无依赖、易于调试,且通过抽象接口保留了切换能力。 + +--- + +## 5. 跨网段问题(重点章节) + +### 5.1 现象根因 + +mDNS 用组播地址 `224.0.0.251:5353`,**TTL=1,RFC 6762 明确禁止路由器转发**,只在二层广播域(同 VLAN)生效。跨 VLAN / 跨三层设备后: + +- 组播包被交换机/路由器丢弃 → **发现失败** +- 但两台设备的 IP 如果路由可达,**TCP/UDP 直连本身没问题** + +> ⚠️ 关键认知:**"发现不到" ≠ "连不上"**。手机发现不了另一网段打印机,但手输 IP 往往能打开管理页。 + +### 5.2 三条解决路径对比 + +| 方案 | 谁来做 | 适用 | 缺点 | +| --- | --- | --- | --- | +| 网络设备开 mDNS 网关/中继 | 网管在交换机配 | 企业内网有运维 | 用户控制不了网络设备,家庭场景没戏 | +| **自部署信令服务器** | 我们自己做 | ✅ 全场景通用 | 需要一台可达的机器 | +| 公网 STUN/TURN 打洞 | — | 跨 NAT 公网场景 | 超出本项目"局域网"定位 | + +**选第二条**。理由:不依赖网络设备配置、用户自己一台树莓派/NAS/旧 PC 就能跑、和 RustDesk 的自托管信令思路一致。 + +### 5.3 三级降级状态机 + +``` +┌─ 主控端点击"连接" ─┐ + ↓ +[1] 同网段 mDNS 浏览(3s 超时) + ↓ 命中 → 直接 TLS 连接,全程无服务器 + 未命中 + ↓ +[2] 查信令服务器 /list(用户预置或扫码配置) + ↓ 拿到 ip:port + TCP 握手探测(500ms 超时) + ↓ 通 → P2P 直连,媒体走 UDP + 不通 + ↓ +[3] 走信令服务器 /relay 中转 + (媒体也走 TCP 到服务器转发,延迟+1跳, + 1080p 建议降码率到 4Mbps) +``` + +状态机在 Rust 层实现,Dart 只订阅状态枚举 `Discovering → Registering → Probing → Direct → Relaying → Failed` 渲染 UI。 + +### 5.4 信令服务器部署形态 + +- **家庭/小办公室**:跑在路由器旁一台常开设备(树莓派/NAS),IP 手写进主控设置 +- **企业多 VLAN**:跑在能被所有 VLAN 路由到的服务器(比如 IT 部门的内网 VM) +- **完全没有固定机器**:被控 Android 自己兼做信令(开 HTTP 服务注册到固定域名/内网 DNS),主控手输被控 IP 兜底 + +### 5.5 ACL 防火墙注意 + +即使路由可达,企业防火墙常 deny UDP 5353/1900 或限制非标端口。对策: + +- 信令服务器**统一走 HTTPS 443**(复用现有放行规则) +- 媒体 UDP 端口若被拦,自动降级到 **TCP 443 上的 WebSocket 媒体通道**(牺牲 ~10ms 换连通性) + +--- + +## 6. 文件传输方案(LocalSend v2 思路,自研实现) + +### 6.1 为什么不自集成 LocalSend App + +LocalSend 是独立 App 不是库,进程间拉起体验割裂、iOS 无深链、进度回不来;且它自带 UDP 组播发现和我们信令服务器模型打架,安全模型(局域网即可信 + 自签证书)也和我们的 TLS 指纹配对不统一。 + +**正确姿势:抄协议,在自己的 TLS 会话里实现文件子协议。** + +### 6.2 子协议端点(对齐 LocalSend v2) + +复用已建立的 TLS 控制通道,走 HTTP/2 over TLS 或自定义二进制帧均可,路径语义保持一致: + +``` +POST /file/prepare {files:[{id,name,size,mime,sha256}]} + → {sessionId, tokens:{fileId:token}, rejected:[]} +POST /file/chunk ?sessionId=&fileId=&token=&offset= + body: 二进制分片(默认 1MB) + → {received: n} +POST /file/cancel ?sessionId= +GET /file/progress ?sessionId= (SSE 或轮询) +``` + +### 6.3 相比原版 LocalSend 的增强 + +- **复用会话密钥**:文件流走已建立的 AES-256-GCM 会话,不再另起 HTTPS 自签证书 +- **offset 分片**:原版是"一个文件一次请求",我们加分片 → **断点续传**天然支持 +- **跨网段**:走信令服务器可达路径,不受组播限制 +- **权限分级**:配对时选"仅投屏"就不能发文件,审计日志统一 +- **秒传**:sha256 先比对,被控端已有同哈希文件直接跳过 + +### 6.4 并发与限速 + +- 单会话并发 4 个分片请求(HTTP/2 多路复用或独立 TCP 连接) +- 投屏进行中文件传输自动限速到 2Mbps,避免抢媒体带宽 +- 纯文件模式(不投屏)放开到链路上限 + +### 6.5 可选:与真实 LocalSend 互操作(二期) + +主控端加"发送到 LocalSend"按钮,实现 LocalSend v2 客户端侧: + +- 同网段:组播 `224.0.0.167:53317` 发现 +- 跨网段:手输 IP 兜底 +- 走原版 prepare-upload/upload 端点 + +单向兼容,不反向依赖。 + +--- + +## 7. 安全模型 + +| 层 | 机制 | +| --- | --- | +| 发现 | mDNS TXT 带 `fp` 指纹,防冒充 | +| 配对 | 二维码扫码 或 6 位 TOTP PIN(30s 过期) | +| 传输 | TLS 1.3 + 自签证书 SHA-256 pinning | +| 会话 | ECDH P-256 → AES-256-GCM | +| 媒体 | 派生子密钥,每包 4 字节 MAC 防篡改 | +| 权限 | 配对时选"仅查看 / 查看+控制 / 全权限(含文件)" | +| 信令 | 客户端 pin 信令服务器公钥,防中间人 | + +**不用**自写 AES、不用自写 TLS——`rustls` + `ring` 够了。 + +--- + +## 8. 平台能力边界(写进 README 免责) + +- **Android 被控**:MediaProjection 每次连接弹授权框(系统限制);免 root 控制只能走 Accessibility,延迟高 +- **iOS 被控**:❌ 不做,无系统级采集 API +- **主控端**:Flutter 四端全覆盖,视频 External Texture(Win: D3D11→DXGI 共享;mac: CVPixelBuffer→Metal;Linux: glTexSubImage2D;Android/iOS: 平台纹理) +- **Wayland 主控**:Flutter 本身走 EGL 没问题,只是未来若加 Linux 被控才需要处理 PipeWire portal + +--- + +## 9. 落地里程碑 + +| 阶段 | 内容 | 产出 | +| --- | --- | --- | +| M1 | mDNS 发现 + Android MediaProjection→H264→UDP→Windows Flutter 收流渲染(单向投屏) | 同网段能看画面 | +| M2 | 控制通道(自定义二进制帧 + 抽象接口) + InputEvent + 剪贴板同步 | 能操作 | +| M3 | 信令服务器(Go)+ 三级降级状态机 | 跨网段能连 | +| M4 | TLS 配对 + 二维码 + 指纹 pinning | 安全闭环 | +| M5 | 文件子协议(LocalSend v2 风格 + offset 分片) | 能传文件 | +| M6 | macOS / Linux 主控补齐 + relay 中转 | 四端齐 | +| M7(可选) | LocalSend 外部互操作、WebRTC 媒体通道替换 | 生态兼容 | + +--- + +## 10. 附:关键决策记录(ADR 摘要) + +- **ADR-001** UI 选 Flutter 而非 Electron/Tauri/Qt —— 四端一致 + 视频纹理路径成熟,RustDesk 已验证 +- **ADR-002** 核心逻辑用 Rust 而非 Dart 全包 —— 媒体/加密/发现必须下沉,Dart 只做手势和列表 +- **ADR-003** 跨网段用自部署信令而非依赖网络设备 mDNS 网关 —— 用户不可控网络设备,家庭场景无运维 +- **ADR-004** 文件传输抄 LocalSend v2 协议但自研实现 —— 复用 TLS 会话 + 加断点续传,不引入 LocalSend 进程 +- **ADR-005** 被控反连主控(scrcpy 模式) —— 避免服务启动竞态 +- **ADR-006** 媒体 UDP 优先,被 ACL 拦时降级 TCP/WS over 443 —— 连通性 > 10ms 延迟 +- **ADR-007** 控制通道帧采用自定义二进制 + 抽象接口 —— 初期轻量高效,后期可平滑切换 Protobuf + +--- + +**此文档已覆盖架构、协议、跨网段、文件传输和控制通道帧设计的全部决策。接下来可以按里程碑逐步实现,或针对任一模块深入细节。** diff --git a/android_receiver/app/build.gradle.kts b/android_receiver/app/build.gradle.kts new file mode 100644 index 0000000..5074ef2 --- /dev/null +++ b/android_receiver/app/build.gradle.kts @@ -0,0 +1,89 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.ttstd.lancast.receiver" + compileSdk = 35 + + defaultConfig { + applicationId = "com.ttstd.lancast.receiver" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "0.1.0" + } + + signingConfigs { + create("keypub") { + storeFile = file("D:/TongTongStudio/TTSTD/keypub.jks") + storePassword = "123456" + keyAlias = "publickey" + keyPassword = "123456" + } + create("crosshatch") { + storeFile = file("D:/TongTongStudio/TTSTD/AospCrosshatch.keystore") + storePassword = "Fan1996" + keyAlias = "AospCrosshatch" + keyPassword = "Fan1996" + } + create("zhanxun") { + storeFile = file("D:/TongTongStudio/TTSTD/zhanxun.keystore") + storePassword = "123456" + keyAlias = "zhanxun" + keyPassword = "123456" + } + } + + // 按签名划分变体:aosp/zhanxun 为系统签名,neutral 为普通(中性)签名。 + flavorDimensions += "signature" + productFlavors { + create("aosp") { + dimension = "signature" + signingConfig = signingConfigs.getByName("crosshatch") + } + create("zhanxun") { + dimension = "signature" + signingConfig = signingConfigs.getByName("zhanxun") + } + create("neutral") { + dimension = "signature" + signingConfig = signingConfigs.getByName("keypub") + } + } + + buildTypes { + getByName("debug") { + // 避免 AGP 默认 debug keystore 覆盖 flavor 指定的签名 + signingConfig = null + } + getByName("release") { + isMinifyEnabled = false + } + } + + lint { + checkReleaseBuilds = false + abortOnError = false + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } + + externalNativeBuild { + cmake { + path = file("src/main/cpp/CMakeLists.txt") + } + } +} + +dependencies { + implementation("org.jetbrains.kotlin:kotlin-stdlib:2.0.21") +} diff --git a/android_receiver/app/src/aosp/AndroidManifest.xml b/android_receiver/app/src/aosp/AndroidManifest.xml new file mode 100644 index 0000000..8230814 --- /dev/null +++ b/android_receiver/app/src/aosp/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/android_receiver/app/src/main/AndroidManifest.xml b/android_receiver/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..96c49fc --- /dev/null +++ b/android_receiver/app/src/main/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android_receiver/app/src/main/cpp/CMakeLists.txt b/android_receiver/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..f0e1669 --- /dev/null +++ b/android_receiver/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.22.1) +project(ttstd_opus) + +add_library(ttstd_opus SHARED opus_jni.cpp) + +find_library(log-lib log) +target_link_libraries(ttstd_opus ${log-lib}) + +# TODO(libopus): 将 opus 源码加入后,取消下面注释并启用 native 编码: +# add_subdirectory(opus) +# target_link_libraries(ttstd_opus opus) +# 同时把 opus_jni.cpp 中的 OPUS_NATIVE_AVAILABLE 改为 1。 diff --git a/android_receiver/app/src/main/cpp/opus_jni.cpp b/android_receiver/app/src/main/cpp/opus_jni.cpp new file mode 100644 index 0000000..44424be --- /dev/null +++ b/android_receiver/app/src/main/cpp/opus_jni.cpp @@ -0,0 +1,31 @@ +#include +#include + +// 接入 libopus 源码后改为 1,Kotlin 侧会自动切换到 native 编码器。 +#define OPUS_NATIVE_AVAILABLE 0 + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_ttstd_lancast_receiver_encode_OpusNative_isAvailable(JNIEnv*, jclass) { + return OPUS_NATIVE_AVAILABLE == 1 ? JNI_TRUE : JNI_FALSE; +} + +extern "C" JNIEXPORT jlong JNICALL +Java_com_ttstd_lancast_receiver_encode_OpusNative_createEncoder( + JNIEnv*, jclass, jint, jint, jint) { + if (OPUS_NATIVE_AVAILABLE != 1) return 0; + // TODO(libopus): return reinterpret_cast(opus_encoder_create(...)); + return 0; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_ttstd_lancast_receiver_encode_OpusNative_destroyEncoder(JNIEnv*, jclass, jlong) { + // TODO(libopus): opus_encoder_destroy(reinterpret_cast(handle)); +} + +extern "C" JNIEXPORT jobjectArray JNICALL +Java_com_ttstd_lancast_receiver_encode_OpusNative_encode( + JNIEnv* env, jclass, jlong, jbyteArray) { + if (OPUS_NATIVE_AVAILABLE != 1) return nullptr; + // TODO(libopus): 调用 opus_encode 生成 OPUS 包并返回 ByteArray 数组。 + return env->NewObjectArray(0, env->FindClass("[B"), nullptr); +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt new file mode 100644 index 0000000..2c13176 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt @@ -0,0 +1,98 @@ +package com.ttstd.lancast.receiver + +import android.app.Activity +import android.content.Intent +import android.media.projection.MediaProjectionManager +import android.os.Bundle +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import com.ttstd.lancast.receiver.session.PairingCode +import com.ttstd.lancast.receiver.session.TlsSession +import java.net.NetworkInterface + +class MainActivity : Activity() { + companion object { + private const val REQUEST_CAPTURE = 1001 + private const val FINGERPRINT = "sha256:ab12cd34ef567890" + } + + private var session: ReceiverSession? = null + private lateinit var status: TextView + private lateinit var hostInput: EditText + private lateinit var signalingInput: EditText + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + status = TextView(this).apply { text = "状态:未开始" } + hostInput = EditText(this).apply { + hint = "主控端 IP" + setText("192.168.1.5") + } + signalingInput = EditText(this).apply { + hint = "信令服务器" + setText("http://192.168.1.5:8080") + } + val pairing = TextView(this).apply { + text = "配对码:\n${PairingCode.build(localIp(), 41001, FINGERPRINT)}" + textSize = 13f + } + val start = Button(this).apply { text = "授权并开始投屏" } + val stop = Button(this).apply { text = "停止" } + + setContentView(LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(48, 64, 48, 48) + addView(status) + addView(hostInput) + addView(signalingInput) + addView(pairing) + addView(start) + addView(stop) + }) + + start.setOnClickListener { + val manager = getSystemService(MediaProjectionManager::class.java) + startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE) + } + stop.setOnClickListener { + session?.stop() + session = null + status.text = "状态:已停止" + } + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return + val manager = getSystemService(MediaProjectionManager::class.java) + val projection = manager.getMediaProjection(resultCode, data) + if (projection == null) { + Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show() + return + } + session = ReceiverSession( + context = this, + projection = projection, + host = hostInput.text.toString().trim(), + signalingUrl = signalingInput.text.toString().trim(), + certificatePem = "", + ) + session?.start() + status.text = "状态:采集中 · 指纹 ${TlsSession.sha256Hex(FINGERPRINT.toByteArray()).take(16)}" + } + + override fun onDestroy() { + session?.stop() + session = null + super.onDestroy() + } + + private fun localIp(): String = NetworkInterface.getNetworkInterfaces().toList() + .flatMap { it.inetAddresses.toList() } + .firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address } + ?.hostAddress ?: "192.168.1.10" +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt new file mode 100644 index 0000000..5bdd454 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt @@ -0,0 +1,121 @@ +package com.ttstd.lancast.receiver + +import android.content.Context +import android.media.projection.MediaProjection +import android.os.Build +import android.os.SystemClock +import com.ttstd.lancast.receiver.capture.AudioCapturer +import com.ttstd.lancast.receiver.capture.ScreenCapturer +import com.ttstd.lancast.receiver.clipboard.ClipboardBridge +import com.ttstd.lancast.receiver.discovery.AnnouncedDevice +import com.ttstd.lancast.receiver.discovery.NsdAdvertiser +import com.ttstd.lancast.receiver.discovery.ReceiverAnnouncer +import com.ttstd.lancast.receiver.encode.OpusEncoder +import com.ttstd.lancast.receiver.encode.VideoEncoder +import com.ttstd.lancast.receiver.file.FileService +import com.ttstd.lancast.receiver.input.InputInjector +import com.ttstd.lancast.receiver.protocol.ControlEvent +import com.ttstd.lancast.receiver.session.ReceiverTransport +import com.ttstd.lancast.receiver.session.TlsSession +import java.io.File +import java.util.UUID +import java.util.concurrent.Executors + +class ReceiverSession( + private val context: Context, + private val projection: MediaProjection, + private val host: String, + private val signalingUrl: String, + private val certificatePem: String, + private val preferH265: Boolean = false, + private val bitrateMbps: Int = 8, +) { + private val executor = Executors.newFixedThreadPool(2) + private val clipboard = ClipboardBridge(context) + private val injector = InputInjector(context) + private val fileService = FileService(File(context.filesDir, "file-inbox")) + private val opusEncoder = OpusEncoder() + private val fingerprint = TlsSession.sha256Hex(certificatePem.toByteArray()).take(16) + private val transport = ReceiverTransport( + host, + 41001, + 41000, + 41002, + fingerprint, + certificatePem, + injector, + clipboard, + fileService, + ) + private val encoder = VideoEncoder { buffer, info -> transport.sendVideo(buffer, info) } + + private var capturer: ScreenCapturer? = null + private var audio: AudioCapturer? = null + private var announcer: ReceiverAnnouncer? = null + private var nsdAdvertiser: NsdAdvertiser? = null + @Volatile + private var running = false + + fun start() { + if (running) return + running = true + val metrics = context.resources.displayMetrics + val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920) + val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080) + + encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265) + val surface = encoder.inputSurface ?: return + capturer = ScreenCapturer(projection, surface, metrics.densityDpi).also { it.start(width, height) } + transport.start() + clipboard.start { text -> transport.sendControl(ControlEvent.Clipboard(text)) } + + val device = AnnouncedDevice( + id = UUID.randomUUID().toString(), + name = "Android Receiver", + ip = localIp, + mediaPort = 41000, + controlPort = 41001, + fingerprint = this@ReceiverSession.fingerprint, + capabilities = listOf("h264", "opus", "uibc", "clipboard", "file"), + model = Build.MODEL, + resolution = "${width}x$height", + ) + announcer = ReceiverAnnouncer(signalingUrl, device).also { it.start() } + nsdAdvertiser = NsdAdvertiser(context, device).also { it.start() } + + opusEncoder.start() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + audio = AudioCapturer(projection) { pcm -> + opusEncoder.encode(pcm).forEach { packet -> + transport.sendAudio(packet, SystemClock.elapsedRealtimeNanos() / 1000) + } + }.also { it.start() } + } + + executor.execute { + while (running) { + encoder.drain() + Thread.sleep(4) + } + } + } + + fun stop() { + running = false + capturer?.stop() + audio?.stop() + clipboard.stop() + announcer?.stop() + nsdAdvertiser?.stop() + opusEncoder.stop() + transport.close() + encoder.stop() + executor.shutdownNow() + } + + private val localIp: String + get() = java.net.NetworkInterface.getNetworkInterfaces().toList() + .flatMap { it.inetAddresses.toList() } + .firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address } + ?.hostAddress ?: "192.168.1.10" +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/AudioCapturer.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/AudioCapturer.kt new file mode 100644 index 0000000..fac3921 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/AudioCapturer.kt @@ -0,0 +1,57 @@ +package com.ttstd.lancast.receiver.capture + +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioPlaybackCaptureConfiguration +import android.media.AudioRecord +import android.media.projection.MediaProjection + +class AudioCapturer( + private val projection: MediaProjection, + private val onPcm: (ByteArray) -> Unit, +) { + private var recorder: AudioRecord? = null + private var thread: Thread? = null + @Volatile + private var running = false + + fun start() { + if (running) return + val sampleRate = 48_000 + val channelMask = AudioFormat.CHANNEL_IN_STEREO + val encoding = AudioFormat.ENCODING_PCM_16BIT + val config = AudioPlaybackCaptureConfiguration.Builder(projection) + .addMatchingUsage(AudioAttributes.USAGE_MEDIA) + .addMatchingUsage(AudioAttributes.USAGE_GAME) + .build() + val format = AudioFormat.Builder() + .setSampleRate(sampleRate) + .setChannelMask(channelMask) + .setEncoding(encoding) + .build() + val bufferSize = maxOf(AudioRecord.getMinBufferSize(sampleRate, channelMask, encoding), 4096) + recorder = AudioRecord.Builder() + .setAudioFormat(format) + .setBufferSizeInBytes(bufferSize) + .setAudioPlaybackCaptureConfig(config) + .build() + + running = true + recorder?.startRecording() + thread = Thread { + val buffer = ByteArray(bufferSize) + while (running) { + val read = recorder?.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING) ?: 0 + if (read > 0) onPcm(buffer.copyOf(read)) + } + }.also { it.isDaemon = true; it.start() } + } + + fun stop() { + running = false + recorder?.stop() + recorder?.release() + recorder = null + thread = null + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/ScreenCapturer.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/ScreenCapturer.kt new file mode 100644 index 0000000..608189c --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/capture/ScreenCapturer.kt @@ -0,0 +1,36 @@ +package com.ttstd.lancast.receiver.capture + +import android.hardware.display.DisplayManager +import android.hardware.display.VirtualDisplay +import android.media.projection.MediaProjection +import android.view.Surface + +class ScreenCapturer( + private val projection: MediaProjection, + private val surface: Surface, + private val density: Int, +) { + private var virtualDisplay: VirtualDisplay? = null + + fun start(width: Int, height: Int) { + virtualDisplay = projection.createVirtualDisplay( + "lancast-capture", + width, + height, + density, + DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, + surface, + null, + null, + ) + } + + fun resize(width: Int, height: Int) { + virtualDisplay?.resize(width, height, density) + } + + fun stop() { + virtualDisplay?.release() + virtualDisplay = null + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/clipboard/ClipboardBridge.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/clipboard/ClipboardBridge.kt new file mode 100644 index 0000000..26a803a --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/clipboard/ClipboardBridge.kt @@ -0,0 +1,27 @@ +package com.ttstd.lancast.receiver.clipboard + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context + +class ClipboardBridge(context: Context) { + private val manager = context.getSystemService(ClipboardManager::class.java) + private var listener: ClipboardManager.OnPrimaryClipChangedListener? = null + + fun start(onText: (String) -> Unit) { + listener = ClipboardManager.OnPrimaryClipChangedListener { + val text = manager?.primaryClip?.getItemAt(0)?.text?.toString() + if (!text.isNullOrEmpty()) onText(text) + } + listener?.let { manager?.addPrimaryClipChangedListener(it) } + } + + fun publish(text: String) { + manager?.setPrimaryClip(ClipData.newPlainText("lancast", text)) + } + + fun stop() { + listener?.let { manager?.removePrimaryClipChangedListener(it) } + listener = null + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/AnnouncedDevice.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/AnnouncedDevice.kt new file mode 100644 index 0000000..1f66bd8 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/AnnouncedDevice.kt @@ -0,0 +1,13 @@ +package com.ttstd.lancast.receiver.discovery + +data class AnnouncedDevice( + val id: String, + val name: String, + val ip: String, + val mediaPort: Int, + val controlPort: Int, + val fingerprint: String, + val capabilities: List, + val model: String, + val resolution: String, +) diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdAdvertiser.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdAdvertiser.kt new file mode 100644 index 0000000..c7a9dd0 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdAdvertiser.kt @@ -0,0 +1,68 @@ +package com.ttstd.lancast.receiver.discovery + +import android.content.Context +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo + +class NsdAdvertiser(private val context: Context, private val device: AnnouncedDevice) { + private val manager = context.getSystemService(Context.NSD_SERVICE) as NsdManager + private var registeredService: NsdServiceInfo? = null + @Volatile + private var running = false + + private val registrationListener = object : NsdManager.RegistrationListener { + override fun onServiceRegistered(info: NsdServiceInfo?) { + registeredService = info + } + + override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) { + running = false + } + + override fun onServiceUnregistered(info: NsdServiceInfo?) { + running = false + } + + override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) = Unit + } + + fun start() { + if (running) return + val info = NsdServiceInfo().apply { + serviceName = device.name + serviceType = SERVICE_TYPE + port = device.controlPort + setAttribute("txtvers", "1") + setAttribute("ver", "1") + setAttribute("dev", "android") + setAttribute("id", device.id) + setAttribute("cap", device.capabilities.joinToString(",")) + setAttribute("res", device.resolution) + setAttribute("model", device.model) + setAttribute("fp", device.fingerprint) + setAttribute("cport", device.controlPort.toString()) + setAttribute("mport", device.mediaPort.toString()) + device.ip.takeIf { it.isNotBlank() }?.let { setAttribute("ip", it) } + } + try { + manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, registrationListener) + running = true + } catch (_: IllegalArgumentException) { + running = false + } + } + + fun stop() { + if (!running) return + try { + manager.unregisterService(registrationListener) + } catch (_: IllegalArgumentException) { + } + running = false + registeredService = null + } + + companion object { + const val SERVICE_TYPE = "_lancast._tcp." + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdDiscovery.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdDiscovery.kt new file mode 100644 index 0000000..fa76a09 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/NsdDiscovery.kt @@ -0,0 +1,89 @@ +package com.ttstd.lancast.receiver.discovery + +import android.content.Context +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo + +class NsdDiscovery( + context: Context, + private val onDeviceFound: (AnnouncedDevice) -> Unit, + private val onDeviceLost: (String) -> Unit = {}, +) { + private val manager = context.getSystemService(Context.NSD_SERVICE) as NsdManager + @Volatile + private var running = false + + private val resolveListener = object : NsdManager.ResolveListener { + override fun onResolveFailed(serviceInfo: NsdServiceInfo?, errorCode: Int) = Unit + + override fun onServiceResolved(serviceInfo: NsdServiceInfo?) { + val info = serviceInfo ?: return + val attributes = info.attributes + val ip = info.host?.hostAddress ?: attributes["ip"]?.decodeToString() ?: return + val fingerprint = attributes["fp"]?.decodeToString() ?: return + val mediaPort = attributes["mport"]?.decodeToString()?.toIntOrNull() ?: info.port + 1 + val controlPort = attributes["cport"]?.decodeToString()?.toIntOrNull() ?: info.port + val device = AnnouncedDevice( + id = attributes["id"]?.decodeToString() ?: info.serviceName, + name = info.serviceName, + ip = ip, + mediaPort = mediaPort, + controlPort = controlPort, + fingerprint = fingerprint, + capabilities = attributes["cap"]?.decodeToString()?.split(",") ?: emptyList(), + model = attributes["model"]?.decodeToString() ?: "", + resolution = attributes["res"]?.decodeToString() ?: "1920x1080", + ) + onDeviceFound(device) + } + } + + private val discoveryListener = object : NsdManager.DiscoveryListener { + override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) { + running = false + } + + override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) = Unit + + override fun onDiscoveryStarted(serviceType: String?) { + running = true + } + + override fun onDiscoveryStopped(serviceType: String?) { + running = false + } + + override fun onServiceFound(serviceInfo: NsdServiceInfo?) { + val info = serviceInfo ?: return + if (info.serviceType == NsdAdvertiser.SERVICE_TYPE) { + manager.resolveService(info, resolveListener) + } + } + + override fun onServiceLost(serviceInfo: NsdServiceInfo?) { + serviceInfo?.serviceName?.let(onDeviceLost) + } + } + + fun start() { + if (running) return + try { + manager.discoverServices( + NsdAdvertiser.SERVICE_TYPE, + NsdManager.PROTOCOL_DNS_SD, + discoveryListener, + ) + } catch (_: IllegalArgumentException) { + running = false + } + } + + fun stop() { + if (!running) return + try { + manager.stopServiceDiscovery(discoveryListener) + } catch (_: IllegalArgumentException) { + } + running = false + } +} 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 new file mode 100644 index 0000000..eaa2287 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/discovery/ReceiverAnnouncer.kt @@ -0,0 +1,65 @@ +package com.ttstd.lancast.receiver.discovery + +import android.os.Handler +import android.os.Looper +import org.json.JSONArray +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL + +class ReceiverAnnouncer( + private val signalingUrl: String, + private val device: AnnouncedDevice, +) { + private val handler = Handler(Looper.getMainLooper()) + private var runnable: Runnable? = null + private var registered = false + + fun start() { + if (runnable != null) return + runnable = object : Runnable { + override fun run() { + val path = if (registered) "/heartbeat" else "/register" + post(path, body()) + registered = true + handler.postDelayed(this, 15_000) + } + } + handler.post(runnable!!) + } + + fun stop() { + runnable?.let { handler.removeCallbacks(it) } + runnable = null + registered = false + } + + private fun body(): String = JSONObject().apply { + put("deviceId", device.id) + put("name", device.name) + put("ip", device.ip) + put("mediaPort", device.mediaPort) + put("controlPort", device.controlPort) + put("fp", device.fingerprint) + put("cap", JSONArray(device.capabilities)) + put("model", device.model) + put("res", device.resolution) + 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 同网段直连。 + } + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusEncoder.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusEncoder.kt new file mode 100644 index 0000000..4f7386b --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusEncoder.kt @@ -0,0 +1,99 @@ +package com.ttstd.lancast.receiver.encode + +import android.media.AudioFormat +import android.media.MediaCodec +import android.media.MediaFormat +import java.io.ByteArrayOutputStream + +/** OPUS 编码器:native libopus 就绪时优先使用,否则回退 Android MediaCodec。 */ +class OpusEncoder { + private var codec: MediaCodec? = null + private var nativeHandle = 0L + private var presentationTimeUs = 0L + private val pending = ByteArrayOutputStream() + private val info = MediaCodec.BufferInfo() + + val usesNative: Boolean get() = nativeHandle != 0L + + fun start(sampleRate: Int = 48_000, channels: Int = 2, bitrate: Int = 64_000) { + nativeHandle = OpusNative.createEncoder(sampleRate, channels, bitrate) + if (nativeHandle != 0L) return + try { + val format = MediaFormat.createAudioFormat(MIME_OPUS, sampleRate, channels).apply { + setInteger(MediaFormat.KEY_BIT_RATE, bitrate) + setInteger(MediaFormat.KEY_PCM_ENCODING, AudioFormat.ENCODING_PCM_16BIT) + } + codec = MediaCodec.createEncoderByType(MIME_OPUS).apply { + configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + start() + } + } catch (_: Exception) { + // 设备不支持 OPUS 硬件编码器时静默降级,音频通道将无输出。 + codec = null + } + } + + fun encode(pcm16: ByteArray): List { + if (nativeHandle != 0L) { + return OpusNative.encode(nativeHandle, pcm16)?.toList() ?: emptyList() + } + val encoder = codec ?: return emptyList() + val frameBytes = FRAME_SAMPLES * CHANNELS * BYTES_PER_SAMPLE + pending.write(pcm16) + val buffered = pending.toByteArray() + pending.reset() + + val packets = mutableListOf() + var offset = 0 + while (offset + frameBytes <= buffered.size) { + val frame = buffered.copyOfRange(offset, offset + frameBytes) + offset += frameBytes + queueFrame(encoder, frame) + drain(encoder, packets) + } + pending.write(buffered, offset, buffered.size - offset) + return packets + } + + fun stop() { + if (nativeHandle != 0L) { + OpusNative.destroyEncoder(nativeHandle) + nativeHandle = 0L + } + codec?.stop() + codec?.release() + codec = null + pending.reset() + } + + private fun queueFrame(encoder: MediaCodec, frame: ByteArray) { + val index = encoder.dequeueInputBuffer(0) + if (index < 0) return + val buffer = encoder.getInputBuffer(index) ?: return + buffer.clear() + buffer.put(frame) + encoder.queueInputBuffer(index, 0, frame.size, presentationTimeUs, 0) + presentationTimeUs += FRAME_SAMPLES * 1_000_000L / 48_000 + } + + private fun drain(encoder: MediaCodec, packets: MutableList) { + var index = encoder.dequeueOutputBuffer(info, 0) + while (index >= 0) { + val buffer = encoder.getOutputBuffer(index) + if (buffer != null && info.size > 0) { + val packet = ByteArray(info.size) + buffer.get(packet) + packets.add(packet) + } + encoder.releaseOutputBuffer(index, false) + index = encoder.dequeueOutputBuffer(info, 0) + } + } + + companion object { + private const val MIME_OPUS = "audio/opus" + private const val FRAME_SAMPLES = 960 + private const val CHANNELS = 2 + private const val BYTES_PER_SAMPLE = 2 + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusNative.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusNative.kt new file mode 100644 index 0000000..3df452d --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/OpusNative.kt @@ -0,0 +1,32 @@ +package com.ttstd.lancast.receiver.encode + +/** libopus JNI 通道。native 库未接入源码时 isAvailable 为 false,由 MediaCodec 承接。 */ +object OpusNative { + private var loaded = true + + init { + try { + System.loadLibrary("ttstd_opus") + } catch (_: UnsatisfiedLinkError) { + loaded = false + } + } + + val isAvailable: Boolean + get() = loaded && nativeIsAvailable() + + fun createEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long = + if (isAvailable) nativeCreateEncoder(sampleRate, channels, bitrate) else 0L + + fun destroyEncoder(handle: Long) { + if (handle != 0L) nativeDestroyEncoder(handle) + } + + fun encode(handle: Long, pcm16: ByteArray): Array? = + if (handle != 0L) nativeEncode(handle, pcm16) else null + + private external fun nativeIsAvailable(): Boolean + private external fun nativeCreateEncoder(sampleRate: Int, channels: Int, bitrate: Int): Long + private external fun nativeDestroyEncoder(handle: Long) + private external fun nativeEncode(handle: Long, pcm16: ByteArray): Array? +} 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 new file mode 100644 index 0000000..d354f53 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/encode/VideoEncoder.kt @@ -0,0 +1,57 @@ +package com.ttstd.lancast.receiver.encode + +import android.media.MediaCodec +import android.media.MediaCodecInfo +import android.media.MediaFormat +import android.os.Bundle +import android.view.Surface +import java.nio.ByteBuffer + +class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) -> Unit) { + private var codec: MediaCodec? = null + var inputSurface: Surface? = null + private set + + 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 { + setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) + setInteger(MediaFormat.KEY_BIT_RATE, bitrateBps) + setInteger(MediaFormat.KEY_FRAME_RATE, fps) + setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2) + } + val encoder = MediaCodec.createEncoderByType(mime) + encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + inputSurface = encoder.createInputSurface() + encoder.start() + codec = encoder + } + + fun drain() { + val encoder = codec ?: return + val info = MediaCodec.BufferInfo() + var index = encoder.dequeueOutputBuffer(info, 0) + while (index >= 0) { + val buffer = encoder.getOutputBuffer(index) + if (buffer != null && info.size > 0) { + onPacket(buffer, info) + } + encoder.releaseOutputBuffer(index, false) + index = encoder.dequeueOutputBuffer(info, 0) + } + } + + fun requestKeyFrame() { + codec?.setParameters(Bundle().apply { + putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) + }) + } + + fun stop() { + codec?.stop() + codec?.release() + codec = null + inputSurface?.release() + inputSurface = null + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/file/FileService.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/file/FileService.kt new file mode 100644 index 0000000..d65968f --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/file/FileService.kt @@ -0,0 +1,99 @@ +package com.ttstd.lancast.receiver.file + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.RandomAccessFile +import java.security.MessageDigest +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +class FileService(private val root: File) { + private data class Entry( + val id: String, + val name: String, + val size: Long, + val sha256: String, + val token: String, + var offset: Long, + ) + + private data class Session(val id: String, val files: MutableMap) + + private val sessions = ConcurrentHashMap() + + fun prepare(body: String): String { + root.mkdirs() + val request = JSONObject(body) + val files = request.getJSONArray("files") + val sessionId = UUID.randomUUID().toString() + val entries = mutableMapOf() + val tokens = JSONObject() + val rejected = JSONArray() + + for (index in 0 until files.length()) { + val file = files.getJSONObject(index) + val id = file.getString("id") + val name = safeName(file.getString("name")) + val size = file.getLong("size") + val hash = file.optString("sha256", "") + val target = File(root, "$sessionId-$name") + val token = UUID.randomUUID().toString() + val alreadyThere = target.exists() && target.length() == size && sha256(target) == hash + entries[id] = Entry(id, name, size, hash, token, if (alreadyThere) size else 0) + tokens.put(id, token) + } + + sessions[sessionId] = Session(sessionId, entries) + return JSONObject().apply { + put("sessionId", sessionId) + put("tokens", tokens) + put("rejected", rejected) + }.toString() + } + + fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int { + val entry = sessions[sessionId]?.files?.get(fileId) + ?: throw IllegalArgumentException("未知文件会话") + if (entry.token != token) throw SecurityException("文件令牌不匹配") + val target = File(root, "$sessionId-${entry.name}") + RandomAccessFile(target, "rw").use { file -> + file.seek(offset) + file.write(bytes) + } + entry.offset = maxOf(entry.offset, offset + bytes.size) + return bytes.size + } + + fun progress(sessionId: String): String { + val session = sessions[sessionId] ?: return JSONObject().put("files", JSONArray()).toString() + val array = JSONArray() + session.files.values.forEach { entry -> + array.put(JSONObject().apply { + put("fileId", entry.id) + put("received", entry.offset) + put("total", entry.size) + }) + } + return JSONObject().put("sessionId", sessionId).put("files", array).toString() + } + + fun cancel(sessionId: String) { + sessions.remove(sessionId) + } + + private fun safeName(name: String) = name.replace("/", "_").replace("\\", "_").replace("..", "_") + + private fun sha256(file: File): String = + MessageDigest.getInstance("SHA-256").let { digest -> + file.inputStream().use { stream -> + val buffer = ByteArray(8192) + while (true) { + val read = stream.read(buffer) + if (read <= 0) break + digest.update(buffer, 0, read) + } + } + digest.digest().joinToString("") { "%02x".format(it) } + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/InputInjector.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/InputInjector.kt new file mode 100644 index 0000000..cc1a58f --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/InputInjector.kt @@ -0,0 +1,75 @@ +package com.ttstd.lancast.receiver.input + +import android.accessibilityservice.AccessibilityService +import android.content.Context +import com.ttstd.lancast.receiver.protocol.ControlEvent +import com.ttstd.lancast.receiver.protocol.ControlFrame + +class InputInjector(private val context: Context) { + private var touchStart: Pair? = null + + fun inject(frame: ControlFrame) { + when (val event = frame.event) { + is ControlEvent.Touch -> injectTouch(event) + is ControlEvent.Mouse -> injectMouse(event) + is ControlEvent.Key -> injectKey(event) + is ControlEvent.Wheel -> injectWheel(event) + is ControlEvent.Clipboard -> injectText(event.text) + is ControlEvent.Ping, is ControlEvent.Pong -> Unit + } + } + + private fun injectTouch(event: ControlEvent.Touch) { + when (event.action) { + 0 -> { + touchStart = event.x to event.y + accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}") + } + 2 -> { + val start = touchStart + if (start != null) { + accessibility()?.swipe(start.first, start.second, event.x, event.y) + ?: shell("input", "swipe", "${start.first}", "${start.second}", "${event.x}", "${event.y}") + } + } + } + } + + private fun injectMouse(event: ControlEvent.Mouse) { + if (event.action == 0) { + accessibility()?.tap(event.x, event.y) ?: shell("input", "tap", "${event.x}", "${event.y}") + } + } + + private fun injectKey(event: ControlEvent.Key) { + when (event.keycode) { + 3 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_HOME) + ?: shell("input", "keyevent", "KEYCODE_HOME") + 4 -> accessibility()?.systemAction(AccessibilityService.GLOBAL_ACTION_BACK) + ?: shell("input", "keyevent", "KEYCODE_BACK") + else -> shell("input", "keyevent", event.keycode.toString()) + } + } + + private fun injectWheel(event: ControlEvent.Wheel) { + // AccessibilityService 不直接支持滚轮;映射为上下滑动。 + val service = accessibility() + if (service != null) { + service.swipe(720, 800, 720 + event.deltaX, 800 - event.deltaY * 60) + } + } + + private fun injectText(text: String) { + shell("input", "text", text.replace(" ", "%s")) + } + + private fun accessibility() = LancastAccessibilityService.instance + + private fun shell(vararg command: String) { + try { + Runtime.getRuntime().exec(command) + } catch (_: Exception) { + // 普通应用无 shell 权限时静默降级到无障碍服务。 + } + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/LancastAccessibilityService.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/LancastAccessibilityService.kt new file mode 100644 index 0000000..73247ab --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/input/LancastAccessibilityService.kt @@ -0,0 +1,55 @@ +package com.ttstd.lancast.receiver.input + +import android.accessibilityservice.AccessibilityService +import android.graphics.Path +import android.view.accessibility.AccessibilityEvent +import android.accessibilityservice.GestureDescription + +class LancastAccessibilityService : AccessibilityService() { + companion object { + @Volatile + var instance: LancastAccessibilityService? = null + } + + override fun onServiceConnected() { + instance = this + } + + override fun onAccessibilityEvent(event: AccessibilityEvent?) = Unit + + override fun onInterrupt() = Unit + + override fun onDestroy() { + instance = null + super.onDestroy() + } + + fun tap(x: Int, y: Int) { + val path = Path().apply { moveTo(x.toFloat(), y.toFloat()) } + dispatchGesture( + GestureDescription.Builder() + .addStroke(GestureDescription.StrokeDescription(path, 0, 80)) + .build(), + null, + null, + ) + } + + fun swipe(x1: Int, y1: Int, x2: Int, y2: Int) { + val path = Path().apply { + moveTo(x1.toFloat(), y1.toFloat()) + lineTo(x2.toFloat(), y2.toFloat()) + } + dispatchGesture( + GestureDescription.Builder() + .addStroke(GestureDescription.StrokeDescription(path, 0, 220)) + .build(), + null, + null, + ) + } + + fun systemAction(action: Int) { + performGlobalAction(action) + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/protocol/ControlFrames.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/protocol/ControlFrames.kt new file mode 100644 index 0000000..1d6e6ec --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/protocol/ControlFrames.kt @@ -0,0 +1,136 @@ +package com.ttstd.lancast.receiver.protocol + +import java.nio.charset.StandardCharsets + +sealed class ControlEvent { + data class Touch(val action: Int, val pointerId: Int, val x: Int, val y: Int, val pressure: Int) : ControlEvent() + data class Mouse(val action: Int, val x: Int, val y: Int, val buttons: Int) : ControlEvent() + data class Key(val action: Int, val keycode: Int, val modifiers: Int) : ControlEvent() + data class Wheel(val deltaX: Int, val deltaY: Int, val buttons: Int) : ControlEvent() + data class Clipboard(val text: String) : ControlEvent() + data class Ping(val timestamp: Long) : ControlEvent() + data class Pong(val timestamp: Long) : ControlEvent() +} + +data class ControlFrame(val version: Int, val sequence: Int, val event: ControlEvent) + +object ControlFrames { + const val VERSION = 1 + private const val HEADER = 8 + + fun decode(bytes: ByteArray): ControlFrame? { + if (bytes.size < HEADER) return null + val version = bytes[0].toInt() and 0xff + if (version != VERSION) return null + val msgType = bytes[1].toInt() and 0xff + val sequence = u16(bytes, 2) + val length = u32(bytes, 4) + if (length < 0 || bytes.size < HEADER + length) return null + val payload = bytes.copyOfRange(HEADER, HEADER + length) + val event = when (msgType) { + 0 -> { + if (payload.size != 8) return null + ControlEvent.Touch( + action = payload[0].toInt() and 0xff, + pointerId = payload[1].toInt() and 0xff, + x = i16(payload, 2), + y = i16(payload, 4), + pressure = u16(payload, 6), + ) + } + 1 -> { + if (payload.size != 6) return null + ControlEvent.Mouse( + action = payload[0].toInt() and 0xff, + x = i16(payload, 1), + y = i16(payload, 3), + buttons = payload[5].toInt() and 0xff, + ) + } + 2 -> { + if (payload.size != 5) return null + ControlEvent.Key( + action = payload[0].toInt() and 0xff, + keycode = u16(payload, 1), + modifiers = u16(payload, 3), + ) + } + 3 -> { + if (payload.size != 5) return null + ControlEvent.Wheel(i16(payload, 0), i16(payload, 2), payload[4].toInt() and 0xff) + } + 4 -> { + if (payload.size < 4) return null + val lengthText = u32(payload, 0) + if (lengthText != payload.size - 4) return null + ControlEvent.Clipboard(String(payload, 4, lengthText, StandardCharsets.UTF_8)) + } + 5 -> { + if (payload.size != 8) return null + ControlEvent.Ping(u64(payload, 0)) + } + 6 -> { + if (payload.size != 8) return null + ControlEvent.Pong(u64(payload, 0)) + } + else -> return null + } + return ControlFrame(version, sequence, event) + } + + fun encode(event: ControlEvent, sequence: Int): ByteArray { + val payload = when (event) { + is ControlEvent.Touch -> byteArrayOf( + event.action.toByte(), event.pointerId.toByte(), + ) + i16Bytes(event.x) + i16Bytes(event.y) + u16Bytes(event.pressure) + is ControlEvent.Mouse -> byteArrayOf(event.action.toByte()) + + i16Bytes(event.x) + i16Bytes(event.y) + byteArrayOf(event.buttons.toByte()) + is ControlEvent.Key -> byteArrayOf(event.action.toByte()) + + u16Bytes(event.keycode) + u16Bytes(event.modifiers) + is ControlEvent.Wheel -> i16Bytes(event.deltaX) + i16Bytes(event.deltaY) + + byteArrayOf(event.buttons.toByte()) + is ControlEvent.Clipboard -> { + val text = event.text.toByteArray(StandardCharsets.UTF_8) + u32Bytes(text.size) + text + } + is ControlEvent.Ping -> u64Bytes(event.timestamp) + is ControlEvent.Pong -> u64Bytes(event.timestamp) + } + return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) + + u16Bytes(sequence) + u32Bytes(payload.size) + payload + } + + private fun msgType(event: ControlEvent) = when (event) { + is ControlEvent.Touch -> 0 + is ControlEvent.Mouse -> 1 + is ControlEvent.Key -> 2 + is ControlEvent.Wheel -> 3 + is ControlEvent.Clipboard -> 4 + is ControlEvent.Ping -> 5 + is ControlEvent.Pong -> 6 + } + + private fun u16(bytes: ByteArray, offset: Int) = + (bytes[offset].toInt() and 0xff) or ((bytes[offset + 1].toInt() and 0xff) shl 8) + + private fun i16(bytes: ByteArray, offset: Int) = u16(bytes, offset).toShort().toInt() + + private fun u32(bytes: ByteArray, offset: Int): Int = + (bytes[offset].toInt() and 0xff) or + ((bytes[offset + 1].toInt() and 0xff) shl 8) or + ((bytes[offset + 2].toInt() and 0xff) shl 16) or + ((bytes[offset + 3].toInt() and 0xff) shl 24) + + private fun u64(bytes: ByteArray, offset: Int): Long = + (0 until 8).fold(0L) { acc, index -> acc or ((bytes[offset + index].toLong() and 0xff) shl (8 * index)) } + + private fun u16Bytes(value: Int) = byteArrayOf(value.toByte(), (value shr 8).toByte()) + + private fun i16Bytes(value: Int) = u16Bytes(value and 0xffff) + + private fun u32Bytes(value: Int) = byteArrayOf( + value.toByte(), (value shr 8).toByte(), (value shr 16).toByte(), (value shr 24).toByte(), + ) + + private fun u64Bytes(value: Long) = ByteArray(8) { index -> (value shr (8 * index)).toByte() } +} 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 new file mode 100644 index 0000000..5b1117b --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt @@ -0,0 +1,26 @@ +package com.ttstd.lancast.receiver.session + +import java.nio.ByteBuffer +import java.nio.ByteOrder +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +object MediaPackets { + const val FLAG_KEYFRAME = 1 + const val FLAG_AUDIO = 2 + private const val HEADER_SIZE = 13 + private const val MAC_SIZE = 4 + + fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray): ByteArray { + val header = ByteBuffer.allocate(HEADER_SIZE).order(ByteOrder.LITTLE_ENDIAN).apply { + putLong(pts) + put(flags.toByte()) + putInt(payload.size) + }.array() + val signed = header + payload + val mac = Mac.getInstance("HmacSHA256").apply { + init(SecretKeySpec(sessionKey, "HmacSHA256")) + }.doFinal(signed) + return signed + mac.copyOf(MAC_SIZE) + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/PairingCode.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/PairingCode.kt new file mode 100644 index 0000000..e099c07 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/PairingCode.kt @@ -0,0 +1,14 @@ +package com.ttstd.lancast.receiver.session + +import android.net.Uri + +object PairingCode { + fun build(ip: String, port: Int, fingerprint: String): String = Uri.Builder() + .scheme("lancast") + .authority("pair") + .appendQueryParameter("ip", ip) + .appendQueryParameter("port", port.toString()) + .appendQueryParameter("fp", fingerprint) + .build() + .toString() +} 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 new file mode 100644 index 0000000..d7aa62a --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/ReceiverTransport.kt @@ -0,0 +1,195 @@ +package com.ttstd.lancast.receiver.session + +import android.media.MediaCodec +import com.ttstd.lancast.receiver.clipboard.ClipboardBridge +import com.ttstd.lancast.receiver.file.FileService +import com.ttstd.lancast.receiver.input.InputInjector +import com.ttstd.lancast.receiver.protocol.ControlEvent +import com.ttstd.lancast.receiver.protocol.ControlFrames +import org.json.JSONObject +import java.io.DataInputStream +import java.io.DataOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetSocketAddress +import java.net.Socket +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets +import java.util.concurrent.Executors + +/** + * demo v1 传输层: + * 1. TCP 反连 host:controlPort,先做 ECDH P-256 握手(互发 65 字节公钥)。 + * 2. 派生 control/video/audio 三把会话密钥。 + * 3. 控制帧使用 AES-256-GCM(8 字节明头作 AAD);媒体包使用 HMAC-SHA256 截断 MAC。 + * + * 握手后控制通道的机密性由控制帧 AES-GCM 保证,demo 阶段不再叠加 TLS。 + */ +class ReceiverTransport( + private val host: String, + private val controlPort: Int, + private val mediaPort: Int, + private val audioPort: Int, + private val expectedFingerprint: String, + private val certificatePem: String, + private val injector: InputInjector, + private val clipboard: ClipboardBridge, + private val fileService: FileService, +) { + private val executor = Executors.newFixedThreadPool(2) + private val crypto = SessionCrypto() + private var socket: Socket? = null + private var output: DataOutputStream? = null + private var udp: DatagramSocket? = null + private var keys: SessionCrypto.SessionKeys? = null + @Volatile + private var running = false + @Volatile + private var sequence = 0 + + val keyEstablished: Boolean get() = keys != null + + fun start() { + 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 + executor.execute { readLoop(input) } + } + + fun sendControl(event: ControlEvent) { + val key = keys?.control ?: return + if (!running) return + val frame = ControlFrames.encode(event, sequence++) + writeFrame(crypto.encodeControlFrame(frame, key)) + } + + fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) { + val key = keys?.video ?: return + if (!running) return + val duplicate = buffer.duplicate().apply { + position(info.offset) + limit(info.offset + info.size) + } + val payload = ByteArray(info.size) + duplicate.get(payload) + val 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))) + } + + 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))) + } + + fun close() { + running = false + try { + socket?.close() + udp?.close() + } catch (_: Exception) { + } + socket = null + udp = null + keys = null + executor.shutdownNow() + } + + private fun readLoop(input: DataInputStream) { + val controlKey = keys?.control ?: return + try { + while (running) { + val header = ByteArray(8) + input.readFully(header) + val length = le32(header, 4) + if (length < 0 || length > 16 * 1024 * 1024) break + val rest = ByteArray(12 + length + 16) + input.readFully(rest) + val secureFrame = header + rest + val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: continue + when (plaintext[1].toInt() and 0xff) { + 7 -> handleFileFrame(plaintext.copyOfRange(8, plaintext.size)) + else -> { + val frame = ControlFrames.decode(plaintext) ?: continue + when (val event = frame.event) { + is ControlEvent.Clipboard -> clipboard.publish(event.text) + is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp)) + else -> injector.inject(frame) + } + } + } + } + } catch (_: Exception) { + // 对端断开时结束读取循环。 + } + } + + private fun handleFileFrame(payload: ByteArray) { + val request = JSONObject(String(payload, StandardCharsets.UTF_8)) + when (request.optString("op")) { + "prepare" -> sendRaw(7, fileService.prepare(request.getString("body"))) + "chunk" -> { + val received = fileService.writeChunk( + request.getString("sessionId"), + request.getString("fileId"), + request.getString("token"), + request.getLong("offset"), + request.getString("data").toByteArray(StandardCharsets.ISO_8859_1), + ) + sendRaw(7, JSONObject().put("op", "chunkAck").put("received", received).toString()) + } + "progress" -> sendRaw(7, fileService.progress(request.getString("sessionId"))) + "cancel" -> fileService.cancel(request.getString("sessionId")) + } + } + + private fun sendRaw(msgType: Int, text: String) { + val controlKey = keys?.control ?: return + val payload = text.toByteArray(StandardCharsets.UTF_8) + val frame = byteArrayOf(ControlFrames.VERSION.toByte(), msgType.toByte()) + + u16(sequence++) + u32(payload.size) + payload + writeFrame(crypto.encodeControlFrame(frame, controlKey)) + } + + private fun writeFrame(frame: ByteArray) { + try { + output?.write(frame) + output?.flush() + } catch (_: Exception) { + // 控制通道断开后忽略写入失败。 + } + } + + private fun u16(value: Int) = byteArrayOf(value.toByte(), (value shr 8).toByte()) + + private fun u32(value: Int) = byteArrayOf( + value.toByte(), (value shr 8).toByte(), (value shr 16).toByte(), (value shr 24).toByte(), + ) + + private fun le32(bytes: ByteArray, offset: Int): Int = + (bytes[offset].toInt() and 0xff) or + ((bytes[offset + 1].toInt() and 0xff) shl 8) or + ((bytes[offset + 2].toInt() and 0xff) shl 16) or + ((bytes[offset + 3].toInt() and 0xff) shl 24) +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/SessionCrypto.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/SessionCrypto.kt new file mode 100644 index 0000000..d0b5a6f --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/SessionCrypto.kt @@ -0,0 +1,127 @@ +package com.ttstd.lancast.receiver.session + +import java.math.BigInteger +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.spec.ECGenParameterSpec +import java.security.spec.ECPoint +import java.security.spec.ECPublicKeySpec +import java.util.concurrent.atomic.AtomicLong +import javax.crypto.Cipher +import javax.crypto.KeyAgreement +import javax.crypto.Mac +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec +import java.security.interfaces.ECPublicKey + +/** + * 与 Rust Core 对齐的会话密码学: + * - ECDH P-256(公钥 65 字节非压缩形式 0x04 || X || Y) + * - HKDF-SHA256(salt="ttstdconnect-v1",info=label,输出 32 字节) + * - AES-256-GCM(12 字节 nonce,8 字节控制帧头作为 AAD,16 字节 tag) + */ +class SessionCrypto { + private val keyPair: KeyPair = KeyPairGenerator.getInstance("EC").apply { + initialize(ECGenParameterSpec("secp256r1")) + }.generateKeyPair() + private val sendCounter = AtomicLong(1) + + val publicBytes: ByteArray + get() { + val point = (keyPair.public as ECPublicKey).w + return byteArrayOf(4) + fixed32(point.affineX) + fixed32(point.affineY) + } + + fun deriveKeys(peerPublic: ByteArray): SessionKeys { + require(peerPublic.size == 65 && (peerPublic[0].toInt() and 0xff) == 4) { + "对端 ECDH 公钥必须为 65 字节未压缩形式" + } + val x = BigInteger(1, peerPublic.copyOfRange(1, 33)) + val y = BigInteger(1, peerPublic.copyOfRange(33, 65)) + val params = (keyPair.public as ECPublicKey).params + val peer = KeyFactory.getInstance("EC") + .generatePublic(ECPublicKeySpec(ECPoint(x, y), params)) + val agreement = KeyAgreement.getInstance("ECDH").apply { + init(keyPair.private) + doPhase(peer, true) + } + val secret = agreement.generateSecret() + return SessionKeys( + control = hkdf(secret, LABEL_CONTROL), + video = hkdf(secret, LABEL_VIDEO), + audio = hkdf(secret, LABEL_AUDIO), + ) + } + + /** 加密控制帧:输出 = 8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag。 */ + fun encodeControlFrame(frame: ByteArray, key: ByteArray): ByteArray { + require(frame.size >= 8) { "控制帧至少需要 8 字节头" } + val header = frame.copyOfRange(0, 8) + val payload = frame.copyOfRange(8, frame.size) + val nonce = ByteArray(12).also { result -> + byteArrayOf('c'.toByte(), 't'.toByte(), 'l'.toByte(), '-'.toByte()).copyInto(result) + val counter = sendCounter.getAndIncrement() + for (index in 0 until 8) { + result[4 + index] = (counter shr (8 * index)).toByte() + } + } + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)) + updateAAD(header) + } + val encrypted = cipher.doFinal(payload) + return header + nonce + encrypted + } + + /** 解密控制帧,返回完整的 8 字节头 + 明文负载。 */ + fun decodeControlFrame(frame: ByteArray, key: ByteArray): ByteArray? { + if (frame.size < 8 + 12 + 16) return null + val header = frame.copyOfRange(0, 8) + val length = le32(header, 4) + if (length < 0 || length > 16 * 1024 * 1024) return null + val total = 8 + 12 + length + 16 + if (frame.size < total) return null + val nonce = frame.copyOfRange(8, 20) + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)) + updateAAD(header) + } + val payload = cipher.doFinal(frame.copyOfRange(20, total)) + return header + payload + } + + private fun hkdf(secret: ByteArray, label: ByteArray): ByteArray { + val salt = "ttstdconnect-v1".toByteArray(Charsets.UTF_8) + val prk = hmacSha256(salt, secret) + return hmacSha256(prk, label + byteArrayOf(0x01)).copyOf(32) + } + + private fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray = + Mac.getInstance("HmacSHA256").apply { + init(SecretKeySpec(key, "HmacSHA256")) + }.doFinal(data) + + private fun fixed32(value: BigInteger): ByteArray { + val raw = value.toByteArray() + return when { + raw.size == 32 -> raw + raw.size > 32 -> raw.copyOfRange(raw.size - 32, raw.size) + else -> ByteArray(32 - raw.size) + raw + } + } + + private fun le32(bytes: ByteArray, offset: Int): Int = + (bytes[offset].toInt() and 0xff) or + ((bytes[offset + 1].toInt() and 0xff) shl 8) or + ((bytes[offset + 2].toInt() and 0xff) shl 16) or + ((bytes[offset + 3].toInt() and 0xff) shl 24) + + data class SessionKeys(val control: ByteArray, val video: ByteArray, val audio: ByteArray) + + companion object { + private val LABEL_CONTROL = "lancast/control/v1".toByteArray(Charsets.UTF_8) + private val LABEL_VIDEO = "lancast/video/v1".toByteArray(Charsets.UTF_8) + private val LABEL_AUDIO = "lancast/audio/v1".toByteArray(Charsets.UTF_8) + } +} diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/TlsSession.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/TlsSession.kt new file mode 100644 index 0000000..64e9132 --- /dev/null +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/TlsSession.kt @@ -0,0 +1,41 @@ +package com.ttstd.lancast.receiver.session + +import java.io.ByteArrayInputStream +import java.security.KeyStore +import java.security.MessageDigest +import java.security.cert.CertificateFactory +import java.security.cert.X509Certificate +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.TrustManagerFactory + +object TlsSession { + fun sha256Hex(bytes: ByteArray): String = + MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + + fun verifyFingerprint(certificate: X509Certificate, expected: String): Boolean { + val actual = sha256Hex(certificate.encoded) + val prefix = expected.removePrefix("sha256:").replace(":", "").lowercase() + return prefix.length >= 16 && actual.startsWith(prefix) + } + + fun socketFactory(expectedFingerprint: String, certificatePem: String?): SSLSocketFactory { + if (certificatePem.isNullOrBlank()) { + return SSLContext.getDefault().socketFactory + } + val certificate = CertificateFactory.getInstance("X.509") + .generateCertificate(ByteArrayInputStream(certificatePem.toByteArray())) as X509Certificate + require(verifyFingerprint(certificate, expectedFingerprint)) { "证书指纹不匹配" } + + val keyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null, null) + setCertificateEntry("peer", certificate) + } + val trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + .apply { init(keyStore) } + .trustManagers + return SSLContext.getInstance("TLSv1.3").apply { + init(null, trustManagers, null) + }.socketFactory + } +} diff --git a/android_receiver/app/src/main/res/values/strings.xml b/android_receiver/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..05d3b0e --- /dev/null +++ b/android_receiver/app/src/main/res/values/strings.xml @@ -0,0 +1,6 @@ + + + TTSTD Receiver + TTSTD 远控注入服务 + 免 root 场景下注入点击、滑动与系统按键。 + diff --git a/android_receiver/app/src/main/res/values/themes.xml b/android_receiver/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..c1e132f --- /dev/null +++ b/android_receiver/app/src/main/res/values/themes.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android_receiver/app/src/main/res/xml/accessibility_service_config.xml b/android_receiver/app/src/main/res/xml/accessibility_service_config.xml new file mode 100644 index 0000000..3265c9c --- /dev/null +++ b/android_receiver/app/src/main/res/xml/accessibility_service_config.xml @@ -0,0 +1,9 @@ + + diff --git a/android_receiver/app/src/zhanxun/AndroidManifest.xml b/android_receiver/app/src/zhanxun/AndroidManifest.xml new file mode 100644 index 0000000..8230814 --- /dev/null +++ b/android_receiver/app/src/zhanxun/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/android_receiver/build.gradle.kts b/android_receiver/build.gradle.kts new file mode 100644 index 0000000..c7ad754 --- /dev/null +++ b/android_receiver/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "2.0.21" apply false +} diff --git a/android_receiver/gradle.properties b/android_receiver/gradle.properties new file mode 100644 index 0000000..5a35c21 --- /dev/null +++ b/android_receiver/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +kotlin.code.style=official +android.useAndroidX=false diff --git a/android_receiver/settings.gradle.kts b/android_receiver/settings.gradle.kts new file mode 100644 index 0000000..2411ed6 --- /dev/null +++ b/android_receiver/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "TTSTDConnectReceiver" +include(":app") diff --git a/docs/DEMO.md b/docs/DEMO.md new file mode 100644 index 0000000..6c47931 --- /dev/null +++ b/docs/DEMO.md @@ -0,0 +1,49 @@ +# TTSTDConnect 可运行 Demo + +本 demo 把此前的占位能力接成一条可验证的端到端链路:Flutter 桌面端通过 `dart:ffi` 调用 Rust Core,Android 被控端用相同协议完成 ECDH 握手、控制帧加密与媒体包校验。 + +## 已打通的能力 + +1. **Flutter -> Rust FFI**:`rust_core` 产出 `cdylib`,Flutter 通过 `dart:ffi` 直接调用 ECDH、HKDF、AES-256-GCM、媒体包编解码、安全控制帧。 +2. **ECDH/AES-GCM 控制通道**:`ReceiverTransport` 反连主控端 41001,先互发 65 字节 P-256 公钥,派生三把会话密钥;控制帧以 8 字节明头为 AAD 做 AES-256-GCM 加密。 +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 普通签名。 + +## 一键验证(无需设备) + +```powershell +cd rust_core +cargo test --offline --test demo_e2e +``` + +该测试会启动本机 demo 服务(TCP 44101 / UDP 44100 / 44102),模拟被控端完成 ECDH 握手、发送加密 Ping 并收到 Pong、发送视频/音频包,最后断言服务端状态记录全部正确。 + +## Flutter 桌面端 + +首页「Rust Core 协议自检」卡片会显示: + +- Rust Core 版本与 ABI +- ECDH 双方共享密钥是否一致 +- 加密控制帧与媒体包的字节数 +- demo 服务运行状态、对端连接、密钥前缀与最近事件 + +点击「启动 demo 服务」后,主控端监听: + +- TCP `41001`:ECDH 握手 + 加密控制帧 +- UDP `41000`:视频包 +- UDP `41002`:音频包 + +运行前确保 `ttstdconnect_core.dll`(Windows)/ `.so`(Linux)位于可执行文件同目录;`installer/windows/package.ps1` 已自动构建并内置该动态库。 + +## Android 被控端 + +```powershell +cd android_receiver +$env:ANDROID_HOME = "F:\AndroidSDK" +gradle :app:assembleNeutralDebug +``` + +安装后在真机上授予屏幕录制与无障碍权限,并在设置里把主控端 IP 指向运行 Flutter 桌面端的机器。连接后 `ReceiverTransport` 会自动完成 ECDH 握手并建立加密通道。 + +注意:demo 阶段控制通道不叠加 TLS,机密性由控制帧 AES-GCM 保证;证书 pinning 的完整闭环(`certificatePem` 由真实证书派生)留待下一阶段。 diff --git a/flutter_sender/.gitignore b/flutter_sender/.gitignore new file mode 100644 index 0000000..79f7eca --- /dev/null +++ b/flutter_sender/.gitignore @@ -0,0 +1,48 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ diff --git a/flutter_sender/.metadata b/flutter_sender/.metadata new file mode 100644 index 0000000..bdd3c38 --- /dev/null +++ b/flutter_sender/.metadata @@ -0,0 +1,36 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "ae9b586f34a8443573f82ef57c3bf914a908cbf7" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + base_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + - platform: linux + create_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + base_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + - platform: macos + create_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + base_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + - platform: windows + create_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + base_revision: ae9b586f34a8443573f82ef57c3bf914a908cbf7 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/flutter_sender/analysis_options.yaml b/flutter_sender/analysis_options.yaml new file mode 100644 index 0000000..cd2b0e1 --- /dev/null +++ b/flutter_sender/analysis_options.yaml @@ -0,0 +1,10 @@ +analyzer: + errors: + unused_import: warning + dead_code: warning + deprecated_member_use: ignore + exclude: + - build/** + - windows/** + - macos/** + - linux/** diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart new file mode 100644 index 0000000..19865b6 --- /dev/null +++ b/flutter_sender/lib/core/bridge.dart @@ -0,0 +1,174 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; + +import 'local_signaling.dart'; +import 'models.dart'; +import 'native_core.dart'; + +class SenderBridge { + SenderBridge({ + MethodChannel? method, + EventChannel? events, + NativeCore? nativeCore, + }) : _method = method ?? const MethodChannel('ttstd/sender'), + _events = events ?? const EventChannel('ttstd/sender/events'), + _native = nativeCore; + + final MethodChannel _method; + final EventChannel _events; + final NativeCore? _native; + final LocalSignalingProcess _localSignaling = LocalSignalingProcess(); + + NativeCore? get nativeCore => _native; + + bool get isLocalSignalingRunning => _localSignaling.isRunning; + + static const mockDevices = [ + DeviceInfo( + id: 'demo-pixel', + name: '客厅 Pixel', + ip: '192.168.1.10', + mediaPort: 41000, + controlPort: 41001, + fingerprint: 'sha256:ab12cd34ef567890', + capabilities: ['h264', 'opus', 'uibc', 'clipboard', 'file'], + model: 'Pixel8', + resolution: '1920x1080', + ), + DeviceInfo( + id: 'demo-tablet', + name: '书房平板', + ip: '192.168.1.23', + mediaPort: 42000, + controlPort: 42001, + fingerprint: 'sha256:9988776655443322', + capabilities: ['h265', 'opus', 'uibc'], + model: 'PadPro', + resolution: '2560x1600', + ), + ]; + + Stream watchPhase() { + return _events + .receiveBroadcastStream() + .handleError((Object _) => null) + .map(ConnectionPhaseX.fromWire) + .distinct(); + } + + Future> discover() async { + try { + final raw = await _method.invokeListMethod('discover'); + if (raw == null || raw.isEmpty) return mockDevices; + return DeviceInfo.listFromJson(raw); + } on MissingPluginException { + return mockDevices; + } on PlatformException { + return mockDevices; + } + } + + Future connect(DeviceInfo device) async { + await _invokeIgnoringMissing('connect', device.toJson()); + } + + Future disconnect() async { + await _invokeIgnoringMissing('disconnect'); + } + + Future sendControl(String type, Map payload) async { + await _invokeIgnoringMissing('control', {'type': type, ...payload}); + } + + Future saveSettings(AppSettings settings) async { + await _invokeIgnoringMissing('settings', settings.toJson()); + } + + Future startLocalSignaling(int port) => _localSignaling.start(port: port); + + Future stopLocalSignaling() => _localSignaling.stop(); + + String localSignalingUrl(int port) => _localSignaling.url(port: port); + + Future resolveSignalingUrl(AppSettings settings) async { + if (settings.useLocalSignaling) { + return _localSignaling.url(port: settings.localSignalingPort); + } + return settings.signalingUrl; + } + + /// 通过 Rust Core 跑一次真实 ECDH + HKDF + AES-GCM + 媒体 MAC 自检。 + Map runCryptoSelfTest() { + final native = _native; + if (native == null) { + return {'available': false, 'reason': 'Rust Core 未加载'}; + } + final alice = native.generateKeyPair(); + final bob = native.generateKeyPair(); + try { + final aliceSecret = alice.agree(bob.publicBytes); + final bobSecret = bob.agree(alice.publicBytes); + final controlKey = native.deriveSubkey(aliceSecret, 'lancast/control/v1'); + final videoKey = native.deriveSubkey(aliceSecret, 'lancast/video/v1'); + final channel = native.createSecureChannel(controlKey); + final frame = channel.encodePing(1, DateTime.now().millisecondsSinceEpoch); + final decoded = channel.decode(frame); + channel.dispose(); + final media = native.mediaEncode( + 1234, + 1, + videoKey, + const [1, 2, 3, 4, 5], + ); + final mediaDecoded = native.mediaDecode(media, videoKey); + return { + 'available': true, + 'ecdhMatch': aliceSecret.join() == bobSecret.join(), + 'controlFrameBytes': frame.length, + 'controlKind': decoded['kind'], + 'mediaPacketBytes': media.length, + 'mediaPts': mediaDecoded['pts'], + 'controlKey': _hexPrefix(controlKey), + 'videoKey': _hexPrefix(videoKey), + }; + } finally { + alice.free(); + bob.free(); + } + } + + /// 启动 Rust Core 的本机 demo 服务。 + bool startDemoServer() => + _native?.startDemoServer() ?? false; + + void stopDemoServer() => _native?.stopDemoServer(); + + Map demoStatus() => + _native?.demoStatus() ?? {'running': false}; + + static String _hexPrefix(List bytes) => bytes + .take(4) + .map((byte) => byte.toRadixString(16).padLeft(2, '0')) + .join(); + + Future pairingUri() async { + try { + final value = await _method.invokeMethod('pairingUri'); + if (value != null && value.isNotEmpty) return value; + } on MissingPluginException { + // 桌面/测试环境没有原生桥时给出可扫描的示例 URI。 + } on PlatformException { + // 同上。 + } + return 'lancast://pair?ip=192.168.1.10&port=41001&fp=sha256:ab12cd34ef567890'; + } + + Future _invokeIgnoringMissing(String method, [Object? argument]) async { + try { + await _method.invokeMethod(method, argument); + } on MissingPluginException { + // 测试或尚未接入 Rust Core 时使用 UI 演示数据。 + } + } +} diff --git a/flutter_sender/lib/core/local_signaling.dart b/flutter_sender/lib/core/local_signaling.dart new file mode 100644 index 0000000..21d4132 --- /dev/null +++ b/flutter_sender/lib/core/local_signaling.dart @@ -0,0 +1,94 @@ +import 'dart:io'; + +class LocalSignalingProcess { + LocalSignalingProcess() { + _refreshLocalIp(); + } + + Process? _process; + bool _running = false; + String _localIp = '127.0.0.1'; + + bool get isRunning => _running; + + Future start({int port = 8080}) async { + if (_running) return true; + await _refreshLocalIp(); + final binary = _resolveBinary(); + if (binary == null) return false; + + try { + final process = await Process.start( + binary.path, + const [], + workingDirectory: binary.parent.path, + environment: {'LISTEN_ADDR': ':$port'}, + ); + process.stdout.listen((_) {}); + process.stderr.listen((_) {}); + process.exitCode.then((_) { + _running = false; + _process = null; + }); + _process = process; + _running = true; + return true; + } on Object { + _running = false; + _process = null; + return false; + } + } + + Future stop() async { + final process = _process; + if (process == null) return; + _process = null; + _running = false; + try { + process.kill(); + await process.exitCode.timeout(const Duration(seconds: 3)); + } on Object { + // 进程未能及时退出时忽略,避免阻塞 UI。 + } + } + + String url({int port = 8080}) => 'http://${localIp()}:$port'; + + String localIp() => _localIp; + + Future _refreshLocalIp() async { + try { + final interfaces = await NetworkInterface.list(); + for (final interface in interfaces) { + for (final address in interface.addresses) { + if (address.type == InternetAddressType.IPv4 && !address.isLoopback) { + _localIp = address.address; + return; + } + } + } + } on Object { + // 网络接口不可用时保留 127.0.0.1。 + } + } + + File? _resolveBinary() { + final candidates = [ + if (Platform.isWindows) 'signaling_server.exe' else 'signaling_server', + if (Platform.isWindows) 'ttstd-signaling.exe' else 'ttstd-signaling', + ]; + final directories = [ + File(Platform.resolvedExecutable).parent, + Directory.current, + Directory('${Directory.current.path}${Platform.pathSeparator}signaling_server'), + ]; + for (final directory in directories) { + for (final name in candidates) { + final file = File('${directory.path}${Platform.pathSeparator}$name'); + if (file.existsSync()) return file; + } + } + return null; + } +} diff --git a/flutter_sender/lib/core/models.dart b/flutter_sender/lib/core/models.dart new file mode 100644 index 0000000..38a67da --- /dev/null +++ b/flutter_sender/lib/core/models.dart @@ -0,0 +1,192 @@ +enum ConnectionPhase { + idle, + discovering, + registering, + probing, + direct, + relaying, + failed, +} + +extension ConnectionPhaseX on ConnectionPhase { + String get wireName => name; + + String get label => switch (this) { + ConnectionPhase.idle => '未连接', + ConnectionPhase.discovering => '正在发现设备', + ConnectionPhase.registering => '正在查询信令', + ConnectionPhase.probing => '正在探测直连', + ConnectionPhase.direct => 'P2P 直连', + ConnectionPhase.relaying => '信令中转', + ConnectionPhase.failed => '连接失败', + }; + + bool get isBusy => switch (this) { + ConnectionPhase.discovering || + ConnectionPhase.registering || + ConnectionPhase.probing => + true, + _ => false, + }; + + bool get isConnected => this == ConnectionPhase.direct || this == ConnectionPhase.relaying; + + static ConnectionPhase fromWire(Object? value) { + final name = value is Map ? value['phase']?.toString() : value?.toString(); + return ConnectionPhase.values.firstWhere( + (phase) => phase.wireName == name, + orElse: () => ConnectionPhase.idle, + ); + } +} + +class DeviceInfo { + final String id; + final String name; + final String ip; + final int mediaPort; + final int controlPort; + final String fingerprint; + final List capabilities; + final String model; + final String resolution; + final String? signalingUrl; + + const DeviceInfo({ + required this.id, + required this.name, + required this.ip, + required this.mediaPort, + required this.controlPort, + required this.fingerprint, + this.capabilities = const [], + this.model = '', + this.resolution = '1920x1080', + this.signalingUrl, + }); + + factory DeviceInfo.fromJson(Map json) { + return DeviceInfo( + id: (json['deviceId'] ?? json['id'] ?? '').toString(), + name: (json['name'] ?? json['deviceId'] ?? '未命名设备').toString(), + ip: (json['ip'] ?? '').toString(), + mediaPort: (json['mediaPort'] is num ? json['mediaPort'] as num : 41000).toInt(), + controlPort: (json['controlPort'] is num ? json['controlPort'] as num : 41001).toInt(), + fingerprint: (json['fp'] ?? json['fingerprint'] ?? '').toString(), + capabilities: (json['cap'] as List? ?? const []) + .map((item) => item.toString()) + .toList(growable: false), + model: (json['model'] ?? '').toString(), + resolution: (json['res'] ?? '1920x1080').toString(), + signalingUrl: json['sig']?.toString(), + ); + } + + Map toJson() => { + 'deviceId': id, + 'name': name, + 'ip': ip, + 'mediaPort': mediaPort, + 'controlPort': controlPort, + 'fp': fingerprint, + 'cap': capabilities, + 'model': model, + 'res': resolution, + if (signalingUrl != null) 'sig': signalingUrl, + }; + + bool supports(String capability) => capabilities.contains(capability); + + String get shortFingerprint { + final cleaned = fingerprint.replaceFirst('sha256:', ''); + return cleaned.length > 12 ? '${cleaned.substring(0, 12)}…' : cleaned; + } + + static List listFromJson(Object? raw) { + if (raw is! List) return const []; + return raw + .whereType>() + .map((item) => DeviceInfo.fromJson(Map.from(item))) + .toList(growable: false); + } +} + +class AppSettings { + final String signalingUrl; + final bool useLocalSignaling; + final bool localSignalingEnabled; + final int localSignalingPort; + final bool preferH265; + final bool audioEnabled; + final bool clipboardSync; + final bool fileTransfer; + final int bitrateMbps; + + const AppSettings({ + this.signalingUrl = 'http://192.168.1.5:8080', + this.useLocalSignaling = true, + this.localSignalingEnabled = true, + this.localSignalingPort = 8080, + this.preferH265 = false, + this.audioEnabled = true, + this.clipboardSync = true, + this.fileTransfer = true, + this.bitrateMbps = 8, + }); + + static const defaults = AppSettings(); + + String get signalingModeLabel => useLocalSignaling ? '本机信令' : '外部信令'; + + AppSettings copyWith({ + String? signalingUrl, + bool? useLocalSignaling, + bool? localSignalingEnabled, + int? localSignalingPort, + bool? preferH265, + bool? audioEnabled, + bool? clipboardSync, + bool? fileTransfer, + int? bitrateMbps, + }) { + return AppSettings( + signalingUrl: signalingUrl ?? this.signalingUrl, + useLocalSignaling: useLocalSignaling ?? this.useLocalSignaling, + localSignalingEnabled: localSignalingEnabled ?? this.localSignalingEnabled, + localSignalingPort: localSignalingPort ?? this.localSignalingPort, + preferH265: preferH265 ?? this.preferH265, + audioEnabled: audioEnabled ?? this.audioEnabled, + clipboardSync: clipboardSync ?? this.clipboardSync, + fileTransfer: fileTransfer ?? this.fileTransfer, + bitrateMbps: bitrateMbps ?? this.bitrateMbps, + ); + } + + factory AppSettings.fromJson(Map json) { + return AppSettings( + signalingUrl: (json['signalingUrl'] ?? defaults.signalingUrl).toString(), + useLocalSignaling: json['useLocalSignaling'] as bool? ?? defaults.useLocalSignaling, + localSignalingEnabled: + json['localSignalingEnabled'] as bool? ?? defaults.localSignalingEnabled, + localSignalingPort: + (json['localSignalingPort'] is num ? json['localSignalingPort'] as num : 8080).toInt(), + preferH265: json['preferH265'] as bool? ?? defaults.preferH265, + audioEnabled: json['audioEnabled'] as bool? ?? defaults.audioEnabled, + clipboardSync: json['clipboardSync'] as bool? ?? defaults.clipboardSync, + fileTransfer: json['fileTransfer'] as bool? ?? defaults.fileTransfer, + bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(), + ); + } + + Map toJson() => { + 'signalingUrl': signalingUrl, + 'useLocalSignaling': useLocalSignaling, + 'localSignalingEnabled': localSignalingEnabled, + 'localSignalingPort': localSignalingPort, + 'preferH265': preferH265, + 'audioEnabled': audioEnabled, + 'clipboardSync': clipboardSync, + 'fileTransfer': fileTransfer, + 'bitrateMbps': bitrateMbps, + }; +} diff --git a/flutter_sender/lib/core/native_core.dart b/flutter_sender/lib/core/native_core.dart new file mode 100644 index 0000000..66d78a8 --- /dev/null +++ b/flutter_sender/lib/core/native_core.dart @@ -0,0 +1,380 @@ +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; + +/// Rust Core 的 ffi 通道。桌面端通过 cdylib 直接调用,测试环境可注入桩实现。 +class NativeCore { + NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary(); + + static const int ok = 0; + static const int errBufferTooSmall = -1; + static const int errInvalidArgument = -2; + static const int errCrypto = -3; + static const int errCodec = -4; + + static const List _libraryNames = [ + 'ttstdconnect_core.dll', + 'libttstdconnect_core.so', + 'libttstdconnect_core.dylib', + ]; + + final DynamicLibrary _library; + bool _disposed = false; + + static DynamicLibrary _openLibrary() { + final errors = []; + for (final name in _libraryNames) { + try { + return DynamicLibrary.open(name); + } on Object catch (error) { + errors.add('$name: $error'); + } + } + final folder = File(Platform.resolvedExecutable).parent.path; + for (final name in _libraryNames) { + final path = '$folder${Platform.pathSeparator}$name'; + if (File(path).existsSync()) { + try { + return DynamicLibrary.open(path); + } on Object catch (error) { + errors.add('$path: $error'); + } + } + } + throw UnsupportedError( + '无法加载 Rust Core 动态库。请先把 cdylib 放到应用目录或系统库路径。\n${errors.join('\n')}', + ); + } + + late final DartVersionFn version = _library + .lookup>('ttstd_core_version') + .asFunction(); + late final DartAbiRevisionFn abiRevision = _library + .lookup>('ttstd_core_abi_revision') + .asFunction(); + late final DartEcdhGenerateFn _ecdhGenerate = _library + .lookup>('ttstd_ecdh_generate') + .asFunction(); + late final DartEcdhAgreeFn _ecdhAgree = _library + .lookup>('ttstd_ecdh_agree') + .asFunction(); + late final DartEcdhFreeFn _ecdhFree = _library + .lookup>('ttstd_ecdh_free') + .asFunction(); + late final DartDeriveSubkeyFn _deriveSubkey = _library + .lookup>('ttstd_derive_subkey') + .asFunction(); + late final DartMediaEncodeFn _mediaEncode = _library + .lookup>('ttstd_media_encode') + .asFunction(); + late final DartMediaDecodeFn _mediaDecode = _library + .lookup>('ttstd_media_decode') + .asFunction(); + late final DartControlNewFn _controlNew = _library + .lookup>('ttstd_control_channel_new') + .asFunction(); + late final DartControlFreeFn _controlFree = _library + .lookup>('ttstd_control_channel_free') + .asFunction(); + late final DartControlEncodePingFn _controlEncodePing = _library + .lookup>('ttstd_control_encode_ping') + .asFunction(); + late final DartControlDecodeFn _controlDecode = _library + .lookup>('ttstd_control_decode') + .asFunction(); + late final DartDemoStartFn _demoStart = _library + .lookup>('ttstd_demo_start') + .asFunction(); + late final DartDemoStopFn _demoStop = _library + .lookup>('ttstd_demo_stop') + .asFunction(); + late final DartDemoStatusFn _demoStatus = _library + .lookup>('ttstd_demo_status') + .asFunction(); + + bool get isAvailable => !_disposed; + + String get versionString => version().cast().toDartString(); + + EcdhKeyPair generateKeyPair() { + final public = calloc(65); + try { + final handle = _ecdhGenerate(public, 65); + if (handle <= 0) { + throw NativeCoreException('ttstd_ecdh_generate', handle); + } + return EcdhKeyPair(this, handle, _copy(public, 65)); + } finally { + calloc.free(public); + } + } + + Uint8List deriveSubkey(List secret, String label) { + return _withBytes(secret, (secretPtr) { + return _withUtf8(label, (labelPtr) { + final out = calloc(32); + try { + final written = _deriveSubkey( + secretPtr, + secret.length, + labelPtr.cast(), + label.length, + out, + 32, + ); + _check(written, 'ttstd_derive_subkey'); + return _copy(out, written); + } finally { + calloc.free(out); + } + }); + }); + } + + Uint8List mediaEncode(int pts, int flags, List key, List payload) { + return _withBytes(key, (keyPtr) { + return _withBytes(payload, (payloadPtr) { + final capacity = 13 + payload.length + 4; + final out = calloc(capacity); + try { + final written = _mediaEncode( + pts, + flags, + keyPtr, + payloadPtr, + payload.length, + out, + capacity, + ); + _check(written, 'ttstd_media_encode'); + return _copy(out, written); + } finally { + calloc.free(out); + } + }); + }); + } + + Map mediaDecode(List packet, List key) { + return _withBytes(packet, (packetPtr) { + return _withBytes(key, (keyPtr) { + final out = calloc(256); + try { + final written = _mediaDecode(packetPtr, packet.length, keyPtr, out, 256); + _check(written, 'ttstd_media_decode'); + return jsonDecode(_copy(out, written).toString()) as Map; + } finally { + calloc.free(out); + } + }); + }); + } + + SecureChannel createSecureChannel(List key) { + return _withBytes(key, (keyPtr) { + final handle = _controlNew(keyPtr); + if (handle <= 0) throw NativeCoreException('ttstd_control_channel_new', handle); + return SecureChannel(this, handle); + }); + } + + bool startDemoServer({int controlPort = 41001, int videoPort = 41000, int audioPort = 41002}) { + return _demoStart(controlPort, videoPort, audioPort) == ok; + } + + void stopDemoServer() => _demoStop(); + + Map demoStatus() { + final out = calloc(8192); + try { + final written = _demoStatus(out, 8192); + _check(written, 'ttstd_demo_status'); + return jsonDecode(_copy(out, written).toString()) as Map; + } finally { + calloc.free(out); + } + } + + void dispose() => _disposed = true; + + void _check(int code, String symbol) { + if (code < 0) throw NativeCoreException(symbol, code); + } + + static Uint8List _copy(Pointer ptr, int length) { + final result = Uint8List(length); + for (var i = 0; i < length; i++) { + result[i] = ptr[i]; + } + return result; + } + + static T _withBytes(List bytes, T Function(Pointer) body) { + final ptr = calloc(bytes.length); + try { + for (var i = 0; i < bytes.length; i++) { + ptr[i] = bytes[i]; + } + return body(ptr); + } finally { + calloc.free(ptr); + } + } + + static T _withUtf8(String text, T Function(Pointer) body) { + final ptr = text.toNativeUtf8(); + try { + return body(ptr.cast()); + } finally { + calloc.free(ptr); + } + } +} + +class NativeCoreException implements Exception { + const NativeCoreException(this.symbol, this.code); + + final String symbol; + final int code; + + @override + String toString() => 'NativeCore 调用失败 ($symbol): $code'; +} + +class EcdhKeyPair { + EcdhKeyPair(this._core, this._handle, this.publicBytes); + + final NativeCore _core; + final int _handle; + final Uint8List publicBytes; + bool _consumed = false; + + Uint8List agree(List peerPublic) { + if (_consumed) throw StateError('ECDH 句柄已被消费'); + _consumed = true; + return _withBytesExternal(peerPublic, (ptr) { + final out = calloc(32); + try { + final written = _core._ecdhAgree(_handle, ptr, peerPublic.length, out, 32); + if (written < 0) throw NativeCoreException('ttstd_ecdh_agree', written); + return NativeCore._copy(out, written); + } finally { + calloc.free(out); + } + }); + } + + void free() { + if (_consumed) return; + _consumed = true; + _core._ecdhFree(_handle); + } + + static T _withBytesExternal(List bytes, T Function(Pointer) body) { + final ptr = calloc(bytes.length); + try { + for (var i = 0; i < bytes.length; i++) { + ptr[i] = bytes[i]; + } + return body(ptr); + } finally { + calloc.free(ptr); + } + } +} + +class SecureChannel { + SecureChannel(this._core, this._handle); + + final NativeCore _core; + final int _handle; + bool _disposed = false; + + Uint8List encodePing(int sequence, int timestamp) { + final out = calloc(512); + try { + final written = _core._controlEncodePing(_handle, sequence, timestamp, out, 512); + if (written < 0) throw NativeCoreException('ttstd_control_encode_ping', written); + return NativeCore._copy(out, written); + } finally { + calloc.free(out); + } + } + + Map decode(List frame) { + return EcdhKeyPair._withBytesExternal(frame, (framePtr) { + final out = calloc(256); + 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; + } finally { + calloc.free(out); + } + }); + } + + void dispose() { + if (_disposed) return; + _disposed = true; + _core._controlFree(_handle); + } +} + +typedef NativeVersionFn = Pointer Function(); +typedef DartVersionFn = Pointer Function(); +typedef NativeAbiRevisionFn = Int32 Function(); +typedef DartAbiRevisionFn = int Function(); +typedef NativeEcdhGenerateFn = Int64 Function(Pointer, UintPtr); +typedef DartEcdhGenerateFn = int Function(Pointer, int); +typedef NativeEcdhAgreeFn = Int32 Function( + Int64, Pointer, UintPtr, Pointer, UintPtr, +); +typedef DartEcdhAgreeFn = int Function( + int, Pointer, int, Pointer, int, +); +typedef NativeEcdhFreeFn = Void Function(Int64); +typedef DartEcdhFreeFn = void Function(int); +typedef NativeDeriveSubkeyFn = Int32 Function( + Pointer, UintPtr, Pointer, UintPtr, Pointer, UintPtr, +); +typedef DartDeriveSubkeyFn = int Function( + Pointer, int, Pointer, int, Pointer, int, +); +typedef NativeMediaEncodeFn = Int32 Function( + Uint64, Uint8, Pointer, Pointer, UintPtr, Pointer, UintPtr, +); +typedef DartMediaEncodeFn = int Function( + int, int, Pointer, Pointer, int, Pointer, int, +); +typedef NativeMediaDecodeFn = Int32 Function( + Pointer, UintPtr, Pointer, Pointer, UintPtr, +); +typedef DartMediaDecodeFn = int Function( + Pointer, int, Pointer, Pointer, int, +); +typedef NativeControlNewFn = Int64 Function(Pointer); +typedef DartControlNewFn = int Function(Pointer); +typedef NativeControlFreeFn = Void Function(Int64); +typedef DartControlFreeFn = void Function(int); +typedef NativeControlEncodePingFn = Int32 Function( + Int64, Uint16, Uint64, Pointer, UintPtr, +); +typedef DartControlEncodePingFn = int Function( + int, int, int, Pointer, int, +); +typedef NativeControlDecodeFn = Int32 Function( + Int64, Pointer, UintPtr, Pointer, UintPtr, +); +typedef DartControlDecodeFn = int Function( + int, Pointer, int, Pointer, int, +); +typedef NativeDemoStartFn = Int32 Function(Uint16, Uint16, Uint16); +typedef DartDemoStartFn = int Function(int, int, int); +typedef NativeDemoStopFn = Void Function(); +typedef DartDemoStopFn = void Function(); +typedef NativeDemoStatusFn = Int32 Function(Pointer, UintPtr); +typedef DartDemoStatusFn = int Function(Pointer, int); diff --git a/flutter_sender/lib/features/control/control_toolbar.dart b/flutter_sender/lib/features/control/control_toolbar.dart new file mode 100644 index 0000000..3cb4f23 --- /dev/null +++ b/flutter_sender/lib/features/control/control_toolbar.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; + +class ControlToolbar extends StatelessWidget { + const ControlToolbar({super.key, required this.enabled, required this.onEvent}); + + final bool enabled; + final void Function(String type, Map payload) onEvent; + + @override + Widget build(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.gamepad), + const SizedBox(width: 8), + Text('远程控制', style: Theme.of(context).textTheme.titleSmall), + const Spacer(), + if (!enabled) + Text('连接后可用', style: Theme.of(context).textTheme.labelSmall), + ], + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + _Action( + icon: Icons.touch_app, + label: '点击中心', + enabled: enabled, + onPressed: () => onEvent('touch', { + 'action': 0, + 'pointerId': 1, + 'x': 960, + 'y': 540, + 'pressure': 800, + }), + ), + _Action( + icon: Icons.arrow_back, + label: '返回', + enabled: enabled, + onPressed: () => onEvent('key', {'action': 0, 'keycode': 4, 'modifiers': 0}), + ), + _Action( + icon: Icons.home, + label: '主页', + enabled: enabled, + onPressed: () => onEvent('key', {'action': 0, 'keycode': 3, 'modifiers': 0}), + ), + _Action( + icon: Icons.mouse, + label: '滚轮向下', + enabled: enabled, + onPressed: () => onEvent('wheel', {'deltaX': 0, 'deltaY': -1, 'buttons': 0}), + ), + _Action( + icon: Icons.content_paste, + label: '发送剪贴板', + enabled: enabled, + onPressed: () => onEvent('clipboard', {'text': 'TTSTD Connect'}), + ), + ], + ), + ], + ), + ), + ); + } +} + +class _Action extends StatelessWidget { + const _Action({ + required this.icon, + required this.label, + required this.enabled, + required this.onPressed, + }); + + final IconData icon; + final String label; + final bool enabled; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + return OutlinedButton.icon( + onPressed: enabled ? onPressed : null, + icon: Icon(icon, size: 18), + label: Text(label), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + ), + ); + } +} diff --git a/flutter_sender/lib/features/discovery/device_list.dart b/flutter_sender/lib/features/discovery/device_list.dart new file mode 100644 index 0000000..c2f47fc --- /dev/null +++ b/flutter_sender/lib/features/discovery/device_list.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; + +import '../../core/models.dart'; + +class DeviceList extends StatelessWidget { + const DeviceList({ + super.key, + required this.devices, + required this.selectedId, + required this.onSelected, + required this.onRefresh, + this.refreshing = false, + this.shrinkWrap = false, + }); + + final List devices; + final String? selectedId; + final ValueChanged onSelected; + final VoidCallback onRefresh; + final bool refreshing; + final bool shrinkWrap; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Row( + children: [ + Icon(Icons.devices_other, size: 20, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text('可连接设备', style: theme.textTheme.titleMedium), + const Spacer(), + Text('${devices.length} 台', style: theme.textTheme.bodySmall), + IconButton( + tooltip: '重新发现', + onPressed: onRefresh, + icon: refreshing + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh), + ), + ], + ), + ), + if (shrinkWrap) + _buildList() + else + Expanded(child: _buildList()), + ], + ); + } + + Widget _buildList() { + if (devices.isEmpty) return _EmptyState(onRefresh: onRefresh); + return ListView.separated( + shrinkWrap: shrinkWrap, + physics: shrinkWrap ? const NeverScrollableScrollPhysics() : null, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + itemCount: devices.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, index) => _DeviceCard( + device: devices[index], + selected: devices[index].id == selectedId, + onTap: () => onSelected(devices[index]), + ), + ); + } +} + +class _DeviceCard extends StatelessWidget { + const _DeviceCard({required this.device, required this.selected, required this.onTap}); + + final DeviceInfo device; + final bool selected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Card( + clipBehavior: Clip.antiAlias, + color: selected ? theme.colorScheme.primaryContainer : null, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + backgroundColor: selected ? theme.colorScheme.primary : theme.colorScheme.surfaceContainerHighest, + foregroundColor: selected ? theme.colorScheme.onPrimary : theme.colorScheme.onSurface, + child: const Icon(Icons.android), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(device.name, style: theme.textTheme.titleSmall), + const SizedBox(height: 2), + Text('${device.ip}:${device.controlPort} · ${device.model}', + style: theme.textTheme.bodySmall, + maxLines: 1, + overflow: TextOverflow.ellipsis), + ], + ), + ), + if (selected) Icon(Icons.check_circle, color: theme.colorScheme.primary), + ], + ), + const SizedBox(height: 10), + Wrap( + spacing: 6, + runSpacing: 4, + children: [ + for (final capability in device.capabilities.take(4)) + Chip( + visualDensity: VisualDensity.compact, + label: Text(capability, style: theme.textTheme.labelSmall), + padding: EdgeInsets.zero, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ], + ), + const SizedBox(height: 6), + Text('指纹 ${device.shortFingerprint} · ${device.resolution}', + style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.outline)), + ], + ), + ), + ), + ); + } +} + +class _EmptyState extends StatelessWidget { + const _EmptyState({required this.onRefresh}); + + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.wifi_find, size: 48), + const SizedBox(height: 12), + const Text('未发现设备'), + const SizedBox(height: 4), + Text('确认手机与主控端处于同一网段', style: Theme.of(context).textTheme.bodySmall), + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: onRefresh, + icon: const Icon(Icons.refresh), + label: const Text('重新扫描'), + ), + ], + ), + ); + } +} diff --git a/flutter_sender/lib/features/media/video_view.dart b/flutter_sender/lib/features/media/video_view.dart new file mode 100644 index 0000000..365085b --- /dev/null +++ b/flutter_sender/lib/features/media/video_view.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; + +class VideoView extends StatelessWidget { + const VideoView({ + super.key, + this.textureId, + this.connected = false, + this.resolution = '1920x1080', + this.pts, + }); + + final int? textureId; + final bool connected; + final String resolution; + final int? pts; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return AspectRatio( + aspectRatio: 16 / 9, + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + theme.colorScheme.surfaceContainerHighest, + theme.colorScheme.surfaceContainerLowest, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + ), + child: Stack( + fit: StackFit.expand, + children: [ + if (textureId != null) + Texture(textureId: textureId!) + else + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.connected_tv, size: 72, color: theme.colorScheme.primary.withValues(alpha: 0.6)), + const SizedBox(height: 12), + Text(connected ? '视频通道已建立' : '等待投屏画面', + style: theme.textTheme.titleMedium), + const SizedBox(height: 4), + Text('H.264/H.265 → External Texture', + style: theme.textTheme.bodySmall), + ], + ), + Positioned( + top: 12, + left: 12, + child: _Badge( + icon: Icons.videocam, + label: resolution, + color: connected ? theme.colorScheme.primary : theme.colorScheme.outline, + ), + ), + if (pts != null) + Positioned( + top: 12, + right: 12, + child: _Badge(icon: Icons.timer, label: 'PTS $pts', color: theme.colorScheme.outline), + ), + ], + ), + ), + ), + ); + } +} + +class _Badge extends StatelessWidget { + const _Badge({required this.icon, required this.label, required this.color}); + + final IconData icon; + final String label; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: Colors.black54, + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: color), + const SizedBox(width: 6), + Text(label, style: const TextStyle(color: Colors.white, fontSize: 12)), + ], + ), + ); + } +} diff --git a/flutter_sender/lib/features/session/connect_bar.dart b/flutter_sender/lib/features/session/connect_bar.dart new file mode 100644 index 0000000..8716aa3 --- /dev/null +++ b/flutter_sender/lib/features/session/connect_bar.dart @@ -0,0 +1,124 @@ +import 'package:flutter/material.dart'; + +import '../../core/models.dart'; + +class ConnectBar extends StatelessWidget { + const ConnectBar({ + super.key, + required this.phase, + required this.device, + required this.onConnect, + required this.onDisconnect, + }); + + final ConnectionPhase phase; + final DeviceInfo? device; + final VoidCallback onConnect; + final VoidCallback onDisconnect; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final connected = phase.isConnected; + final busy = phase.isBusy; + final discovered = phase != ConnectionPhase.idle; + final handshaken = phase == ConnectionPhase.probing || + phase == ConnectionPhase.direct || + phase == ConnectionPhase.relaying; + final color = switch (phase) { + ConnectionPhase.direct || ConnectionPhase.relaying => theme.colorScheme.primary, + ConnectionPhase.failed => theme.colorScheme.error, + _ => theme.colorScheme.outline, + }; + + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 10, + height: 10, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(phase.label, style: theme.textTheme.titleSmall), + Text( + device == null ? '请从左侧选择一台设备' : '${device!.name} · ${device!.ip}', + style: theme.textTheme.bodySmall, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + FilledButton.icon( + onPressed: device == null || busy ? null : (connected ? onDisconnect : onConnect), + icon: Icon(connected ? Icons.link_off : Icons.play_arrow), + label: Text(connected ? '断开' : '连接'), + ), + ], + ), + if (busy) ...[ + const SizedBox(height: 12), + const LinearProgressIndicator(), + ], + const SizedBox(height: 12), + Row( + children: [ + _StepDone(active: discovered, label: '发现'), + _StepDivider(active: handshaken), + _StepDone(active: handshaken, label: '握手'), + _StepDivider(active: connected), + _StepDone(active: connected, label: '媒体'), + ], + ), + ], + ), + ), + ); + } +} + +class _StepDone extends StatelessWidget { + const _StepDone({required this.active, required this.label}); + + final bool active; + final String label; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(active ? Icons.task_alt : Icons.radio_button_unchecked, + size: 16, color: active ? theme.colorScheme.primary : theme.colorScheme.outline), + const SizedBox(width: 4), + Text(label, style: theme.textTheme.labelSmall), + ], + ); + } +} + +class _StepDivider extends StatelessWidget { + const _StepDivider({required this.active}); + + final bool active; + + @override + Widget build(BuildContext context) { + return Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Divider(thickness: 2, color: active ? Theme.of(context).colorScheme.primary : null), + ), + ); + } +} diff --git a/flutter_sender/lib/features/settings/settings_page.dart b/flutter_sender/lib/features/settings/settings_page.dart new file mode 100644 index 0000000..8019b25 --- /dev/null +++ b/flutter_sender/lib/features/settings/settings_page.dart @@ -0,0 +1,254 @@ +import 'package:flutter/material.dart'; + +import '../../core/bridge.dart'; +import '../../core/models.dart'; + +class SettingsPage extends StatefulWidget { + const SettingsPage({ + super.key, + required this.settings, + required this.bridge, + }); + + final AppSettings settings; + final SenderBridge bridge; + + @override + State createState() => _SettingsPageState(); +} + +class _SettingsPageState extends State { + late final TextEditingController _signalingUrl; + late final TextEditingController _localPort; + late bool _useLocalSignaling; + late bool _localSignalingEnabled; + late bool _localRunning; + late bool _preferH265; + late bool _audioEnabled; + late bool _clipboardSync; + late bool _fileTransfer; + late int _bitrateMbps; + + @override + void initState() { + super.initState(); + _signalingUrl = TextEditingController(text: widget.settings.signalingUrl); + _localPort = TextEditingController(text: '${widget.settings.localSignalingPort}'); + _useLocalSignaling = widget.settings.useLocalSignaling; + _localSignalingEnabled = widget.settings.localSignalingEnabled; + _localRunning = widget.bridge.isLocalSignalingRunning; + _preferH265 = widget.settings.preferH265; + _audioEnabled = widget.settings.audioEnabled; + _clipboardSync = widget.settings.clipboardSync; + _fileTransfer = widget.settings.fileTransfer; + _bitrateMbps = widget.settings.bitrateMbps; + } + + @override + void dispose() { + _signalingUrl.dispose(); + _localPort.dispose(); + super.dispose(); + } + + int get _port { + final parsed = int.tryParse(_localPort.text.trim()); + return parsed != null && parsed >= 1 && parsed <= 65535 ? parsed : 8080; + } + + void _snack(String message) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); + } + } + + void _setLocalServer(bool enabled) { + setState(() => _localSignalingEnabled = enabled); + } + + Future _save() async { + if (!_useLocalSignaling && _signalingUrl.text.trim().isEmpty) { + _snack('请填写外部信令服务器地址'); + return; + } + if (int.tryParse(_localPort.text.trim()) == null) { + _snack('本机端口必须是数字'); + return; + } + + if (_localSignalingEnabled) { + if (!_localRunning || _port != widget.settings.localSignalingPort) { + await widget.bridge.stopLocalSignaling(); + final started = await widget.bridge.startLocalSignaling(_port); + if (!mounted) return; + setState(() => _localRunning = started); + if (!started) _snack('本机信令服务启动失败'); + } + } else if (_localRunning) { + await widget.bridge.stopLocalSignaling(); + if (!mounted) return; + setState(() => _localRunning = false); + } + + if (!mounted) return; + Navigator.of(context).pop(AppSettings( + signalingUrl: _signalingUrl.text.trim(), + useLocalSignaling: _useLocalSignaling, + localSignalingEnabled: _localSignalingEnabled, + localSignalingPort: _port, + preferH265: _preferH265, + audioEnabled: _audioEnabled, + clipboardSync: _clipboardSync, + fileTransfer: _fileTransfer, + bitrateMbps: _bitrateMbps, + )); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Scaffold( + appBar: AppBar(title: const Text('设置')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.dns, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text('信令服务器', style: theme.textTheme.titleMedium), + ], + ), + const SizedBox(height: 8), + SwitchListTile( + title: const Text('使用本机信令服务器'), + subtitle: const Text('默认开启;安装包内置独立 Go 信令服务'), + value: _useLocalSignaling, + onChanged: (value) => setState(() => _useLocalSignaling = value), + ), + if (_useLocalSignaling) ...[ + SwitchListTile( + title: const Text('开启本机信令服务'), + subtitle: Text( + !_localSignalingEnabled + ? '已关闭' + : (_localRunning ? '服务运行中' : '保存设置后启动'), + style: TextStyle( + color: _localSignalingEnabled && _localRunning + ? theme.colorScheme.primary + : theme.colorScheme.error, + ), + ), + value: _localSignalingEnabled, + onChanged: _setLocalServer, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: TextField( + controller: _localPort, + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: '本机监听端口', + hintText: '8080', + prefixIcon: Icon(Icons.numbers), + border: OutlineInputBorder(), + ), + ), + ), + const SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + '本机地址:${widget.bridge.localSignalingUrl(_port)}\n手机端扫码或手动填写该地址即可注册。', + style: theme.textTheme.bodySmall, + ), + ), + if (!_localSignalingEnabled) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Text( + '本机服务已关闭,但当前仍选择“使用本机信令服务器”,设备列表将不可用。', + style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.error), + ), + ), + ] else ...[ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: TextField( + controller: _signalingUrl, + decoration: const InputDecoration( + labelText: '外部信令服务器', + hintText: 'http://192.168.1.5:8080', + prefixIcon: Icon(Icons.cloud), + border: OutlineInputBorder(), + ), + ), + ), + const SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + '跨网段时通过自部署信令服务器交换地址。', + style: theme.textTheme.bodySmall, + ), + ), + ], + ], + ), + ), + ), + const Divider(height: 32), + SwitchListTile( + title: const Text('优先使用 H.265'), + subtitle: const Text('带宽更省,要求被控端支持'), + value: _preferH265, + onChanged: (value) => setState(() => _preferH265 = value), + ), + SwitchListTile( + title: const Text('启用音频'), + subtitle: const Text('AudioPlaybackCapture / OPUS'), + value: _audioEnabled, + onChanged: (value) => setState(() => _audioEnabled = value), + ), + SwitchListTile( + title: const Text('剪贴板同步'), + subtitle: const Text('通过控制通道双向同步文本'), + value: _clipboardSync, + onChanged: (value) => setState(() => _clipboardSync = value), + ), + SwitchListTile( + title: const Text('允许文件传输'), + subtitle: const Text('复用 TLS 会话,支持分片续传'), + value: _fileTransfer, + onChanged: (value) => setState(() => _fileTransfer = value), + ), + const Divider(height: 32), + ListTile( + title: const Text('投屏码率'), + subtitle: Text('$_bitrateMbps Mbps · 1080p 建议 6–10 Mbps'), + ), + Slider( + min: 2, + max: 20, + divisions: 18, + value: _bitrateMbps.toDouble(), + label: '$_bitrateMbps Mbps', + onChanged: (value) => setState(() => _bitrateMbps = value.round()), + ), + const SizedBox(height: 24), + FilledButton.icon( + onPressed: _save, + icon: const Icon(Icons.save), + label: const Text('保存设置'), + ), + ], + ), + ); + } +} diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart new file mode 100644 index 0000000..086e6b5 --- /dev/null +++ b/flutter_sender/lib/main.dart @@ -0,0 +1,409 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import 'core/bridge.dart'; +import 'core/native_core.dart'; +import 'core/models.dart'; +import 'features/control/control_toolbar.dart'; +import 'features/discovery/device_list.dart'; +import 'features/media/video_view.dart'; +import 'features/session/connect_bar.dart'; +import 'features/settings/settings_page.dart'; + +void main() => runApp(const TTSTDConnectApp()); + +class TTSTDConnectApp extends StatelessWidget { + const TTSTDConnectApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'TTSTD Connect', + debugShowCheckedModeBanner: false, + theme: ThemeData( + useMaterial3: true, + colorSchemeSeed: const Color(0xFF5468FF), + brightness: Brightness.dark, + ), + home: const HomePage(), + ); + } +} + +class HomePage extends StatefulWidget { + const HomePage({super.key}); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + NativeCore? _nativeCore; + late final SenderBridge _bridge; + Timer? _demoStatusTimer; + + List _devices = SenderBridge.mockDevices; + DeviceInfo? _selected = SenderBridge.mockDevices.first; + ConnectionPhase _phase = ConnectionPhase.idle; + AppSettings _settings = AppSettings.defaults; + String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl; + bool _localSignalingRunning = false; + bool _refreshing = false; + Map? _selfTest; + Map _demoStatus = const {'running': false}; + String? _nativeError; + + @override + void initState() { + super.initState(); + try { + _nativeCore = NativeCore(); + } on Object catch (error) { + _nativeError = error.toString(); + } + _bridge = SenderBridge(nativeCore: _nativeCore); + _bridge.watchPhase().listen((phase) { + if (mounted) setState(() => _phase = phase); + }); + _applySignalingSettings(); + _refreshDevices(); + _runSelfTest(); + _demoStatusTimer = Timer.periodic( + const Duration(seconds: 1), + (_) => _refreshDemoStatus(), + ); + } + + @override + void dispose() { + _demoStatusTimer?.cancel(); + _bridge.stopDemoServer(); + _bridge.stopLocalSignaling(); + _nativeCore?.dispose(); + super.dispose(); + } + + void _runSelfTest() { + if (_nativeCore == null) return; + try { + final result = _bridge.runCryptoSelfTest(); + if (mounted) setState(() => _selfTest = result); + } on Object catch (error) { + if (mounted) setState(() => _nativeError = error.toString()); + } + } + + void _refreshDemoStatus() { + if (_nativeCore == null || !mounted) return; + try { + final status = _bridge.demoStatus(); + setState(() => _demoStatus = status); + } on Object catch (_) { + // 动态库不可用时忽略轮询错误。 + } + } + + void _toggleDemoServer() { + if (_nativeCore == null) return; + try { + final running = _demoStatus['running'] == true; + if (running) { + _bridge.stopDemoServer(); + } else { + _bridge.startDemoServer(); + } + _refreshDemoStatus(); + } on Object catch (error) { + if (mounted) setState(() => _nativeError = error.toString()); + } + } + + Future _applySignalingSettings() async { + if (_settings.localSignalingEnabled) { + final started = await _bridge.startLocalSignaling(_settings.localSignalingPort); + if (!mounted) return; + setState(() => _localSignalingRunning = started); + } else { + await _bridge.stopLocalSignaling(); + if (!mounted) return; + setState(() => _localSignalingRunning = false); + } + final url = await _bridge.resolveSignalingUrl(_settings); + if (!mounted) return; + setState(() => _effectiveSignalingUrl = url); + } + + Future _refreshDevices() async { + if (_refreshing) return; + setState(() => _refreshing = true); + final devices = await _bridge.discover(); + if (!mounted) return; + setState(() { + _devices = devices; + if (_selected == null || !devices.any((device) => device.id == _selected!.id)) { + _selected = devices.isEmpty ? null : devices.first; + } + _refreshing = false; + }); + } + + Future _connect() async { + final device = _selected; + if (device == null) return; + setState(() => _phase = ConnectionPhase.probing); + await _bridge.connect(device); + if (!mounted) return; + setState(() => _phase = ConnectionPhase.direct); + } + + Future _disconnect() async { + await _bridge.disconnect(); + if (!mounted) return; + setState(() => _phase = ConnectionPhase.idle); + } + + Future _openSettings() async { + final updated = await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsPage(settings: _settings, bridge: _bridge), + ), + ); + if (updated == null) return; + setState(() => _settings = updated); + await _bridge.saveSettings(updated); + await _applySignalingSettings(); + } + + Future _showPairing() async { + final uri = await _bridge.pairingUri(); + if (!mounted) return; + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('扫码配对'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 180, + height: 180, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.qr_code_2, size: 140, color: Colors.black87), + ), + const SizedBox(height: 16), + SelectableText(uri, textAlign: TextAlign.center), + const SizedBox(height: 12), + Text( + '首次连接需在被控端确认指纹;配对时可选择“仅查看 / 查看+控制 / 全权限”。', + style: Theme.of(context).textTheme.bodySmall, + textAlign: TextAlign.center, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('关闭'), + ), + ], + ), + ); + } + + void _sendControl(String type, Map payload) { + _bridge.sendControl(type, payload); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('已发送 $type 控制事件'), duration: const Duration(milliseconds: 900)), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('TTSTD Connect'), + actions: [ + IconButton( + tooltip: '扫码配对', + onPressed: _showPairing, + icon: const Icon(Icons.qr_code_scanner), + ), + IconButton( + tooltip: '设置', + onPressed: _openSettings, + icon: const Icon(Icons.settings), + ), + ], + ), + floatingActionButton: FloatingActionButton( + onPressed: _showPairing, + tooltip: '扫码配对', + child: const Icon(Icons.add_link), + ), + body: LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth >= 1000) { + return Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: 360, + child: Card( + margin: const EdgeInsets.all(12), + clipBehavior: Clip.antiAlias, + child: DeviceList( + devices: _devices, + selectedId: _selected?.id, + onSelected: (device) => setState(() => _selected = device), + onRefresh: _refreshDevices, + refreshing: _refreshing, + ), + ), + ), + const VerticalDivider(width: 1), + Expanded(child: SingleChildScrollView(child: _buildStage())), + ], + ); + } + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + height: 360, + child: Card( + margin: const EdgeInsets.fromLTRB(12, 12, 12, 0), + clipBehavior: Clip.antiAlias, + child: DeviceList( + devices: _devices, + selectedId: _selected?.id, + onSelected: (device) => setState(() => _selected = device), + onRefresh: _refreshDevices, + refreshing: _refreshing, + ), + ), + ), + _buildStage(), + ], + ), + ); + }, + ), + ); + } + + Widget _buildNativeDemoCard() { + final native = _nativeCore; + final test = _selfTest; + final status = _demoStatus; + final running = status['running'] == true; + final connected = status['peerConnected'] == true; + final keyEstablished = status['keyEstablished'] == true; + final events = (status['events'] as List? ?? const []) + .map((item) => item.toString()) + .toList(); + + return Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Icon(Icons.bolt_outlined, size: 18), + const SizedBox(width: 8), + const Text('Rust Core 协议自检', style: TextStyle(fontWeight: FontWeight.bold)), + const Spacer(), + if (native != null) + TextButton( + onPressed: _toggleDemoServer, + child: Text(running ? '停止 demo 服务' : '启动 demo 服务'), + ), + ], + ), + if (_nativeError != null) + Text( + _nativeError!, + style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12), + ) + else if (native == null) + const Text('未加载 Rust Core 动态库(桌面端编译后自动可用)。') + else + Text( + '版本 ${native.versionString} · ABI ${native.abiRevision()} · ' + 'ECDH ${test?['ecdhMatch'] == true ? '一致' : '未验证'} · ' + '控制帧 ${test?['controlFrameBytes'] ?? '-'} B · ' + '媒体包 ${test?['mediaPacketBytes'] ?? '-'} B', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 8), + Text( + 'demo 服务:${running ? '运行中' : '已停止'} · ' + '被控端 ${connected ? '已连接' : '未连接'} · ' + '${keyEstablished ? '会话密钥已建立' : '等待 ECDH'} · ' + '密钥 ${status['controlKey'] ?? '----'}', + style: Theme.of(context).textTheme.bodySmall, + ), + if (events.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + events.take(5).join('\n'), + style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 11), + ), + ), + ], + ), + ), + ); + } + + Widget _buildStage() { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + VideoView( + textureId: null, + connected: _phase.isConnected, + resolution: _selected?.resolution ?? '1920x1080', + ), + const SizedBox(height: 16), + ConnectBar( + phase: _phase, + device: _selected, + onConnect: _connect, + onDisconnect: _disconnect, + ), + const SizedBox(height: 16), + ControlToolbar( + enabled: _phase.isConnected, + onEvent: _sendControl, + ), + const SizedBox(height: 12), + _buildNativeDemoCard(), + const SizedBox(height: 12), + Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text( + _settings.useLocalSignaling + ? 'mDNS 同网段优先;本机信令${_localSignalingRunning ? '运行中' : '未运行'} · $_effectiveSignalingUrl,探测失败自动降级到信令中转。' + : 'mDNS 同网段优先;外部信令 · $_effectiveSignalingUrl,探测失败自动降级到信令中转。', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ], + ), + ); + } +} diff --git a/flutter_sender/linux/.gitignore b/flutter_sender/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/flutter_sender/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/flutter_sender/linux/CMakeLists.txt b/flutter_sender/linux/CMakeLists.txt new file mode 100644 index 0000000..0d05d39 --- /dev/null +++ b/flutter_sender/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "ttstd_sender") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.ttstd.ttstd_sender") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the hook/build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/flutter_sender/linux/flutter/CMakeLists.txt b/flutter_sender/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/flutter_sender/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/flutter_sender/linux/flutter/generated_plugin_registrant.cc b/flutter_sender/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/flutter_sender/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/flutter_sender/linux/flutter/generated_plugin_registrant.h b/flutter_sender/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/flutter_sender/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/flutter_sender/linux/flutter/generated_plugins.cmake b/flutter_sender/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/flutter_sender/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/flutter_sender/linux/runner/CMakeLists.txt b/flutter_sender/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/flutter_sender/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/flutter_sender/linux/runner/main.cc b/flutter_sender/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/flutter_sender/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/flutter_sender/linux/runner/my_application.cc b/flutter_sender/linux/runner/my_application.cc new file mode 100644 index 0000000..04d4382 --- /dev/null +++ b/flutter_sender/linux/runner/my_application.cc @@ -0,0 +1,129 @@ +#include "my_application.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + gtk_window_set_default_size(window, 1280, 720); + + // If you want to use a header bar, uncomment the following lines. + // Header bars are commonly used in GNOME based desktop environments and + // allow additional widgets to be added to the title bar. + // See https://docs.gtk.org/gtk3/class.HeaderBar.html + // GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + // gtk_widget_show(GTK_WIDGET(header_bar)); + // gtk_header_bar_set_show_close_button(header_bar, TRUE); + // gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + + gtk_window_set_title(window, "ttstd_sender"); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/flutter_sender/linux/runner/my_application.h b/flutter_sender/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/flutter_sender/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/flutter_sender/macos/.gitignore b/flutter_sender/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/flutter_sender/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/flutter_sender/macos/Flutter/Flutter-Debug.xcconfig b/flutter_sender/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/flutter_sender/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/flutter_sender/macos/Flutter/Flutter-Release.xcconfig b/flutter_sender/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/flutter_sender/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift b/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..cccf817 --- /dev/null +++ b/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,10 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { +} diff --git a/flutter_sender/macos/Runner.xcodeproj/project.pbxproj b/flutter_sender/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..be3fa0f --- /dev/null +++ b/flutter_sender/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* ttstd_sender.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ttstd_sender.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* ttstd_sender.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* ttstd_sender.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.ttstdSender.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ttstd_sender.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/ttstd_sender"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.ttstdSender.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ttstd_sender.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/ttstd_sender"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.ttstdSender.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ttstd_sender.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/ttstd_sender"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/flutter_sender/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_sender/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/flutter_sender/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/flutter_sender/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/flutter_sender/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..7250e0f --- /dev/null +++ b/flutter_sender/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flutter_sender/macos/Runner.xcworkspace/contents.xcworkspacedata b/flutter_sender/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/flutter_sender/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/flutter_sender/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_sender/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/flutter_sender/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/flutter_sender/macos/Runner/AppDelegate.swift b/flutter_sender/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/flutter_sender/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/flutter_sender/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/flutter_sender/macos/Runner/Base.lproj/MainMenu.xib b/flutter_sender/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/flutter_sender/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/flutter_sender/macos/Runner/Configs/AppInfo.xcconfig b/flutter_sender/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..571740e --- /dev/null +++ b/flutter_sender/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = ttstd_sender + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.ttstdSender + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.ttstd. All rights reserved. diff --git a/flutter_sender/macos/Runner/Configs/Debug.xcconfig b/flutter_sender/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/flutter_sender/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/flutter_sender/macos/Runner/Configs/Release.xcconfig b/flutter_sender/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/flutter_sender/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/flutter_sender/macos/Runner/Configs/Warnings.xcconfig b/flutter_sender/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/flutter_sender/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/flutter_sender/macos/Runner/DebugProfile.entitlements b/flutter_sender/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/flutter_sender/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/flutter_sender/macos/Runner/Info.plist b/flutter_sender/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/flutter_sender/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/flutter_sender/macos/Runner/MainFlutterWindow.swift b/flutter_sender/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/flutter_sender/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/flutter_sender/macos/Runner/Release.entitlements b/flutter_sender/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/flutter_sender/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/flutter_sender/macos/RunnerTests/RunnerTests.swift b/flutter_sender/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..1600651 --- /dev/null +++ b/flutter_sender/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS +import Testing + +struct RunnerTests { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/xcode/swift-testing/ for more information about using + // Swift Testing. + } + +} diff --git a/flutter_sender/pubspec.lock b/flutter_sender/pubspec.lock new file mode 100644 index 0000000..7af3f23 --- /dev/null +++ b/flutter_sender/pubspec.lock @@ -0,0 +1,205 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.3" + ffi: + dependency: "direct main" + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.flutter-io.cn" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.9.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.14" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.flutter-io.cn" + source: hosted + version: "15.4.0" +sdks: + dart: ">=3.13.0-0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/flutter_sender/pubspec.yaml b/flutter_sender/pubspec.yaml new file mode 100644 index 0000000..bc042ec --- /dev/null +++ b/flutter_sender/pubspec.yaml @@ -0,0 +1,19 @@ +name: ttstd_sender +description: TTSTDConnect 跨平台主控端(Flutter UI + Rust Core 桥接) +publish_to: none +version: 0.1.0+1 + +environment: + sdk: '>=3.4.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + ffi: ^2.1.0 + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + uses-material-design: true diff --git a/flutter_sender/test/widget_test.dart b/flutter_sender/test/widget_test.dart new file mode 100644 index 0000000..7c713ba --- /dev/null +++ b/flutter_sender/test/widget_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_sender/core/bridge.dart'; +import 'package:ttstd_sender/main.dart'; + +const MethodChannel _methodChannel = MethodChannel('ttstd/sender'); +const EventChannel _eventChannel = EventChannel('ttstd/sender/events'); + +void _mockChannels() { + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(_methodChannel, (call) async { + switch (call.method) { + case 'discover': + return SenderBridge.mockDevices.map((device) => device.toJson()).toList(); + case 'pairingUri': + return 'lancast://pair?ip=192.168.1.10&port=41001&fp=sha256:ab12cd34ef567890'; + default: + return null; + } + }); + messenger.setMockStreamHandler( + _eventChannel, + MockStreamHandler.inline(onListen: (arguments, events) {}), + ); +} + +void main() { + tearDown(() { + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(_methodChannel, null); + messenger.setMockStreamHandler(_eventChannel, null); + }); + + testWidgets('首页展示设备列表与连接工具栏', (tester) async { + _mockChannels(); + await tester.pumpWidget(const TTSTDConnectApp()); + await tester.pumpAndSettle(); + + expect(find.text('TTSTD Connect'), findsOneWidget); + expect(find.text('客厅 Pixel'), findsOneWidget); + expect(find.text('可连接设备'), findsOneWidget); + expect(find.byIcon(Icons.play_arrow), findsOneWidget); + + await tester.tap(find.byIcon(Icons.refresh)); + await tester.pumpAndSettle(); + expect(find.text('可连接设备'), findsOneWidget); + }); + + testWidgets('扫码配对对话框展示 pairing URI', (tester) async { + _mockChannels(); + await tester.pumpWidget(const TTSTDConnectApp()); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.qr_code_scanner)); + await tester.pumpAndSettle(); + + expect(find.text('扫码配对'), findsOneWidget); + expect(find.textContaining('lancast://pair?'), findsOneWidget); + }); + + testWidgets('设置页可切换本机信令与外部信令', (tester) async { + _mockChannels(); + await tester.pumpWidget(const TTSTDConnectApp()); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.settings)); + await tester.pumpAndSettle(); + + expect(find.text('使用本机信令服务器'), findsOneWidget); + expect(find.text('开启本机信令服务'), findsOneWidget); + expect(find.textContaining('本机地址:http://'), findsOneWidget); + + await tester.tap(find.text('使用本机信令服务器')); + await tester.pumpAndSettle(); + + expect(find.text('外部信令服务器'), findsOneWidget); + }); +} diff --git a/flutter_sender/windows/.gitignore b/flutter_sender/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/flutter_sender/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/flutter_sender/windows/CMakeLists.txt b/flutter_sender/windows/CMakeLists.txt new file mode 100644 index 0000000..2688db8 --- /dev/null +++ b/flutter_sender/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(ttstd_sender LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "ttstd_sender") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd4100) + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the hook/build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/flutter_sender/windows/flutter/CMakeLists.txt b/flutter_sender/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/flutter_sender/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/flutter_sender/windows/flutter/generated_plugin_registrant.cc b/flutter_sender/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/flutter_sender/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/flutter_sender/windows/flutter/generated_plugin_registrant.h b/flutter_sender/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/flutter_sender/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/flutter_sender/windows/flutter/generated_plugins.cmake b/flutter_sender/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/flutter_sender/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/flutter_sender/windows/runner/CMakeLists.txt b/flutter_sender/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/flutter_sender/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# 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}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +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) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.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) diff --git a/flutter_sender/windows/runner/Runner.rc b/flutter_sender/windows/runner/Runner.rc new file mode 100644 index 0000000..edf00b6 --- /dev/null +++ b/flutter_sender/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.ttstd" "\0" + VALUE "FileDescription", "ttstd_sender" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "ttstd_sender" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.ttstd. All rights reserved." "\0" + VALUE "OriginalFilename", "ttstd_sender.exe" "\0" + VALUE "ProductName", "ttstd_sender" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/flutter_sender/windows/runner/flutter_window.cpp b/flutter_sender/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/flutter_sender/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/flutter_sender/windows/runner/flutter_window.h b/flutter_sender/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/flutter_sender/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/flutter_sender/windows/runner/main.cpp b/flutter_sender/windows/runner/main.cpp new file mode 100644 index 0000000..c50ad15 --- /dev/null +++ b/flutter_sender/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"ttstd_sender", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/flutter_sender/windows/runner/resource.h b/flutter_sender/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/flutter_sender/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/flutter_sender/windows/runner/resources/app_icon.ico b/flutter_sender/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/flutter_sender/windows/runner/resources/app_icon.ico differ diff --git a/flutter_sender/windows/runner/runner.exe.manifest b/flutter_sender/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/flutter_sender/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/flutter_sender/windows/runner/utils.cpp b/flutter_sender/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/flutter_sender/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/flutter_sender/windows/runner/utils.h b/flutter_sender/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/flutter_sender/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/flutter_sender/windows/runner/win32_window.cpp b/flutter_sender/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/flutter_sender/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/flutter_sender/windows/runner/win32_window.h b/flutter_sender/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/flutter_sender/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/installer/package.sh b/installer/package.sh new file mode 100644 index 0000000..2ea89e9 --- /dev/null +++ b/installer/package.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +FLUTTER_DIR="$ROOT/flutter_sender" +SIGNAL_DIR="$ROOT/signaling_server" +PLATFORM="$(uname -s)" + +case "$PLATFORM" in + Darwin) + DIST="$ROOT/dist/TTSTDConnect-macOS" + mkdir -p "$DIST" + echo "构建 Flutter macOS 应用..." + (cd "$FLUTTER_DIR" && flutter build macos --release) + APP_SOURCE="$FLUTTER_DIR/build/macos/Build/Products/Release/ttstd_sender.app" + cp -R "$APP_SOURCE" "$DIST/" + echo "构建内置信令服务..." + (cd "$SIGNAL_DIR" && go build -o "$DIST/ttstd_sender.app/Contents/MacOS/signaling_server" .) + ;; + Linux) + DIST="$ROOT/dist/TTSTDConnect-Linux" + mkdir -p "$DIST" + echo "构建 Flutter Linux 应用..." + (cd "$FLUTTER_DIR" && flutter build linux --release) + cp -R "$FLUTTER_DIR/build/linux/x64/release/bundle/." "$DIST/" + echo "构建内置信令服务..." + (cd "$SIGNAL_DIR" && go build -o "$DIST/signaling_server" .) + ;; + *) + echo "不支持的平台:$PLATFORM,请使用 installer/windows/package.ps1" >&2 + exit 1 + ;; +esac + +echo "打包完成:$DIST" +echo "安装包默认使用本机信令服务器,端口 8080;可在设置页关闭或切换为外部服务器。" diff --git a/installer/windows/package.ps1 b/installer/windows/package.ps1 new file mode 100644 index 0000000..88f4852 --- /dev/null +++ b/installer/windows/package.ps1 @@ -0,0 +1,40 @@ +$ErrorActionPreference = "Stop" + +$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +$flutterDir = Join-Path $root "flutter_sender" +$signalDir = Join-Path $root "signaling_server" +$rustDir = Join-Path $root "rust_core" +$dist = Join-Path $root "dist\TTSTDConnect-Windows" + +foreach ($required in @($flutterDir, $signalDir, $rustDir)) { + if (-not (Test-Path $required)) { + throw "Missing project directory: $required" + } +} + +Write-Host "Building Flutter Windows app..." +Push-Location $flutterDir +flutter build windows --release +Pop-Location + +New-Item -ItemType Directory -Force -Path $dist | Out-Null +$flutterOutput = Join-Path $flutterDir "build\windows\x64\runner\Release" +Copy-Item -Recurse -Force (Join-Path $flutterOutput "*") $dist + +Write-Host "Building embedded signaling server..." +Push-Location $signalDir +go build -o (Join-Path $dist "signaling_server.exe") . +Pop-Location + +Write-Host "Building Rust Core cdylib..." +Push-Location $rustDir +cargo build --release +Pop-Location +$coreDll = Join-Path $rustDir "target\release\ttstdconnect_core.dll" +if (-not (Test-Path $coreDll)) { + throw "Rust Core dynamic library not found: $coreDll" +} +Copy-Item -Force $coreDll (Join-Path $dist "ttstdconnect_core.dll") + +Write-Host "Package ready: $dist" +Write-Host "Default mode: local signaling on port 8080. Use Settings to disable it or switch to an external server." diff --git a/rust_core/Cargo.lock b/rust_core/Cargo.lock new file mode 100644 index 0000000..eae9f31 --- /dev/null +++ b/rust_core/Cargo.lock @@ -0,0 +1,340 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "if-addrs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "mdns-sd" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aaf7ecb589a3bb5e9642c3e5f79e1e54a8ea8c1c48bc9975c39d77fa640764c" +dependencies = [ + "fastrand", + "flume", + "if-addrs", + "log", + "mio", + "socket-pktinfo", + "socket2", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "socket-pktinfo" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512f5c35377cf69f350b106df2366c3a1df6bd01b047a7a58c8390b70d28838d" +dependencies = [ + "libc", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "ttstdconnect_core" +version = "0.1.0" +dependencies = [ + "mdns-sd", + "ring", + "rustls", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" diff --git a/rust_core/Cargo.toml b/rust_core/Cargo.toml new file mode 100644 index 0000000..33601b4 --- /dev/null +++ b/rust_core/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ttstdconnect_core" +version = "0.1.0" +edition = "2021" +description = "TTSTDConnect 核心协议层:控制帧、发现、会话、媒体、文件与连接状态机" + +[lib] +name = "ttstdconnect_core" +path = "src/lib.rs" +crate-type = ["rlib", "cdylib"] + +[dependencies] +ring = "0.17" +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +mdns-sd = "0.22" + +[dev-dependencies] diff --git a/rust_core/src/connection/mod.rs b/rust_core/src/connection/mod.rs new file mode 100644 index 0000000..693be1a --- /dev/null +++ b/rust_core/src/connection/mod.rs @@ -0,0 +1,3 @@ +pub mod state; + +pub use state::{ConnectionEvent, ConnectionPhase, ConnectionSnapshot, ConnectionStateMachine, StateError}; diff --git a/rust_core/src/connection/state.rs b/rust_core/src/connection/state.rs new file mode 100644 index 0000000..7d51bfd --- /dev/null +++ b/rust_core/src/connection/state.rs @@ -0,0 +1,194 @@ +use std::fmt; + +use crate::discovery::DeviceInfo; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConnectionPhase { + Idle, + Discovering, + Registering, + Probing, + Direct, + Relaying, + Failed, +} + +impl ConnectionPhase { + pub fn as_str(self) -> &'static str { + match self { + Self::Idle => "idle", + Self::Discovering => "discovering", + Self::Registering => "registering", + Self::Probing => "probing", + Self::Direct => "direct", + Self::Relaying => "relaying", + Self::Failed => "failed", + } + } +} + +#[derive(Debug, Clone)] +pub enum ConnectionEvent { + Start, + Cancel, + MdnsFound(DeviceInfo), + MdnsTimeout, + SignalingConfigured(bool), + SignalingDevices(Vec), + ProbeOk, + ProbeFailed, + RelayOk, + RelayFailed, + DirectUpgraded, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConnectionSnapshot { + pub phase: ConnectionPhase, + pub device_id: Option, + pub reason: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StateError { + pub from: ConnectionPhase, + pub event: &'static str, +} + +impl fmt::Display for StateError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "状态 {} 不接受事件 {}", self.from.as_str(), self.event) + } +} + +impl std::error::Error for StateError {} + +#[derive(Debug, Clone)] +pub struct ConnectionStateMachine { + phase: ConnectionPhase, + device: Option, + reason: Option, +} + +impl Default for ConnectionStateMachine { + fn default() -> Self { + Self::new() + } +} + +impl ConnectionStateMachine { + pub fn new() -> Self { + Self { + phase: ConnectionPhase::Idle, + device: None, + reason: None, + } + } + + pub fn phase(&self) -> ConnectionPhase { + self.phase + } + + pub fn device(&self) -> Option<&DeviceInfo> { + self.device.as_ref() + } + + pub fn snapshot(&self) -> ConnectionSnapshot { + ConnectionSnapshot { + phase: self.phase, + device_id: self.device.as_ref().map(|device| device.device_id.clone()), + reason: self.reason.clone(), + } + } + + pub fn apply(&mut self, event: ConnectionEvent) -> Result { + use ConnectionEvent as E; + use ConnectionPhase as P; + + match (self.phase, event) { + (P::Idle, E::Start) => { + self.reason = None; + self.device = None; + self.phase = P::Discovering; + } + (_, E::Cancel) => { + self.phase = P::Idle; + self.reason = None; + } + (P::Discovering, E::MdnsFound(device)) => { + self.device = Some(device); + self.reason = None; + self.phase = P::Probing; + } + (P::Discovering, E::MdnsTimeout) => { + self.phase = P::Registering; + } + (P::Registering, E::SignalingConfigured(false)) => { + self.reason = Some("未配置信令服务器".to_string()); + self.phase = P::Failed; + } + (P::Registering, E::SignalingConfigured(true)) => {} + (P::Registering, E::SignalingDevices(devices)) => match devices.into_iter().next() { + Some(device) => { + self.device = Some(device); + self.reason = None; + self.phase = P::Probing; + } + None => { + self.reason = Some("信令服务器未返回在线设备".to_string()); + self.phase = P::Failed; + } + }, + (P::Probing, E::ProbeOk) => { + self.reason = None; + self.phase = P::Direct; + } + (P::Probing, E::ProbeFailed) => { + self.reason = Some("直连探测超时,切换到信令中转".to_string()); + self.phase = P::Relaying; + } + (P::Relaying, E::RelayOk) => { + self.reason = None; + } + (P::Relaying, E::DirectUpgraded) => { + self.phase = P::Direct; + } + (P::Direct, E::ProbeFailed) => { + self.reason = Some("直连中断,切换到信令中转".to_string()); + self.phase = P::Relaying; + } + (P::Relaying | P::Failed, E::RelayFailed) => { + self.reason = Some("信令中转失败".to_string()); + self.phase = P::Failed; + } + (P::Failed, E::Start) => { + self.reason = None; + self.device = None; + self.phase = P::Discovering; + } + (from, event) => { + return Err(StateError { + from, + event: event_name(&event), + }) + } + } + Ok(self.phase) + } +} + +fn event_name(event: &ConnectionEvent) -> &'static str { + match event { + ConnectionEvent::Start => "Start", + ConnectionEvent::Cancel => "Cancel", + ConnectionEvent::MdnsFound(_) => "MdnsFound", + ConnectionEvent::MdnsTimeout => "MdnsTimeout", + ConnectionEvent::SignalingConfigured(_) => "SignalingConfigured", + ConnectionEvent::SignalingDevices(_) => "SignalingDevices", + ConnectionEvent::ProbeOk => "ProbeOk", + ConnectionEvent::ProbeFailed => "ProbeFailed", + ConnectionEvent::RelayOk => "RelayOk", + ConnectionEvent::RelayFailed => "RelayFailed", + ConnectionEvent::DirectUpgraded => "DirectUpgraded", + } +} diff --git a/rust_core/src/control/binary.rs b/rust_core/src/control/binary.rs new file mode 100644 index 0000000..cb798d2 --- /dev/null +++ b/rust_core/src/control/binary.rs @@ -0,0 +1,225 @@ +use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader}; +use super::events::{ + ClipboardEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent, MouseAction, + MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_KEY, MSG_MOUSE, MSG_PING, + MSG_PONG, MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION, +}; + +#[derive(Debug, Default, Clone, Copy)] +pub struct BinaryCodec; + +impl ControlFrameCodec for BinaryCodec { + fn encode(&self, event: &ControlEvent) -> Vec { + let mut buffer = Vec::with_capacity(8 + 64); + let header = ControlFrameHeader { + version: PROTOCOL_VERSION, + msg_type: event.msg_type(), + sequence: event.sequence(), + payload_len: 0, + }; + header.write(&mut buffer); + + match &event.kind { + ControlEventKind::Touch(payload) => { + buffer.push(payload.action.as_u8()); + buffer.push(payload.pointer_id); + buffer.extend_from_slice(&payload.x.to_le_bytes()); + buffer.extend_from_slice(&payload.y.to_le_bytes()); + buffer.extend_from_slice(&payload.pressure.to_le_bytes()); + } + ControlEventKind::Mouse(payload) => { + buffer.push(payload.action.as_u8()); + buffer.extend_from_slice(&payload.x.to_le_bytes()); + buffer.extend_from_slice(&payload.y.to_le_bytes()); + buffer.push(payload.buttons); + } + ControlEventKind::Key(payload) => { + buffer.push(payload.action.as_u8()); + buffer.extend_from_slice(&payload.keycode.to_le_bytes()); + buffer.extend_from_slice(&payload.modifiers.to_le_bytes()); + } + ControlEventKind::Wheel(payload) => { + buffer.extend_from_slice(&payload.delta_x.to_le_bytes()); + buffer.extend_from_slice(&payload.delta_y.to_le_bytes()); + buffer.push(payload.buttons); + } + ControlEventKind::Clipboard(payload) => { + let bytes = payload.text.as_bytes(); + buffer.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); + buffer.extend_from_slice(bytes); + } + ControlEventKind::Ping(timestamp) | ControlEventKind::Pong(timestamp) => { + buffer.extend_from_slice(×tamp.to_le_bytes()); + } + } + + let payload_len = (buffer.len() - ControlFrameHeader::LEN) as u32; + buffer[4..8].copy_from_slice(&payload_len.to_le_bytes()); + buffer + } + + fn decode(&self, buffer: &[u8]) -> Result, CodecError> { + if buffer.len() < ControlFrameHeader::LEN { + return Ok(None); + } + let header = ControlFrameHeader::parse(buffer)?; + let total = ControlFrameHeader::LEN + header.payload_len as usize; + if buffer.len() < total { + return Ok(None); + } + let payload = &buffer[ControlFrameHeader::LEN..total]; + let kind = decode_payload(header.msg_type, payload)?; + Ok(Some((ControlEvent::new(header.sequence, kind), total))) + } +} + +fn decode_payload(msg_type: u8, payload: &[u8]) -> Result { + match msg_type { + MSG_TOUCH => { + if payload.len() != TouchEvent::PAYLOAD_LEN { + return Err(CodecError::InvalidPayload("触摸负载长度必须为 8")); + } + let action = TouchAction::from_u8(payload[0]) + .ok_or(CodecError::InvalidPayload("未知触摸动作"))?; + Ok(ControlEventKind::Touch(TouchEvent { + action, + pointer_id: payload[1], + x: i16::from_le_bytes([payload[2], payload[3]]), + y: i16::from_le_bytes([payload[4], payload[5]]), + pressure: u16::from_le_bytes([payload[6], payload[7]]), + })) + } + MSG_MOUSE => { + if payload.len() != MouseEvent::PAYLOAD_LEN { + return Err(CodecError::InvalidPayload("鼠标负载长度必须为 6")); + } + let action = MouseAction::from_u8(payload[0]) + .ok_or(CodecError::InvalidPayload("未知鼠标动作"))?; + Ok(ControlEventKind::Mouse(MouseEvent { + action, + x: i16::from_le_bytes([payload[1], payload[2]]), + y: i16::from_le_bytes([payload[3], payload[4]]), + buttons: payload[5], + })) + } + MSG_KEY => { + if payload.len() != KeyboardEvent::PAYLOAD_LEN { + return Err(CodecError::InvalidPayload("键盘负载长度必须为 5")); + } + let action = + KeyAction::from_u8(payload[0]).ok_or(CodecError::InvalidPayload("未知按键动作"))?; + Ok(ControlEventKind::Key(KeyboardEvent { + action, + keycode: u16::from_le_bytes([payload[1], payload[2]]), + modifiers: u16::from_le_bytes([payload[3], payload[4]]), + })) + } + MSG_WHEEL => { + if payload.len() != WheelEvent::PAYLOAD_LEN { + return Err(CodecError::InvalidPayload("滚轮负载长度必须为 5")); + } + Ok(ControlEventKind::Wheel(WheelEvent { + delta_x: i16::from_le_bytes([payload[0], payload[1]]), + delta_y: i16::from_le_bytes([payload[2], payload[3]]), + buttons: payload[4], + })) + } + MSG_CLIPBOARD => { + if payload.len() < 4 { + return Err(CodecError::InvalidPayload("剪贴板负载缺少长度字段")); + } + let declared = u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize; + if payload.len() != 4 + declared { + return Err(CodecError::InvalidPayload("剪贴板长度与负载不一致")); + } + let text = String::from_utf8(payload[4..].to_vec()).map_err(|_| CodecError::InvalidUtf8)?; + Ok(ControlEventKind::Clipboard(ClipboardEvent { text })) + } + MSG_PING | MSG_PONG => { + if payload.len() != 8 { + return Err(CodecError::InvalidPayload("时间戳负载长度必须为 8")); + } + let timestamp = u64::from_le_bytes([ + payload[0], payload[1], payload[2], payload[3], payload[4], payload[5], payload[6], + payload[7], + ]); + if msg_type == MSG_PING { + Ok(ControlEventKind::Ping(timestamp)) + } else { + Ok(ControlEventKind::Pong(timestamp)) + } + } + other => Err(CodecError::UnknownMsgType(other)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn assert_roundtrip(kind: ControlEventKind) { + let codec = BinaryCodec; + let event = ControlEvent::new(0x1234, kind); + let bytes = codec.encode(&event); + assert_eq!(bytes[0], PROTOCOL_VERSION); + assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]), 0x1234); + let (decoded, consumed) = codec.decode(&bytes).unwrap().expect("完整帧可解码"); + assert_eq!(consumed, bytes.len()); + assert_eq!(decoded, event); + } + + #[test] + fn all_event_roundtrip() { + assert_roundtrip(ControlEventKind::Touch(TouchEvent { + action: TouchAction::Move, + pointer_id: 3, + x: -120, + y: 480, + pressure: 512, + })); + assert_roundtrip(ControlEventKind::Mouse(MouseEvent { + action: MouseAction::Down, + x: 640, + y: 360, + buttons: 1, + })); + assert_roundtrip(ControlEventKind::Key(KeyboardEvent { + action: KeyAction::Up, + keycode: 66, + modifiers: 1, + })); + assert_roundtrip(ControlEventKind::Wheel(WheelEvent { + delta_x: 0, + delta_y: -3, + buttons: 0, + })); + assert_roundtrip(ControlEventKind::Clipboard(ClipboardEvent { + text: "你好 lancast".to_string(), + })); + assert_roundtrip(ControlEventKind::Ping(1_700_000_000_000)); + assert_roundtrip(ControlEventKind::Pong(1_700_000_000_001)); + } + + #[test] + fn incomplete_frame_waits_for_more_bytes() { + let codec = BinaryCodec; + let event = ControlEvent::new(1, ControlEventKind::Ping(7)); + let bytes = codec.encode(&event); + assert_eq!(codec.decode(&bytes[..bytes.len() - 1]).unwrap(), None); + } + + #[test] + fn rejects_unknown_message_type() { + let codec = BinaryCodec; + let mut bytes = vec![PROTOCOL_VERSION, 99, 0, 0, 0, 0, 0, 0]; + assert!(matches!( + codec.decode(&bytes), + Err(CodecError::UnknownMsgType(99)) + )); + bytes[0] = 2; + assert!(matches!( + codec.decode(&bytes), + Err(CodecError::UnsupportedVersion(2)) + )); + } +} diff --git a/rust_core/src/control/codec.rs b/rust_core/src/control/codec.rs new file mode 100644 index 0000000..28a9e5f --- /dev/null +++ b/rust_core/src/control/codec.rs @@ -0,0 +1,70 @@ +use std::fmt; + +use super::events::PROTOCOL_VERSION; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ControlFrameHeader { + pub version: u8, + pub msg_type: u8, + pub sequence: u16, + pub payload_len: u32, +} + +impl ControlFrameHeader { + pub const LEN: usize = 8; + + pub fn parse(buffer: &[u8]) -> Result { + if buffer.len() < Self::LEN { + return Err(CodecError::InvalidHeader("头部不足 8 字节")); + } + let version = buffer[0]; + if version != PROTOCOL_VERSION { + return Err(CodecError::UnsupportedVersion(version)); + } + Ok(Self { + version, + msg_type: buffer[1], + sequence: u16::from_le_bytes([buffer[2], buffer[3]]), + payload_len: u32::from_le_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]), + }) + } + + pub fn write(&self, output: &mut Vec) { + output.push(self.version); + output.push(self.msg_type); + output.extend_from_slice(&self.sequence.to_le_bytes()); + output.extend_from_slice(&self.payload_len.to_le_bytes()); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CodecError { + InvalidHeader(&'static str), + UnsupportedVersion(u8), + UnknownMsgType(u8), + InvalidPayload(&'static str), + InvalidUtf8, +} + +impl fmt::Display for CodecError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidHeader(reason) => write!(formatter, "控制帧头无效:{}", reason), + Self::UnsupportedVersion(version) => write!(formatter, "不支持的协议版本:{}", version), + Self::UnknownMsgType(msg_type) => write!(formatter, "未知消息类型:{}", msg_type), + Self::InvalidPayload(reason) => write!(formatter, "负载无效:{}", reason), + Self::InvalidUtf8 => write!(formatter, "剪贴板内容不是合法 UTF-8"), + } + } +} + +impl std::error::Error for CodecError {} + +pub trait ControlFrameCodec: Send + Sync { + fn encode(&self, event: &super::ControlEvent) -> Vec; + + fn decode<'a>( + &self, + buffer: &'a [u8], + ) -> Result, CodecError>; +} diff --git a/rust_core/src/control/events.rs b/rust_core/src/control/events.rs new file mode 100644 index 0000000..ebdd0bc --- /dev/null +++ b/rust_core/src/control/events.rs @@ -0,0 +1,178 @@ +pub const PROTOCOL_VERSION: u8 = 1; + +pub const MSG_TOUCH: u8 = 0; +pub const MSG_MOUSE: u8 = 1; +pub const MSG_KEY: u8 = 2; +pub const MSG_WHEEL: u8 = 3; +pub const MSG_CLIPBOARD: u8 = 4; +pub const MSG_PING: u8 = 5; +pub const MSG_PONG: u8 = 6; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TouchAction { + Down, + Up, + Move, + Cancel, +} + +impl TouchAction { + pub fn from_u8(value: u8) -> Option { + match value { + 0 => Some(Self::Down), + 1 => Some(Self::Up), + 2 => Some(Self::Move), + 3 => Some(Self::Cancel), + _ => None, + } + } + + pub fn as_u8(self) -> u8 { + match self { + Self::Down => 0, + Self::Up => 1, + Self::Move => 2, + Self::Cancel => 3, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MouseAction { + Down, + Up, + Move, +} + +impl MouseAction { + pub fn from_u8(value: u8) -> Option { + match value { + 0 => Some(Self::Down), + 1 => Some(Self::Up), + 2 => Some(Self::Move), + _ => None, + } + } + + pub fn as_u8(self) -> u8 { + match self { + Self::Down => 0, + Self::Up => 1, + Self::Move => 2, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KeyAction { + Down, + Up, +} + +impl KeyAction { + pub fn from_u8(value: u8) -> Option { + match value { + 0 => Some(Self::Down), + 1 => Some(Self::Up), + _ => None, + } + } + + pub fn as_u8(self) -> u8 { + match self { + Self::Down => 0, + Self::Up => 1, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TouchEvent { + pub action: TouchAction, + pub pointer_id: u8, + pub x: i16, + pub y: i16, + pub pressure: u16, +} + +impl TouchEvent { + pub const PAYLOAD_LEN: usize = 8; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MouseEvent { + pub action: MouseAction, + pub x: i16, + pub y: i16, + pub buttons: u8, +} + +impl MouseEvent { + pub const PAYLOAD_LEN: usize = 6; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KeyboardEvent { + pub action: KeyAction, + pub keycode: u16, + pub modifiers: u16, +} + +impl KeyboardEvent { + pub const PAYLOAD_LEN: usize = 5; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WheelEvent { + pub delta_x: i16, + pub delta_y: i16, + pub buttons: u8, +} + +impl WheelEvent { + pub const PAYLOAD_LEN: usize = 5; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClipboardEvent { + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ControlEventKind { + Touch(TouchEvent), + Mouse(MouseEvent), + Key(KeyboardEvent), + Wheel(WheelEvent), + Clipboard(ClipboardEvent), + Ping(u64), + Pong(u64), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ControlEvent { + pub sequence: u16, + pub kind: ControlEventKind, +} + +impl ControlEvent { + pub fn new(sequence: u16, kind: ControlEventKind) -> Self { + Self { sequence, kind } + } + + pub fn sequence(&self) -> u16 { + self.sequence + } + + pub fn msg_type(&self) -> u8 { + match self.kind { + ControlEventKind::Touch(_) => MSG_TOUCH, + ControlEventKind::Mouse(_) => MSG_MOUSE, + ControlEventKind::Key(_) => MSG_KEY, + ControlEventKind::Wheel(_) => MSG_WHEEL, + ControlEventKind::Clipboard(_) => MSG_CLIPBOARD, + ControlEventKind::Ping(_) => MSG_PING, + ControlEventKind::Pong(_) => MSG_PONG, + } + } +} diff --git a/rust_core/src/control/mod.rs b/rust_core/src/control/mod.rs new file mode 100644 index 0000000..44c78ba --- /dev/null +++ b/rust_core/src/control/mod.rs @@ -0,0 +1,12 @@ +pub mod binary; +pub mod codec; +pub mod events; +pub mod secure; + +pub use binary::BinaryCodec; +pub use codec::{CodecError, ControlFrameCodec, ControlFrameHeader}; +pub use secure::{SecureCodecError, SecureControlChannel}; +pub use events::{ + ClipboardEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent, MouseAction, + MouseEvent, TouchAction, TouchEvent, WheelEvent, PROTOCOL_VERSION, +}; diff --git a/rust_core/src/control/secure.rs b/rust_core/src/control/secure.rs new file mode 100644 index 0000000..8e04015 --- /dev/null +++ b/rust_core/src/control/secure.rs @@ -0,0 +1,136 @@ +use std::fmt; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::crypto::{decrypt, encrypt, CryptoError, NONCE_LEN, TAG_LEN}; + +use super::binary::BinaryCodec; +use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader}; +use super::events::ControlEvent; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SecureCodecError { + Codec(CodecError), + Crypto(CryptoError), +} + +impl fmt::Display for SecureCodecError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Codec(error) => write!(formatter, "控制帧解析失败:{}", error), + Self::Crypto(error) => write!(formatter, "控制帧解密失败:{}", error), + } + } +} + +impl std::error::Error for SecureCodecError {} + +impl From for SecureCodecError { + fn from(error: CodecError) -> Self { + Self::Codec(error) + } +} + +impl From for SecureCodecError { + fn from(error: CryptoError) -> Self { + Self::Crypto(error) + } +} + +pub struct SecureControlChannel { + key: [u8; 32], + counter: AtomicU64, + codec: BinaryCodec, +} + +impl SecureControlChannel { + pub fn new(key: [u8; 32]) -> Self { + Self { + key, + counter: AtomicU64::new(1), + codec: BinaryCodec, + } + } + + pub fn encode(&self, event: &ControlEvent) -> Result, SecureCodecError> { + let frame = self.codec.encode(event); + let header = frame[..ControlFrameHeader::LEN].to_vec(); + let payload = &frame[ControlFrameHeader::LEN..]; + let nonce = self.next_nonce(); + let ciphertext = encrypt(&self.key, &nonce, payload, &header)?; + + let mut output = header; + output.extend_from_slice(&nonce); + output.extend_from_slice(&ciphertext); + Ok(output) + } + + pub fn decode( + &self, + buffer: &[u8], + ) -> Result, SecureCodecError> { + let minimum = ControlFrameHeader::LEN + NONCE_LEN + TAG_LEN; + if buffer.len() < minimum { + return Ok(None); + } + let header = ControlFrameHeader::parse(&buffer[..ControlFrameHeader::LEN])?; + let ciphertext_len = header.payload_len as usize + TAG_LEN; + let total = ControlFrameHeader::LEN + NONCE_LEN + ciphertext_len; + if buffer.len() < total { + return Ok(None); + } + + let nonce_slice = &buffer[ControlFrameHeader::LEN..ControlFrameHeader::LEN + NONCE_LEN]; + let mut nonce = [0u8; NONCE_LEN]; + nonce.copy_from_slice(nonce_slice); + let plaintext = decrypt( + &self.key, + &nonce, + &buffer[ControlFrameHeader::LEN + NONCE_LEN..total], + &buffer[..ControlFrameHeader::LEN], + )?; + + let mut frame = buffer[..ControlFrameHeader::LEN].to_vec(); + frame.extend_from_slice(&plaintext); + let (event, consumed) = self + .codec + .decode(&frame)? + .expect("重建后的控制帧必然完整"); + debug_assert_eq!(consumed, frame.len()); + Ok(Some((event, total))) + } + + fn next_nonce(&self) -> [u8; NONCE_LEN] { + let mut nonce = [0u8; NONCE_LEN]; + nonce[..4].copy_from_slice(b"ctl-"); + nonce[4..].copy_from_slice( + &self + .counter + .fetch_add(1, Ordering::Relaxed) + .to_le_bytes(), + ); + nonce + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::control::events::ControlEventKind; + + #[test] + fn encrypted_control_frame_roundtrip() { + let channel = SecureControlChannel::new([9u8; 32]); + let event = ControlEvent::new(7, ControlEventKind::Ping(1234)); + let first = channel.encode(&event).unwrap(); + let second = channel.encode(&event).unwrap(); + assert_ne!(first, second); + + let (decoded, consumed) = channel.decode(&first).unwrap().expect("完整密文帧"); + assert_eq!(decoded, event); + assert_eq!(consumed, first.len()); + assert_eq!( + channel.decode(&first[..first.len() - 1]).unwrap(), + None + ); + } +} diff --git a/rust_core/src/crypto/aead.rs b/rust_core/src/crypto/aead.rs new file mode 100644 index 0000000..c7c1000 --- /dev/null +++ b/rust_core/src/crypto/aead.rs @@ -0,0 +1,62 @@ +use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM}; + +use super::CryptoError; + +pub const NONCE_LEN: usize = 12; +pub const TAG_LEN: usize = 16; + +pub fn encrypt( + key: &[u8; 32], + nonce: &[u8; NONCE_LEN], + plaintext: &[u8], + aad: &[u8], +) -> Result, CryptoError> { + let algorithm = UnboundKey::new(&AES_256_GCM, key) + .map_err(|_| CryptoError::InvalidKeyLength)?; + let key = LessSafeKey::new(algorithm); + let nonce = Nonce::try_assume_unique_for_key(nonce) + .map_err(|_| CryptoError::InvalidNonce)?; + let mut buffer = plaintext.to_vec(); + key.seal_in_place_append_tag(nonce, Aad::from(aad), &mut buffer) + .map_err(|_| CryptoError::EncryptionFailed)?; + Ok(buffer) +} + +pub fn decrypt( + key: &[u8; 32], + nonce: &[u8; NONCE_LEN], + ciphertext_with_tag: &[u8], + aad: &[u8], +) -> Result, CryptoError> { + if ciphertext_with_tag.len() < TAG_LEN { + return Err(CryptoError::DecryptionFailed); + } + let algorithm = UnboundKey::new(&AES_256_GCM, key) + .map_err(|_| CryptoError::InvalidKeyLength)?; + let key = LessSafeKey::new(algorithm); + let nonce = Nonce::try_assume_unique_for_key(nonce) + .map_err(|_| CryptoError::InvalidNonce)?; + let mut buffer = ciphertext_with_tag.to_vec(); + let plaintext = key + .open_in_place(nonce, Aad::from(aad), &mut buffer) + .map_err(|_| CryptoError::DecryptionFailed)?; + Ok(plaintext.to_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aes_gcm_roundtrip() { + let key = [42u8; 32]; + let nonce = [1u8; NONCE_LEN]; + let cipher = encrypt(&key, &nonce, b"hello lancast", b"header").unwrap(); + assert_ne!(cipher, b"hello lancast".to_vec()); + assert_eq!( + decrypt(&key, &nonce, &cipher, b"header").unwrap(), + b"hello lancast".to_vec() + ); + assert!(decrypt(&key, &nonce, &cipher, b"other").is_err()); + } +} diff --git a/rust_core/src/crypto/ecdh.rs b/rust_core/src/crypto/ecdh.rs new file mode 100644 index 0000000..d8049e5 --- /dev/null +++ b/rust_core/src/crypto/ecdh.rs @@ -0,0 +1,90 @@ +use ring::agreement::{agree_ephemeral, EphemeralPrivateKey, UnparsedPublicKey, ECDH_P256}; +use ring::rand::{SecureRandom, SystemRandom}; + +use super::CryptoError; + +pub struct EphemeralKeyPair { + private: EphemeralPrivateKey, + public: Vec, +} + +impl EphemeralKeyPair { + pub fn generate() -> Result { + let rng = SystemRandom::new(); + let private = EphemeralPrivateKey::generate(&ECDH_P256, &rng) + .map_err(|_| CryptoError::KeyGenerationFailed)?; + let public = private + .compute_public_key() + .map_err(|_| CryptoError::KeyGenerationFailed)? + .as_ref() + .to_vec(); + Ok(Self { private, public }) + } + + pub fn public_bytes(&self) -> &[u8] { + &self.public + } + + pub fn into_shared_secret(self, peer_public: &[u8]) -> Result<[u8; 32], CryptoError> { + let peer = UnparsedPublicKey::new(&ECDH_P256, peer_public); + match agree_ephemeral(self.private, &peer, |secret| { + if secret.len() < 32 { + return Err(ring::error::Unspecified); + } + let mut output = [0u8; 32]; + output.copy_from_slice(&secret[..32]); + Ok(output) + }) { + Ok(secret) => secret.map_err(|_| CryptoError::KeyAgreementFailed), + Err(_) => Err(CryptoError::KeyAgreementFailed), + } + } +} + +pub fn random_bytes(len: usize) -> Result, CryptoError> { + let mut bytes = vec![0u8; len]; + SystemRandom::new() + .fill(&mut bytes) + .map_err(|_| CryptoError::KeyGenerationFailed)?; + Ok(bytes) +} + +pub fn derive_subkey(secret: &[u8], label: &[u8]) -> Result<[u8; 32], CryptoError> { + use ring::hkdf; + + let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, b"ttstdconnect-v1"); + let prk = salt.extract(secret); + let info = [label]; + let okm = prk + .expand(&info, hkdf::HKDF_SHA256) + .map_err(|_| CryptoError::KeyDerivationFailed)?; + let mut output = [0u8; 32]; + okm.fill(&mut output) + .map_err(|_| CryptoError::KeyDerivationFailed)?; + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ecdh_shared_secret_matches() { + let alice = EphemeralKeyPair::generate().unwrap(); + let bob = EphemeralKeyPair::generate().unwrap(); + let alice_public = alice.public_bytes().to_vec(); + let bob_public = bob.public_bytes().to_vec(); + + let alice_secret = alice.into_shared_secret(&bob_public).unwrap(); + let bob_secret = bob.into_shared_secret(&alice_public).unwrap(); + assert_eq!(alice_secret, bob_secret); + assert_ne!(alice_secret, [0u8; 32]); + } + + #[test] + fn hkdf_labels_differ() { + let control = derive_subkey(&[7u8; 32], b"lancast/control/v1").unwrap(); + let video = derive_subkey(&[7u8; 32], b"lancast/video/v1").unwrap(); + assert_ne!(control, video); + } +} diff --git a/rust_core/src/crypto/mod.rs b/rust_core/src/crypto/mod.rs new file mode 100644 index 0000000..1fab030 --- /dev/null +++ b/rust_core/src/crypto/mod.rs @@ -0,0 +1,37 @@ +pub mod aead; +pub mod ecdh; +pub mod sha256; + +use std::fmt; + +pub use aead::{decrypt, encrypt, NONCE_LEN, TAG_LEN}; +pub use ecdh::{derive_subkey, random_bytes, EphemeralKeyPair}; +pub use sha256::{hmac_sha256, sha256}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CryptoError { + InvalidKeyLength, + InvalidNonce, + KeyGenerationFailed, + KeyAgreementFailed, + KeyDerivationFailed, + EncryptionFailed, + DecryptionFailed, +} + +impl fmt::Display for CryptoError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let message = match self { + Self::InvalidKeyLength => "密钥长度无效", + Self::InvalidNonce => "nonce 长度无效", + Self::KeyGenerationFailed => "密钥生成失败", + Self::KeyAgreementFailed => "ECDH 密钥协商失败", + Self::KeyDerivationFailed => "子密钥派生失败", + Self::EncryptionFailed => "AES-GCM 加密失败", + Self::DecryptionFailed => "AES-GCM 解密或校验失败", + }; + write!(formatter, "{}", message) + } +} + +impl std::error::Error for CryptoError {} diff --git a/rust_core/src/crypto/sha256.rs b/rust_core/src/crypto/sha256.rs new file mode 100644 index 0000000..5e82b62 --- /dev/null +++ b/rust_core/src/crypto/sha256.rs @@ -0,0 +1,143 @@ +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, + 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, + 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, + 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, + 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, + 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, + 0xc67178f2, +]; + +pub fn sha256(data: &[u8]) -> [u8; 32] { + let mut state = [ + 0x6a09e667u32, + 0xbb67ae85, + 0x3c6ef372, + 0xa54ff53a, + 0x510e527f, + 0x9b05688c, + 0x1f83d9ab, + 0x5be0cd19, + ]; + + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut message = data.to_vec(); + message.push(0x80); + while message.len() % 64 != 56 { + message.push(0); + } + message.extend_from_slice(&bit_len.to_be_bytes()); + + for chunk in message.chunks_exact(64) { + let mut words = [0u32; 64]; + for (index, word) in words.iter_mut().enumerate().take(16) { + let offset = index * 4; + *word = u32::from_be_bytes([ + chunk[offset], + chunk[offset + 1], + chunk[offset + 2], + chunk[offset + 3], + ]); + } + for index in 16..64 { + let s0 = words[index - 15].rotate_right(7) + ^ words[index - 15].rotate_right(18) + ^ (words[index - 15] >> 3); + let s1 = words[index - 2].rotate_right(17) + ^ words[index - 2].rotate_right(19) + ^ (words[index - 2] >> 10); + words[index] = words[index - 16] + .wrapping_add(s0) + .wrapping_add(words[index - 7]) + .wrapping_add(s1); + } + + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = state; + for (index, &word) in words.iter().enumerate() { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choice = (e & f) ^ ((!e) & g); + let temp1 = h + .wrapping_add(s1) + .wrapping_add(choice) + .wrapping_add(K[index]) + .wrapping_add(word); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + + state[0] = state[0].wrapping_add(a); + state[1] = state[1].wrapping_add(b); + state[2] = state[2].wrapping_add(c); + state[3] = state[3].wrapping_add(d); + state[4] = state[4].wrapping_add(e); + state[5] = state[5].wrapping_add(f); + state[6] = state[6].wrapping_add(g); + state[7] = state[7].wrapping_add(h); + } + + let mut output = [0u8; 32]; + for (index, word) in state.iter().enumerate() { + output[index * 4..index * 4 + 4].copy_from_slice(&word.to_be_bytes()); + } + output +} + +pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { + let mut normalized = [0u8; 64]; + if key.len() > 64 { + normalized[..32].copy_from_slice(&sha256(key)); + } else { + normalized[..key.len()].copy_from_slice(key); + } + + let mut inner_pad = [0x36u8; 64]; + let mut outer_pad = [0x5cu8; 64]; + for index in 0..64 { + inner_pad[index] ^= normalized[index]; + outer_pad[index] ^= normalized[index]; + } + + let mut inner = Vec::with_capacity(64 + data.len()); + inner.extend_from_slice(&inner_pad); + inner.extend_from_slice(data); + let inner_hash = sha256(&inner); + + let mut outer = Vec::with_capacity(96); + outer.extend_from_slice(&outer_pad); + outer.extend_from_slice(&inner_hash); + sha256(&outer) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::util::hex_encode; + + #[test] + fn known_vector() { + assert_eq!( + hex_encode(&sha256(b"abc")), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn hmac_known_vector() { + assert_eq!( + hex_encode(&hmac_sha256(b"key", b"The quick brown fox jumps over the lazy dog")), + "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" + ); + } +} diff --git a/rust_core/src/demo_server.rs b/rust_core/src/demo_server.rs new file mode 100644 index 0000000..6754b10 --- /dev/null +++ b/rust_core/src/demo_server.rs @@ -0,0 +1,343 @@ +//! 可运行的本机 demo 服务端。 +//! +//! 协议(demo v1,控制通道不叠加 TLS,保密性由 AES-GCM 控制帧保证): +//! 1. 被控端反连 TCP 41001,先发送 65 字节 ECDH P-256 公钥。 +//! 2. 主控端回送 65 字节自己的公钥;双方用 HKDF 派生 control/video/audio 三把 32 字节子密钥。 +//! 3. 后续控制帧使用 `SecureControlChannel`(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。 +//! 4. 视频/音频通过 UDP 41000/41002 发送,使用 `MediaPackets` 的 13 字节头 + 4 字节 HMAC。 + +use std::io::{Read, Write}; +use std::net::{TcpListener, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; + +use crate::control::SecureControlChannel; +use crate::crypto::{derive_subkey, EphemeralKeyPair}; +use crate::media::decode_media_packet; + +pub const DEFAULT_CONTROL_PORT: u16 = 41001; +pub const DEFAULT_VIDEO_PORT: u16 = 41000; +pub const DEFAULT_AUDIO_PORT: u16 = 41002; +const PUBLIC_KEY_LEN: usize = 65; +const MAX_FRAME: usize = 64 * 1024; + +#[derive(Debug, Clone, Default)] +pub struct DemoStatus { + pub running: bool, + pub peer_connected: bool, + pub key_established: bool, + pub peer_ip: String, + pub control_key_prefix: String, + pub video_key_prefix: String, + pub audio_key_prefix: String, + pub events: Vec, +} + +impl DemoStatus { + pub fn to_json(&self) -> String { + let events = self + .events + .iter() + .map(|event| format!("\"{}\"", event.replace('"', "\\\""))) + .collect::>() + .join(","); + format!( + concat!( + "{{\"running\":{},\"peerConnected\":{},\"keyEstablished\":{},", + "\"peerIp\":\"{}\",\"controlKey\":\"{}\",\"videoKey\":\"{}\",", + "\"audioKey\":\"{}\",\"events\":[{}]}}" + ), + self.running, + self.peer_connected, + self.key_established, + self.peer_ip.replace('"', ""), + self.control_key_prefix, + self.video_key_prefix, + self.audio_key_prefix, + events + ) + } +} + +struct Shared { + running: AtomicBool, + peer_connected: AtomicBool, + key_established: AtomicBool, + peer_ip: Mutex, + control_key: Mutex>, + video_key: Mutex>, + audio_key: Mutex>, + events: Mutex>, +} + +impl Shared { + fn new() -> Self { + Self { + running: AtomicBool::new(false), + peer_connected: AtomicBool::new(false), + key_established: AtomicBool::new(false), + peer_ip: Mutex::new(String::new()), + control_key: Mutex::new(None), + video_key: Mutex::new(None), + audio_key: Mutex::new(None), + events: Mutex::new(Vec::new()), + } + } + + fn push_event(&self, event: String) { + if let Ok(mut queue) = self.events.lock() { + if queue.len() >= 200 { + queue.remove(0); + } + queue.push(event); + } + } + + fn status(&self) -> DemoStatus { + let key_prefix = |key: &Mutex>| -> String { + key.lock() + .ok() + .and_then(|guard| *guard) + .map(|bytes| { + bytes[..4] + .iter() + .map(|byte| format!("{:02x}", byte)) + .collect() + }) + .unwrap_or_default() + }; + DemoStatus { + running: self.running.load(Ordering::Relaxed), + peer_connected: self.peer_connected.load(Ordering::Relaxed), + key_established: self.key_established.load(Ordering::Relaxed), + peer_ip: self.peer_ip.lock().map(|value| value.clone()).unwrap_or_default(), + control_key_prefix: key_prefix(&self.control_key), + video_key_prefix: key_prefix(&self.video_key), + audio_key_prefix: key_prefix(&self.audio_key), + events: self.events.lock().map(|value| value.clone()).unwrap_or_default(), + } + } +} + +struct ServerHandle { + shared: Arc, + threads: Mutex>>, +} + +static SERVER: OnceLock = OnceLock::new(); + +fn server_handle() -> &'static ServerHandle { + SERVER.get_or_init(|| ServerHandle { + shared: Arc::new(Shared::new()), + threads: Mutex::new(Vec::new()), + }) +} + +/// 启动 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()); + } + + 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]); + } + Ok(()) +} + +/// 停止 demo 服务端。 +pub fn stop() { + let handle = server_handle(); + handle.shared.running.store(false, Ordering::SeqCst); + handle.shared.peer_connected.store(false, Ordering::SeqCst); + handle.shared.key_established.store(false, Ordering::SeqCst); +} + +/// 读取当前状态快照。 +pub fn status() -> DemoStatus { + server_handle().shared.status() +} + +fn run_tcp(listener: TcpListener, shared: Arc) { + while shared.running.load(Ordering::Relaxed) { + match listener.accept() { + Ok((mut stream, address)) => { + // listener 是非阻塞的,accept 出的连接会继承该标志;改回阻塞以便 read_exact。 + let _ = stream.set_nonblocking(false); + if let Ok(mut ip) = shared.peer_ip.lock() { + *ip = address.ip().to_string(); + } + shared.peer_connected.store(true, Ordering::Relaxed); + shared.push_event(format!("peer:{}", address)); + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + handle_peer(&mut stream, &shared); + shared.peer_connected.store(false, Ordering::Relaxed); + shared.key_established.store(false, Ordering::Relaxed); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(50)); + } + Err(_) => break, + } + } +} + +fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc) { + let local_pair = match EphemeralKeyPair::generate() { + Ok(pair) => pair, + Err(_) => { + shared.push_event("error:ecdh-generate".to_string()); + return; + } + }; + let local_public = local_pair.public_bytes().to_vec(); + let mut peer_public = [0u8; PUBLIC_KEY_LEN]; + if stream.read_exact(&mut peer_public).is_err() { + shared.push_event("error:peer-public".to_string()); + return; + } + let shared_secret = match local_pair.into_shared_secret(&peer_public) { + Ok(secret) => secret, + Err(_) => { + shared.push_event("error:ecdh-agree".to_string()); + return; + } + }; + let control = match derive_subkey(&shared_secret, b"lancast/control/v1") { + Ok(key) => key, + Err(_) => return, + }; + let video = match derive_subkey(&shared_secret, b"lancast/video/v1") { + Ok(key) => key, + Err(_) => return, + }; + let audio = match derive_subkey(&shared_secret, b"lancast/audio/v1") { + Ok(key) => key, + Err(_) => return, + }; + for (slot, key) in [(&shared.control_key, control), (&shared.video_key, video), (&shared.audio_key, audio)] { + if let Ok(mut guard) = slot.lock() { + *guard = Some(key); + } + } + shared.key_established.store(true, Ordering::Relaxed); + shared.push_event("key-established".to_string()); + + if stream.write_all(&local_public).is_err() { + return; + } + let _ = stream.flush(); + + let channel = SecureControlChannel::new(control); + let mut buffer = Vec::new(); + let mut chunk = [0u8; 4096]; + while shared.running.load(Ordering::Relaxed) { + let read = match stream.read(&mut chunk) { + Ok(0) => { + shared.push_event("control:eof".to_string()); + break; + } + Ok(size) => size, + Err(error) => { + shared.push_event(format!("control:read-error:{}", error)); + break; + } + }; + buffer.extend_from_slice(&chunk[..read]); + if buffer.len() > MAX_FRAME { + shared.push_event("error:frame-too-large".to_string()); + break; + } + loop { + match channel.decode(&buffer) { + Ok(Some((event, consumed))) => { + shared.push_event(format!( + "control:seq={}:type={}", + event.sequence(), + event.msg_type() + )); + buffer.drain(..consumed); + if let crate::control::ControlEventKind::Ping(timestamp) = event.kind { + let pong = crate::control::ControlEvent::new( + event.sequence(), + crate::control::ControlEventKind::Pong(timestamp), + ); + if let Ok(frame) = channel.encode(&pong) { + let _ = stream.write_all(&frame); + let _ = stream.flush(); + } + } + } + Ok(None) => break, + Err(error) => { + shared.push_event(format!("error:control:{}", error)); + buffer.clear(); + break; + } + } + } + } +} + +fn run_udp(socket: UdpSocket, shared: Arc, kind: &str) { + let mut buffer = [0u8; MAX_FRAME]; + while shared.running.load(Ordering::Relaxed) { + let (size, source) = match socket.recv_from(&mut buffer) { + Ok(value) => value, + Err(_) => continue, + }; + let key_slot = if kind == "video" { + &shared.video_key + } else { + &shared.audio_key + }; + let key = match key_slot.lock().ok().and_then(|guard| *guard) { + Some(key) => key, + None => { + shared.push_event(format!("error:{}:no-key", kind)); + continue; + } + }; + 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(None) => shared.push_event(format!("error:{}:incomplete", kind)), + Err(error) => shared.push_event(format!("error:{}:{}", kind, error)), + } + } +} diff --git a/rust_core/src/discovery/device.rs b/rust_core/src/discovery/device.rs new file mode 100644 index 0000000..6fc6608 --- /dev/null +++ b/rust_core/src/discovery/device.rs @@ -0,0 +1,122 @@ +use crate::json::JsonValue; + +use super::DiscoveryError; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeviceInfo { + pub device_id: String, + pub name: String, + pub ip: String, + pub media_port: u16, + pub control_port: u16, + pub fingerprint: String, + pub capabilities: Vec, + pub model: String, + pub resolution: String, + pub signaling_url: Option, +} + +impl DeviceInfo { + pub fn from_json(value: &JsonValue) -> Result { + let device_id = required_string(value, "deviceId") + .or_else(|| required_string(value, "id")) + .ok_or(DiscoveryError::InvalidRecord("缺少 deviceId"))?; + let ip = required_string(value, "ip").ok_or(DiscoveryError::InvalidRecord("缺少 ip"))?; + let fingerprint = required_string(value, "fp") + .or_else(|| required_string(value, "fingerprint")) + .ok_or(DiscoveryError::InvalidRecord("缺少证书指纹 fp"))?; + let media_port = port_from(value, "mediaPort")?; + let control_port = port_from(value, "controlPort")?; + let capabilities = value + .get("cap") + .and_then(JsonValue::as_array) + .map(|values| { + values + .iter() + .filter_map(JsonValue::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + + let name = required_string(value, "name").unwrap_or_else(|| device_id.clone()); + Ok(Self { + device_id, + name, + ip, + media_port, + control_port, + fingerprint, + capabilities, + model: required_string(value, "model").unwrap_or_default(), + resolution: required_string(value, "res").unwrap_or_default(), + signaling_url: required_string(value, "sig"), + }) + } + + pub fn to_register_json(&self, ttl: u64) -> JsonValue { + let mut value = JsonValue::object(); + value.insert("deviceId", JsonValue::from(self.device_id.as_str())); + value.insert("name", JsonValue::from(self.name.as_str())); + value.insert("ip", JsonValue::from(self.ip.as_str())); + value.insert("mediaPort", JsonValue::from(self.media_port as u64)); + value.insert("controlPort", JsonValue::from(self.control_port as u64)); + value.insert("fp", JsonValue::from(self.fingerprint.as_str())); + value.insert( + "cap", + JsonValue::Array(self.capabilities.iter().map(JsonValue::from).collect()), + ); + value.insert("ttl", JsonValue::from(ttl)); + value.insert("model", JsonValue::from(self.model.as_str())); + value.insert("res", JsonValue::from(self.resolution.as_str())); + if let Some(url) = &self.signaling_url { + value.insert("sig", JsonValue::from(url.as_str())); + } + value + } + + pub fn supports(&self, capability: &str) -> bool { + self.capabilities.iter().any(|item| item == capability) + } +} + +fn required_string(value: &JsonValue, key: &str) -> Option { + value + .get(key) + .and_then(JsonValue::as_str) + .filter(|text| !text.is_empty()) + .map(str::to_string) +} + +fn port_from(value: &JsonValue, key: &str) -> Result { + let number = value + .get(key) + .and_then(JsonValue::as_u64) + .ok_or_else(|| DiscoveryError::InvalidRecord("端口字段无效"))?; + if number == 0 || number > u16::MAX as u64 { + return Err(DiscoveryError::InvalidRecord("端口超出范围")); + } + Ok(number as u16) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::json::parse; + + #[test] + fn device_from_signaling_payload() { + let raw = r#"{"deviceId":"uuid-1","name":"客厅Pixel","ip":"192.168.1.10", + "mediaPort":41000,"controlPort":41001,"fp":"sha256:ab12","cap":["h264","opus"]}"#; + let device = DeviceInfo::from_json(&parse(raw).unwrap()).unwrap(); + assert_eq!(device.name, "客厅Pixel"); + assert_eq!(device.media_port, 41000); + assert!(device.supports("opus")); + } + + #[test] + fn invalid_port_is_rejected() { + let raw = r#"{"deviceId":"a","ip":"1.2.3.4","fp":"f","mediaPort":0,"controlPort":1}"#; + assert!(DeviceInfo::from_json(&parse(raw).unwrap()).is_err()); + } +} diff --git a/rust_core/src/discovery/mdns.rs b/rust_core/src/discovery/mdns.rs new file mode 100644 index 0000000..29fdcdc --- /dev/null +++ b/rust_core/src/discovery/mdns.rs @@ -0,0 +1,270 @@ +use std::time::{Duration, Instant}; + +use mdns_sd::{ResolvedService, ServiceDaemon, ServiceEvent, ServiceInfo}; + +use super::{DeviceInfo, DiscoveryError}; + +pub const SERVICE_TYPE: &str = "_lancast._tcp.local."; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MdnsTxt { + pub txtvers: u8, + pub ver: u8, + pub dev: String, + pub capabilities: Vec, + pub resolution: String, + pub model: String, + pub fingerprint: String, + pub signaling_url: Option, + pub media_port: Option, +} + +impl MdnsTxt { + pub fn new(fingerprint: impl Into, capabilities: &[&str]) -> Self { + Self { + txtvers: 1, + ver: 1, + dev: "android".to_string(), + capabilities: capabilities.iter().map(|item| item.to_string()).collect(), + resolution: "1920x1080".to_string(), + model: String::new(), + fingerprint: fingerprint.into(), + signaling_url: None, + media_port: None, + } + } + + pub fn to_records(&self) -> Vec { + let mut records = vec![ + format!("txtvers={}", self.txtvers), + format!("ver={}", self.ver), + format!("dev={}", self.dev), + format!("cap={}", self.capabilities.join(",")), + format!("res={}", self.resolution), + format!("model={}", self.model), + format!("fp={}", self.fingerprint), + ]; + if let Some(url) = &self.signaling_url { + records.push(format!("sig={}", url)); + } + if let Some(port) = self.media_port { + records.push(format!("mport={}", port)); + } + records + } + + pub fn parse_records(records: &[String]) -> Result { + let mut result = Self { + txtvers: 0, + ver: 0, + dev: String::new(), + capabilities: Vec::new(), + resolution: String::new(), + model: String::new(), + fingerprint: String::new(), + signaling_url: None, + media_port: None, + }; + for record in records { + let (key, value) = record + .split_once('=') + .ok_or(DiscoveryError::InvalidRecord("TXT 记录缺少 '='"))?; + match key { + "txtvers" => result.txtvers = parse_u8(value)?, + "ver" => result.ver = parse_u8(value)?, + "dev" => result.dev = value.to_string(), + "cap" => { + result.capabilities = value + .split(',') + .filter(|item| !item.is_empty()) + .map(str::to_string) + .collect() + } + "res" => result.resolution = value.to_string(), + "model" => result.model = value.to_string(), + "fp" => result.fingerprint = value.to_string(), + "sig" => result.signaling_url = Some(value.to_string()), + "mport" => result.media_port = Some(parse_u16(value)?), + _ => {} + } + } + if result.txtvers != 1 || result.ver != 1 { + return Err(DiscoveryError::InvalidRecord("不支持的 TXT/协议版本")); + } + if result.fingerprint.is_empty() { + return Err(DiscoveryError::InvalidRecord("TXT 记录缺少证书指纹")); + } + Ok(result) + } + + pub fn into_device( + self, + device_id: String, + ip: String, + control_port: u16, + media_port: u16, + ) -> DeviceInfo { + DeviceInfo { + device_id, + name: if self.model.is_empty() { + ip.clone() + } else { + self.model.clone() + }, + ip, + media_port: self.media_port.unwrap_or(media_port), + control_port, + fingerprint: self.fingerprint, + capabilities: self.capabilities, + model: self.model, + resolution: self.resolution, + signaling_url: self.signaling_url, + } + } +} + +fn parse_u8(value: &str) -> Result { + value + .parse::() + .map_err(|_| DiscoveryError::InvalidRecord("版本号不是合法数字")) +} + +fn parse_u16(value: &str) -> Result { + value + .parse::() + .map_err(|_| DiscoveryError::InvalidRecord("端口不是合法数字")) +} + +pub trait DeviceDiscovery: Send { + fn browse(&mut self, timeout: Duration) -> Result, DiscoveryError>; +} + +#[derive(Debug, Default)] +pub struct StaticDiscovery { + devices: Vec, +} + +impl StaticDiscovery { + pub fn new(devices: Vec) -> Self { + Self { devices } + } +} + +impl DeviceDiscovery for StaticDiscovery { + fn browse(&mut self, _timeout: Duration) -> Result, DiscoveryError> { + Ok(self.devices.clone()) + } +} + +pub trait MdnsAdapter: Send { + fn browse_devices(&self, timeout: Duration) -> Result, DiscoveryError>; + fn advertise(&self, device: &DeviceInfo) -> Result<(), DiscoveryError>; +} + +pub struct NativeMdnsAdapter { + daemon: ServiceDaemon, +} + +impl NativeMdnsAdapter { + pub fn new() -> Result { + Ok(Self { + daemon: ServiceDaemon::new().map_err(|error| DiscoveryError::Mdns(error.to_string()))?, + }) + } +} + +impl MdnsAdapter for NativeMdnsAdapter { + fn browse_devices(&self, timeout: Duration) -> Result, DiscoveryError> { + let receiver = self + .daemon + .browse(SERVICE_TYPE) + .map_err(|error| DiscoveryError::Mdns(error.to_string()))?; + let deadline = Instant::now() + timeout; + let mut devices: Vec = Vec::new(); + + while let Ok(event) = receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + if let ServiceEvent::ServiceResolved(service) = event { + if let Some(device) = device_from_resolved(&service) { + if !devices.iter().any(|existing| existing.device_id == device.device_id) { + devices.push(device); + } + } + } + } + let _ = self.daemon.stop_browse(SERVICE_TYPE); + Ok(devices) + } + + fn advertise(&self, device: &DeviceInfo) -> Result<(), DiscoveryError> { + let capabilities: Vec<&str> = device.capabilities.iter().map(String::as_str).collect(); + let mut txt = MdnsTxt::new(&device.fingerprint, &capabilities); + txt.model = device.model.clone(); + txt.resolution = device.resolution.clone(); + txt.media_port = Some(device.media_port); + txt.signaling_url = device.signaling_url.clone(); + + let properties: Vec<(String, String)> = txt + .to_records() + .iter() + .filter_map(|record| { + record.split_once('=').map(|(key, value)| (key.to_string(), value.to_string())) + }) + .collect(); + let ip = device + .ip + .parse::() + .map_err(|_| DiscoveryError::InvalidRecord("mDNS 广播需要 IPv4 地址"))?; + let service = ServiceInfo::new( + SERVICE_TYPE, + &device.device_id, + "lancast.local.", + std::net::IpAddr::V4(ip), + device.control_port, + &properties[..], + ) + .map_err(|error| DiscoveryError::Mdns(error.to_string()))?; + self.daemon + .register(service) + .map_err(|error| DiscoveryError::Mdns(error.to_string())) + } +} + +fn device_from_resolved(service: &ResolvedService) -> Option { + let ip = service.get_addresses_v4().into_iter().next()?.to_string(); + let records: Vec = service + .get_properties() + .iter() + .map(|property| format!("{}={}", property.key(), property.val_str())) + .collect(); + let txt = MdnsTxt::parse_records(&records).ok()?; + let device_id = mdns_sd::instance_name_unescaped(service.get_fullname()); + let control_port = service.get_port(); + Some(txt.into_device(device_id, ip, control_port, control_port.saturating_add(1))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn txt_record_roundtrip() { + let txt = MdnsTxt::new("sha256:ab12cd34", &["h264", "opus"]); + let records = txt.to_records(); + let parsed = MdnsTxt::parse_records(&records).unwrap(); + assert_eq!(parsed, txt); + } + + #[test] + fn media_port_record_roundtrip() { + let mut txt = MdnsTxt::new("sha256:ab12cd34", &["h264"]); + txt.media_port = Some(41000); + let parsed = MdnsTxt::parse_records(&txt.to_records()).unwrap(); + assert_eq!(parsed.media_port, Some(41000)); + } + + #[test] + fn reject_missing_fingerprint() { + let records = vec!["txtvers=1".into(), "ver=1".into(), "cap=h264".into()]; + assert!(MdnsTxt::parse_records(&records).is_err()); + } +} diff --git a/rust_core/src/discovery/mod.rs b/rust_core/src/discovery/mod.rs new file mode 100644 index 0000000..2ff918a --- /dev/null +++ b/rust_core/src/discovery/mod.rs @@ -0,0 +1,50 @@ +pub mod device; +pub mod mdns; +pub mod signaling; + +use std::fmt; + +use crate::json::JsonError; + +pub use device::DeviceInfo; +pub use mdns::{DeviceDiscovery, MdnsAdapter, MdnsTxt, NativeMdnsAdapter, StaticDiscovery, SERVICE_TYPE}; +pub use signaling::SignalingClient; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DiscoveryError { + InvalidUrl(&'static str), + InvalidRecord(&'static str), + Http(String), + Io(String), + Json(JsonError), + Mdns(String), + Unsupported(&'static str), +} + +impl fmt::Display for DiscoveryError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidUrl(reason) => write!(formatter, "信令地址无效:{}", reason), + Self::InvalidRecord(reason) => write!(formatter, "发现记录无效:{}", reason), + Self::Http(reason) => write!(formatter, "信令请求失败:{}", reason), + Self::Io(reason) => write!(formatter, "网络 I/O 失败:{}", reason), + Self::Json(error) => write!(formatter, "信令 JSON 解析失败:{}", error), + Self::Mdns(reason) => write!(formatter, "mDNS 失败:{}", reason), + Self::Unsupported(reason) => write!(formatter, "当前实现尚不支持:{}", reason), + } + } +} + +impl std::error::Error for DiscoveryError {} + +impl From for DiscoveryError { + fn from(error: JsonError) -> Self { + Self::Json(error) + } +} + +impl From for DiscoveryError { + fn from(error: std::io::Error) -> Self { + Self::Io(error.to_string()) + } +} diff --git a/rust_core/src/discovery/signaling.rs b/rust_core/src/discovery/signaling.rs new file mode 100644 index 0000000..b7ba45c --- /dev/null +++ b/rust_core/src/discovery/signaling.rs @@ -0,0 +1,223 @@ +use std::io::{Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::time::Duration; + +use crate::json::{self, JsonValue}; + +use super::{DeviceInfo, DiscoveryError}; + +#[derive(Debug, Clone)] +struct Endpoint { + host: String, + authority: String, + port: u16, + prefix: String, +} + +#[derive(Debug, Clone)] +pub struct SignalingClient { + endpoint: Endpoint, + timeout: Duration, +} + +impl SignalingClient { + pub fn new(base_url: impl Into, timeout: Duration) -> Result { + Ok(Self { + endpoint: parse_endpoint(&base_url.into())?, + timeout, + }) + } + + pub fn register(&self, device: &DeviceInfo, ttl: u64) -> Result<(), DiscoveryError> { + let body = device.to_register_json(ttl).encode(); + let response = self.send_request("POST", "/register", Some(&body))?; + let value = json::parse(&response)?; + if value.get("ok").and_then(JsonValue::as_bool) == Some(false) { + return Err(DiscoveryError::Http("信令服务器拒绝注册".to_string())); + } + Ok(()) + } + + pub fn list(&self) -> Result, DiscoveryError> { + let response = self.send_request("GET", "/list", None)?; + let value = json::parse(&response)?; + let devices = value + .get("devices") + .and_then(JsonValue::as_array) + .or_else(|| value.as_array()) + .ok_or(DiscoveryError::InvalidRecord("/list 响应缺少 devices 数组"))?; + devices.iter().map(DeviceInfo::from_json).collect() + } + + pub fn heartbeat(&self, device_id: &str) -> Result<(), DiscoveryError> { + let mut body = JsonValue::object(); + body.insert("deviceId", JsonValue::from(device_id)); + self.send_request("POST", "/heartbeat", Some(&body.encode()))?; + Ok(()) + } + + pub fn send_relay( + &self, + from: &str, + to: &str, + payload: &JsonValue, + ) -> Result<(), DiscoveryError> { + let mut body = JsonValue::object(); + body.insert("from", JsonValue::from(from)); + body.insert("to", JsonValue::from(to)); + body.insert("payload", payload.clone()); + self.send_request("POST", "/relay", Some(&body.encode()))?; + Ok(()) + } + + pub fn poll_relay(&self, device_id: &str) -> Result, DiscoveryError> { + let path = format!("/relay/poll?deviceId={}", crate::util::url_encode(device_id)); + let response = self.send_request("GET", &path, None)?; + let value = json::parse(&response)?; + Ok(value + .get("messages") + .and_then(JsonValue::as_array) + .unwrap_or_default() + .to_vec()) + } + + fn send_request( + &self, + method: &str, + path: &str, + body: Option<&str>, + ) -> Result { + let address = (self.endpoint.host.as_str(), self.endpoint.port) + .to_socket_addrs()? + .next() + .ok_or(DiscoveryError::InvalidUrl("无法解析信令服务器地址"))?; + let mut stream = TcpStream::connect_timeout(&address, self.timeout)?; + stream.set_read_timeout(Some(self.timeout))?; + stream.set_write_timeout(Some(self.timeout))?; + + let body = body.unwrap_or(""); + let full_path = if self.endpoint.prefix.is_empty() { + path.to_string() + } else { + format!("{}{}", self.endpoint.prefix, path) + }; + let request = format!( + "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}", + method, full_path, self.endpoint.authority, body.len(), body + ); + stream.write_all(request.as_bytes())?; + stream.flush()?; + + let mut response = String::new(); + stream.read_to_string(&mut response)?; + let (headers, raw_body) = response + .split_once("\r\n\r\n") + .ok_or_else(|| DiscoveryError::Http("信令响应缺少头部分隔符".to_string()))?; + let status_line = headers + .lines() + .next() + .ok_or_else(|| DiscoveryError::Http("信令响应缺少状态行".to_string()))?; + let status_code = status_line + .split_whitespace() + .nth(1) + .and_then(|code| code.parse::().ok()) + .ok_or_else(|| DiscoveryError::Http("信令响应状态码无效".to_string()))?; + if status_code >= 400 { + return Err(DiscoveryError::Http(format!( + "HTTP {} {}", + status_code, + raw_body.trim() + ))); + } + if headers + .lines() + .any(|line| line.to_ascii_lowercase().contains("transfer-encoding: chunked")) + { + decode_chunked(raw_body) + } else { + Ok(raw_body.to_string()) + } + } +} + +fn parse_endpoint(base_url: &str) -> Result { + let rest = base_url + .strip_prefix("http://") + .ok_or(DiscoveryError::InvalidUrl("当前版本仅支持 http://,HTTPS 由平台网络栈处理"))?; + let (authority, path) = match rest.find('/') { + Some(index) => (&rest[..index], &rest[index..]), + None => (rest, ""), + }; + if authority.is_empty() { + return Err(DiscoveryError::InvalidUrl("缺少主机名")); + } + let (host, port) = if let Some(inner) = authority.strip_prefix('[').and_then(|v| v.strip_suffix(']')) { + let port = authority + .rsplit_once(':') + .and_then(|(_, value)| value.parse::().ok()) + .ok_or(DiscoveryError::InvalidUrl("IPv6 地址缺少合法端口"))?; + (inner.to_string(), port) + } else if let Some((host, raw_port)) = authority.rsplit_once(':') { + let port = raw_port + .parse::() + .map_err(|_| DiscoveryError::InvalidUrl("端口号不是合法数字"))?; + (host.to_string(), port) + } else { + (authority.to_string(), 80) + }; + if host.is_empty() { + return Err(DiscoveryError::InvalidUrl("主机名为空")); + } + Ok(Endpoint { + host, + authority: authority.to_string(), + port, + prefix: path.trim_end_matches('/').to_string(), + }) +} + +fn decode_chunked(raw: &str) -> Result { + let bytes = raw.as_bytes(); + let mut position = 0; + let mut output = Vec::new(); + loop { + let relative_end = bytes[position..] + .windows(2) + .position(|window| window == b"\r\n") + .ok_or_else(|| DiscoveryError::Http("分块响应格式错误".to_string()))?; + let line_end = position + relative_end; + let size_line = std::str::from_utf8(&bytes[position..line_end]) + .map_err(|_| DiscoveryError::Http("分块长度不是 UTF-8".to_string()))?; + let size_text = size_line.split(';').next().unwrap_or("").trim(); + let size = usize::from_str_radix(size_text, 16) + .map_err(|_| DiscoveryError::Http("分块长度不是十六进制".to_string()))?; + position = line_end + 2; + if size == 0 { + break; + } + if position + size > bytes.len() { + return Err(DiscoveryError::Http("分块内容不完整".to_string())); + } + output.extend_from_slice(&bytes[position..position + size]); + position += size + 2; + } + String::from_utf8(output).map_err(|_| DiscoveryError::Http("响应内容不是 UTF-8".to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_base_url() { + let endpoint = parse_endpoint("http://127.0.0.1:8080/api/").unwrap(); + assert_eq!(endpoint.host, "127.0.0.1"); + assert_eq!(endpoint.port, 8080); + assert_eq!(endpoint.prefix, "/api"); + } + + #[test] + fn decode_chunked_body() { + assert_eq!(decode_chunked("5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n").unwrap(), "hello world"); + } +} diff --git a/rust_core/src/ffi.rs b/rust_core/src/ffi.rs new file mode 100644 index 0000000..c4005ed --- /dev/null +++ b/rust_core/src/ffi.rs @@ -0,0 +1,339 @@ +//! C ABI 出口:供 Flutter(dart:ffi) 与其他原生端调用核心协议能力。 +//! 该函数集只暴露无状态的密码学/编解码原语;会话状态由调用方持有。 + +use std::ffi::c_char; +use std::slice; + +use crate::control::{ControlEvent, ControlEventKind, SecureControlChannel}; +use crate::crypto::{derive_subkey, encrypt, EphemeralKeyPair}; +use crate::media::{decode_media_packet, encode_media_packet, MediaPacket}; + +/// 输出缓冲区不足。 +pub const ERR_BUFFER_TOO_SMALL: i32 = -1; +/// 输入参数非法(空指针、长度错误等)。 +pub const ERR_INVALID_ARGUMENT: i32 = -2; +/// 密码学操作失败。 +pub const ERR_CRYPTO: i32 = -3; +/// 编解码失败。 +pub const ERR_CODEC: i32 = -4; +/// 成功。 +pub const OK: i32 = 0; + +unsafe fn copy_out(data: &[u8], out: *mut u8, capacity: usize) -> i32 { + if out.is_null() || capacity < data.len() { + return ERR_BUFFER_TOO_SMALL; + } + slice::from_raw_parts_mut(out, data.len()).copy_from_slice(data); + data.len() as i32 +} + +unsafe fn read_slice<'a>(ptr: *const u8, len: usize) -> Result<&'a [u8], i32> { + if ptr.is_null() && len > 0 { + Err(ERR_INVALID_ARGUMENT) + } else { + Ok(slice::from_raw_parts(ptr, len)) + } +} + +unsafe fn read_key(ptr: *const u8) -> Result<[u8; 32], i32> { + let bytes = read_slice(ptr, 32)?; + let mut key = [0u8; 32]; + key.copy_from_slice(bytes); + Ok(key) +} + +/// 返回 Rust Core 版本号字符串(静态内存,调用方不要释放)。 +#[no_mangle] +pub extern "C" fn ttstd_core_version() -> *const c_char { + concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char +} + +/// 生成 ECDH P-256 临时密钥对,公钥(65 字节非压缩形式)写入 out_public。 +/// 返回非负句柄(i64,避免 64 位指针截断),调用方必须用 ttstd_ecdh_free 释放。 +/// +/// # Safety +/// out_public 必须可写且容量 >= 65。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_ecdh_generate(out_public: *mut u8, capacity: usize) -> i64 { + let pair = match EphemeralKeyPair::generate() { + Ok(pair) => pair, + Err(_) => return ERR_CRYPTO as i64, + }; + let public = pair.public_bytes().to_vec(); + let written = copy_out(&public, out_public, capacity); + if written < 0 { + return written as i64; + } + Box::into_raw(Box::new(pair)) as i64 +} + +/// 完成 ECDH 协商并把 32 字节共享密钥写入 out_secret。返回写入字节数或错误码。 +/// 调用后句柄即被消费,无需再调用 ttstd_ecdh_free。 +/// +/// # Safety +/// handle 必须来自 ttstd_ecdh_generate 且尚未释放;peer_public 长度必须为 65。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_ecdh_agree( + handle: i64, + peer_public: *const u8, + peer_len: usize, + out_secret: *mut u8, + capacity: usize, +) -> i32 { + if handle <= 0 { + return ERR_INVALID_ARGUMENT; + } + let pair = Box::from_raw(handle as *mut EphemeralKeyPair); + let peer = match read_slice(peer_public, peer_len) { + Ok(bytes) => bytes, + Err(code) => return code, + }; + let secret = match pair.into_shared_secret(peer) { + Ok(value) => value, + Err(_) => return ERR_CRYPTO, + }; + copy_out(&secret, out_secret, capacity) +} + +/// 释放 ttstd_ecdh_generate 返回的句柄。 +/// +/// # Safety +/// handle 必须是有效的、未释放的句柄。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_ecdh_free(handle: i64) { + if handle > 0 { + drop(Box::from_raw(handle as *mut EphemeralKeyPair)); + } +} + +/// HKDF-SHA256 子密钥派生:secret + label -> 32 字节子密钥。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_derive_subkey( + secret: *const u8, + secret_len: usize, + label: *const u8, + label_len: usize, + out_key: *mut u8, + capacity: usize, +) -> i32 { + let secret = match read_slice(secret, secret_len) { + Ok(value) => value, + Err(code) => return code, + }; + let label = match read_slice(label, label_len) { + Ok(value) => value, + Err(code) => return code, + }; + let key = match derive_subkey(secret, label) { + Ok(value) => value, + Err(_) => return ERR_CRYPTO, + }; + copy_out(&key, out_key, capacity) +} + +/// AES-256-GCM 加密:out = ciphertext || tag(16)。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_aes_encrypt( + key: *const u8, + nonce: *const u8, + plaintext: *const u8, + plaintext_len: usize, + aad: *const u8, + aad_len: usize, + out: *mut u8, + capacity: usize, +) -> i32 { + let key = match read_key(key) { + Ok(value) => value, + Err(code) => return code, + }; + let nonce_bytes = match read_slice(nonce, 12) { + Ok(value) => value, + Err(code) => return code, + }; + let mut nonce = [0u8; 12]; + nonce.copy_from_slice(nonce_bytes); + let plaintext = match read_slice(plaintext, plaintext_len) { + Ok(value) => value, + Err(code) => return code, + }; + let aad = match read_slice(aad, aad_len) { + Ok(value) => value, + Err(code) => return code, + }; + let cipher = match encrypt(&key, &nonce, plaintext, aad) { + Ok(value) => value, + Err(_) => return ERR_CRYPTO, + }; + copy_out(&cipher, out, capacity) +} + +/// 媒体包封装:13 字节头 + payload + 4 字节截断 HMAC。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_media_encode( + pts: u64, + flags: u8, + key: *const u8, + payload: *const u8, + payload_len: usize, + out: *mut u8, + capacity: usize, +) -> i32 { + let key = match read_key(key) { + Ok(value) => value, + Err(code) => return code, + }; + let payload = match read_slice(payload, payload_len) { + Ok(value) => value, + Err(code) => return code, + }; + let packet = encode_media_packet( + &MediaPacket { + pts, + flags, + payload: payload.to_vec(), + }, + &key, + ); + copy_out(&packet, out, capacity) +} + +/// 媒体包解析与 MAC 校验。成功时把解析结果写到 out_packet(JSON UTF-8)。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_media_decode( + buffer: *const u8, + buffer_len: usize, + key: *const u8, + out_json: *mut u8, + capacity: usize, +) -> i32 { + let buffer = match read_slice(buffer, buffer_len) { + Ok(value) => value, + Err(code) => return code, + }; + let key = match read_key(key) { + Ok(value) => value, + Err(code) => return code, + }; + let decoded = match decode_media_packet(buffer, &key) { + Ok(Some(value)) => value, + Ok(None) => return ERR_CODEC, + Err(_) => return ERR_CRYPTO, + }; + let (packet, _) = decoded; + let json = format!( + "{{\"pts\":{},\"flags\":{},\"payloadLen\":{}}}", + packet.pts, + packet.flags, + packet.payload.len() + ); + copy_out(json.as_bytes(), out_json, capacity) +} + +/// 创建安全控制通道句柄(持 32 字节密钥与发送计数器)。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_control_channel_new(key: *const u8) -> i64 { + let key = match read_key(key) { + Ok(value) => value, + Err(code) => return code as i64, + }; + Box::into_raw(Box::new(SecureControlChannel::new(key))) as i64 +} + +/// 释放安全控制通道句柄。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_control_channel_free(handle: i64) { + if handle > 0 { + drop(Box::from_raw(handle as *mut SecureControlChannel)); + } +} + +/// 编码 Ping 控制帧(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_control_encode_ping( + handle: i64, + sequence: u16, + timestamp: u64, + out: *mut u8, + capacity: usize, +) -> i32 { + if handle <= 0 { + return ERR_INVALID_ARGUMENT; + } + let channel = &*(handle as *const SecureControlChannel); + let event = ControlEvent::new(sequence, ControlEventKind::Ping(timestamp)); + let frame = match channel.encode(&event) { + Ok(value) => value, + Err(_) => return ERR_CRYPTO, + }; + copy_out(&frame, out, capacity) +} + +/// 解码安全控制帧,成功时把事件写到 out_json。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_control_decode( + handle: i64, + buffer: *const u8, + buffer_len: usize, + out_json: *mut u8, + capacity: usize, +) -> i32 { + if handle <= 0 { + return ERR_INVALID_ARGUMENT; + } + let channel = &*(handle as *const SecureControlChannel); + let buffer = match read_slice(buffer, buffer_len) { + Ok(value) => value, + Err(code) => return code, + }; + let decoded = match channel.decode(buffer) { + Ok(Some(value)) => value, + Ok(None) => return ERR_CODEC, + Err(_) => return ERR_CRYPTO, + }; + let (event, _) = decoded; + let kind = match event.kind { + ControlEventKind::Ping(_) => "ping", + ControlEventKind::Pong(_) => "pong", + ControlEventKind::Touch(_) => "touch", + ControlEventKind::Mouse(_) => "mouse", + ControlEventKind::Key(_) => "key", + ControlEventKind::Wheel(_) => "wheel", + ControlEventKind::Clipboard(_) => "clipboard", + }; + let json = format!( + "{{\"sequence\":{},\"msgType\":{},\"kind\":\"{}\"}}", + event.sequence(), + event.msg_type(), + kind + ); + copy_out(json.as_bytes(), out_json, capacity) +} + +/// 启动本机 demo 服务:TCP 控制 + UDP 视频/音频。 +#[no_mangle] +pub extern "C" fn ttstd_demo_start(control_port: u16, video_port: u16, audio_port: u16) -> i32 { + match crate::demo_server::start(control_port, video_port, audio_port) { + Ok(()) => OK, + Err(_) => ERR_INVALID_ARGUMENT, + } +} + +/// 停止本机 demo 服务。 +#[no_mangle] +pub extern "C" fn ttstd_demo_stop() { + crate::demo_server::stop(); +} + +/// 获取 demo 服务状态 JSON。 +#[no_mangle] +pub unsafe extern "C" fn ttstd_demo_status(out_json: *mut u8, capacity: usize) -> i32 { + let json = crate::demo_server::status().to_json(); + copy_out(json.as_bytes(), out_json, capacity) +} + +/// ABI 版本,便于 Dart 侧校验动态库是否匹配。 +#[no_mangle] +pub extern "C" fn ttstd_core_abi_revision() -> i32 { + 1 +} diff --git a/rust_core/src/file/mod.rs b/rust_core/src/file/mod.rs new file mode 100644 index 0000000..8ac3685 --- /dev/null +++ b/rust_core/src/file/mod.rs @@ -0,0 +1,7 @@ +pub mod protocol; +pub mod transfer; + +pub use protocol::{ + ChunkAck, ChunkQuery, FileError, FileMeta, PrepareRequest, PrepareResponse, ProgressEvent, +}; +pub use transfer::{PendingFile, TransferSession}; diff --git a/rust_core/src/file/protocol.rs b/rust_core/src/file/protocol.rs new file mode 100644 index 0000000..08a4ff2 --- /dev/null +++ b/rust_core/src/file/protocol.rs @@ -0,0 +1,235 @@ +use std::collections::HashMap; +use std::fmt; + +use crate::json::{JsonError, JsonValue}; +use crate::util::url_encode; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FileError { + InvalidPayload(&'static str), + MissingField(String), + Json(JsonError), +} + +impl fmt::Display for FileError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidPayload(reason) => write!(formatter, "文件子协议字段无效:{}", reason), + Self::MissingField(field) => write!(formatter, "文件子协议缺少字段:{}", field), + Self::Json(error) => write!(formatter, "文件子协议 JSON 无效:{}", error), + } + } +} + +impl std::error::Error for FileError {} + +impl From for FileError { + fn from(error: JsonError) -> Self { + Self::Json(error) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileMeta { + pub id: String, + pub name: String, + pub size: u64, + pub mime: String, + pub sha256: String, +} + +impl FileMeta { + pub fn to_json(&self) -> JsonValue { + let mut value = JsonValue::object(); + value.insert("id", JsonValue::from(self.id.as_str())); + value.insert("name", JsonValue::from(self.name.as_str())); + value.insert("size", JsonValue::from(self.size)); + value.insert("mime", JsonValue::from(self.mime.as_str())); + value.insert("sha256", JsonValue::from(self.sha256.as_str())); + value + } + + pub fn from_json(value: &JsonValue) -> Result { + Ok(Self { + id: string_field(value, "id")?, + name: string_field(value, "name")?, + size: value + .get("size") + .and_then(JsonValue::as_u64) + .ok_or(FileError::InvalidPayload("size"))?, + mime: string_field(value, "mime")?, + sha256: string_field(value, "sha256")?, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PrepareRequest { + pub files: Vec, +} + +impl PrepareRequest { + pub fn to_json(&self) -> JsonValue { + let mut value = JsonValue::object(); + value.insert( + "files", + JsonValue::Array(self.files.iter().map(FileMeta::to_json).collect()), + ); + value + } + + pub fn from_json(value: &JsonValue) -> Result { + let files = value + .get("files") + .and_then(JsonValue::as_array) + .ok_or(FileError::InvalidPayload("files"))? + .iter() + .map(FileMeta::from_json) + .collect::, _>>()?; + Ok(Self { files }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PrepareResponse { + pub session_id: String, + pub tokens: HashMap, + pub rejected: Vec, +} + +impl PrepareResponse { + pub fn to_json(&self) -> JsonValue { + let mut value = JsonValue::object(); + value.insert("sessionId", JsonValue::from(self.session_id.as_str())); + let mut tokens = JsonValue::object(); + for (file_id, token) in &self.tokens { + tokens.insert(file_id, JsonValue::from(token.as_str())); + } + value.insert("tokens", tokens); + value.insert( + "rejected", + JsonValue::Array(self.rejected.iter().map(JsonValue::from).collect()), + ); + value + } + + pub fn from_json(value: &JsonValue) -> Result { + let mut tokens = HashMap::new(); + if let Some(object) = value.get("tokens") { + if let JsonValue::Object(pairs) = object { + for (file_id, token) in pairs { + if let Some(token) = token.as_str() { + tokens.insert(file_id.clone(), token.to_string()); + } + } + } + } + let rejected = value + .get("rejected") + .and_then(JsonValue::as_array) + .map(|values| { + values + .iter() + .filter_map(JsonValue::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + Ok(Self { + session_id: string_field(value, "sessionId")?, + tokens, + rejected, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkQuery { + pub session_id: String, + pub file_id: String, + pub token: String, + pub offset: u64, +} + +impl ChunkQuery { + pub fn to_query_string(&self) -> String { + format!( + "sessionId={}&fileId={}&token={}&offset={}", + url_encode(&self.session_id), + url_encode(&self.file_id), + url_encode(&self.token), + self.offset + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkAck { + pub received: u64, +} + +impl ChunkAck { + pub fn from_json(value: &JsonValue) -> Result { + Ok(Self { + received: value + .get("received") + .and_then(JsonValue::as_u64) + .ok_or(FileError::InvalidPayload("received"))?, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProgressEvent { + pub session_id: String, + pub file_id: String, + pub received: u64, + pub total: u64, +} + +impl ProgressEvent { + pub fn to_json(&self) -> JsonValue { + let mut value = JsonValue::object(); + value.insert("sessionId", JsonValue::from(self.session_id.as_str())); + value.insert("fileId", JsonValue::from(self.file_id.as_str())); + value.insert("received", JsonValue::from(self.received)); + value.insert("total", JsonValue::from(self.total)); + value + } +} + +fn string_field(value: &JsonValue, key: &str) -> Result { + value + .get(key) + .and_then(JsonValue::as_str) + .map(str::to_string) + .ok_or_else(|| FileError::MissingField(key.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::json::parse; + + #[test] + fn prepare_request_roundtrip() { + let request = PrepareRequest { + files: vec![FileMeta { + id: "f1".into(), + name: "照片.jpg".into(), + size: 2048, + mime: "image/jpeg".into(), + sha256: "abc".into(), + }], + }; + let encoded = request.to_json().encode(); + assert_eq!(PrepareRequest::from_json(&parse(&encoded).unwrap()).unwrap(), request); + } + + #[test] + fn prepare_response_tokens() { + let raw = r#"{"sessionId":"s1","tokens":{"f1":"t1"},"rejected":[]}"#; + let response = PrepareResponse::from_json(&parse(raw).unwrap()).unwrap(); + assert_eq!(response.tokens.get("f1").map(String::as_str), Some("t1")); + } +} diff --git a/rust_core/src/file/transfer.rs b/rust_core/src/file/transfer.rs new file mode 100644 index 0000000..2cf9ee5 --- /dev/null +++ b/rust_core/src/file/transfer.rs @@ -0,0 +1,136 @@ +use std::collections::HashSet; + +use super::protocol::{ChunkQuery, FileMeta, PrepareResponse, ProgressEvent}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PendingFile { + pub meta: FileMeta, + pub token: String, + pub offset: u64, +} + +impl PendingFile { + pub fn is_complete(&self) -> bool { + self.offset >= self.meta.size + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TransferSession { + pub session_id: String, + pub files: Vec, +} + +impl TransferSession { + pub fn start(response: PrepareResponse, files: Vec) -> Self { + let rejected: HashSet = response.rejected.into_iter().collect(); + let files = files + .into_iter() + .filter(|file| !rejected.contains(&file.id)) + .filter_map(|file| { + response + .tokens + .get(&file.id) + .map(|token| PendingFile { + meta: file, + token: token.clone(), + offset: 0, + }) + }) + .collect(); + Self { + session_id: response.session_id, + files, + } + } + + pub fn next_chunk(&self, chunk_size: u64) -> Option { + if chunk_size == 0 { + return None; + } + self.files + .iter() + .find(|file| !file.is_complete()) + .map(|file| ChunkQuery { + session_id: self.session_id.clone(), + file_id: file.meta.id.clone(), + token: file.token.clone(), + offset: file.offset, + }) + } + + pub fn on_ack(&mut self, query: &ChunkQuery, received: u64) { + if let Some(file) = self + .files + .iter_mut() + .find(|file| file.meta.id == query.file_id && file.token == query.token) + { + file.offset = (file.offset + received).min(file.meta.size); + } + } + + pub fn progress(&self) -> Vec { + self.files + .iter() + .map(|file| ProgressEvent { + session_id: self.session_id.clone(), + file_id: file.meta.id.clone(), + received: file.offset, + total: file.meta.size, + }) + .collect() + } + + pub fn is_complete(&self) -> bool { + self.files.iter().all(PendingFile::is_complete) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn file(id: &str, size: u64) -> FileMeta { + FileMeta { + id: id.into(), + name: format!("{}.bin", id), + size, + mime: "application/octet-stream".into(), + sha256: "hash".into(), + } + } + + #[test] + fn chunk_offsets_advance_and_finish() { + let response = PrepareResponse { + session_id: "s1".into(), + tokens: HashMap::from([("f1".to_string(), "t1".to_string())]), + rejected: Vec::new(), + }; + let mut session = TransferSession::start(response, vec![file("f1", 10)]); + let first = session.next_chunk(4).unwrap(); + assert_eq!(first.offset, 0); + session.on_ack(&first, 4); + assert_eq!(session.next_chunk(4).unwrap().offset, 4); + let last = session.next_chunk(4).unwrap(); + session.on_ack(&last, 4); + assert_eq!(session.next_chunk(4).unwrap().offset, 8); + let end = session.next_chunk(4).unwrap(); + session.on_ack(&end, 2); + assert!(session.is_complete()); + assert_eq!(session.next_chunk(4), None); + assert_eq!(session.progress()[0].received, 10); + } + + #[test] + fn rejected_file_is_skipped() { + let response = PrepareResponse { + session_id: "s1".into(), + tokens: HashMap::from([("f1".to_string(), "t1".to_string())]), + rejected: vec!["f2".into()], + }; + let session = TransferSession::start(response, vec![file("f1", 4), file("f2", 4)]); + assert_eq!(session.files.len(), 1); + } +} diff --git a/rust_core/src/json.rs b/rust_core/src/json.rs new file mode 100644 index 0000000..f6b649d --- /dev/null +++ b/rust_core/src/json.rs @@ -0,0 +1,405 @@ +use std::fmt; + +#[derive(Debug, Clone, PartialEq)] +pub enum JsonValue { + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + Object(Vec<(String, JsonValue)>), +} + +impl JsonValue { + pub fn object() -> Self { + JsonValue::Object(Vec::new()) + } + + pub fn insert(&mut self, key: &str, value: JsonValue) { + if let JsonValue::Object(pairs) = self { + if let Some(pair) = pairs.iter_mut().find(|(name, _)| name == key) { + pair.1 = value; + } else { + pairs.push((key.to_string(), value)); + } + } + } + + pub fn get(&self, key: &str) -> Option<&JsonValue> { + match self { + JsonValue::Object(pairs) => pairs + .iter() + .find(|(name, _)| name == key) + .map(|(_, value)| value), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + JsonValue::String(value) => Some(value.as_str()), + _ => None, + } + } + + pub fn as_bool(&self) -> Option { + match self { + JsonValue::Bool(value) => Some(*value), + _ => None, + } + } + + pub fn as_u64(&self) -> Option { + match self { + JsonValue::Number(value) if *value >= 0.0 && value.fract() == 0.0 => Some(*value as u64), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[JsonValue]> { + match self { + JsonValue::Array(values) => Some(values.as_slice()), + _ => None, + } + } + + pub fn encode(&self) -> String { + let mut output = String::new(); + encode_value(self, &mut output); + output + } +} + +impl From<&str> for JsonValue { + fn from(value: &str) -> Self { + JsonValue::String(value.to_string()) + } +} + +impl From for JsonValue { + fn from(value: String) -> Self { + JsonValue::String(value) + } +} + +impl From<&String> for JsonValue { + fn from(value: &String) -> Self { + JsonValue::String(value.clone()) + } +} + +impl From for JsonValue { + fn from(value: u64) -> Self { + JsonValue::Number(value as f64) + } +} + +impl From for JsonValue { + fn from(value: bool) -> Self { + JsonValue::Bool(value) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JsonError { + pub message: String, + pub position: usize, +} + +impl fmt::Display for JsonError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "JSON 解析失败(位置 {}):{}", self.position, self.message) + } +} + +impl std::error::Error for JsonError {} + +pub fn parse(input: &str) -> Result { + let mut parser = Parser { + bytes: input.as_bytes(), + position: 0, + }; + parser.skip_whitespace(); + let value = parser.parse_value()?; + parser.skip_whitespace(); + if parser.position != parser.bytes.len() { + return Err(parser.error("尾部存在多余内容")); + } + Ok(value) +} + +struct Parser<'a> { + bytes: &'a [u8], + position: usize, +} + +impl<'a> Parser<'a> { + fn error(&self, message: &str) -> JsonError { + JsonError { + message: message.to_string(), + position: self.position, + } + } + + fn skip_whitespace(&mut self) { + while self.position < self.bytes.len() && self.bytes[self.position].is_ascii_whitespace() { + self.position += 1; + } + } + + fn peek(&self) -> Option { + self.bytes.get(self.position).copied() + } + + fn consume(&mut self, expected: u8) -> Result<(), JsonError> { + match self.peek() { + Some(actual) if actual == expected => { + self.position += 1; + Ok(()) + } + _ => Err(self.error(&format!("期望字符 '{}'", expected as char))), + } + } + + fn parse_value(&mut self) -> Result { + match self.peek() { + Some(b'{') => self.parse_object(), + Some(b'[') => self.parse_array(), + Some(b'"') => Ok(JsonValue::String(self.parse_string()?)), + Some(b't') => { + self.parse_literal(b"true")?; + Ok(JsonValue::Bool(true)) + } + Some(b'f') => { + self.parse_literal(b"false")?; + Ok(JsonValue::Bool(false)) + } + Some(b'n') => { + self.parse_literal(b"null")?; + Ok(JsonValue::Null) + } + Some(b'-' | b'0'..=b'9') => self.parse_number(), + Some(_) => Err(self.error("无法识别的 JSON 值")), + None => Err(self.error("JSON 内容意外结束")), + } + } + + fn parse_literal(&mut self, literal: &[u8]) -> Result<(), JsonError> { + if self.bytes[self.position..].starts_with(literal) { + self.position += literal.len(); + Ok(()) + } else { + Err(self.error("字面量不匹配")) + } + } + + fn parse_number(&mut self) -> Result { + let start = self.position; + while let Some(byte) = self.peek() { + if byte.is_ascii_digit() || matches!(byte, b'-' | b'+' | b'.' | b'e' | b'E') { + self.position += 1; + } else { + break; + } + } + let raw = std::str::from_utf8(&self.bytes[start..self.position]).map_err(|_| self.error("数字包含非法字符"))?; + raw.parse::() + .map(JsonValue::Number) + .map_err(|_| self.error("无效的 JSON 数字")) + } + + fn parse_string(&mut self) -> Result { + self.consume(b'"')?; + let mut output = String::new(); + while let Some(byte) = self.peek() { + match byte { + b'"' => { + self.position += 1; + return Ok(output); + } + b'\\' => { + self.position += 1; + let escaped = self.peek().ok_or_else(|| self.error("转义序列不完整"))?; + self.position += 1; + match escaped { + b'"' => output.push('"'), + b'\\' => output.push('\\'), + b'/' => output.push('/'), + b'b' => output.push('\u{0008}'), + b'f' => output.push('\u{000c}'), + b'n' => output.push('\n'), + b'r' => output.push('\r'), + b't' => output.push('\t'), + b'u' => { + let first = self.parse_hex4()?; + let codepoint = if (0xd800..=0xdbff).contains(&first) { + self.consume(b'\\')?; + self.consume(b'u')?; + let second = self.parse_hex4()?; + if !(0xdc00..=0xdfff).contains(&second) { + return Err(self.error("无效的 Unicode 低位代理项")); + } + 0x10000 + (((first - 0xd800) as u32) << 10) + (second - 0xdc00) as u32 + } else { + first as u32 + }; + output.push(char::from_u32(codepoint).ok_or_else(|| self.error("无效的 Unicode 码点"))?); + } + _ => return Err(self.error("无效的转义序列")), + } + } + 0x00..=0x1f => return Err(self.error("字符串中包含未转义控制字符")), + _ => { + let start = self.position; + while let Some(next) = self.peek() { + if next == b'"' || next == b'\\' || next < 0x20 { + break; + } + self.position += 1; + } + let slice = std::str::from_utf8(&self.bytes[start..self.position]) + .map_err(|_| self.error("字符串不是合法 UTF-8"))?; + output.push_str(slice); + } + } + } + Err(self.error("字符串缺少结束引号")) + } + + fn parse_hex4(&mut self) -> Result { + if self.position + 4 > self.bytes.len() { + return Err(self.error("Unicode 转义序列不完整")); + } + let raw = std::str::from_utf8(&self.bytes[self.position..self.position + 4]) + .map_err(|_| self.error("Unicode 转义序列非法"))?; + self.position += 4; + u16::from_str_radix(raw, 16).map_err(|_| self.error("Unicode 转义序列非法")) + } + + fn parse_array(&mut self) -> Result { + self.consume(b'[')?; + let mut values = Vec::new(); + self.skip_whitespace(); + if self.peek() == Some(b']') { + self.position += 1; + return Ok(JsonValue::Array(values)); + } + loop { + self.skip_whitespace(); + values.push(self.parse_value()?); + self.skip_whitespace(); + match self.peek() { + Some(b',') => self.position += 1, + Some(b']') => { + self.position += 1; + return Ok(JsonValue::Array(values)); + } + _ => return Err(self.error("数组缺少 ',' 或 ']'")), + } + } + } + + fn parse_object(&mut self) -> Result { + self.consume(b'{')?; + let mut pairs = Vec::new(); + self.skip_whitespace(); + if self.peek() == Some(b'}') { + self.position += 1; + return Ok(JsonValue::Object(pairs)); + } + loop { + self.skip_whitespace(); + let key = self.parse_string()?; + self.skip_whitespace(); + self.consume(b':')?; + self.skip_whitespace(); + let value = self.parse_value()?; + pairs.push((key, value)); + self.skip_whitespace(); + match self.peek() { + Some(b',') => self.position += 1, + Some(b'}') => { + self.position += 1; + return Ok(JsonValue::Object(pairs)); + } + _ => return Err(self.error("对象缺少 ',' 或 '}'")), + } + } + } +} + +fn encode_value(value: &JsonValue, output: &mut String) { + match value { + JsonValue::Null => output.push_str("null"), + JsonValue::Bool(true) => output.push_str("true"), + JsonValue::Bool(false) => output.push_str("false"), + JsonValue::Number(number) => { + if number.fract() == 0.0 && number.is_finite() { + output.push_str(&format!("{}", *number as i64)); + } else { + output.push_str(&number.to_string()); + } + } + JsonValue::String(text) => encode_string(text, output), + JsonValue::Array(values) => { + output.push('['); + for (index, item) in values.iter().enumerate() { + if index > 0 { + output.push(','); + } + encode_value(item, output); + } + output.push(']'); + } + JsonValue::Object(pairs) => { + output.push('{'); + for (index, (key, item)) in pairs.iter().enumerate() { + if index > 0 { + output.push(','); + } + encode_string(key, output); + output.push(':'); + encode_value(item, output); + } + output.push('}'); + } + } +} + +fn encode_string(text: &str, output: &mut String) { + output.push('"'); + for character in text.chars() { + match character { + '"' => output.push_str("\\\""), + '\\' => output.push_str("\\\\"), + '\n' => output.push_str("\\n"), + '\r' => output.push_str("\\r"), + '\t' => output.push_str("\\t"), + '\u{0008}' => output.push_str("\\b"), + '\u{000c}' => output.push_str("\\f"), + control if (control as u32) < 0x20 => output.push_str(&format!("\\u{:04x}", control as u32)), + other => output.push(other), + } + } + output.push('"'); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_encode_nested_object() { + let raw = r#"{"devices":[{"id":"a","ports":[41000,41001]}],"ok":true}"#; + let value = parse(raw).expect("解析成功"); + assert_eq!(value.get("ok").and_then(JsonValue::as_bool), Some(true)); + let devices = value.get("devices").and_then(JsonValue::as_array).expect("设备数组"); + assert_eq!(devices[0].get("id").and_then(JsonValue::as_str), Some("a")); + assert_eq!(parse(&value.encode()).unwrap(), value); + } + + #[test] + fn reject_trailing_content() { + assert!(parse("{} x").is_err()); + } +} diff --git a/rust_core/src/lib.rs b/rust_core/src/lib.rs new file mode 100644 index 0000000..797c6a9 --- /dev/null +++ b/rust_core/src/lib.rs @@ -0,0 +1,24 @@ +pub mod connection; +pub mod control; +pub mod crypto; +pub mod demo_server; +pub mod discovery; +pub mod ffi; +pub mod file; +pub mod json; +pub mod media; +pub mod session; +pub mod util; + +pub use connection::{ConnectionEvent, ConnectionPhase, ConnectionStateMachine}; +pub use control::{BinaryCodec, ControlEvent, ControlEventKind, ControlFrameCodec, SecureControlChannel}; +pub use discovery::{DeviceDiscovery, DeviceInfo, MdnsTxt, NativeMdnsAdapter, SignalingClient, StaticDiscovery}; +pub use file::{FileMeta, PrepareRequest, TransferSession}; +pub use media::{MediaPacket, VideoRenderer}; +pub use session::{PairingUri, SessionContext, SessionState}; + +pub const VERSION: &str = "0.1.0"; + +pub fn version() -> &'static str { + VERSION +} diff --git a/rust_core/src/media/mod.rs b/rust_core/src/media/mod.rs new file mode 100644 index 0000000..545d528 --- /dev/null +++ b/rust_core/src/media/mod.rs @@ -0,0 +1,5 @@ +pub mod packet; +pub mod renderer; + +pub use packet::{decode_media_packet, encode_media_packet, MediaError, MediaPacket, FLAG_AUDIO, FLAG_KEYFRAME}; +pub use renderer::{AudioSink, DecodedFrame, FrameQueue, PixelFormat, VideoRenderer}; diff --git a/rust_core/src/media/packet.rs b/rust_core/src/media/packet.rs new file mode 100644 index 0000000..8b14ccf --- /dev/null +++ b/rust_core/src/media/packet.rs @@ -0,0 +1,109 @@ +use std::fmt; + +use crate::crypto::hmac_sha256; + +pub const FLAG_KEYFRAME: u8 = 0x01; +pub const FLAG_AUDIO: u8 = 0x02; +pub const FLAG_END: u8 = 0x04; +pub const HEADER_LEN: usize = 13; +pub const MAC_LEN: usize = 4; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MediaPacket { + pub pts: u64, + pub flags: u8, + pub payload: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MediaError { + InvalidMac, + LengthMismatch, +} + +impl fmt::Display for MediaError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidMac => write!(formatter, "媒体包 MAC 校验失败"), + Self::LengthMismatch => write!(formatter, "媒体包长度字段与实际负载不一致"), + } + } +} + +impl std::error::Error for MediaError {} + +pub fn encode_media_packet(packet: &MediaPacket, session_key: &[u8; 32]) -> Vec { + let mut output = Vec::with_capacity(HEADER_LEN + packet.payload.len() + MAC_LEN); + output.extend_from_slice(&packet.pts.to_le_bytes()); + output.push(packet.flags); + output.extend_from_slice(&(packet.payload.len() as u32).to_le_bytes()); + output.extend_from_slice(&packet.payload); + let mac = hmac_sha256(session_key, &output[..HEADER_LEN + packet.payload.len()]); + output.extend_from_slice(&mac[..MAC_LEN]); + output +} + +pub fn decode_media_packet( + buffer: &[u8], + session_key: &[u8; 32], +) -> Result, MediaError> { + if buffer.len() < HEADER_LEN { + return Ok(None); + } + let pts = u64::from_le_bytes([ + buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7], + ]); + let flags = buffer[8]; + let declared = u32::from_le_bytes([buffer[9], buffer[10], buffer[11], buffer[12]]) as usize; + let total = HEADER_LEN + declared + MAC_LEN; + if buffer.len() < total { + return Ok(None); + } + let signed_part = &buffer[..HEADER_LEN + declared]; + let expected = hmac_sha256(session_key, signed_part); + if expected[..MAC_LEN] != buffer[HEADER_LEN + declared..total] { + return Err(MediaError::InvalidMac); + } + Ok(Some(( + MediaPacket { + pts, + flags, + payload: signed_part[HEADER_LEN..].to_vec(), + }, + total, + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packet_roundtrip_and_mac() { + let key = [7u8; 32]; + let packet = MediaPacket { + pts: 1234, + flags: FLAG_KEYFRAME, + payload: vec![1, 2, 3, 4], + }; + let bytes = encode_media_packet(&packet, &key); + let (decoded, consumed) = decode_media_packet(&bytes, &key).unwrap().unwrap(); + assert_eq!(decoded, packet); + assert_eq!(consumed, bytes.len()); + assert_eq!(decode_media_packet(&bytes, &[8u8; 32]), Err(MediaError::InvalidMac)); + } + + #[test] + fn incomplete_packet_waits() { + let key = [1u8; 32]; + let bytes = encode_media_packet( + &MediaPacket { + pts: 0, + flags: 0, + payload: vec![9; 32], + }, + &key, + ); + assert_eq!(decode_media_packet(&bytes[..20], &key).unwrap(), None); + } +} diff --git a/rust_core/src/media/renderer.rs b/rust_core/src/media/renderer.rs new file mode 100644 index 0000000..bb2f168 --- /dev/null +++ b/rust_core/src/media/renderer.rs @@ -0,0 +1,90 @@ +use std::collections::VecDeque; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PixelFormat { + Nv12, + Bgra8888, + Yuv420p, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecodedFrame { + pub pts: u64, + pub width: u32, + pub height: u32, + pub format: PixelFormat, + pub data: Vec, +} + +pub trait VideoRenderer: Send { + fn submit(&mut self, frame: DecodedFrame) -> Result<(), String>; + fn clear(&mut self); +} + +pub trait AudioSink: Send { + fn submit(&mut self, pcm: &[i16]) -> Result<(), String>; +} + +#[derive(Debug, Default)] +pub struct FrameQueue { + frames: VecDeque, + capacity: usize, +} + +impl FrameQueue { + pub fn new(capacity: usize) -> Self { + Self { + frames: VecDeque::new(), + capacity, + } + } + + pub fn len(&self) -> usize { + self.frames.len() + } + + pub fn is_empty(&self) -> bool { + self.frames.is_empty() + } + + pub fn pop_frame(&mut self) -> Option { + self.frames.pop_front() + } +} + +impl VideoRenderer for FrameQueue { + fn submit(&mut self, frame: DecodedFrame) -> Result<(), String> { + if self.capacity > 0 && self.frames.len() >= self.capacity { + self.frames.pop_front(); + } + self.frames.push_back(frame); + Ok(()) + } + + fn clear(&mut self) { + self.frames.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frame_queue_drops_oldest_frame() { + let mut queue = FrameQueue::new(2); + for pts in 0..3 { + queue + .submit(DecodedFrame { + pts, + width: 1920, + height: 1080, + format: PixelFormat::Nv12, + data: Vec::new(), + }) + .unwrap(); + } + assert_eq!(queue.len(), 2); + assert_eq!(queue.pop_frame().unwrap().pts, 1); + } +} diff --git a/rust_core/src/session/mod.rs b/rust_core/src/session/mod.rs new file mode 100644 index 0000000..0c6162b --- /dev/null +++ b/rust_core/src/session/mod.rs @@ -0,0 +1,7 @@ +pub mod pair; +pub mod state; +pub mod tls; + +pub use pair::PairingUri; +pub use state::{KeyExchange, SessionContext, SessionError, SessionKeys, SessionState}; +pub use tls::{PinnedTlsStream, TlsError}; diff --git a/rust_core/src/session/pair.rs b/rust_core/src/session/pair.rs new file mode 100644 index 0000000..2cb601a --- /dev/null +++ b/rust_core/src/session/pair.rs @@ -0,0 +1,98 @@ +use std::fmt; + +use crate::util::{url_decode, url_encode}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairingUri { + pub ip: String, + pub port: u16, + pub fingerprint: String, + pub name: Option, +} + +impl PairingUri { + pub fn new(ip: impl Into, port: u16, fingerprint: impl Into) -> Self { + Self { + ip: ip.into(), + port, + fingerprint: fingerprint.into(), + name: None, + } + } + + pub fn to_uri(&self) -> String { + let mut uri = format!( + "lancast://pair?ip={}&port={}&fp={}", + url_encode(&self.ip), + self.port, + url_encode(&self.fingerprint) + ); + if let Some(name) = &self.name { + uri.push_str(&format!("&name={}", url_encode(name))); + } + uri + } + + pub fn parse(input: &str) -> Result { + let rest = input + .strip_prefix("lancast://pair?") + .ok_or(PairError::InvalidScheme)?; + let mut ip = None; + let mut port = None; + let mut fingerprint = None; + let mut name = None; + for pair in rest.split('&') { + let (key, raw_value) = pair.split_once('=').ok_or(PairError::InvalidQuery)?; + let value = url_decode(raw_value).ok_or(PairError::InvalidEscape)?; + match key { + "ip" => ip = Some(value), + "port" => port = Some(value.parse::().map_err(|_| PairError::InvalidPort)?), + "fp" => fingerprint = Some(value), + "name" => name = Some(value), + _ => {} + } + } + Ok(Self { + ip: ip.ok_or(PairError::MissingField("ip"))?, + port: port.ok_or(PairError::MissingField("port"))?, + fingerprint: fingerprint.ok_or(PairError::MissingField("fp"))?, + name, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PairError { + InvalidScheme, + InvalidQuery, + InvalidEscape, + InvalidPort, + MissingField(&'static str), +} + +impl fmt::Display for PairError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidScheme => write!(formatter, "配对 URI 必须以 lancast://pair? 开头"), + Self::InvalidQuery => write!(formatter, "配对查询参数格式错误"), + Self::InvalidEscape => write!(formatter, "配对参数包含非法转义"), + Self::InvalidPort => write!(formatter, "配对端口无效"), + Self::MissingField(field) => write!(formatter, "配对 URI 缺少字段:{}", field), + } + } +} + +impl std::error::Error for PairError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pairing_uri_roundtrip() { + let mut uri = PairingUri::new("192.168.1.10", 41001, "sha256:ab12cd34"); + uri.name = Some("客厅 Pixel".to_string()); + let parsed = PairingUri::parse(&uri.to_uri()).unwrap(); + assert_eq!(parsed, uri); + } +} diff --git a/rust_core/src/session/state.rs b/rust_core/src/session/state.rs new file mode 100644 index 0000000..e4280ef --- /dev/null +++ b/rust_core/src/session/state.rs @@ -0,0 +1,165 @@ +use std::fmt; + +use crate::crypto::{derive_subkey, sha256, CryptoError, EphemeralKeyPair}; +use crate::util::hex_encode; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionState { + Disconnected, + TcpConnected, + TlsVerified, + KeyEstablished, + Secured, +} + +impl SessionState { + pub fn as_str(self) -> &'static str { + match self { + Self::Disconnected => "disconnected", + Self::TcpConnected => "tcp-connected", + Self::TlsVerified => "tls-verified", + Self::KeyEstablished => "key-established", + Self::Secured => "secured", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionKeys { + pub control: [u8; 32], + pub video: [u8; 32], + pub audio: [u8; 32], +} + +#[derive(Debug, Clone)] +pub struct SessionContext { + pub expected_fingerprint: String, + pub state: SessionState, +} + +impl SessionContext { + pub fn new(expected_fingerprint: impl Into) -> Self { + Self { + expected_fingerprint: expected_fingerprint.into(), + state: SessionState::Disconnected, + } + } + + pub fn verify_certificate_der(&self, certificate_der: &[u8]) -> Result<(), SessionError> { + let actual = hex_encode(&sha256(certificate_der)); + let expected = self + .expected_fingerprint + .trim_start_matches("sha256:") + .replace(':', "") + .to_ascii_lowercase(); + if expected.len() < 16 { + return Err(SessionError::FingerprintTooShort); + } + if actual.starts_with(&expected) { + Ok(()) + } else { + Err(SessionError::FingerprintMismatch) + } + } + + pub fn derive_keys(&self, shared_secret: &[u8]) -> Result { + Ok(SessionKeys { + control: derive_subkey(shared_secret, b"lancast/control/v1")?, + video: derive_subkey(shared_secret, b"lancast/video/v1")?, + audio: derive_subkey(shared_secret, b"lancast/audio/v1")?, + }) + } + + pub fn begin_ecdh(&self) -> Result { + Ok(EphemeralKeyPair::generate()?) + } + + pub fn complete_ecdh( + &self, + key_pair: EphemeralKeyPair, + peer_public: &[u8], + ) -> Result { + let shared = key_pair.into_shared_secret(peer_public)?; + self.derive_keys(&shared) + } + + pub fn advance(&mut self, next: SessionState) -> Result<(), SessionError> { + let valid = match (self.state, next) { + (SessionState::Disconnected, SessionState::TcpConnected) => true, + (SessionState::TcpConnected, SessionState::TlsVerified) => true, + (SessionState::TlsVerified, SessionState::KeyEstablished) => true, + (SessionState::KeyEstablished, SessionState::Secured) => true, + (current, SessionState::Disconnected) if current != SessionState::Disconnected => true, + _ => false, + }; + if valid { + self.state = next; + Ok(()) + } else { + Err(SessionError::InvalidTransition(self.state, next)) + } + } +} + +pub trait KeyExchange: Send { + fn shared_secret(&mut self) -> Result, SessionError>; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SessionError { + FingerprintTooShort, + FingerprintMismatch, + InvalidTransition(SessionState, SessionState), + KeyExchange(&'static str), + Crypto(CryptoError), +} + +impl From for SessionError { + fn from(error: CryptoError) -> Self { + Self::Crypto(error) + } +} + +impl fmt::Display for SessionError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::FingerprintTooShort => write!(formatter, "指纹至少需要 16 个十六进制字符"), + Self::FingerprintMismatch => write!(formatter, "证书指纹与配对记录不一致"), + Self::InvalidTransition(from, to) => { + write!(formatter, "非法会话状态迁移:{} -> {}", from.as_str(), to.as_str()) + } + Self::KeyExchange(reason) => write!(formatter, "密钥协商失败:{}", reason), + Self::Crypto(error) => write!(formatter, "密码学操作失败:{}", error), + } + } +} + +impl std::error::Error for SessionError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fingerprint_pinning() { + let der = b"mock certificate der"; + let fingerprint = hex_encode(&sha256(der)); + let context = SessionContext::new(format!("sha256:{}", &fingerprint[..16])); + assert!(context.verify_certificate_der(der).is_ok()); + assert_eq!( + context.verify_certificate_der(b"other"), + Err(SessionError::FingerprintMismatch) + ); + } + + #[test] + fn session_state_flow() { + let mut context = SessionContext::new("ab".repeat(16)); + context.advance(SessionState::TcpConnected).unwrap(); + context.advance(SessionState::TlsVerified).unwrap(); + context.advance(SessionState::KeyEstablished).unwrap(); + context.advance(SessionState::Secured).unwrap(); + assert_eq!(context.state, SessionState::Secured); + assert!(context.advance(SessionState::TlsVerified).is_err()); + } +} diff --git a/rust_core/src/session/tls.rs b/rust_core/src/session/tls.rs new file mode 100644 index 0000000..7baae4f --- /dev/null +++ b/rust_core/src/session/tls.rs @@ -0,0 +1,189 @@ +use std::fmt; +use std::io::{Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::sync::Arc; +use std::time::Duration; + +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::crypto::ring; +use rustls::crypto::{verify_tls12_signature, verify_tls13_signature, WebPkiSupportedAlgorithms}; +use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; +use rustls::{ClientConfig, ClientConnection, DigitallySignedStruct, Error as RustlsError, SignatureScheme, Stream}; + +use crate::crypto::sha256; +use crate::util::hex_encode; + +#[derive(Debug)] +pub enum TlsError { + Address(String), + Io(String), + Tls(String), + Fingerprint(String), +} + +impl fmt::Display for TlsError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Address(message) => write!(formatter, "地址无效:{}", message), + Self::Io(message) => write!(formatter, "TLS 连接 I/O 失败:{}", message), + Self::Tls(message) => write!(formatter, "TLS 握手失败:{}", message), + Self::Fingerprint(message) => write!(formatter, "证书指纹校验失败:{}", message), + } + } +} + +impl std::error::Error for TlsError {} + +impl From for TlsError { + fn from(error: std::io::Error) -> Self { + Self::Io(error.to_string()) + } +} + +impl From for TlsError { + fn from(error: RustlsError) -> Self { + Self::Tls(error.to_string()) + } +} + +#[derive(Debug)] +struct PinnedVerifier { + expected: String, + algorithms: WebPkiSupportedAlgorithms, +} + +impl PinnedVerifier { + fn new(expected: &str, algorithms: WebPkiSupportedAlgorithms) -> Self { + Self { + expected: normalize_fingerprint(expected), + algorithms, + } + } +} + +impl ServerCertVerifier for PinnedVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + let actual = hex_encode(&sha256(end_entity.as_ref())); + if self.expected.len() < 16 || !actual.starts_with(&self.expected) { + return Err(RustlsError::General("certificate fingerprint mismatch".to_string())); + } + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + verify_tls12_signature(message, cert, dss, &self.algorithms) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + verify_tls13_signature(message, cert, dss, &self.algorithms) + } + + fn supported_verify_schemes(&self) -> Vec { + self.algorithms.supported_schemes() + } +} + +fn normalize_fingerprint(value: &str) -> String { + value + .trim_start_matches("sha256:") + .replace(':', "") + .to_ascii_lowercase() +} + +pub struct PinnedTlsStream { + connection: ClientConnection, + socket: TcpStream, +} + +impl PinnedTlsStream { + pub fn connect( + host: &str, + port: u16, + expected_fingerprint: &str, + timeout: Duration, + ) -> Result { + let normalized = normalize_fingerprint(expected_fingerprint); + if normalized.len() < 16 || !normalized.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(TlsError::Fingerprint("指纹至少需要 16 位十六进制字符".to_string())); + } + + let address = (host, port) + .to_socket_addrs() + .map_err(|error| TlsError::Address(error.to_string()))? + .next() + .ok_or_else(|| TlsError::Address(host.to_string()))?; + let socket = TcpStream::connect_timeout(&address, timeout)?; + socket.set_read_timeout(Some(timeout))?; + socket.set_write_timeout(Some(timeout))?; + + let provider = Arc::new(ring::default_provider()); + let verifier = Arc::new(PinnedVerifier::new( + expected_fingerprint, + provider.signature_verification_algorithms.clone(), + )); + let config = ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions()? + .dangerous() + .with_custom_certificate_verifier(verifier) + .with_no_client_auth(); + let server_name = ServerName::try_from(host.to_string()) + .map_err(|error| TlsError::Address(error.to_string()))?; + let connection = ClientConnection::new(Arc::new(config), server_name)?; + Ok(Self { connection, socket }) + } + + pub fn complete_handshake(&mut self) -> Result<(), TlsError> { + while self.connection.is_handshaking() { + self.connection.complete_io(&mut self.socket)?; + } + Ok(()) + } + + pub fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { + let mut stream = Stream::new(&mut self.connection, &mut self.socket); + stream.read(buffer) + } + + pub fn write_all(&mut self, bytes: &[u8]) -> std::io::Result<()> { + let mut stream = Stream::new(&mut self.connection, &mut self.socket); + stream.write_all(bytes) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalize_sha256_fingerprint() { + assert_eq!( + normalize_fingerprint("sha256:AB:CD:ef"), + "abcdef" + ); + } + + #[test] + fn reject_short_fingerprint() { + assert!(matches!( + PinnedTlsStream::connect("127.0.0.1", 1, "abc", Duration::from_millis(10)), + Err(TlsError::Fingerprint(_)) + )); + } +} diff --git a/rust_core/src/util.rs b/rust_core/src/util.rs new file mode 100644 index 0000000..819dd57 --- /dev/null +++ b/rust_core/src/util.rs @@ -0,0 +1,84 @@ +const HEX: &[u8; 16] = b"0123456789abcdef"; + +pub fn hex_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +pub fn hex_decode(input: &str) -> Option> { + if input.len() % 2 != 0 { + return None; + } + let mut out = Vec::with_capacity(input.len() / 2); + let bytes = input.as_bytes(); + for pair in bytes.chunks_exact(2) { + let high = (pair[0] as char).to_digit(16)? as u8; + let low = (pair[1] as char).to_digit(16)? as u8; + out.push((high << 4) | low); + } + Some(out) +} + +pub fn url_encode(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for &byte in input.as_bytes() { + let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~'); + if unreserved { + out.push(byte as char); + } else { + out.push('%'); + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + } + out +} + +pub fn url_decode(input: &str) -> Option { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' => { + if index + 2 >= bytes.len() { + return None; + } + let high = (bytes[index + 1] as char).to_digit(16)? as u8; + let low = (bytes[index + 2] as char).to_digit(16)? as u8; + out.push((high << 4) | low); + index += 3; + } + b'+' => { + out.push(b' '); + index += 1; + } + other => { + out.push(other); + index += 1; + } + } + } + String::from_utf8(out).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hex_roundtrip() { + let bytes = [0xab, 0x12, 0x00, 0xff]; + assert_eq!(hex_decode(&hex_encode(&bytes)), Some(bytes.to_vec())); + } + + #[test] + fn url_roundtrip() { + let raw = "客厅 Pixel/1?fp=ab:12"; + assert_eq!(url_decode(&url_encode(raw)).as_deref(), Some(raw)); + } +} diff --git a/rust_core/tests/demo_e2e.rs b/rust_core/tests/demo_e2e.rs new file mode 100644 index 0000000..2a48075 --- /dev/null +++ b/rust_core/tests/demo_e2e.rs @@ -0,0 +1,100 @@ +//! 端到端 demo 的回环验证:模拟被控端走完整握手 + 加密控制帧 + 媒体包校验。 + +use std::io::{Read, Write}; +use std::net::{TcpStream, UdpSocket}; +use std::thread; +use std::time::Duration; + +use ttstdconnect_core::control::{ControlEvent, ControlEventKind, SecureControlChannel}; +use ttstdconnect_core::crypto::{derive_subkey, EphemeralKeyPair}; +use ttstdconnect_core::media::{encode_media_packet, MediaPacket, FLAG_AUDIO}; +use ttstdconnect_core::demo_server; + +const CONTROL_PORT: u16 = 44101; +const VIDEO_PORT: u16 = 44100; +const AUDIO_PORT: u16 = 44102; + +#[test] +fn demo_server_handshake_control_and_media_roundtrip() { + demo_server::start(CONTROL_PORT, VIDEO_PORT, AUDIO_PORT).expect("启动 demo 服务"); + thread::sleep(Duration::from_millis(100)); + + let receiver_pair = EphemeralKeyPair::generate().expect("生成被控端 ECDH 密钥"); + let receiver_public = receiver_pair.public_bytes().to_vec(); + + let mut control = TcpStream::connect(("127.0.0.1", CONTROL_PORT)).expect("连接 demo 服务"); + control + .set_read_timeout(Some(Duration::from_secs(2))) + .expect("设置超时"); + control.write_all(&receiver_public).expect("发送被控端公钥"); + + let mut sender_public = [0u8; 65]; + control.read_exact(&mut sender_public).expect("读取主控端公钥"); + let shared = receiver_pair + .into_shared_secret(&sender_public) + .expect("ECDH 协商成功"); + let control_key = derive_subkey(&shared, b"lancast/control/v1").expect("派生控制密钥"); + let video_key = derive_subkey(&shared, b"lancast/video/v1").expect("派生视频密钥"); + let audio_key = derive_subkey(&shared, b"lancast/audio/v1").expect("派生音频密钥"); + + let channel = SecureControlChannel::new(control_key); + let ping = ControlEvent::new(1, ControlEventKind::Ping(1234)); + let frame = channel.encode(&ping).expect("加密 Ping 帧"); + control.write_all(&frame).expect("发送加密控制帧"); + + let mut echoed = [0u8; 512]; + let size = match control.read(&mut echoed) { + Ok(size) => size, + Err(error) => panic!( + "读取 Pong 帧失败: {}; 服务状态: {}", + error, + demo_server::status().to_json() + ), + }; + let (pong, _) = channel + .decode(&echoed[..size]) + .expect("解密 Pong 帧") + .expect("完整的 Pong 帧"); + assert_eq!(pong.sequence(), 1); + assert!(matches!(pong.kind, ControlEventKind::Pong(1234))); + + let video = UdpSocket::bind("127.0.0.1:0").expect("创建视频 UDP"); + let video_packet = encode_media_packet( + &MediaPacket { + pts: 42, + flags: 1, + payload: vec![1, 2, 3, 4], + }, + &video_key, + ); + video + .send_to(&video_packet, ("127.0.0.1", VIDEO_PORT)) + .expect("发送视频包"); + + let audio = UdpSocket::bind("127.0.0.1:0").expect("创建音频 UDP"); + let audio_packet = encode_media_packet( + &MediaPacket { + pts: 7, + flags: FLAG_AUDIO, + payload: vec![9, 8, 7], + }, + &audio_key, + ); + audio + .send_to(&audio_packet, ("127.0.0.1", AUDIO_PORT)) + .expect("发送音频包"); + + thread::sleep(Duration::from_millis(300)); + let status = demo_server::status(); + assert!(status.running, "服务应处于运行状态"); + assert!(status.key_established, "ECDH 密钥应已建立"); + assert!(!status.control_key_prefix.is_empty(), "控制密钥前缀应可见"); + + let events = status.events.join("|"); + assert!(events.contains("key-established"), "应记录密钥建立事件: {}", events); + assert!(events.contains("control:seq=1"), "应记录控制帧事件: {}", events); + assert!(events.contains("video:pts=42"), "应记录视频包事件: {}", events); + assert!(events.contains("audio:pts=7"), "应记录音频包事件: {}", events); + + demo_server::stop(); +} diff --git a/rust_core/tests/protocol.rs b/rust_core/tests/protocol.rs new file mode 100644 index 0000000..95aaf52 --- /dev/null +++ b/rust_core/tests/protocol.rs @@ -0,0 +1,105 @@ +use std::collections::HashMap; +use std::time::Duration; + +use ttstdconnect_core::connection::{ConnectionEvent, ConnectionPhase, ConnectionStateMachine}; +use ttstdconnect_core::control::{ + BinaryCodec, ControlEvent, ControlEventKind, ControlFrameCodec, MouseAction, MouseEvent, +}; +use ttstdconnect_core::crypto::sha256; +use ttstdconnect_core::discovery::{DeviceInfo, MdnsTxt, StaticDiscovery, DeviceDiscovery}; +use ttstdconnect_core::file::{FileMeta, PrepareResponse, TransferSession}; +use ttstdconnect_core::media::{encode_media_packet, decode_media_packet, MediaPacket}; +use ttstdconnect_core::session::SessionContext; +use ttstdconnect_core::util::hex_encode; + +fn sample_device() -> DeviceInfo { + DeviceInfo { + device_id: "device-1".into(), + name: "客厅 Pixel".into(), + ip: "192.168.1.10".into(), + media_port: 41000, + control_port: 41001, + fingerprint: "sha256:ab12cd34".into(), + capabilities: vec!["h264".into(), "opus".into(), "file".into()], + model: "Pixel8".into(), + resolution: "1920x1080".into(), + signaling_url: None, + } +} + +#[test] +fn control_frame_binary_roundtrip() { + let codec = BinaryCodec; + let event = ControlEvent::new( + 42, + ControlEventKind::Mouse(MouseEvent { + action: MouseAction::Move, + x: 960, + y: 540, + buttons: 0, + }), + ); + let bytes = codec.encode(&event); + assert_eq!(bytes.len(), 14); + let (decoded, consumed) = codec.decode(&bytes).unwrap().expect("一帧完整控制消息"); + assert_eq!(decoded, event); + assert_eq!(consumed, 14); +} + +#[test] +fn discovery_and_state_machine_fallback() { + let txt = MdnsTxt::new("sha256:ab12cd34", &["h264", "file"]); + let device = txt.clone().into_device("device-1".into(), "192.168.1.10".into(), 41001, 41000); + assert_eq!(txt.to_records().len(), 7); + + let mut discovery = StaticDiscovery::new(vec![device]); + assert_eq!(discovery.browse(Duration::from_secs(3)).unwrap().len(), 1); + + let mut machine = ConnectionStateMachine::new(); + machine.apply(ConnectionEvent::Start).unwrap(); + machine.apply(ConnectionEvent::MdnsTimeout).unwrap(); + assert_eq!(machine.phase(), ConnectionPhase::Registering); + machine + .apply(ConnectionEvent::SignalingDevices(vec![sample_device()])) + .unwrap(); + machine.apply(ConnectionEvent::ProbeFailed).unwrap(); + assert_eq!(machine.phase(), ConnectionPhase::Relaying); + machine.apply(ConnectionEvent::DirectUpgraded).unwrap(); + assert_eq!(machine.phase(), ConnectionPhase::Direct); +} + +#[test] +fn session_fingerprint_and_media_key() { + let certificate = b"mock der"; + let fingerprint = hex_encode(&sha256(certificate)); + let context = SessionContext::new(&fingerprint); + assert!(context.verify_certificate_der(certificate).is_ok()); + let keys = context.derive_keys(b"shared secret").unwrap(); + let packet = MediaPacket { + pts: 99, + flags: 1, + payload: vec![1, 2, 3], + }; + let encoded = encode_media_packet(&packet, &keys.video); + assert_eq!(decode_media_packet(&encoded, &keys.video).unwrap().unwrap().0, packet); +} + +#[test] +fn file_transfer_tracks_offsets() { + let response = PrepareResponse { + session_id: "s-1".into(), + tokens: HashMap::from([("f1".into(), "token".into())]), + rejected: vec![], + }; + let file = FileMeta { + id: "f1".into(), + name: "a.bin".into(), + size: 5, + mime: "application/octet-stream".into(), + sha256: "hash".into(), + }; + let mut transfer = TransferSession::start(response, vec![file]); + let query = transfer.next_chunk(2).expect("有待传分片"); + transfer.on_ack(&query, 2); + assert_eq!(transfer.next_chunk(2).unwrap().offset, 2); +} diff --git a/signaling_server/go.mod b/signaling_server/go.mod new file mode 100644 index 0000000..d690045 --- /dev/null +++ b/signaling_server/go.mod @@ -0,0 +1,3 @@ +module ttstdconnect/signaling + +go 1.26 diff --git a/signaling_server/internal/httpapi/handler.go b/signaling_server/internal/httpapi/handler.go new file mode 100644 index 0000000..194430a --- /dev/null +++ b/signaling_server/internal/httpapi/handler.go @@ -0,0 +1,197 @@ +package httpapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "time" + + "ttstdconnect/signaling/internal/registry" + "ttstdconnect/signaling/internal/relay" + "ttstdconnect/signaling/internal/websocket" +) + +type Handler struct { + registry *registry.Registry + relay *relay.Relay +} + +func NewHandler(reg *registry.Registry, relayStore *relay.Relay) http.Handler { + return &Handler{registry: reg, relay: relayStore} +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + + switch { + case r.URL.Path == "/healthz" && r.Method == http.MethodGet: + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) + case r.URL.Path == "/register" && r.Method == http.MethodPost: + h.register(w, r) + case r.URL.Path == "/heartbeat" && r.Method == http.MethodPost: + h.heartbeat(w, r) + case r.URL.Path == "/unregister" && r.Method == http.MethodPost: + h.unregister(w, r) + case r.URL.Path == "/list" && r.Method == http.MethodGet: + writeJSON(w, http.StatusOK, map[string]any{"devices": h.registry.List()}) + case r.URL.Path == "/watch" && r.Method == http.MethodGet: + h.watch(w, r) + case r.URL.Path == "/relay" && r.Method == http.MethodPost: + h.sendRelay(w, r) + case r.URL.Path == "/relay/poll" && r.Method == http.MethodGet: + h.pollRelay(w, r) + default: + writeJSON(w, http.StatusNotFound, map[string]any{"ok": false, "error": "未知端点"}) + } +} + +func (h *Handler) register(w http.ResponseWriter, r *http.Request) { + var device registry.Device + if err := decodeJSON(r, &device); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + stored, err := h.registry.Register(device) + if err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "device": stored}) +} + +func (h *Handler) heartbeat(w http.ResponseWriter, r *http.Request) { + var request struct { + DeviceID string `json:"deviceId"` + } + if err := decodeJSON(r, &request); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + if !h.registry.Heartbeat(request.DeviceID) { + writeError(w, http.StatusNotFound, fmt.Errorf("设备 %s 未注册", request.DeviceID)) + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (h *Handler) unregister(w http.ResponseWriter, r *http.Request) { + var request struct { + DeviceID string `json:"deviceId"` + } + if err := decodeJSON(r, &request); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + h.registry.Unregister(request.DeviceID) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (h *Handler) sendRelay(w http.ResponseWriter, r *http.Request) { + var request struct { + From string `json:"from"` + To string `json:"to"` + Payload json.RawMessage `json:"payload"` + } + if err := decodeJSON(r, &request); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + if _, ok := h.registry.Get(request.To); !ok { + writeError(w, http.StatusNotFound, fmt.Errorf("目标设备 %s 不在线", request.To)) + return + } + if err := h.relay.Send(request.From, request.To, request.Payload); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (h *Handler) pollRelay(w http.ResponseWriter, r *http.Request) { + deviceID := r.URL.Query().Get("deviceId") + if deviceID == "" { + writeError(w, http.StatusBadRequest, fmt.Errorf("缺少 deviceId")) + return + } + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + messages := h.relay.Poll(deviceID, limit) + writeJSON(w, http.StatusOK, map[string]any{"messages": messages}) +} + +func (h *Handler) watch(w http.ResponseWriter, r *http.Request) { + conn, reader, err := websocket.Upgrade(w, r) + if err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + defer conn.Close() + + events, unsubscribe := h.registry.Subscribe() + defer unsubscribe() + + snapshot := map[string]any{"event": "snapshot", "devices": h.registry.List()} + if err := websocket.WriteText(conn, mustJSON(snapshot)); err != nil { + return + } + + done := make(chan struct{}) + go func() { + defer close(done) + for { + if _, err := websocket.ReadText(reader); err != nil { + return + } + } + }() + + ticker := time.NewTicker(25 * time.Second) + defer ticker.Stop() + for { + select { + case event := <-events: + if err := websocket.WriteText(conn, mustJSON(event)); err != nil { + return + } + case <-ticker.C: + if err := websocket.WritePing(conn); err != nil { + return + } + case <-done: + return + } + } +} + +func decodeJSON(r *http.Request, target any) error { + decoder := json.NewDecoder(http.MaxBytesReader(nil, r.Body, 1<<20)) + if err := decoder.Decode(target); err != nil { + return fmt.Errorf("请求 JSON 无效:%w", err) + } + return nil +} + +func mustJSON(value any) string { + bytes, err := json.Marshal(value) + if err != nil { + return "{}" + } + return string(bytes) +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, err error) { + writeJSON(w, status, map[string]any{"ok": false, "error": err.Error()}) +} diff --git a/signaling_server/internal/httpapi/handler_test.go b/signaling_server/internal/httpapi/handler_test.go new file mode 100644 index 0000000..fad4e9b --- /dev/null +++ b/signaling_server/internal/httpapi/handler_test.go @@ -0,0 +1,131 @@ +package httpapi + +import ( + "bufio" + "encoding/base64" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "ttstdconnect/signaling/internal/registry" + "ttstdconnect/signaling/internal/relay" + "ttstdconnect/signaling/internal/websocket" +) + +const samplePayload = `{"deviceId":"a","name":"客厅Pixel","ip":"192.168.1.10","mediaPort":41000,"controlPort":41001,"fp":"sha256:ab12","cap":["h264","file"]}` + +func postJSON(t *testing.T, url, body string) map[string]any { + t.Helper() + response, err := http.Post(url, "application/json", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var result map[string]any + if err := json.NewDecoder(response.Body).Decode(&result); err != nil { + t.Fatal(err) + } + return result +} + +func TestRegisterListHeartbeatAndRelay(t *testing.T) { + reg := registry.New(45 * time.Second) + server := httptest.NewServer(NewHandler(reg, relay.New())) + defer server.Close() + + result := postJSON(t, server.URL+"/register", samplePayload) + if result["ok"] != true { + t.Fatalf("注册失败: %+v", result) + } + + response, err := http.Get(server.URL + "/list") + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var list struct { + Devices []registry.Device `json:"devices"` + } + if err := json.NewDecoder(response.Body).Decode(&list); err != nil { + t.Fatal(err) + } + if len(list.Devices) != 1 || list.Devices[0].DeviceID != "a" { + t.Fatalf("列表异常: %+v", list.Devices) + } + + if result = postJSON(t, server.URL+"/heartbeat", `{"deviceId":"a"}`); result["ok"] != true { + t.Fatalf("心跳失败: %+v", result) + } + + relayPayload := `{"from":"b","to":"a","payload":{"type":"offer"}}` + if result = postJSON(t, server.URL+"/relay", relayPayload); result["ok"] != true { + t.Fatalf("relay 失败: %+v", result) + } + response, err = http.Get(server.URL + "/relay/poll?deviceId=a") + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var polled struct { + Messages []map[string]any `json:"messages"` + } + if err := json.NewDecoder(response.Body).Decode(&polled); err != nil { + t.Fatal(err) + } + if len(polled.Messages) != 1 { + t.Fatalf("期望 1 条中转消息,实际 %+v", polled.Messages) + } +} + +func TestWatchReceivesSnapshotAndOnlineEvent(t *testing.T) { + reg := registry.New(45 * time.Second) + server := httptest.NewServer(NewHandler(reg, relay.New())) + defer server.Close() + + host := server.Listener.Addr().String() + conn, err := net.Dial("tcp", host) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + key := base64.StdEncoding.EncodeToString([]byte("unit-test-key")) + request := fmt.Sprintf("GET /watch HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n", host, key) + if _, err := conn.Write([]byte(request)); err != nil { + t.Fatal(err) + } + reader := bufio.NewReader(conn) + for { + line, err := reader.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" { + break + } + } + + snapshot, err := websocket.ReadText(reader) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(snapshot, `"snapshot"`) { + t.Fatalf("首帧应为 snapshot,实际 %s", snapshot) + } + + if result := postJSON(t, server.URL+"/register", samplePayload); result["ok"] != true { + t.Fatalf("注册失败: %+v", result) + } + event, err := websocket.ReadText(reader) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(event, `"online"`) { + t.Fatalf("应收到 online 事件,实际 %s", event) + } +} diff --git a/signaling_server/internal/registry/registry.go b/signaling_server/internal/registry/registry.go new file mode 100644 index 0000000..c0a29db --- /dev/null +++ b/signaling_server/internal/registry/registry.go @@ -0,0 +1,195 @@ +package registry + +import ( + "context" + "fmt" + "sort" + "strings" + "sync" + "time" +) + +type Device struct { + DeviceID string `json:"deviceId"` + Name string `json:"name"` + IP string `json:"ip"` + MediaPort int `json:"mediaPort"` + ControlPort int `json:"controlPort"` + FP string `json:"fp"` + Cap []string `json:"cap"` + TTL int `json:"ttl,omitempty"` + Model string `json:"model,omitempty"` + Res string `json:"res,omitempty"` + Sig string `json:"sig,omitempty"` + LastSeen time.Time `json:"-"` +} + +type Event struct { + Event string `json:"event"` + DeviceID string `json:"deviceId"` + Device *Device `json:"device,omitempty"` +} + +type Registry struct { + mu sync.RWMutex + devices map[string]Device + subscribers map[chan Event]struct{} + expiry time.Duration + now func() time.Time +} + +func New(expiry time.Duration) *Registry { + if expiry <= 0 { + expiry = 45 * time.Second + } + return &Registry{ + devices: make(map[string]Device), + subscribers: make(map[chan Event]struct{}), + expiry: expiry, + now: time.Now, + } +} + +func (r *Registry) Register(device Device) (Device, error) { + if err := validate(device); err != nil { + return Device{}, err + } + device.Cap = append([]string(nil), device.Cap...) + if device.TTL <= 0 { + device.TTL = 30 + } + device.LastSeen = r.now() + + r.mu.Lock() + defer r.mu.Unlock() + _, existed := r.devices[device.DeviceID] + r.devices[device.DeviceID] = device + eventType := "online" + if existed { + eventType = "heartbeat" + } + stored := device + r.notifyLocked(Event{Event: eventType, DeviceID: device.DeviceID, Device: &stored}) + return stored, nil +} + +func (r *Registry) Heartbeat(deviceID string) bool { + r.mu.Lock() + defer r.mu.Unlock() + device, ok := r.devices[deviceID] + if !ok { + return false + } + if r.expired(device) { + delete(r.devices, deviceID) + r.notifyLocked(Event{Event: "offline", DeviceID: deviceID}) + return false + } + device.LastSeen = r.now() + r.devices[deviceID] = device + r.notifyLocked(Event{Event: "heartbeat", DeviceID: deviceID}) + return true +} + +func (r *Registry) Unregister(deviceID string) { + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.devices[deviceID]; !ok { + return + } + delete(r.devices, deviceID) + r.notifyLocked(Event{Event: "offline", DeviceID: deviceID}) +} + +func (r *Registry) Get(deviceID string) (Device, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + device, ok := r.devices[deviceID] + return device, ok +} + +func (r *Registry) List() []Device { + r.mu.Lock() + defer r.mu.Unlock() + r.purgeLocked() + devices := make([]Device, 0, len(r.devices)) + for _, device := range r.devices { + device.Cap = append([]string(nil), device.Cap...) + devices = append(devices, device) + } + sort.Slice(devices, func(i, j int) bool { + return devices[i].DeviceID < devices[j].DeviceID + }) + return devices +} + +func (r *Registry) Subscribe() (chan Event, func()) { + events := make(chan Event, 16) + r.mu.Lock() + r.subscribers[events] = struct{}{} + r.mu.Unlock() + return events, func() { + r.mu.Lock() + if _, ok := r.subscribers[events]; ok { + delete(r.subscribers, events) + close(events) + } + r.mu.Unlock() + } +} + +func (r *Registry) StartJanitor(ctx context.Context, interval time.Duration) { + if interval <= 0 { + interval = 5 * time.Second + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + r.mu.Lock() + r.purgeLocked() + r.mu.Unlock() + } + } +} + +func (r *Registry) expired(device Device) bool { + return r.now().Sub(device.LastSeen) > r.expiry +} + +func (r *Registry) purgeLocked() { + for id, device := range r.devices { + if r.expired(device) { + delete(r.devices, id) + r.notifyLocked(Event{Event: "offline", DeviceID: id}) + } + } +} + +func (r *Registry) notifyLocked(event Event) { + for subscriber := range r.subscribers { + select { + case subscriber <- event: + default: + } + } +} + +func validate(device Device) error { + if strings.TrimSpace(device.DeviceID) == "" { + return fmt.Errorf("deviceId 不能为空") + } + if strings.TrimSpace(device.IP) == "" { + return fmt.Errorf("ip 不能为空") + } + if device.MediaPort < 1 || device.MediaPort > 65535 { + return fmt.Errorf("mediaPort 超出范围") + } + if device.ControlPort < 1 || device.ControlPort > 65535 { + return fmt.Errorf("controlPort 超出范围") + } + return nil +} diff --git a/signaling_server/internal/registry/registry_test.go b/signaling_server/internal/registry/registry_test.go new file mode 100644 index 0000000..f6a7704 --- /dev/null +++ b/signaling_server/internal/registry/registry_test.go @@ -0,0 +1,75 @@ +package registry + +import ( + "testing" + "time" +) + +func sampleDevice(id string) Device { + return Device{ + DeviceID: id, + Name: "Pixel", + IP: "192.168.1.10", + MediaPort: 41000, + ControlPort: 41001, + FP: "sha256:ab12", + Cap: []string{"h264", "file"}, + } +} + +func TestRegisterAndList(t *testing.T) { + reg := New(45 * time.Second) + if _, err := reg.Register(sampleDevice("a")); err != nil { + t.Fatalf("register: %v", err) + } + if _, err := reg.Register(sampleDevice("b")); err != nil { + t.Fatalf("register: %v", err) + } + devices := reg.List() + if len(devices) != 2 { + t.Fatalf("期望 2 台设备,实际 %d", len(devices)) + } + if devices[0].DeviceID != "a" { + t.Fatalf("列表未按 deviceId 排序: %+v", devices) + } +} + +func TestHeartbeatAndExpiry(t *testing.T) { + now := time.Now() + reg := New(10 * time.Second) + reg.now = func() time.Time { return now } + + events, unsubscribe := reg.Subscribe() + defer unsubscribe() + if _, err := reg.Register(sampleDevice("a")); err != nil { + t.Fatal(err) + } + if event := <-events; event.Event != "online" { + t.Fatalf("期望 online,实际 %s", event.Event) + } + + now = now.Add(8 * time.Second) + if !reg.Heartbeat("a") { + t.Fatal("心跳应成功") + } + if event := <-events; event.Event != "heartbeat" { + t.Fatalf("期望 heartbeat,实际 %s", event.Event) + } + + now = now.Add(11 * time.Second) + if devices := reg.List(); len(devices) != 0 { + t.Fatalf("过期设备应被摘除,实际 %+v", devices) + } + if event := <-events; event.Event != "offline" { + t.Fatalf("期望 offline,实际 %s", event.Event) + } +} + +func TestRejectInvalidDevice(t *testing.T) { + reg := New(time.Minute) + device := sampleDevice("a") + device.MediaPort = 0 + if _, err := reg.Register(device); err == nil { + t.Fatal("非法端口应被拒绝") + } +} diff --git a/signaling_server/internal/relay/relay.go b/signaling_server/internal/relay/relay.go new file mode 100644 index 0000000..d19dc0d --- /dev/null +++ b/signaling_server/internal/relay/relay.go @@ -0,0 +1,101 @@ +package relay + +import ( + "encoding/json" + "errors" + "sync" + "time" +) + +type Message struct { + From string `json:"from"` + To string `json:"to"` + Payload json.RawMessage `json:"payload"` + CreatedAt time.Time `json:"createdAt"` +} + +type Relay struct { + mu sync.Mutex + queues map[string][]Message + max int + expiry time.Duration + now func() time.Time +} + +func New() *Relay { + return &Relay{ + queues: make(map[string][]Message), + max: 256, + expiry: 5 * time.Minute, + now: time.Now, + } +} + +func (r *Relay) Send(from, to string, payload json.RawMessage) error { + if to == "" { + return errors.New("目标设备不能为空") + } + if len(payload) == 0 || string(payload) == "null" { + return errors.New("中转内容不能为空") + } + message := Message{ + From: from, + To: to, + Payload: append(json.RawMessage(nil), payload...), + CreatedAt: r.now(), + } + + r.mu.Lock() + defer r.mu.Unlock() + r.pruneLocked(to) + queue := append(r.queues[to], message) + if len(queue) > r.max { + queue = queue[len(queue)-r.max:] + } + r.queues[to] = queue + return nil +} + +func (r *Relay) Poll(to string, limit int) []Message { + if limit <= 0 || limit > 100 { + limit = 20 + } + r.mu.Lock() + defer r.mu.Unlock() + r.pruneLocked(to) + queue := r.queues[to] + if len(queue) == 0 { + return []Message{} + } + if len(queue) > limit { + queue = queue[:limit] + } + messages := append([]Message(nil), queue...) + r.queues[to] = r.queues[to][len(messages):] + return messages +} + +func (r *Relay) Size(to string) int { + r.mu.Lock() + defer r.mu.Unlock() + r.pruneLocked(to) + return len(r.queues[to]) +} + +func (r *Relay) pruneLocked(to string) { + queue := r.queues[to] + if len(queue) == 0 { + return + } + kept := queue[:0] + for _, message := range queue { + if r.now().Sub(message.CreatedAt) <= r.expiry { + kept = append(kept, message) + } + } + if len(kept) == 0 { + delete(r.queues, to) + } else { + r.queues[to] = kept + } +} diff --git a/signaling_server/internal/relay/relay_test.go b/signaling_server/internal/relay/relay_test.go new file mode 100644 index 0000000..79dc89b --- /dev/null +++ b/signaling_server/internal/relay/relay_test.go @@ -0,0 +1,40 @@ +package relay + +import ( + "encoding/json" + "testing" + "time" +) + +func TestSendAndPoll(t *testing.T) { + store := New() + if err := store.Send("a", "b", json.RawMessage(`{"type":"offer"}`)); err != nil { + t.Fatal(err) + } + if err := store.Send("a", "b", json.RawMessage(`{"type":"candidate"}`)); err != nil { + t.Fatal(err) + } + messages := store.Poll("b", 10) + if len(messages) != 2 { + t.Fatalf("期望 2 条消息,实际 %d", len(messages)) + } + if string(messages[0].Payload) != `{"type":"offer"}` { + t.Fatalf("消息顺序错误: %s", messages[0].Payload) + } + if store.Size("b") != 0 { + t.Fatal("Poll 后队列应清空") + } +} + +func TestExpiredMessagesAreDropped(t *testing.T) { + store := New() + now := time.Now() + store.now = func() time.Time { return now } + if err := store.Send("a", "b", json.RawMessage(`1`)); err != nil { + t.Fatal(err) + } + now = now.Add(6 * time.Minute) + if messages := store.Poll("b", 10); len(messages) != 0 { + t.Fatalf("过期消息应被丢弃,实际 %+v", messages) + } +} diff --git a/signaling_server/internal/websocket/websocket.go b/signaling_server/internal/websocket/websocket.go new file mode 100644 index 0000000..1e06f80 --- /dev/null +++ b/signaling_server/internal/websocket/websocket.go @@ -0,0 +1,136 @@ +package websocket + +import ( + "bufio" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "strings" +) + +const websocketMagic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +func Upgrade(w http.ResponseWriter, r *http.Request) (net.Conn, *bufio.Reader, error) { + if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") || + !strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade") { + return nil, nil, errors.New("请求不是 WebSocket 升级请求") + } + key := r.Header.Get("Sec-WebSocket-Key") + if key == "" { + return nil, nil, errors.New("缺少 Sec-WebSocket-Key") + } + if r.Header.Get("Sec-WebSocket-Version") != "13" { + return nil, nil, errors.New("仅支持 WebSocket 版本 13") + } + hijacker, ok := w.(http.Hijacker) + if !ok { + return nil, nil, errors.New("当前响应器不支持连接劫持") + } + conn, buffer, err := hijacker.Hijack() + if err != nil { + return nil, nil, err + } + sum := sha1.Sum([]byte(key + websocketMagic)) + accept := base64.StdEncoding.EncodeToString(sum[:]) + response := "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + accept + "\r\n\r\n" + if _, err := conn.Write([]byte(response)); err != nil { + conn.Close() + return nil, nil, err + } + return conn, buffer.Reader, nil +} + +func WriteText(conn net.Conn, text string) error { + return writeFrame(conn, 0x81, []byte(text)) +} + +func WritePing(conn net.Conn) error { + return writeFrame(conn, 0x89, nil) +} + +func writeFrame(conn net.Conn, opcode byte, payload []byte) error { + header := []byte{opcode} + switch size := len(payload); { + case size < 126: + header = append(header, byte(size)) + case size <= 0xffff: + header = append(header, 126, 0, 0) + binary.BigEndian.PutUint16(header[2:], uint16(size)) + default: + header = append(header, 127, 0, 0, 0, 0, 0, 0, 0, 0) + binary.BigEndian.PutUint64(header[2:], uint64(size)) + } + if _, err := conn.Write(append(header, payload...)); err != nil { + return err + } + return nil +} + +func ReadText(reader *bufio.Reader) (string, error) { + for { + first, err := reader.ReadByte() + if err != nil { + return "", err + } + fin := first&0x80 != 0 + opcode := first & 0x0f + second, err := reader.ReadByte() + if err != nil { + return "", err + } + masked := second&0x80 != 0 + length := uint64(second & 0x7f) + if length == 126 { + var raw [2]byte + if _, err := io.ReadFull(reader, raw[:]); err != nil { + return "", err + } + length = uint64(binary.BigEndian.Uint16(raw[:])) + } else if length == 127 { + var raw [8]byte + if _, err := io.ReadFull(reader, raw[:]); err != nil { + return "", err + } + length = binary.BigEndian.Uint64(raw[:]) + } + var mask [4]byte + if masked { + if _, err := io.ReadFull(reader, mask[:]); err != nil { + return "", err + } + } + if length > 8<<20 { + return "", fmt.Errorf("WebSocket 帧过大:%d", length) + } + payload := make([]byte, length) + if _, err := io.ReadFull(reader, payload); err != nil { + return "", err + } + if masked { + for index := range payload { + payload[index] ^= mask[index%4] + } + } + switch opcode { + case 0x1: + if !fin { + return "", errors.New("暂不支持分片文本帧") + } + return string(payload), nil + case 0x8: + return "", io.EOF + case 0x9, 0xa: + continue + default: + continue + } + } +} diff --git a/signaling_server/internal/websocket/websocket_test.go b/signaling_server/internal/websocket/websocket_test.go new file mode 100644 index 0000000..89b58f7 --- /dev/null +++ b/signaling_server/internal/websocket/websocket_test.go @@ -0,0 +1,26 @@ +package websocket + +import ( + "bufio" + "net" + "testing" +) + +func TestWriteAndReadTextFrame(t *testing.T) { + left, right := net.Pipe() + defer left.Close() + defer right.Close() + + payload := `{"event":"online","deviceId":"a"}` + go func() { + _ = WriteText(left, payload) + }() + + received, err := ReadText(bufio.NewReader(right)) + if err != nil { + t.Fatal(err) + } + if received != payload { + t.Fatalf("期望 %s,实际 %s", payload, received) + } +} diff --git a/signaling_server/main.go b/signaling_server/main.go new file mode 100644 index 0000000..b34de77 --- /dev/null +++ b/signaling_server/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "time" + + "ttstdconnect/signaling/internal/httpapi" + "ttstdconnect/signaling/internal/registry" + "ttstdconnect/signaling/internal/relay" +) + +func main() { + reg := registry.New(45 * time.Second) + relayStore := relay.New() + + address := os.Getenv("LISTEN_ADDR") + if address == "" { + address = ":8080" + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + go reg.StartJanitor(ctx, 5*time.Second) + + server := &http.Server{ + Addr: address, + Handler: httpapi.NewHandler(reg, relayStore), + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 0, + IdleTimeout: 60 * time.Second, + } + + log.Printf("TTSTDConnect 信令服务器监听 %s", address) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatal(err) + } +}