Compare commits

...

145 Commits

Author SHA1 Message Date
mofeng-git
198552014b chore: bump version to v0.2.2 2026-05-24 14:04:03 +00:00
mofeng-git
3e3937605e fix:修复在线升级错误 2026-05-24 14:03:49 +00:00
mofeng-git
4a85fbfab8 ci: 统一 Android APK 产物命名 2026-05-24 13:21:34 +00:00
mofeng-git
87d1110a87 ci: 调整 GitHub Actions 构建与发布流程 2026-05-24 09:58:30 +00:00
mofeng-git
b31aae284d feat: 新增安卓平台支持 2026-05-24 09:44:41 +00:00
mofeng-git
dc6475776e fix: 修复 rtsp 和 RustDesk 扩展启停错误;修改部分参数描述文本 2026-05-23 15:16:39 +00:00
mofeng-git
3de72677e6 fix: 优化 RustDesk 中继服务器推导策略;修复鼠键输入异常 2026-05-23 12:21:13 +00:00
mofeng-git
6a1616c32a chore: vendor trimmed v4l2r capture crate 2026-05-23 02:36:40 +00:00
mofeng-git
032f47a891 fix: 完善晶晨视频设备探测逻辑,避免内核缺陷引起软件崩溃 #262 2026-05-21 14:45:47 +00:00
mofeng-git
2e0ca89943 chore: bump version to v0.2.1 2026-05-20 00:09:31 +08:00
mofeng-git
1f7cfb373c fix: 修复设置页滚动和 HID 继电器识别 #252 2026-05-19 22:17:50 +08:00
mofeng-git
da05656a89 fix(web): 设置页按菜单加载并优化错误提示 2026-05-19 21:38:56 +08:00
mofeng-git
265852b312 fix: 避免 CH9329 配置保存时误触发 OTG reconcile 2026-05-19 20:50:33 +08:00
mofeng-git
02bf04ed7f fix: 修复 MSD 状态卡片 i18n 键名 2026-05-19 20:44:12 +08:00
mofeng-git
8915d36bcf fix: 升级 Vite、Rollup、PostCSS 等依赖清除 Github 安全漏洞提示 2026-05-19 11:45:45 +00:00
mofeng-git
3ea15e37a4 feat: 增加 CHINAMIRRO 构建环境变量 2026-05-19 11:22:04 +00:00
mofeng-git
cb0c66af96 ci: 调整 GitHub Actions 构建与发布流程 2026-05-19 18:01:53 +08:00
SilentWind
a3ebcded34 Merge pull request #261 from fcsha/fix/issue-260-msd-endpoint-budget
fix: 关闭 MSD 后保存 HID 配置时端点预算校验误判超限
2026-05-19 09:58:03 +08:00
mofeng-git
f7c2cd1b90 ci: 支持 GitHub Actions 构建 2026-05-19 09:54:54 +08:00
mofeng-git
e774210ae3 fix: 修复构建错误并清理未使用导入 2026-05-18 15:23:42 +00:00
mofeng-git
935fa823f2 feat: 初步增加 Windows 支持 2026-05-18 22:44:59 +08:00
Fucheng Sha
dd3f73ae54 fix: 关闭 MSD 后保存 HID 配置时先更新 MSD 状态再校验端点预算
saveConfig 中调换 updateMsd 和 updateHid 的调用顺序,确保 HID
校验端点预算时 MSD enabled 状态已是最新值,避免被误判为超限。

Fixes mofeng-git/One-KVM#260
2026-05-16 13:00:49 +08:00
SilentWind
0b9d94f53f docs: Update README with 贝塔网络 sponsorship 2026-05-13 22:38:58 +08:00
SilentWind
e5d6279a54 Merge pull request #257 from btzen/redfish
feat: 实现 Redfish API 标准接口;支持通过前端开关控制 Redfish 服务
2026-05-13 13:47:07 +08:00
Fucheng Sha
57d4091497 fix: 恢复被误删的 MSD Section 注释 2026-05-12 14:53:04 +08:00
Fucheng Sha
4e8c342905 feat: 实现 Redfish API 标准接口;支持通过前端开关控制 Redfish 服务 2026-05-12 10:53:26 +08:00
SilentWind
17cd74f64c Merge pull request #250 from arounyf/pr/audio-fix
fix: 修复 WebRTC 音频/视频接收器重启时破音问题
2026-05-05 12:12:17 +08:00
arounyf
9923670426 fix: 修复 WebRTC 音频/视频接收器重启时破音问题
start_audio_from_opus 和 start_from_video_frames 替换旧 handle 时先
abort 旧任务,防止新旧两个任务同时向同一个 track 写数据导致破音。
2026-05-05 05:11:04 +08:00
mofeng-git
3ee3df77b8 chroe: 不再配置 iceCandidatePoolSize,沿用浏览器默认 2026-05-05 01:19:17 +08:00
mofeng-git
8ec2f25e82 chore: bump version to v0.2.0 2026-05-05 00:59:16 +08:00
mofeng-git
c27d3a6703 fix:改进atx usb 继电器适配;修复 webrtc 无法建立连接问题;网页样式优化 2026-05-05 00:52:16 +08:00
mofeng-git
6723f432a3 feat: 允许通过环境变量手动指定前端资源路径,删除 debug 分支默认资源路径 2026-05-04 17:53:27 +08:00
mofeng-git
12a3f1c947 feat: 增加设备丢失自恢复机制
增加音频设备丢失自恢复机制,完善视频设备丢失自恢复机制

降级部分日志级别,GOSTC key打印脱敏

代码格式化
2026-05-02 10:55:05 +08:00
mofeng-git
52754c862b feat: 优化网页消息提醒样式 2026-05-01 21:46:32 +08:00
mofeng-git
e51d243324 feat: 增加 MSD 虚拟盘文件路径编码 2026-05-01 21:27:03 +08:00
mofeng-git
a1ebd34083 feat: 外部扩展程序输出日志级别修改为 info 级别 2026-05-01 21:21:54 +08:00
mofeng-git
89b19ea7dd refactor: 修改为同步请求 2026-05-01 20:06:22 +08:00
mofeng-git
0d47d8395d refactor: 重构视频采集状态与错误分类公共逻辑 2026-05-01 17:56:56 +08:00
mofeng-git
d82c863f40 refactor: 精简依赖 2026-05-01 17:41:11 +08:00
mofeng-git
d8e7de74a6 refactor: 删除部分多余的代码和注释 2026-05-01 17:31:04 +08:00
SilentWind
74035f8e12 Merge pull request #247 from tedaimengtech/main
Update: Add CQU Mirror Information
2026-04-29 14:13:25 +08:00
tedaimeng
8d45186eba Add Mirror Download Services to README
Added a section for Mirror Download Services and updated sponsors.
2026-04-29 13:12:35 +08:00
tedaimeng
c484580b8f Update README with CQUMirror details
Added CQUMirror information and links to the README.
2026-04-29 13:09:23 +08:00
SilentWind
56bce7937c Add GNU General Public License v3 2026-04-29 10:38:30 +08:00
mofeng-git
07b982d1d2 feat: 完善 USB UVC 设备异常处理,添加 USB 设备复位功能 2026-04-27 16:37:04 +08:00
mofeng-git
9065e01225 feat: 优化控制台页面状态工具栏在不同宽度网页下的自适应能力 2026-04-25 20:32:44 +08:00
mofeng-git
cc3cc15774 refactor: 删除部分多余的 Ventoy 逻辑 2026-04-20 14:07:28 +08:00
mofeng-git
fcb39c73fc refactor: 删除未使用的公共 STUN/TURN 逻辑 2026-04-20 10:15:53 +08:00
mofeng-git
7c703b8b4b feat: 深入适配 RK628D CSI 采集卡的设备识别、参数读取、自恢复和音频采集 2026-04-19 11:26:21 +08:00
mofeng-git
8eac31f69f chore: bump version to v0.1.9
Made-with: Cursor
2026-04-12 20:43:44 +08:00
mofeng-git
9653e16a68 feat: CLI 改密、自定义 TLS、移动端适配与扩展校验
- 新增 one-kvm user set-password(交互式),改密后吊销该用户全部会话
- /api/config/web 支持 PEM 证书/密钥上传与清除,响应含 has_custom_cert
- 移动端:ActionBar 溢出菜单、ATX/粘贴底部 Sheet、BrandMark 与控制台等响应式优化
- GOSTC:校验服务器地址非空,管理器启动条件与 HTTP 热更新一致
- RustDesk:中继密钥 relay_key 校验为标准 Base64 且解码后恰好 32 字节
- StatusCard、InfoBar:合并精简冗余状态信息
2026-04-12 19:28:17 +08:00
mofeng-git
d0c0852fbb fix: 修复设置页 IPv6 URL 拼接问题 #241
统一处理 Settings 页面中的主机地址格式,避免 IPv6 场景下 RTSP 地址展示和重启后跳转 URL 因缺少方括号而失效。

Made-with: Cursor
2026-04-12 09:49:42 +08:00
mofeng-git
c0a0c90cbd fix: 修复 ATX 串口继电器共享设备失效 #233
当 power/reset 配置为同一串口设备时,改为复用同一个串口句柄,避免重复 open 导致 reset 不生效。

Made-with: Cursor
2026-04-11 22:31:17 +08:00
mofeng-git
9e3483b836 style: 统一代码格式
应用 fmt 对已暂存 Rust 文件进行格式化,保持代码风格一致并减少无意义差异。

Made-with: Cursor
2026-04-11 22:25:46 +08:00
mofeng-git
132f445c29 完善音频采集 2026-04-11 22:22:05 +08:00
mofeng-git
4952cbaf19 fix: 修复 RTSP 功能对 VLC 视频播放器的兼容性 #237 2026-04-11 21:55:34 +08:00
mofeng-git
099f0b1ca2 fix: 优化视频切换流畅性;修复 OTG HID 功能无法一次保存成功和页面未即刻生效问题 2026-04-11 21:20:54 +08:00
mofeng-git
eecbc0fc13 CSI 采集适配优化 2026-04-11 20:26:33 +08:00
mofeng-git
2d81a071e5 fix: 修复 MJPEG模式可用但状态显示离线的问题 2026-04-11 15:11:47 +08:00
mofeng-git
3e35181583 fix: 修复镜像列表滚动条问题 #238 2026-04-11 13:13:24 +08:00
mofeng-git
c3a3f41a2c 修改 .gitignore 2026-04-11 13:12:11 +08:00
mofeng-git
2b2b471cfb chore(release): bump version to v0.1.8 2026-04-01 21:30:41 +08:00
mofeng-git
abb319068b feat: 适配 RK 原生 HDMI IN 适配采集 2026-04-01 21:28:15 +08:00
mofeng-git
51d7d8b8be chore: bump version to v0.1.7 2026-03-28 22:45:39 +08:00
mofeng-git
f95714d9f0 删除无用测试 2026-03-28 22:41:35 +08:00
mofeng-git
7d52b2e2ea fix(otg): 优化运行时状态监测与未枚举提示 2026-03-28 22:06:53 +08:00
mofeng-git
a2a8b3802d feat(web): 优化视频格式与虚拟键盘显示 2026-03-28 21:34:22 +08:00
mofeng-git
f4283f45a4 refactor(otg): 简化运行时与设置逻辑 2026-03-28 21:09:10 +08:00
mofeng-git
4784cb75e4 调整登录页文案并改为点击切换语言 2026-03-28 20:47:29 +08:00
mofeng-git
abc6bd1677 feat(otg): 增加 libcomposite 自动加载兜底 2026-03-28 17:06:41 +08:00
mofeng-git
1c5288d783 优化控制台与设置页切换时的 WebRTC 会话保活与恢复逻辑 2026-03-27 11:29:27 +08:00
mofeng-git
6bcb54bd22 feat(web): 改为通过 WebSocket 推送 ttyd 状态并清理轮询与冗余接口 2026-03-27 10:49:04 +08:00
mofeng-git
e20136a5ab fix(web): 修复 WebRTC 首帧状态与视频状态判定 2026-03-27 10:44:59 +08:00
mofeng-git
c8fd3648ad refactor(video): 删除废弃视频流水线并收敛 MJPEG/WebRTC 编排与死代码 2026-03-27 08:21:14 +08:00
mofeng-git
6ef2d394d9 fix(video): 启动时丢弃前三帧无效 MJPEG 2026-03-26 23:27:42 +08:00
mofeng-git
762a3b037d chore(hid): 删除 CH9329 收发 trace 日志 2026-03-26 23:05:49 +08:00
mofeng-git
e09a906f93 refactor(hid): 统一 HID 键盘 CanonicalKey 语义并清理前端布局与输入链路冗余代码 2026-03-26 22:51:29 +08:00
mofeng-git
95bf1a852e feat(web): 登录页改为引导卡片样式并增加语言切换按钮 2026-03-26 22:45:28 +08:00
mofeng-git
200f947b5d fix(video): 修复 FFmpeg 硬编码 EAGAIN 刷屏并为编码错误增加日志节流 2026-03-26 22:30:53 +08:00
mofeng-git
46ae0c81e2 refactor(events): 将设备状态广播降级为快照同步并按需订阅 WebSocket 事件,顺带修复相关测试 2026-03-26 22:01:50 +08:00
mofeng-git
779aa180ad refactor: 重构部分事件检查逻辑,修复 ch9329 hid 状态显示异常 2026-03-26 12:33:24 +08:00
mofeng-git
ae26e3c863 feat: 支持自动检测因特尔 GPU 驱动类型 2026-03-25 20:27:26 +08:00
mofeng-git
eeb41159b7 build: 增加硬件编码所需驱动依赖 2026-03-22 20:19:30 +08:00
mofeng-git
24a10aa222 feat: 支持硬件编码能力测试,otg 自检修改为需要手动执行 2026-03-22 20:19:30 +08:00
mofeng-git
c119db4908 perf: 编码器探测测试分辨率由 1080p 调整为 720p 2026-03-22 20:19:30 +08:00
mofeng-git
0db287bf55 refactor: 重构 ffmpeg 编码器探测模块 2026-03-22 20:19:30 +08:00
mofeng-git
e229f35777 fix(web): 修复控制台全屏视频时鼠标定位偏移问题 2026-03-22 20:19:30 +08:00
SilentWind
df647b45cd Merge pull request #230 from a15355447898a/main
修复树莓派4B上 V4L2 编码时 WebRTC 无画面的问题
2026-03-02 19:05:32 +08:00
a15355447898a
b74659dcd4 refactor(video): restore v4l2r and remove temporary debug logs 2026-03-01 01:40:28 +08:00
a15355447898a
4f2fb534a4 fix(video): v4l path + webrtc h264 startup diagnostics 2026-03-01 01:24:26 +08:00
mofeng-git
bd17f8d0f8 chore: 更新版本号到 v0.1.6 2026-02-22 23:03:24 +08:00
mofeng-git
cee43795f8 fix: 添加前端电源状态显示 #226 2026-02-22 22:55:56 +08:00
mofeng-git
79d90ea703 docs: 更新版本号到 v0.1.5,更新 readme,删除落后的文档 2026-02-20 21:51:17 +08:00
mofeng-git
486db7b4aa feat(hid): 增加 HID 后端健康检查与错误码上报,完善前端掉线恢复状态同步及错误提示展示 2026-02-20 20:30:12 +08:00
mofeng-git
016c0d5dbb fix(atx): 完善串口继电器配置校验与前端防冲突 2026-02-20 15:36:08 +08:00
mofeng-git
6e2c6dea1c revert: remove non-ATX changes from #223 merge 2026-02-20 14:24:38 +08:00
SilentWind
078c4e4ea1 Merge pull request #223 from Fridayssheep/main
尝试添加了对串口协议的USB继电器的支持
2026-02-20 14:19:51 +08:00
SilentWind
6daa348c63 Merge branch 'main' into main 2026-02-20 14:19:38 +08:00
SilentWind
3341d8b5cd Merge pull request #225 from mofeng-git/pr-223-atx-only
feat(atx): merge serial relay support from #223
2026-02-20 14:14:30 +08:00
mofeng-git
251a1e00c4 feat(atx): merge serial relay support from #223 2026-02-20 14:11:00 +08:00
mofeng-git
ce622e4492 fix: 优化 WebRTC 建连流程、修复平台信息、修复虚拟键盘键值映射
- WebRTC:默认 mDNS 调整为 QueryOnly,Answer 阶段改为等待 ICE gathering complete(2.5s 超时),提升首次建连成功率与候选完整性
- WebRTC:前端建连流程增加阶段化状态与串行保护(connectInFlight/ready gate),优化配置变更后的重连时机与失败处理,减少竞态和无效重试
- Device:平台信息补充 `/proc/device-tree/model` 回退并统一展示为“处理器/平台”
- HID:键盘输入链路统一为 HID usage + modifier bitmask,修复虚拟键盘/宏/粘贴键值映射错误
2026-02-20 13:34:49 +08:00
mofeng-git
5f03971579 feat(web): 新增 HID OTG 自检接口与设置页环境诊断面板,并优化在线升级状态文案本地化及重启后自动刷新体验 2026-02-20 09:44:02 +08:00
mofeng-git
ba1b5224ff fix(web): 调整控制台HID状态卡片内容与弹层对齐 2026-02-11 22:16:54 +08:00
mofeng-git
ccaf4d1205 fix(rtsp): 修复清空用户名后仍触发认证导致 401 的问题 2026-02-11 20:55:20 +08:00
mofeng-git
6ed1cf5bef feat: HID串口优先ttyUSB并在视频设备名称后显示路径 2026-02-11 20:45:13 +08:00
mofeng-git
74411d354c fix: 修复卡片字体大小不一致 2026-02-11 20:00:49 +08:00
mofeng-git
3133db9c86 fix: 修复 rtsp 服务连接错误 2026-02-11 20:00:33 +08:00
mofeng-git
934dc48208 feat: 支持在线升级功能 2026-02-11 19:41:19 +08:00
mofeng-git
60b294e0ab feat: 增加WOL服务端历史记录并支持跨浏览器同步 2026-02-11 17:04:40 +08:00
mofeng-git
fb975875f1 feat: 新增 RTSP 设置菜单与配置面板 2026-02-11 17:01:25 +08:00
mofeng-git
f912c977d0 refactor: 移除 ttyd 扩展的“用户凭据”功能 2026-02-11 16:50:49 +08:00
mofeng-git
24c4002ef2 fix: 修复 RustDesk 中继选择逻辑,使“用户本地配置的 relay_server(非空)”在运行时优先生效 2026-02-11 16:29:47 +08:00
mofeng-git
a7143287d9 fix: 修复构建错误,构建时安装 rsync 2026-02-11 16:17:27 +08:00
mofeng-git
3824e57fc5 feat: 支持 rtsp 功能 2026-02-11 16:06:06 +08:00
Fridayssheep
ba6ec56cee fix: 修复了确认对话框操作的变量在点击时被重置的bug 2026-02-11 15:16:42 +08:00
Fridayssheep
21bea797e4 feat: 添加了对串口协议的继电器的支持 2026-02-11 13:06:05 +08:00
mofeng-git
261deb1303 refactor: 收敛单用户模型并优化可访问性与响应式体验
- 后端移除 is_admin 权限字段与相关逻辑,统一为单用户系统模型
- 修复会话过期清理的时间比较方式(改为 RFC3339 参数比较)
- /api/config 聚合配置增加敏感字段脱敏,避免暴露 TURN/RustDesk 密钥与密码
- 配置更新日志改为摘要,避免打印完整配置内容
- 前端修复可点击卡片语义与键盘可达,补齐图标按钮可访问名称
- 调整弹窗与抽屉的响应式尺寸,优化多端显示与交互
2026-02-10 22:30:52 +08:00
mofeng-git
394baca938 fix: 补齐 ATX 控制器缺失接口并完成全项目 clippy -D warnings 修复 2026-02-10 21:37:33 +08:00
SilentWind
7baf6fcf44 Merge pull request #214 from a15355447898a/main
支持v4l2编码,arm机器原生构建,允许初始化时禁用HID,修改README
2026-02-10 14:31:46 +08:00
SilentWind
04a2ff9724 Merge branch 'main' into main 2026-02-10 14:31:17 +08:00
mofeng-git
72eb2c450d feat: 迁移视频采集到 v4l2r,支持多平面设备并完善构建头文件
- 将 V4L2 采集依赖从 v4l 切换到 v4l2r

- 新增基于 v4l2r 的 mmap 采集实现,优先使用 VIDEO_CAPTURE_MPLANE

- 更新像素格式转换与设备枚举逻辑,探测阶段改为只读打开

- 增加采集错误日志节流,避免 dqbuf EINVAL 日志风暴

- 交叉编译镜像安装更新的 Linux 内核头文件供 bindgen 使用
2026-02-10 13:52:52 +08:00
mofeng
f8a031c90c feat: 支持树莓派 v4l2m2m 编码器探测 2026-02-09 14:54:46 +08:00
mofeng
8b17a0c48b chore: 更新版本号到 v0.1.3 2026-01-31 02:10:39 +08:00
mofeng
e75f0500e2 fix: 默认跳过晶晨 /dev/video0 vdec 探测,仅在设置环境变量时允许,修复内核 BUG 带来的软件卡死 2026-01-31 02:04:52 +08:00
mofeng
a14e0fb26d chore: 更新版本号到 v0.1.3 2026-01-30 15:32:04 +08:00
mofeng
d649c1ac20 feat: 引入统一配置 store 并迁移 Console/Settings 配置读写;自动显示当前使用的配置 2026-01-30 15:24:26 +08:00
mofeng
6a110258b9 feat: 支持 ipv4/ipv6 双栈访问 2026-01-30 14:47:41 +08:00
mofeng
58f9020192 feat: RustDesk 扩展支持相对鼠标模式,上报设备标识修改为 Windows 2026-01-30 13:10:55 +08:00
mofeng
f3b42e2aaf fix: 引导流程结束后,再次访问引导页面自动跳转 2026-01-30 13:06:32 +08:00
mofeng
b2b99115ec fix: 修复 USB HID 端点异常时鼠标事件写入会阻塞把服务端音视频线程拖死的问题 2026-01-30 12:33:19 +08:00
mofeng
1a0b285fe6 fix: 初步修复移动端 UI 错乱 2026-01-29 22:43:47 +08:00
mofeng
d9daeb211a fix: 修复 /dev/videoX 设备非视频设备 v4l2 不返回内容,导致主程序挂起的问题 2026-01-29 21:23:48 +08:00
mofeng
78aca25722 fix: 修复部分资源未授权访问,删除冗余 Admin 判断逻辑 2026-01-29 20:16:53 +08:00
mofeng
9cb0dd146e fix: 修复适配全志平台 OTG 低端点情况 2026-01-29 20:00:40 +08:00
mofeng
2938af32a9 fix: 将会话失效处理集中到路由并避免在登录页刷新循环 2026-01-28 21:52:12 +08:00
mofeng
ece0bbdcef fix: 修复 rustdesk 扩展前端校验逻辑,自动补全端口 2026-01-28 21:44:45 +08:00
mofeng
2dc055a5b2 dcos: 更新 README.md 2026-01-27 23:31:09 +08:00
mofeng
46c2edeb96 fix: 完善前端 USB OTG 动态配置功能的选项 2026-01-27 22:16:45 +08:00
mofeng
9d5451f588 fix: 完善 rustdsk 丢帧策略 2026-01-27 17:32:28 +08:00
mofeng
9193c54f86 fix: mpp 性能优化和修复
- mjpeg-->h265 mpp 编码速度优化
- 修复 mpp 编码后的视频 rustdesk 无法解码问题
- 更新版本号为 v0.1.2
2026-01-27 17:06:47 +08:00
mofeng
1786b7689d feat: 完善架构优化性能
- 调整音视频架构,提升 RKMPP 编码 MJPEG-->H264 性能,同时解决丢帧马赛克问题;
- 删除多用户逻辑,只保留单用户,支持设置 web 单会话;
- 修复删除体验不好的的回退逻辑,前端页面菜单位置微调;
- 增加 OTG USB 设备动态调整功能;
- 修复 mdns 问题,webrtc 视频切换更顺畅。
2026-01-25 16:04:29 +08:00
ayaya
176e71c79e 修改readme 2026-01-23 21:24:22 +08:00
a15355447898a
d78c6ed047 回滚docker构建脚本 2026-01-23 21:20:48 +08:00
a15355447898a
89072ad58d 支持v4l2编码,arm机器原生构建,docker镜像换archlinux,允许初始化时禁用HID 2026-01-23 17:11:19 +08:00
mofeng
e7d8c93bff docs: 新明 2026-01-20 19:53:15 +08:00
439 changed files with 57083 additions and 44428 deletions

301
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,301 @@
name: Build
on:
pull_request:
workflow_dispatch:
inputs:
publish_release:
description: Publish GitHub Release
required: false
default: false
type: boolean
release_tag:
description: Release tag name when publishing
required: false
default: ""
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
jobs:
frontend:
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
cache-dependency-path: web/package-lock.json
- name: Build frontend
working-directory: web
run: |
npm ci
npm run build
- name: Upload frontend dist
uses: actions/upload-artifact@v4
with:
name: web-dist
path: web/dist
if-no-files-found: error
retention-days: 7
deb:
runs-on: ubuntu-22.04
needs: frontend
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- name: Download frontend dist
uses: actions/download-artifact@v4
with:
name: web-dist
path: web/dist
- uses: dtolnay/rust-toolchain@stable
- name: Install cross
run: cargo install cross --locked
- name: Build linux binary
run: bash build/build-images.sh
- name: Package deb
run: bash build/package-deb.sh
- name: Upload deb
uses: actions/upload-artifact@v4
with:
name: one-kvm-deb
path: target/debian/*.deb
if-no-files-found: error
retention-days: 7
windows:
runs-on: windows-2022
needs: frontend
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- name: Download frontend dist
uses: actions/download-artifact@v4
with:
name: web-dist
path: web/dist
- uses: dtolnay/rust-toolchain@stable
- name: Set up MSVC
uses: ilammy/msvc-dev-cmd@v1
- name: Prepare vcpkg and dependencies
shell: pwsh
run: |
$env:VCPKG_ROOT = "C:\vcpkg"
$env:VCPKG_DEFAULT_TRIPLET = "x64-windows-static"
$env:VCPKG_INSTALLED_DIR = Join-Path $pwd "vcpkg_installed"
if (-not (Test-Path $env:VCPKG_ROOT)) {
git clone https://github.com/microsoft/vcpkg $env:VCPKG_ROOT
}
& "$env:VCPKG_ROOT\bootstrap-vcpkg.bat" -disableMetrics
& "$env:VCPKG_ROOT\vcpkg.exe" install --triplet $env:VCPKG_DEFAULT_TRIPLET --x-install-root="$env:VCPKG_INSTALLED_DIR"
$tripletRoot = Join-Path $env:VCPKG_INSTALLED_DIR $env:VCPKG_DEFAULT_TRIPLET
$env:TURBOJPEG_SOURCE = "explicit"
$env:TURBOJPEG_LIB_DIR = Join-Path $tripletRoot "lib"
$env:TURBOJPEG_INCLUDE_DIR = Join-Path $tripletRoot "include"
"VCPKG_ROOT=$env:VCPKG_ROOT" | Out-File -FilePath $env:GITHUB_ENV -Append
"VCPKG_DEFAULT_TRIPLET=$env:VCPKG_DEFAULT_TRIPLET" | Out-File -FilePath $env:GITHUB_ENV -Append
"VCPKG_INSTALLED_DIR=$env:VCPKG_INSTALLED_DIR" | Out-File -FilePath $env:GITHUB_ENV -Append
"TURBOJPEG_SOURCE=$env:TURBOJPEG_SOURCE" | Out-File -FilePath $env:GITHUB_ENV -Append
"TURBOJPEG_LIB_DIR=$env:TURBOJPEG_LIB_DIR" | Out-File -FilePath $env:GITHUB_ENV -Append
"TURBOJPEG_INCLUDE_DIR=$env:TURBOJPEG_INCLUDE_DIR" | Out-File -FilePath $env:GITHUB_ENV -Append
- name: Build Windows exe
shell: pwsh
run: .\build\windows\build.ps1 -Configuration release -Package
- name: Upload exe
uses: actions/upload-artifact@v4
with:
name: one-kvm-windows-exe
path: target/x86_64-pc-windows-msvc/release/one-kvm_*.exe
if-no-files-found: error
retention-days: 7
android:
runs-on: ubuntu-22.04
needs: frontend
timeout-minutes: 240
steps:
- uses: actions/checkout@v4
- name: Download frontend dist
uses: actions/download-artifact@v4
with:
name: web-dist
path: web/dist
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Cache Android Docker layers
uses: actions/cache@v4
with:
path: /tmp/.buildx-cache/android
key: android-buildx-${{ runner.os }}-${{ hashFiles('build/cross/Dockerfile.android') }}
restore-keys: |
android-buildx-${{ runner.os }}-
- name: Build Android Docker image
uses: docker/build-push-action@v6
with:
context: build/cross
file: build/cross/Dockerfile.android
tags: one-kvm-android-build:ci
load: true
cache-from: type=local,src=/tmp/.buildx-cache/android
cache-to: type=local,dest=/tmp/.buildx-cache/android-new,mode=max
- name: Rotate Android Docker layer cache
run: |
rm -rf /tmp/.buildx-cache/android
mv /tmp/.buildx-cache/android-new /tmp/.buildx-cache/android
- name: Cache Android build dependencies
uses: actions/cache@v4
with:
path: |
.github/android-cache/gradle
.github/android-cache/cargo-registry
.github/android-cache/cargo-git
.tmp/android-ffmpeg-check
.tmp/android-turbojpeg-src
.tmp/android-libyuv-src
.tmp/android-alsa-src
.tmp/android-opus-src
dist/android-ffmpeg-mediacodec
dist/android-turbojpeg
dist/android-libyuv
dist/android-alsa
dist/android-opus
key: android-deps-${{ runner.os }}-${{ hashFiles('android/**/*.gradle.kts', 'android/gradle/wrapper/gradle-wrapper.properties', 'android/native/Cargo.lock', 'Cargo.lock', 'scripts/build-android-*.sh') }}
restore-keys: |
android-deps-${{ runner.os }}-
- name: Prepare Android FFmpeg source
run: |
chmod +x android/gradlew
if [ ! -x .tmp/android-ffmpeg-check/src/ffmpeg-rockchip/configure ]; then
rm -rf .tmp/android-ffmpeg-check/src
mkdir -p .tmp/android-ffmpeg-check/src
wget -q https://files.mofeng.run/src/image/other/ffmpeg.tar.gz -O .tmp/android-ffmpeg-check/ffmpeg.tar.gz
tar -xzf .tmp/android-ffmpeg-check/ffmpeg.tar.gz -C .tmp/android-ffmpeg-check/src --strip-components=1
fi
- name: Build Android APK
env:
ONE_KVM_ANDROID_DOCKER_IMAGE: one-kvm-android-build:ci
ONE_KVM_ANDROID_SKIP_DOCKER_BUILD: "1"
ONE_KVM_ANDROID_GRADLE_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/gradle
ONE_KVM_ANDROID_CARGO_REGISTRY_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/cargo-registry
ONE_KVM_ANDROID_CARGO_GIT_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/cargo-git
run: bash build/build-android.sh all
- name: Fix Android build permissions
if: ${{ always() }}
run: |
paths=(
.github/android-cache
.tmp/android-ffmpeg-check
.tmp/android-turbojpeg-src
.tmp/android-libyuv-src
.tmp/android-alsa-src
.tmp/android-opus-src
dist/android-ffmpeg-mediacodec
dist/android-turbojpeg
dist/android-libyuv
dist/android-alsa
dist/android-opus
target/android
android/.gradle
android/app/build
android/native/target
)
existing=()
for path in "${paths[@]}"; do
if [ -e "$path" ]; then
existing+=("$path")
fi
done
if [ "${#existing[@]}" -gt 0 ]; then
sudo chown -R "$USER:$USER" "${existing[@]}"
fi
- name: Upload Android APK
uses: actions/upload-artifact@v4
with:
name: one-kvm-android-apk
path: target/android/one-kvm_*.apk
if-no-files-found: error
retention-days: 7
release:
runs-on: ubuntu-22.04
needs: [deb, windows, android]
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_release }}
timeout-minutes: 30
permissions:
contents: write
steps:
- name: Validate release tag
run: |
if [ -z "${{ inputs.release_tag }}" ]; then
echo "release_tag is required when publish_release is true"
exit 1
fi
- name: Download deb artifact
uses: actions/download-artifact@v4
with:
name: one-kvm-deb
path: release-artifacts/deb
- name: Download exe artifact
uses: actions/download-artifact@v4
with:
name: one-kvm-windows-exe
path: release-artifacts/windows
- name: Download Android artifact
uses: actions/download-artifact@v4
with:
name: one-kvm-android-apk
path: release-artifacts/android
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ inputs.release_tag }}
prerelease: true
generate_release_notes: true
files: |
release-artifacts/deb/*.deb
release-artifacts/windows/*.exe
release-artifacts/android/*.apk

7
.gitignore vendored
View File

@@ -1,5 +1,5 @@
# Rust
/target/
target/
Cargo.lock
# IDE
@@ -30,6 +30,8 @@ Thumbs.db
# Build artifacts
/dist/
/build-staging
/.tmp/
# Frontend (built files)
/web/node_modules/
@@ -39,3 +41,6 @@ CLAUDE.md
# Secrets (compile-time configuration)
secrets.toml
.env
/docs/
web/package-lock.json

View File

@@ -1,6 +1,6 @@
[package]
name = "one-kvm"
version = "0.1.1"
version = "0.2.2"
edition = "2021"
authors = ["SilentWind"]
description = "A open and lightweight IP-KVM solution written in Rust"
@@ -9,126 +9,259 @@ repository = "https://github.com/mofeng-git/One-KVM"
keywords = ["kvm", "ipkvm", "remote-management", "embedded"]
categories = ["embedded", "network-programming"]
[features]
default = ["desktop"]
desktop = [
"dep:tokio",
"dep:tokio-util",
"dep:axum",
"dep:axum-extra",
"dep:tower-http",
"dep:sqlx",
"dep:serde",
"dep:serde_json",
"dep:tracing",
"dep:tracing-subscriber",
"dep:thiserror",
"dep:anyhow",
"dep:argon2",
"dep:rand",
"dep:uuid",
"dep:base64",
"dep:nix",
"dep:reqwest",
"dep:urlencoding",
"dep:rust-embed",
"dep:mime_guess",
"dep:rustls",
"dep:rcgen",
"dep:axum-server",
"dep:clap",
"dep:time",
"dep:bytes",
"dep:bytemuck",
"dep:xxhash-rust",
"dep:async-stream",
"dep:futures",
"dep:tokio-tungstenite",
"dep:parking_lot",
"dep:arc-swap",
"dep:webrtc",
"dep:rtp",
"dep:rtsp-types",
"dep:sdp-types",
"dep:serialport",
"dep:async-trait",
"dep:libc",
"dep:ventoy-img",
"dep:protobuf",
"dep:sodiumoxide",
"dep:sha2",
"dep:typeshare",
"dep:hwcodec",
"dep:libyuv",
"dep:turbojpeg",
"dep:audiopus",
"dep:v4l2r",
"dep:alsa",
"dep:gpio-cdev",
"dep:cpal",
"dep:windows-sys",
]
android = [
"dep:anyhow",
"dep:argon2",
"dep:arc-swap",
"dep:async-stream",
"dep:async-trait",
"dep:axum",
"dep:axum-extra",
"dep:base64",
"dep:bytemuck",
"dep:bytes",
"dep:futures",
"dep:gpio-cdev",
"dep:hwcodec",
"dep:libc",
"dep:libyuv",
"dep:mime_guess",
"dep:nix",
"dep:parking_lot",
"dep:protobuf",
"dep:rand",
"dep:rcgen",
"dep:reqwest",
"dep:rtp",
"dep:rtsp-types",
"dep:rust-embed",
"dep:rustls",
"dep:sdp-types",
"dep:serde",
"dep:serde_json",
"dep:serialport",
"dep:sha2",
"dep:sodiumoxide",
"dep:sqlx",
"dep:alsa",
"dep:audiopus",
"dep:thiserror",
"dep:time",
"dep:tokio",
"dep:tokio-tungstenite",
"dep:tokio-util",
"dep:axum-server",
"dep:tower-http",
"dep:tracing",
"dep:tracing-log",
"dep:tracing-subscriber",
"dep:turbojpeg",
"dep:typeshare",
"dep:urlencoding",
"dep:uuid",
"dep:ventoy-img",
"dep:v4l2r",
"dep:webrtc",
"dep:xxhash-rust",
]
android-mediacodec = [
"android",
]
[dependencies]
# Async runtime
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.7", features = ["rt"] }
tokio = { version = "1", features = ["full"], optional = true }
tokio-util = { version = "0.7", features = ["rt"], optional = true }
# Web framework
axum = { version = "0.8", features = ["ws", "multipart", "tokio"] }
axum-extra = { version = "0.12", features = ["typed-header", "cookie"] }
tower-http = { version = "0.6", features = ["fs", "cors", "trace", "compression-gzip"] }
axum = { version = "0.8", features = ["ws", "multipart", "tokio"], optional = true }
axum-extra = { version = "0.12", features = ["cookie"], optional = true }
tower-http = { version = "0.6", features = ["cors", "trace", "set-header"], optional = true }
# Database - Use bundled SQLite for static linking
sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite"] }
sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite"], optional = true }
# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde = { version = "1", features = ["derive"], optional = true }
serde_json = { version = "1", optional = true }
# Logging
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
tracing = { version = "0.1", optional = true }
tracing-log = { version = "0.2", optional = true }
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "tracing-log"], optional = true }
# Error handling
thiserror = "2"
anyhow = "1"
thiserror = { version = "2", optional = true }
anyhow = { version = "1", optional = true }
# Authentication
argon2 = "0.5"
rand = "0.9"
argon2 = { version = "0.5", optional = true }
rand = { version = "0.9", optional = true }
# Utilities
uuid = { version = "1", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
base64 = "0.22"
nix = { version = "0.30", features = ["fs", "net", "hostname", "poll"] }
uuid = { version = "1", features = ["v4", "serde"], optional = true }
base64 = { version = "0.22", optional = true }
# HTTP client (for URL downloads)
# Use rustls by default, but allow native-tls for systems with older GLIBC
reqwest = { version = "0.13", features = ["stream", "rustls"], default-features = false }
urlencoding = "2"
reqwest = { version = "0.13", features = ["stream", "rustls", "json"], default-features = false, optional = true }
urlencoding = { version = "2", optional = true }
# Static file embedding
rust-embed = { version = "8", features = ["compression"] }
mime_guess = "2"
rust-embed = { version = "8", features = ["compression", "debug-embed"], optional = true }
mime_guess = { version = "2", optional = true }
# TLS/HTTPS
rustls = { version = "0.23", features = ["ring"] }
rcgen = "0.14"
axum-server = { version = "0.8", features = ["tls-rustls"] }
rustls = { version = "0.23", features = ["ring"], optional = true }
rcgen = { version = "0.14", optional = true }
axum-server = { version = "0.8", features = ["tls-rustls"], optional = true }
# CLI argument parsing
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive"], optional = true }
# Time
time = "0.3"
# Video capture (V4L2)
v4l = "0.14"
# JPEG encoding (libjpeg-turbo, SIMD accelerated)
turbojpeg = "1.3"
# Time (cookie max_age + RFC3339 timestamps)
time = { version = "0.3", features = ["serde", "formatting", "parsing"], optional = true }
# Bytes handling
bytes = "1"
bytemuck = { version = "1.24", features = ["derive"] }
bytes = { version = "1", optional = true }
bytemuck = { version = "1.24", features = ["derive"], optional = true }
# Frame deduplication (hash-based comparison)
xxhash-rust = { version = "0.8", features = ["xxh64"] }
xxhash-rust = { version = "0.8", features = ["xxh64"], optional = true }
# Async channels
async-stream = "0.3"
futures = "0.3"
async-stream = { version = "0.3", optional = true }
futures = { version = "0.3", optional = true }
# WebSocket client (for ttyd proxy)
tokio-tungstenite = "0.28"
tokio-tungstenite = { version = "0.28", optional = true }
# High-performance synchronization
parking_lot = "0.12"
arc-swap = "1.8"
parking_lot = { version = "0.12", optional = true }
arc-swap = { version = "1.8", optional = true }
# WebRTC
webrtc = "0.14"
rtp = "0.14"
# Audio (ALSA capture + Opus encoding)
# Note: audiopus links to libopus.so (unavoidable for audio support)
alsa = "0.11"
audiopus = "0.2"
webrtc = { version = "0.14", optional = true }
rtp = { version = "0.14", optional = true }
rtsp-types = { version = "0.1", optional = true }
sdp-types = { version = "0.1", optional = true }
# HID (serial port for CH9329)
serialport = "4"
async-trait = "0.1"
libc = "0.2"
serialport = { version = "4", optional = true }
async-trait = { version = "0.1", optional = true }
libc = { version = "0.2", optional = true }
# Ventoy bootable image support
ventoy-img = { path = "libs/ventoy-img-rs" }
# ATX (GPIO control)
gpio-cdev = "0.6"
# H264 hardware/software encoding (hwcodec from rustdesk)
hwcodec = { path = "libs/hwcodec" }
ventoy-img = { path = "libs/ventoy-img-rs", optional = true }
# RustDesk protocol support
protobuf = { version = "3.7", features = ["with-bytes"] }
sodiumoxide = "0.2"
sha2 = "0.10"
# High-performance pixel format conversion (libyuv)
libyuv = { path = "res/vcpkg/libyuv" }
protobuf = { version = "3.7", features = ["with-bytes"], optional = true }
sodiumoxide = { version = "0.2", optional = true }
sha2 = { version = "0.10", optional = true }
# TypeScript type generation
typeshare = "1.0"
typeshare = { version = "1.0", optional = true }
[target.'cfg(any(unix, windows))'.dependencies]
# Video encoding/decoding (FFmpeg/libjpeg-turbo/libyuv; available on Windows and Linux)
hwcodec = { path = "libs/hwcodec", features = ["bytes"], optional = true }
libyuv = { path = "res/vcpkg/libyuv", optional = true }
turbojpeg = { version = "1.3", optional = true }
# Note: audiopus links to libopus.so (unavoidable for audio support)
audiopus = { version = "0.2", optional = true }
[target.'cfg(all(unix, not(target_os = "android")))'.dependencies]
# Utilities
nix = { version = "0.30", default-features = false, features = ["fs", "socket", "net", "hostname", "poll"], optional = true }
[target.'cfg(target_os = "android")'.dependencies]
# Utilities
nix = { version = "0.30", default-features = false, features = ["fs", "socket", "hostname", "poll"], optional = true }
[target.'cfg(unix)'.dependencies]
# Video capture (V4L2)
v4l2r = { path = "libs/v4l2r", optional = true }
# Audio (ALSA capture)
alsa = { version = "0.11", optional = true }
# ATX (GPIO control)
gpio-cdev = { version = "0.6", optional = true }
[target.'cfg(windows)'.dependencies]
cpal = { version = "0.17", default-features = false, optional = true }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
"Win32_System_SystemInformation",
"Win32_System_Threading",
], optional = true }
[dev-dependencies]
tokio-test = "0.4"
tempfile = "3"
[build-dependencies]
protobuf-codegen = "3.7"
toml = "0.9"
[profile.release]
opt-level = 3

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

238
README.en.md Normal file
View File

@@ -0,0 +1,238 @@
<div align="center">
<h1>One-KVM</h1>
<p><strong>An open, lightweight IP-KVM stack in Rust — remote management down to BIOS level</strong></p>
<p><a href="README.md">简体中文</a> · <a href="README.en.md">English</a></p>
[![GitHub Release](https://img.shields.io/github/v/release/mofeng-git/One-KVM)](https://github.com/mofeng-git/One-KVM/releases)
[![GitHub stars](https://img.shields.io/github/stars/mofeng-git/One-KVM?style=social)](https://github.com/mofeng-git/One-KVM/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/mofeng-git/One-KVM?style=social)](https://github.com/mofeng-git/One-KVM/network/members)
[![GitHub issues](https://img.shields.io/github/issues/mofeng-git/One-KVM)](https://github.com/mofeng-git/One-KVM/issues)
</div>
---
## Overview
**One-KVM (Rust)** is a lightweight IP-KVM solution written in Rust. It lets you manage servers and workstations over the network, including at BIOS level.
Goals: an open, lightweight, easy-to-use IP-KVM stack.
- **Open**: not tied to one hardware recipe; runs across many setups.
- **Lightweight**: shipped as a binary with minimal moving parts for deployment.
- **Easy to use**: no hand-edited config files required; settings are done in the web UI.
> **One-KVM (Python)** is no longer maintained. If you still need it, see <https://github.com/mofeng-git/One-KVM/tree/python>.
<div align="center">
![One-KVM web console](https://one-kvm.cn/hero-app-effect.png)
</div>
## Features
### Core
| Area | Capabilities |
|------|----------------|
| Video capture | HDMI USB / MIPI CSI / RK3588 HDMI IN; MJPEG and WebRTC (H.264 / H.265 / VP8 / VP9) |
| Video encoding | VAAPI / QSV / RKMPP / V4L2 M2M hardware paths, with software fallback |
| Keyboard & mouse | USB OTG HID or CH340 + CH9329 HID; absolute / relative mouse |
| Virtual media | USB mass storage; ISO/IMG mount and Ventoy-style virtual USB |
| ATX power | GPIO or USB relay; power and reset control |
| Audio | ALSA capture + Opus (HTTP / WebRTC) |
The web UI supports visual configuration and Chinese/English locales. Built-ins include a web terminal (ttyd), intranet tunnel (gostc), P2P (EasyTier), RustDesk protocol (optional cross-platform remote access), and RTSP streaming.
## Installation
Release artifacts are on [GitHub Releases](https://github.com/mofeng-git/One-KVM/releases). Below are short paths for common setups. For **system requirements, hardware, Docker env vars, USB OTG**, and full troubleshooting, see the [One-KVM documentation](https://docs.one-kvm.cn/) (Chinese; use a translator if needed).
### Debian / Ubuntu (.deb)
Download a `one-kvm_*.deb` matching your CPU architecture from Releases, then from the directory containing the package:
```bash
sudo apt update
sudo apt install ./one-kvm_0.x.x_<arch>.deb
```
Replace the version and architecture in the filename with your actual file name.
### Docker
Images:
- **one-kvm** — main app + ttyd
- **one-kvm-full** — same plus optional extras (e.g. gostc, easytier-core)
Example:
```bash
docker run --name one-kvm -itd \
--privileged=true --restart unless-stopped \
-v /dev:/dev -v /sys:/sys \
--net=host \
silentwind0/one-kvm-full
```
If pulls are slow, use the Aliyun mirror, e.g. `registry.cn-hangzhou.aliyuncs.com/silentwind/one-kvm-full` (and `registry.cn-hangzhou.aliyuncs.com/silentwind/one-kvm` for the slim image).
### fnOS NAS (Feiniu / 飞牛)
One-KVM is listed in the fnOS **app store**; search and install on your NAS.
### Web UI and first run
Open `http://<device-ip>:8080` in a browser (**8420** after fnOS install). The first visit runs initial setup.
## Reporting issues
If something breaks:
1. Open [GitHub Issues](https://github.com/mofeng-git/One-KVM/issues) or report in the project QQ group.
2. Include **useful** error messages and steps to reproduce.
3. Mention software version, hardware, and OS details.
## Sponsorship
One-KVM builds on many great open-source projects; a lot of time goes into testing and maintenance. If you find it useful, you can support development on **[Afdian (为爱发电)](https://afdian.com/a/silentwind)**.
### Thanks
<details>
<summary><strong>Supporter list</strong></summary>
- 浩龙的电子嵌入式之路
- Tsuki
- H_xiaoming
- 0蓝蓝0
- fairybl
- Will
- 自.知
- 观棋不语٩ ི۶
- 爱发电用户_a57a4
- 爱发电用户_2c769
- 霜序
- 远方(闲鱼用户名:小远技术店铺)
- 爱发电用户_399fc
- 斐斐の
- 爱发电用户_09451
- 超高校级的錆鱼
- 爱发电用户_08cff
- guoke
- mgt
- 姜沢掵
- ui_beam
- 爱发电用户_c0dd7
- 爱发电用户_dnjK
- 忍者胖猪
- 永遠の願い
- 爱发电用户_GBrF
- 爱发电用户_fd65c
- 爱发电用户_vhNa
- 爱发电用户_Xu6S
- moss
- woshididi
- 爱发电用户_a0fd1
- 爱发电用户_f6bH
- 码农
- 爱发电用户_6639f
- jeron
- 爱发电用户_CN7y
- 爱发电用户_Up6w
- 爱发电用户_e3202
- 一语念白
- 云边
- 爱发电用户_5a711
- 爱发电用户_9a706
- T0m9ir1SUKI
- 爱发电用户_56d52
- 爱发电用户_3N6F
- DUSK
- 飘零
- .
- 饭太稀
-
- MaxZ
- 爱发电用户_c5f33
- 爱发电用户_09386
- 爱发电用户_JT6c
- 爱发电用户_d3d9c
- ......
</details>
### Sponsors
**Mirror Download Services:**
- **[Chongqing University Open Source Software Mirror](https://mirrors.cqu.edu.cn/)** — provides mirror download services
**File hosting**
- **[Huang1111 public-interest program](https://pan.huang1111.cn/s/mxkx3T1)** — login-free downloads
**Cloud**
- **[林枫云](https://www.dkdun.cn)** — project server sponsorship
![林枫云](https://docs.one-kvm.cn/img/36076FEFF0898A80EBD5756D28F4076C.png)
林枫云 offers premium network routes, high-frequency game servers, and high-bandwidth servers in China and abroad.

260
README.md
View File

@@ -1,81 +1,239 @@
# One-KVM
<div align="center">
<h1>One-KVM</h1>
<p><strong>Rust 编写的开放轻量 IP-KVM 解决方案,实现 BIOS 级远程管理</strong></p>
<p align="center">
<strong>开放轻量的 IP-KVM 解决方案,实现 BIOS 级远程管理</strong>
</p>
<p><a href="README.md">简体中文</a> · <a href="README.en.md">English</a></p>
<p align="center">
<a href="#功能特性">功能特性</a>
<a href="#快速开始">快速开始</a>
</p>
[![GitHub Release](https://img.shields.io/github/v/release/mofeng-git/One-KVM)](https://github.com/mofeng-git/One-KVM/releases)
[![GitHub stars](https://img.shields.io/github/stars/mofeng-git/One-KVM?style=social)](https://github.com/mofeng-git/One-KVM/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/mofeng-git/One-KVM?style=social)](https://github.com/mofeng-git/One-KVM/network/members)
[![GitHub issues](https://img.shields.io/github/issues/mofeng-git/One-KVM)](https://github.com/mofeng-git/One-KVM/issues)
</div>
---
## 介绍
## 📖 项目概述
One-KVM 是一个用 Rust 编写的开放轻量 IP-KVM(基于 IP 的键盘、视频、鼠标)解决方案,让你可以通过网络远程控制计算机,包括 BIOS 级别的操作
**One-KVM Rust** 是一个用 Rust 编写的轻量 IP-KVM 解决方案,通过网络远程管理服务器和工作站,实现 BIOS 级远程控制
**当前软件处于开发早期阶段,各种功能和细节还有待完善,欢迎体验,但请勿应用于生产环境。**
项目目标:提供一个开放、轻量、易用的 IPKVM 解决方案。
## 功能特性
- **开放**:不绑定特定硬件配置,可在各类硬件环境中稳定运行。
- **轻量**:以二进制文件形式分发,无繁杂的依赖项,部署过程简单。
- **易用**:无需手动编辑配置文件,参数设置均可通过网页界面完成。
> **One-KVM Python** 已停止开发,如有需要可访问 <https://github.com/mofeng-git/One-KVM/tree/python>。
<div align="center">
![One-KVM Web 控制台界面](https://one-kvm.cn/hero-app-effect.png)
</div>
## 📊 功能介绍
### 核心功能
| 功能 | 说明 |
| 功能 | 能力说明 |
|------|------|
| 视频采集 | HDMI USB 采集支持,提供 MJPEG/H264/H265/VP8/VP9 视频流 |
| 键鼠控制 | USB OTG HID 或 CH340 + CH39329 HID支持绝对/相对鼠标模式 |
| 虚拟U盘 | USB Mass Storage支持 ISO/IMG 镜像挂载和 Ventoy 虚拟U盘模式 |
| ATX 电源控制 | GPIO 控制电源/重启按钮 |
| 视频采集 | HDMI USB /MIPI CSI/RK3588 HDMI IN 采集支持,提供 MJPEG / WebRTCH.264/H.265/VP8/VP9 视频流|
| 视频编码 | VAAPI/QSV/RKMPP/V4L2M2M 硬件编码支持,以及软件编码兜底 |
| 键鼠控制 | USB OTG HID 或 CH340 + CH9329 HID支持绝对/相对鼠标模式 |
| 虚拟媒体 | USB Mass Storage支持 ISO/IMG 镜像挂载和 Ventoy 虚拟U盘模式 |
| ATX 电源控制 | GPIO /USB 继电器,支持控制电源、重启按钮 |
| 音频传输 | ALSA 采集 + Opus 编码HTTP/WebRTC |
### 硬件编码
此外提供基于 Web UI 的可视化配置与中英文界面;并集成 Web 终端ttyd、内网穿透gostc、P2P 组网EasyTier、RustDesk 协议(扩展跨平台远程访问)以及 RTSP 推流等能力。
支持自动检测和选择硬件加速:
- **VAAPI** - Intel/AMD GPU
- **RKMPP** - Rockchip SoC (**尚未实现**)
- **V4L2 M2M** - 通用硬件编码器 (**尚未实现**)
- **软件编码** - CPU 编码
## ⚡ 安装使用
### 其他特性
构建产物见 [GitHub Releases](https://github.com/mofeng-git/One-KVM/releases)。以下为常见安装方式的简要步骤;**系统要求、硬件准备、Docker 环境变量与 USB OTG 等完整说明**请查阅 [One-KVM Rust 文档站点](https://docs.one-kvm.cn/)。
- 单二进制部署,依赖更轻量
- Web UI 配置,无需编辑配置文件,多语言支持 (中文/英文)
- 内置 Web 终端 (ttyd),内网穿透支持 (gostc)P2P 组网支持 (EasyTier)
### 使用 deb 安装Debian / Ubuntu
## 快速开始
### Docker 运行
从 Releases 下载与本机架构匹配的 `one-kvm_*.deb`,在包所在目录执行:
```bash
docker run -d --privileged \
--name one-kvm \
-v /dev:/dev \
-v /sys/kernel/config:/sys/kernel/config \
--net=host \
silentwind0/one-kvm
sudo apt update
sudo apt install ./one-kvm_0.x.x_<arch>.deb
```
访问 http://IP:8080
将文件名中的版本号与架构替换为实际下载的包名。
### 环境变量
### 使用 Docker
| 变量 | 说明 | 默认值 |
|------|------|--------|
| `ENABLE_HTTPS` | 启用 HTTPS | `false` |
| `HTTP_PORT` | HTTP 端口 | `8080` |
| `VERBOSE` | 日志级别 (1/2/3) | - |
镜像分为 **one-kvm**One-KVM 主程序 + ttyd**one-kvm-full**(另含 gostc、easytier-core 等可选扩展),按需选用。
```bash
docker run --name one-kvm -itd \
--privileged=true --restart unless-stopped \
-v /dev:/dev -v /sys:/sys \
--net=host \
silentwind0/one-kvm-full
```
## 致谢
拉取较慢时,可将镜像名替换为阿里云加速,例如 `registry.cn-hangzhou.aliyuncs.com/silentwind/one-kvm-full``one-kvm` 镜像同理,将 `silentwind0/one-kvm` 换为 `registry.cn-hangzhou.aliyuncs.com/silentwind/one-kvm`)。
感谢以下项目:
### 飞牛 NAS
- [PiKVM](https://github.com/pikvm/pikvm) - 原始 Python 版 IP-KVM
- [RustDesk](https://github.com/rustdesk/rustdesk) - hwcodec 硬件编码库
- [ttyd](https://github.com/tsl0922/ttyd) - Web 终端
- [EasyTier](https://github.com/EasyTier/EasyTier) - P2P 组网
One-KVM 已上架飞牛 **应用市场**,在 NAS 上直接搜索安装即可。
## 许可证
### 访问 Web 与首次配置
待定
浏览器访问 `http://<设备 IP>:8080`(飞牛 NAS 安装后为 8420 端口)。首次访问将引导完成初始配置。
## 报告问题
如果您发现了问题,请:
1. 使用 [GitHub Issues](https://github.com/mofeng-git/One-KVM/issues) 报告,或加入 QQ 群聊反馈。
2. 提供有帮助的错误信息和复现步骤
3. 包含您使用的软件版本、硬件配置和系统信息
## 赞助支持
本项目基于多个优秀开源项目进行二次开发,作者投入了大量时间进行测试和维护。如果您觉得这个项目有价值,欢迎通过 **[为爱发电](https://afdian.com/a/silentwind)** 支持项目发展。
### 感谢名单
<details>
<summary><strong>点击查看感谢名单</strong></summary>
- 浩龙的电子嵌入式之路
- Tsuki
- H_xiaoming
- 0蓝蓝0
- fairybl
- Will
- 自.知
- 观棋不语٩ ི۶
- 爱发电用户_a57a4
- 爱发电用户_2c769
- 霜序
- 远方(闲鱼用户名:小远技术店铺)
- 爱发电用户_399fc
- 斐斐の
- 爱发电用户_09451
- 超高校级的錆鱼
- 爱发电用户_08cff
- guoke
- mgt
- 姜沢掵
- ui_beam
- 爱发电用户_c0dd7
- 爱发电用户_dnjK
- 忍者胖猪
- 永遠の願い
- 爱发电用户_GBrF
- 爱发电用户_fd65c
- 爱发电用户_vhNa
- 爱发电用户_Xu6S
- moss
- woshididi
- 爱发电用户_a0fd1
- 爱发电用户_f6bH
- 码农
- 爱发电用户_6639f
- jeron
- 爱发电用户_CN7y
- 爱发电用户_Up6w
- 爱发电用户_e3202
- 一语念白
- 云边
- 爱发电用户_5a711
- 爱发电用户_9a706
- T0m9ir1SUKI
- 爱发电用户_56d52
- 爱发电用户_3N6F
- DUSK
- 飘零
- .
- 饭太稀
-
- MaxZ
- 爱发电用户_c5f33
- 爱发电用户_09386
- 爱发电用户_JT6c
- 爱发电用户_d3d9c
- ......
</details>
### 赞助商
本项目得到以下赞助商的支持:
**镜像下载服务:**
- **[重庆大学开源软件镜像站](https://mirrors.cqu.edu.cn/)** - 提供镜像站下载服务
**文件存储服务:**
- **[Huang1111公益计划](https://pan.huang1111.cn/s/mxkx3T1)** - 提供免登录下载服务
**云服务商**
- **[林枫云](https://www.dkdun.cn)** - 赞助了本项目服务器
<img height="128" alt="林枫云" src="https://docs.one-kvm.cn/img/36076FEFF0898A80EBD5756D28F4076C.png" />
林枫云主营国内外地域的精品线路业务服务器、高主频游戏服务器和大带宽服务器。
- **[贝塔网络](https://my.beita.cc/?ref=github_onekvm)** - 赞助了本项目服务器
<img height="128" alt="BTBT" src="https://github.com/user-attachments/assets/c442d5f5-d72f-4a07-b9f4-400a6a0c3f1e" />
远程电脑、消费级GPU服务器、独服物理机全自动在线交付。

14
agents.md Normal file
View File

@@ -0,0 +1,14 @@
# Agents Notes
## Windows MSVC Build
Run from the repository root in PowerShell:
```powershell
$env:VCPKG_ROOT='C:\Users\mofen\code\vcpkg'
$env:TURBOJPEG_SOURCE='explicit'
$env:TURBOJPEG_LIB_DIR='C:\Users\mofen\code\vcpkg\installed\x64-windows-static\lib'
$env:TURBOJPEG_INCLUDE_DIR='C:\Users\mofen\code\vcpkg\installed\x64-windows-static\include'
cargo build --target x86_64-pc-windows-msvc
```

7
android/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
.gradle/
.kotlin/
build/
local.properties
app/build/
app/src/main/jniLibs/
native/target/

View File

@@ -0,0 +1,571 @@
import org.gradle.api.tasks.Exec
import java.security.MessageDigest
import java.util.Properties
plugins {
id("com.android.application")
}
val androidNdkVersion = "27.3.13750724"
val androidApiLevel = 21
val nativeCrateDir = layout.projectDirectory.dir("../native")
val rootCrateDir = layout.projectDirectory.dir("../..")
val nativeCargoOutputDir = layout.buildDirectory.dir("generated/oneKvm/cargoJniLibs")
val nativeOutputRoot = layout.buildDirectory.dir("generated/oneKvm/jniLibs")
val nativeAssetRoot = layout.buildDirectory.dir("generated/oneKvm/assets")
val defaultAndroidFfmpegRoot = rootProject.layout.projectDirectory.dir("../dist/android-ffmpeg-mediacodec")
val defaultAndroidLibyuvRoot = rootProject.layout.projectDirectory.dir("../dist/android-libyuv")
val defaultAndroidTurbojpegRoot = rootProject.layout.projectDirectory.dir("../dist/android-turbojpeg")
val defaultAndroidAlsaRoot = rootProject.layout.projectDirectory.dir("../dist/android-alsa")
val defaultAndroidOpusRoot = rootProject.layout.projectDirectory.dir("../dist/android-opus")
val androidFfmpegRoot = providers.environmentVariable("ONE_KVM_ANDROID_FFMPEG_ROOT")
.orElse(defaultAndroidFfmpegRoot.asFile.absolutePath)
val androidLibyuvRoot = providers.environmentVariable("ONE_KVM_ANDROID_LIBYUV_ROOT")
.orElse(defaultAndroidLibyuvRoot.asFile.absolutePath)
val androidTurbojpegRoot = providers.environmentVariable("ONE_KVM_ANDROID_TURBOJPEG_ROOT")
.orElse(defaultAndroidTurbojpegRoot.asFile.absolutePath)
val androidAlsaRoot = providers.environmentVariable("ONE_KVM_ANDROID_ALSA_ROOT")
.orElse(defaultAndroidAlsaRoot.asFile.absolutePath)
val androidOpusRoot = providers.environmentVariable("ONE_KVM_ANDROID_OPUS_ROOT")
.orElse(defaultAndroidOpusRoot.asFile.absolutePath)
val selectedAndroidAbis = providers.environmentVariable("ONE_KVM_ANDROID_ABIS")
.orElse("arm64-v8a,armeabi-v7a")
.get()
.split(',', ' ', ';')
.map { it.trim() }
.filter { it.isNotEmpty() }
.distinct()
val androidBuildProfile = providers.environmentVariable("ONE_KVM_ANDROID_PROFILE")
.orElse("debug")
.get()
.lowercase()
val oneKvmVersion = Regex("""(?m)^version\s*=\s*"([^"]+)"""")
.find(rootCrateDir.file("Cargo.toml").asFile.readText())
?.groupValues
?.get(1)
?: throw GradleException("Failed to resolve version from root Cargo.toml")
val androidFfmpegSourceDir = rootProject.layout.projectDirectory
.dir("../.tmp/android-ffmpeg-check/src/ffmpeg-rockchip")
val localProperties = Properties().apply {
val file = rootProject.file("local.properties")
if (file.exists()) {
file.inputStream().use { load(it) }
}
}
val androidSdkDir = file(
providers.environmentVariable("ANDROID_HOME")
.orElse(providers.environmentVariable("ANDROID_SDK_ROOT"))
.orElse(localProperties.getProperty("sdk.dir") ?: "/root/android-sdk")
.get(),
)
val androidNdkDir = androidSdkDir.resolve("ndk/$androidNdkVersion")
val androidFfmpegBuildScript = rootProject.layout.projectDirectory
.dir("..")
.file("scripts/build-android-ffmpeg-mediacodec.sh")
val androidLibyuvBuildScript = rootProject.layout.projectDirectory
.dir("..")
.file("scripts/build-android-libyuv.sh")
val androidTurbojpegBuildScript = rootProject.layout.projectDirectory
.dir("..")
.file("scripts/build-android-turbojpeg.sh")
val androidAlsaBuildScript = rootProject.layout.projectDirectory
.dir("..")
.file("scripts/build-android-alsa.sh")
val androidOpusBuildScript = rootProject.layout.projectDirectory
.dir("..")
.file("scripts/build-android-opus.sh")
val androidAbiTargets = mapOf(
"arm64-v8a" to Triple("arm64", "aarch64-linux-android", "aarch64-linux-android"),
"armeabi-v7a" to Triple("arm32", "armv7-linux-androideabi", "arm-linux-androideabi"),
)
val selectedAndroidAbiTargets = selectedAndroidAbis.associateWith { abi ->
androidAbiTargets[abi] ?: throw GradleException(
"Unsupported ONE_KVM_ANDROID_ABIS entry: $abi. Supported values: ${androidAbiTargets.keys.joinToString(", ")}",
)
}
if (androidBuildProfile != "debug" && androidBuildProfile != "release") {
throw GradleException("Unsupported ONE_KVM_ANDROID_PROFILE: $androidBuildProfile. Use debug or release.")
}
fun androidFfmpegBuildStamp(script: File): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest(script.readBytes())
.joinToString("") { "%02x".format(it) }
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
}
fun androidFfmpegRequiredFiles(root: File): List<File> = listOf(
"include/libavcodec/avcodec.h",
"lib/libavcodec.a",
"lib/libavutil.a",
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
fun androidLibyuvBuildStamp(script: File): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest(script.readBytes())
.joinToString("") { "%02x".format(it) }
val turbojpegScriptDigest = MessageDigest.getInstance("SHA-256")
.digest(androidTurbojpegBuildScript.asFile.readBytes())
.joinToString("") { "%02x".format(it) }
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest;turbojpegScript=$turbojpegScriptDigest"
}
fun androidLibyuvRequiredFiles(root: File): List<File> = listOf(
"include/libyuv.h",
"lib/libyuv.a",
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
fun androidTurbojpegBuildStamp(script: File): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest(script.readBytes())
.joinToString("") { "%02x".format(it) }
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
}
fun androidAlsaBuildStamp(script: File): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest(script.readBytes())
.joinToString("") { "%02x".format(it) }
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
}
fun androidOpusBuildStamp(script: File): String {
val digest = MessageDigest.getInstance("SHA-256")
.digest(script.readBytes())
.joinToString("") { "%02x".format(it) }
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
}
fun androidTurbojpegRequiredFiles(root: File): List<File> = listOf(
"include/turbojpeg.h",
"include/jpeglib.h",
"lib/libjpeg.a",
"lib/libturbojpeg.a",
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
fun androidAlsaRequiredFiles(root: File): List<File> = listOf(
"include/alsa/asoundlib.h",
"lib/libasound.so",
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
fun androidOpusRequiredFiles(root: File): List<File> = listOf(
"include/opus/opus.h",
"lib/libopus.so",
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
android {
namespace = "cn.one_kvm.androidhost"
compileSdk = 36
ndkVersion = androidNdkVersion
flavorDimensions += "abi"
defaultConfig {
applicationId = "cn.one_kvm.androidhost"
minSdk = androidApiLevel
targetSdk = 36
versionCode = 1
versionName = oneKvmVersion
}
productFlavors {
create("arm32") {
dimension = "abi"
ndk {
abiFilters += "armeabi-v7a"
}
}
create("arm64") {
dimension = "abi"
ndk {
abiFilters += "arm64-v8a"
}
}
}
sourceSets {
getByName("main") {
assets.directories.clear()
jniLibs.directories.clear()
}
getByName("arm32") {
assets.directories.add("build/generated/oneKvm/assets/arm32")
jniLibs.directories.add("build/generated/oneKvm/jniLibs/arm32")
}
getByName("arm64") {
assets.directories.add("build/generated/oneKvm/assets/arm64")
jniLibs.directories.add("build/generated/oneKvm/jniLibs/arm64")
}
}
}
tasks.register<Exec>("buildAndroidFfmpegMediaCodec") {
description = "Builds the default Android FFmpeg MediaCodec static libraries."
group = "build"
val ffmpegRoot = file(androidFfmpegRoot.get())
val sourceDir = androidFfmpegSourceDir.asFile
val scriptFile = androidFfmpegBuildScript.asFile
val stampFile = ffmpegRoot.resolve(".one-kvm-android-ffmpeg.stamp")
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
commandLine(
"bash",
scriptFile.absolutePath,
"--source",
sourceDir.absolutePath,
"--output",
ffmpegRoot.absolutePath,
"--ndk",
androidNdkDir.absolutePath,
"--api",
androidApiLevel.toString(),
"--abis",
selectedAndroidAbis.joinToString(","),
)
inputs.dir(sourceDir)
inputs.file(scriptFile)
outputs.dir(ffmpegRoot)
onlyIf {
val hasAndroidFfmpeg = androidFfmpegRequiredFiles(ffmpegRoot).all { it.exists() }
val hasCurrentBuildStamp =
stampFile.exists() && stampFile.readText() == androidFfmpegBuildStamp(scriptFile)
if (!hasAndroidFfmpeg && !sourceDir.resolve("configure").exists()) {
throw GradleException(
"Missing Android FFmpeg MediaCodec build at ${ffmpegRoot.absolutePath}, " +
"and source was not found at ${sourceDir.absolutePath}",
)
}
!hasAndroidFfmpeg || !hasCurrentBuildStamp
}
doLast {
stampFile.writeText(androidFfmpegBuildStamp(scriptFile))
}
}
tasks.register<Exec>("buildAndroidLibyuv") {
description = "Builds Android libyuv static libraries."
group = "build"
val libyuvRoot = file(androidLibyuvRoot.get())
val turbojpegRoot = file(androidTurbojpegRoot.get())
val scriptFile = androidLibyuvBuildScript.asFile
val stampFile = libyuvRoot.resolve(".one-kvm-android-libyuv.stamp")
dependsOn("buildAndroidTurbojpeg")
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
commandLine(
"bash",
scriptFile.absolutePath,
"--output",
libyuvRoot.absolutePath,
"--ndk",
androidNdkDir.absolutePath,
"--api",
androidApiLevel.toString(),
"--abis",
selectedAndroidAbis.joinToString(","),
"--jpeg-root",
turbojpegRoot.absolutePath,
)
inputs.file(scriptFile)
outputs.dir(libyuvRoot)
onlyIf {
val hasAndroidLibyuv = androidLibyuvRequiredFiles(libyuvRoot).all { it.exists() }
val hasCurrentBuildStamp =
stampFile.exists() && stampFile.readText() == androidLibyuvBuildStamp(scriptFile)
!hasAndroidLibyuv || !hasCurrentBuildStamp
}
doLast {
stampFile.writeText(androidLibyuvBuildStamp(scriptFile))
}
}
tasks.register<Exec>("buildAndroidTurbojpeg") {
description = "Builds Android TurboJPEG static libraries."
group = "build"
val turbojpegRoot = file(androidTurbojpegRoot.get())
val scriptFile = androidTurbojpegBuildScript.asFile
val stampFile = turbojpegRoot.resolve(".one-kvm-android-turbojpeg.stamp")
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
commandLine(
"bash",
scriptFile.absolutePath,
"--output",
turbojpegRoot.absolutePath,
"--ndk",
androidNdkDir.absolutePath,
"--api",
androidApiLevel.toString(),
"--abis",
selectedAndroidAbis.joinToString(","),
)
inputs.file(scriptFile)
outputs.dir(turbojpegRoot)
onlyIf {
val hasAndroidTurbojpeg = androidTurbojpegRequiredFiles(turbojpegRoot).all { it.exists() }
val hasCurrentBuildStamp =
stampFile.exists() && stampFile.readText() == androidTurbojpegBuildStamp(scriptFile)
!hasAndroidTurbojpeg || !hasCurrentBuildStamp
}
doLast {
stampFile.writeText(androidTurbojpegBuildStamp(scriptFile))
}
}
tasks.register<Exec>("buildAndroidAlsa") {
description = "Builds Android ALSA shared libraries."
group = "build"
val alsaRoot = file(androidAlsaRoot.get())
val scriptFile = androidAlsaBuildScript.asFile
val stampFile = alsaRoot.resolve(".one-kvm-android-alsa.stamp")
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
commandLine(
"bash",
scriptFile.absolutePath,
"--output",
alsaRoot.absolutePath,
"--ndk",
androidNdkDir.absolutePath,
"--api",
androidApiLevel.toString(),
"--abis",
selectedAndroidAbis.joinToString(","),
)
inputs.file(scriptFile)
outputs.dir(alsaRoot)
onlyIf {
val hasAndroidAlsa = androidAlsaRequiredFiles(alsaRoot).all { it.exists() }
val hasCurrentBuildStamp =
stampFile.exists() && stampFile.readText() == androidAlsaBuildStamp(scriptFile)
!hasAndroidAlsa || !hasCurrentBuildStamp
}
doLast {
stampFile.writeText(androidAlsaBuildStamp(scriptFile))
}
}
tasks.register<Exec>("buildAndroidOpus") {
description = "Builds Android Opus shared libraries."
group = "build"
val opusRoot = file(androidOpusRoot.get())
val scriptFile = androidOpusBuildScript.asFile
val stampFile = opusRoot.resolve(".one-kvm-android-opus.stamp")
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
commandLine(
"bash",
scriptFile.absolutePath,
"--output",
opusRoot.absolutePath,
"--ndk",
androidNdkDir.absolutePath,
"--api",
androidApiLevel.toString(),
"--abis",
selectedAndroidAbis.joinToString(","),
)
inputs.file(scriptFile)
outputs.dir(opusRoot)
onlyIf {
val hasAndroidOpus = androidOpusRequiredFiles(opusRoot).all { it.exists() }
val hasCurrentBuildStamp =
stampFile.exists() && stampFile.readText() == androidOpusBuildStamp(scriptFile)
!hasAndroidOpus || !hasCurrentBuildStamp
}
doLast {
stampFile.writeText(androidOpusBuildStamp(scriptFile))
}
}
val cargoBuildAndroidAbiTaskNames = selectedAndroidAbiTargets.map { (abi, targets) ->
val (flavor, _, _) = targets
val taskName = "cargoBuildAndroid" + flavor.replaceFirstChar {
if (it.isLowerCase()) it.titlecase() else it.toString()
}
tasks.register<Exec>(taskName) {
description = "Builds the Android Rust bootstrap libraries for $abi."
group = "build"
dependsOn(
"buildAndroidFfmpegMediaCodec",
"buildAndroidLibyuv",
"buildAndroidTurbojpeg",
"buildAndroidAlsa",
"buildAndroidOpus",
)
val cargoCommand = mutableListOf(
"cargo",
"ndk",
"-t",
abi,
"-P",
androidApiLevel.toString(),
"-o",
nativeCargoOutputDir.get().asFile.absolutePath,
"build",
"--lib",
"--bins",
)
if (androidBuildProfile == "release") {
cargoCommand.add("--release")
}
workingDir = nativeCrateDir.asFile
commandLine(cargoCommand)
args("--features", "android-mediacodec")
environment("ONE_KVM_ANDROID_FFMPEG_ROOT", androidFfmpegRoot.get())
environment("ONE_KVM_ANDROID_LIBYUV_ROOT", androidLibyuvRoot.get())
environment("ONE_KVM_ANDROID_LIBYUV_STATIC", "1")
environment("TURBOJPEG_SOURCE", "explicit")
environment("TURBOJPEG_STATIC", "1")
environment(
"TURBOJPEG_LIB_DIR",
file(androidTurbojpegRoot.get()).resolve("$abi/lib").absolutePath,
)
environment(
"TURBOJPEG_INCLUDE_DIR",
file(androidTurbojpegRoot.get()).resolve("$abi/include").absolutePath,
)
environment("PKG_CONFIG_ALLOW_CROSS", "1")
environment(
"PKG_CONFIG_LIBDIR",
file(androidAlsaRoot.get()).resolve("$abi/lib/pkgconfig").absolutePath,
)
environment("PKG_CONFIG_SYSROOT_DIR", "")
environment("LIBOPUS_NO_PKG", "1")
environment("LIBOPUS_LIB_DIR", file(androidOpusRoot.get()).resolve("$abi/lib").absolutePath)
environment("ANDROID_HOME", androidSdkDir.absolutePath)
environment("ANDROID_SDK_ROOT", androidSdkDir.absolutePath)
environment("ANDROID_NDK_HOME", androidNdkDir.absolutePath)
environment("ANDROID_NDK", androidNdkDir.absolutePath)
environment("ANDROID_NDK_ROOT", androidNdkDir.absolutePath)
inputs.files(
nativeCrateDir.file("Cargo.toml"),
nativeCrateDir.dir("src"),
rootCrateDir.file("Cargo.lock"),
rootCrateDir.file("Cargo.toml"),
rootCrateDir.file("build.rs"),
rootCrateDir.dir("libs"),
rootCrateDir.dir("res/vcpkg/libyuv"),
rootCrateDir.dir("src"),
)
outputs.dir(nativeCargoOutputDir)
outputs.dir(file(androidFfmpegRoot.get()))
outputs.dir(file(androidLibyuvRoot.get()))
outputs.dir(file(androidTurbojpegRoot.get()))
outputs.dir(file(androidAlsaRoot.get()))
outputs.dir(file(androidOpusRoot.get()))
}
taskName
}
tasks.register("cargoBuildAndroid") {
description = "Builds the Android Rust bootstrap libraries."
group = "build"
dependsOn(cargoBuildAndroidAbiTaskNames)
outputs.dir(nativeOutputRoot)
outputs.dir(nativeAssetRoot)
doLast {
selectedAndroidAbiTargets.forEach { (abi, targets) ->
val (flavor, rustTriple, ndkTriple) = targets
val nativeLibSource = nativeCargoOutputDir.get().file("$abi/libone_kvm_android_bootstrap.so").asFile
if (!nativeLibSource.exists()) {
throw GradleException("Missing Android JNI library: ${nativeLibSource.absolutePath}")
}
copy {
from(nativeLibSource)
into(nativeOutputRoot.get().dir(flavor).dir(abi))
}
val source = nativeCrateDir.file("target/$rustTriple/$androidBuildProfile/one-kvm-android-host").asFile
if (!source.exists()) {
throw GradleException("Missing Android host binary: ${source.absolutePath}")
}
copy {
from(source)
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
rename { "one-kvm-android-host" }
}
val cxxShared = androidNdkDir
.resolve("toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/$ndkTriple/libc++_shared.so")
if (!cxxShared.exists()) {
throw GradleException("Missing NDK libc++_shared.so: ${cxxShared.absolutePath}")
}
copy {
from(cxxShared)
into(nativeOutputRoot.get().dir(flavor).dir(abi))
}
copy {
from(cxxShared)
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
}
val alsaShared = file(androidAlsaRoot.get()).resolve("$abi/lib/libasound.so")
if (!alsaShared.exists()) {
throw GradleException("Missing Android ALSA library: ${alsaShared.absolutePath}")
}
copy {
from(alsaShared)
into(nativeOutputRoot.get().dir(flavor).dir(abi))
}
copy {
from(alsaShared)
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
}
copy {
from(file(androidAlsaRoot.get()).resolve("$abi/share/alsa"))
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi/alsa"))
}
val opusShared = file(androidOpusRoot.get()).resolve("$abi/lib/libopus.so")
if (!opusShared.exists()) {
throw GradleException("Missing Android Opus library: ${opusShared.absolutePath}")
}
copy {
from(opusShared)
into(nativeOutputRoot.get().dir(flavor).dir(abi))
}
copy {
from(opusShared)
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
}
}
}
}
tasks.named("preBuild") {
dependsOn("cargoBuildAndroid")
}

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="false"
android:icon="@drawable/ic_launcher_one_kvm"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<service
android:name=".OneKvmService"
android:exported="false"
android:foregroundServiceType="connectedDevice" />
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,13 @@
package cn.one_kvm.androidhost
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED && HostSettings.getAutoStart(context)) {
OneKvmService.start(context)
}
}
}

View File

@@ -0,0 +1,33 @@
package cn.one_kvm.androidhost
import android.content.Context
object HostSettings {
private const val PREFS = "one_kvm_android"
private const val KEY_AUTO_START = "auto_start"
private const val KEY_CLEAR_EXISTING_OTG = "clear_existing_otg"
fun getAutoStart(context: Context): Boolean {
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_AUTO_START, false)
}
fun setAutoStart(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.edit()
.putBoolean(KEY_AUTO_START, enabled)
.apply()
}
fun getClearExistingOtg(context: Context): Boolean {
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getBoolean(KEY_CLEAR_EXISTING_OTG, false)
}
fun setClearExistingOtg(context: Context, enabled: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.edit()
.putBoolean(KEY_CLEAR_EXISTING_OTG, enabled)
.apply()
}
}

View File

@@ -0,0 +1,30 @@
package cn.one_kvm.androidhost
import android.content.Context
object LogConfig {
private const val PREFS = "one_kvm_android"
private const val KEY_LOG_LEVEL = "log_level"
const val DEFAULT_LEVEL = "info"
val LEVELS = arrayOf("error", "warn", "info", "debug", "trace")
fun getLevel(context: Context): String {
val value = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getString(KEY_LOG_LEVEL, DEFAULT_LEVEL)
?: DEFAULT_LEVEL
return if (LEVELS.contains(value)) value else DEFAULT_LEVEL
}
fun setLevel(context: Context, level: String) {
val safeLevel = if (LEVELS.contains(level)) level else DEFAULT_LEVEL
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.edit()
.putString(KEY_LOG_LEVEL, safeLevel)
.apply()
}
fun rustLogFilter(level: String): String {
val safeLevel = if (LEVELS.contains(level)) level else DEFAULT_LEVEL
return "one_kvm=$safeLevel,hwcodec=$safeLevel,tower_http=$safeLevel,webrtc_sctp=warn"
}
}

View File

@@ -0,0 +1,71 @@
package cn.one_kvm.androidhost
import android.content.Context
import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
object LogStore {
private const val FLUSH_DELAY_MS = 250L
private const val MAX_BUFFER_CHARS = 64 * 1024
private val lock = Any()
private val buffer = StringBuilder()
private val executor = Executors.newSingleThreadScheduledExecutor { runnable ->
Thread(runnable, "OneKvmLogStore").apply { isDaemon = true }
}
private var logFile: File? = null
private var flushScheduled = false
fun defaultLogFile(context: Context): File {
return File(File(context.getExternalFilesDir(null), "runtime"), "one-kvm.log")
}
fun configure(file: File) {
synchronized(lock) {
flushLocked()
file.parentFile?.mkdirs()
file.writeText("")
buffer.clear()
logFile = file
flushScheduled = false
}
}
fun append(line: String) {
synchronized(lock) {
if (logFile == null) return
buffer.append(line).append('\n')
if (buffer.length >= MAX_BUFFER_CHARS) {
flushLocked()
return
}
if (!flushScheduled) {
flushScheduled = true
executor.schedule({ flush() }, FLUSH_DELAY_MS, TimeUnit.MILLISECONDS)
}
}
}
fun flush() {
synchronized(lock) {
flushLocked()
}
}
private fun flushLocked() {
val file = logFile ?: return
if (buffer.isEmpty()) {
flushScheduled = false
return
}
val text = buffer.toString()
buffer.clear()
flushScheduled = false
file.appendText(text)
}
}

View File

@@ -0,0 +1,452 @@
package cn.one_kvm.androidhost
import android.app.Activity
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.Spinner
import android.widget.Switch
import android.widget.TextView
import java.net.Inet4Address
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.Socket
import java.util.Collections
class MainActivity : Activity() {
private lateinit var statusValue: TextView
private lateinit var hostActionButton: Button
private lateinit var logLevelSpinner: Spinner
private lateinit var autoStartSwitch: Switch
private lateinit var clearOtgSwitch: Switch
private val statusHandler = Handler(Looper.getMainLooper())
private var statusPollsRemaining = 0
private val statusPoller = object : Runnable {
override fun run() {
refreshStatus()
statusPollsRemaining -= 1
if (statusPollsRemaining > 0) {
statusHandler.postDelayed(this, STATUS_POLL_INTERVAL_MS)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.statusBarColor = color("#F8FAFC")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
window.navigationBarColor = color("#F8FAFC")
}
val content = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(20.dp(), 24.dp(), 20.dp(), 28.dp())
background = solid("#F8FAFC")
}
content.addView(startCard())
content.addView(settingsCard())
content.addView(infoCard())
setContentView(ScrollView(this).apply {
isFillViewport = true
setBackgroundColor(color("#F8FAFC"))
addView(content)
})
}
override fun onResume() {
super.onResume()
reconcilePersistedStatus()
refreshStatus()
autoStartSwitch.isChecked = HostSettings.getAutoStart(this)
clearOtgSwitch.isChecked = HostSettings.getClearExistingOtg(this)
}
override fun onPause() {
statusHandler.removeCallbacks(statusPoller)
super.onPause()
}
private fun startCard(): View {
return card {
addView(sectionTitle("启动管理"))
addView(TextView(this@MainActivity).apply {
text = "管理本机 One-KVM 服务进程。暂停会停止前台服务并释放运行资源。"
textSize = 14f
setTextColor(color("#64748B"))
setPadding(0, 6.dp(), 0, 14.dp())
})
statusValue = TextView(this@MainActivity).apply {
textSize = 14f
typeface = Typeface.DEFAULT_BOLD
setTextColor(color("#0F172A"))
background = rounded("#EFF6FF", "#BFDBFE", 8)
setPadding(12.dp(), 8.dp(), 12.dp(), 8.dp())
}
addView(statusValue, matchWrap())
addView(LinearLayout(this@MainActivity).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(0, 14.dp(), 0, 0)
hostActionButton = actionButton("启动", primary = true) { toggleHost() }
addView(hostActionButton, matchButton())
})
refreshStatus()
}
}
private fun settingsCard(): View {
return card {
addView(sectionTitle("运行设置"))
val (autoStartRow, autoStartControl) = settingSwitchRow(
title = "开机自启动",
subtitle = "系统启动完成后自动拉起 One-KVM 前台服务。",
checked = HostSettings.getAutoStart(this@MainActivity),
) { _, checked ->
HostSettings.setAutoStart(this@MainActivity, checked)
LogStore.append("Boot auto-start ${if (checked) "enabled" else "disabled"}")
}
autoStartSwitch = autoStartControl
addView(autoStartRow)
addView(divider())
val (clearOtgRow, clearOtgControl) = settingSwitchRow(
title = "清除已有 OTG Gadget",
subtitle = "启动 root host 前尝试解绑并删除 configfs 中已有的 USB gadget。",
checked = HostSettings.getClearExistingOtg(this@MainActivity),
) { _, checked ->
HostSettings.setClearExistingOtg(this@MainActivity, checked)
LogStore.append("Clear existing OTG gadget ${if (checked) "enabled" else "disabled"}")
}
clearOtgSwitch = clearOtgControl
addView(clearOtgRow)
addView(divider())
addView(logLevelRow())
}
}
private fun infoCard(): View {
return card {
addView(sectionTitle("应用信息"))
addView(infoRow("软件内核版本", kernelVersion()))
addView(infoRow("访问地址", accessAddresses(), selectable = true))
addView(infoRow("日志文件", LogStore.defaultLogFile(this@MainActivity).absolutePath, selectable = true))
}
}
private fun settingSwitchRow(
title: String,
subtitle: String,
checked: Boolean,
listener: CompoundButton.OnCheckedChangeListener,
): Pair<View, Switch> {
val switch = Switch(this).apply {
isChecked = checked
setOnCheckedChangeListener(listener)
}
val row = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(0, 12.dp(), 0, 12.dp())
addView(LinearLayout(this@MainActivity).apply {
orientation = LinearLayout.VERTICAL
addView(TextView(this@MainActivity).apply {
text = title
textSize = 15f
typeface = Typeface.DEFAULT_BOLD
setTextColor(color("#0F172A"))
})
addView(TextView(this@MainActivity).apply {
text = subtitle
textSize = 13f
setTextColor(color("#64748B"))
setPadding(0, 4.dp(), 12.dp(), 0)
})
}, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
addView(switch)
}
return row to switch
}
private fun infoRow(label: String, value: String, selectable: Boolean = false): View {
return LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(0, 12.dp(), 0, 12.dp())
addView(TextView(this@MainActivity).apply {
text = label
textSize = 13f
setTextColor(color("#64748B"))
})
addView(TextView(this@MainActivity).apply {
text = value
textSize = 15f
setTextColor(color("#0F172A"))
setPadding(0, 4.dp(), 0, 0)
setTextIsSelectable(selectable)
})
addView(divider())
}
}
private fun logLevelRow(): View {
return LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(0, 12.dp(), 0, 0)
addView(TextView(this@MainActivity).apply {
text = "日志级别"
textSize = 15f
typeface = Typeface.DEFAULT_BOLD
setTextColor(color("#0F172A"))
}, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
logLevelSpinner = Spinner(this@MainActivity).apply {
adapter = ArrayAdapter(
this@MainActivity,
android.R.layout.simple_spinner_dropdown_item,
LogConfig.LEVELS,
)
setSelection(LogConfig.LEVELS.indexOf(LogConfig.getLevel(this@MainActivity)).coerceAtLeast(0))
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val level = LogConfig.LEVELS[position]
if (level != LogConfig.getLevel(this@MainActivity)) {
LogConfig.setLevel(this@MainActivity, level)
LogStore.append("Log level set to $level; restart service to apply")
}
}
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
}
}
addView(logLevelSpinner)
}
}
private fun card(build: LinearLayout.() -> Unit): View {
return LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(16.dp(), 16.dp(), 16.dp(), 16.dp())
background = rounded("#FFFFFF", "#E2E8F0", 10)
elevation = 1.5f.dpFloat()
build()
}.also {
it.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { setMargins(0, 0, 0, 14.dp()) }
}
}
private fun sectionTitle(text: String): View {
return TextView(this).apply {
this.text = text
textSize = 17f
typeface = Typeface.DEFAULT_BOLD
setTextColor(color("#0F172A"))
}
}
private fun actionButton(text: String, primary: Boolean, action: () -> Unit): Button {
return Button(this).apply {
this.text = text
textSize = 15f
isAllCaps = false
minHeight = 44.dp()
setTextColor(color(if (primary) "#FFFFFF" else "#0F172A"))
background = if (primary) rounded("#2563EB", "#2563EB", 8) else rounded("#FFFFFF", "#CBD5E1", 8)
setOnClickListener { action() }
}
}
private fun toggleHost() {
when (ServiceStatusStore.snapshot(this).state) {
ServiceStatusStore.STATE_RUNNING -> pauseHost()
ServiceStatusStore.STATE_STOPPED, ServiceStatusStore.STATE_ERROR -> startHost()
}
}
private fun startHost() {
ServiceStatusStore.setStarting(this)
refreshStatus()
OneKvmService.start(this)
LogStore.append("Start requested from app UI")
pollStatusForAWhile()
}
private fun pauseHost() {
ServiceStatusStore.setStopping(this)
refreshStatus()
OneKvmService.stop(this)
LogStore.append("Pause requested from app UI")
pollStatusForAWhile()
}
private fun refreshStatus() {
if (::statusValue.isInitialized) {
statusValue.text = "状态:${hostStatusSummary()}"
}
updateHostActionButton()
}
private fun hostStatusSummary(): String {
val serviceStatus = ServiceStatusStore.snapshot(this)
if (serviceStatus.state != ServiceStatusStore.STATE_STOPPED) {
return serviceStatus.labelText()
}
val nativeRunning = runCatching {
NativeBridge.hostStatus().contains("running", ignoreCase = true)
}.getOrDefault(false)
return if (nativeRunning) "运行中" else "已停止"
}
private fun reconcilePersistedStatus() {
val serviceStatus = ServiceStatusStore.snapshot(this)
if (serviceStatus.state == ServiceStatusStore.STATE_STOPPED) return
if (
serviceStatus.state == ServiceStatusStore.STATE_STARTING &&
System.currentTimeMillis() - serviceStatus.updatedAt < STARTING_RECONCILE_GRACE_MS
) {
return
}
Thread {
val portOpen = isLocalWebPortOpen()
val nativeRunning = runCatching { NativeBridge.hostStatus().contains("running", ignoreCase = true) }
.getOrDefault(false)
if (!portOpen && !nativeRunning) {
ServiceStatusStore.setStopped(this, "服务未运行")
runOnUiThread { refreshStatus() }
}
}.start()
}
private fun isLocalWebPortOpen(): Boolean {
return runCatching {
Socket().use { socket ->
socket.connect(InetSocketAddress("127.0.0.1", 8080), 250)
}
true
}.getOrDefault(false)
}
private fun updateHostActionButton() {
if (!::hostActionButton.isInitialized) return
when (ServiceStatusStore.snapshot(this).state) {
ServiceStatusStore.STATE_STARTING -> setHostActionButton("启动中...", enabled = false, primary = true)
ServiceStatusStore.STATE_RUNNING -> setHostActionButton("停止", enabled = true, primary = false)
ServiceStatusStore.STATE_STOPPING -> setHostActionButton("停止中...", enabled = false, primary = false)
else -> setHostActionButton("启动", enabled = true, primary = true)
}
}
private fun setHostActionButton(text: String, enabled: Boolean, primary: Boolean) {
hostActionButton.text = text
hostActionButton.isEnabled = enabled
hostActionButton.alpha = if (enabled) 1f else 0.65f
hostActionButton.setTextColor(color(if (primary) "#FFFFFF" else "#0F172A"))
hostActionButton.background = if (primary) {
rounded("#2563EB", "#2563EB", 8)
} else {
rounded("#FFFFFF", "#CBD5E1", 8)
}
}
private fun pollStatusForAWhile() {
statusPollsRemaining = 20
statusHandler.removeCallbacks(statusPoller)
statusHandler.postDelayed(statusPoller, STATUS_POLL_INTERVAL_MS)
}
private fun kernelVersion(): String {
return runCatching { NativeBridge.kernelVersion() }
.getOrElse { "unknown" }
}
private fun accessAddresses(): String {
val addresses = runCatching {
Collections.list(NetworkInterface.getNetworkInterfaces())
.filter { it.isUp && !it.isLoopback }
.flatMap { iface -> Collections.list(iface.inetAddresses) }
.filterIsInstance<Inet4Address>()
.filter { !it.isLoopbackAddress }
.map { "http://${it.hostAddress}:8080" }
.distinct()
}.getOrDefault(emptyList())
return (addresses.ifEmpty { listOf("http://127.0.0.1:8080") }).joinToString("\n")
}
private fun divider(): View {
return View(this).apply {
setBackgroundColor(color("#E2E8F0"))
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
1,
).apply { setMargins(0, 0, 0, 0) }
}
}
private fun matchWrap(): LinearLayout.LayoutParams {
return LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
)
}
private fun matchButton(): LinearLayout.LayoutParams {
return LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
48.dp(),
)
}
private fun solid(hex: String): GradientDrawable = GradientDrawable().apply {
setColor(color(hex))
}
private fun rounded(fill: String, stroke: String, radiusDp: Int): GradientDrawable {
return GradientDrawable().apply {
setColor(color(fill))
cornerRadius = radiusDp.dpFloat()
setStroke(1.dp(), color(stroke))
}
}
private fun color(hex: String): Int = Color.parseColor(hex)
private fun Int.dp(): Int = (this * resources.displayMetrics.density + 0.5f).toInt()
private fun Int.dpFloat(): Float = this * resources.displayMetrics.density
private fun Float.dpFloat(): Float = this * resources.displayMetrics.density
companion object {
private const val STATUS_POLL_INTERVAL_MS = 500L
private const val STARTING_RECONCILE_GRACE_MS = 15_000L
}
}

View File

@@ -0,0 +1,21 @@
package cn.one_kvm.androidhost
import android.content.Context
object NativeBridge {
init {
System.loadLibrary("one_kvm_android_bootstrap")
}
external fun initTlsVerifier(context: Context): Int
external fun setEnv(name: String, value: String): Int
external fun startHost(dataDir: String, bindAddress: String, port: Int): String
external fun stopHost(): String
external fun hostStatus(): String
external fun kernelVersion(): String
}

View File

@@ -0,0 +1,413 @@
package cn.one_kvm.androidhost
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.io.InterruptedIOException
import java.util.concurrent.Executors
class OneKvmService : Service() {
private var rootProcess: Process? = null
private val commandExecutor = Executors.newSingleThreadExecutor { runnable ->
Thread(runnable, "OneKvmServiceCommand")
}
override fun onCreate() {
super.onCreate()
ensureNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action ?: ACTION_START) {
ACTION_STOP -> {
ServiceStatusStore.setStopping(this)
commandExecutor.execute {
stopHostRuntime()
stopSelfResult(startId)
}
return START_NOT_STICKY
}
ACTION_START -> {
ServiceStatusStore.setStarting(this)
startForegroundCompat(NOTIFICATION_ID, notification("启动中"))
commandExecutor.execute {
val currentState = ServiceStatusStore.snapshot(this).state
if (currentState == ServiceStatusStore.STATE_RUNNING && isPortOpen(8080, 100)) {
return@execute
}
val dataDir = File(getExternalFilesDir(null), "runtime")
if (!dataDir.exists()) dataDir.mkdirs()
val result = startRustHost(dataDir)
if (result.startsWith("Running") && !result.contains("start failed", ignoreCase = true)) {
ServiceStatusStore.setRunning(this, "服务已启动")
notificationManager().notify(NOTIFICATION_ID, notification("运行中"))
} else {
ServiceStatusStore.setError(this, "启动失败")
notificationManager().notify(NOTIFICATION_ID, notification("启动失败"))
}
}
}
}
return START_STICKY
}
override fun onDestroy() {
stopHostRuntime(updateNotification = false)
commandExecutor.shutdownNow()
ServiceStatusStore.setStopped(this)
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun notification(state: String): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = createContentIntent(intent)
val builder = createNotificationBuilder()
return builder
.setSmallIcon(R.drawable.ic_stat_one_kvm)
.setContentTitle("One-KVM Android Host")
.setContentText(state)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build()
}
private fun ensureNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(
CHANNEL_ID,
"One-KVM Host",
NotificationManager.IMPORTANCE_LOW,
)
notificationManager().createNotificationChannel(channel)
}
@Suppress("DEPRECATION")
private fun createNotificationBuilder(): Notification.Builder {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
Notification.Builder(this)
}
}
private fun createContentIntent(intent: Intent): PendingIntent {
val flags = pendingIntentFlags()
return PendingIntent.getActivity(this, 0, intent, flags)
}
private fun pendingIntentFlags(): Int {
var flags = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags = flags or pendingIntentImmutableFlag()
}
return flags
}
private fun pendingIntentImmutableFlag(): Int {
return try {
PendingIntent::class.java.getField("FLAG_IMMUTABLE").getInt(null)
} catch (_: ReflectiveOperationException) {
0
}
}
private fun notificationManager(): NotificationManager {
return getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
private fun stopHostRuntime(updateNotification: Boolean = true) {
stopRootHost()
NativeBridge.stopHost()
waitForPortRelease(8080, 2_000)
LogStore.flush()
ServiceStatusStore.setStopped(this)
if (updateNotification) {
notificationManager().notify(NOTIFICATION_ID, notification("已停止"))
}
}
private fun startRustHost(dataDir: File): String {
val logLevel = LogConfig.getLevel(this)
val rustLog = LogConfig.rustLogFilter(logLevel)
val appLogFile = LogStore.defaultLogFile(this)
LogStore.configure(appLogFile)
val rustLogFile = appLogFile
LogStore.append("Starting One-KVM Rust host, data_dir=${dataDir.absolutePath}, log_level=$logLevel")
val executable = extractHostBinary()
return runCatching {
val tlsInit = NativeBridge.initTlsVerifier(this)
if (tlsInit != 0) {
throw IllegalStateException("rustls platform verifier init failed with code $tlsInit")
}
stopRootHost(executable)
clearExistingOtgGadgetsIfEnabled()
startRootHost(executable, dataDir, rustLog, rustLogFile, logLevel)
LogStore.append("Rust host running as root on port 8080")
"Running as root on port 8080"
}.getOrElse { rootError ->
LogStore.append("Root host unavailable: ${rootError.message ?: rootError::class.java.simpleName}")
configureAlsaEnvironment(executable)
NativeBridge.setEnv("RUST_LOG", rustLog)
NativeBridge.setEnv("ONE_KVM_FFMPEG_LOG", ffmpegLogLevel(logLevel))
NativeBridge.setEnv("ONE_KVM_ANDROID_LOG_FILE", rustLogFile.absolutePath)
val jniResult = NativeBridge.startHost(dataDir.absolutePath, "0.0.0.0", 8080)
LogStore.append("Rust host running in app process on port 8080: $jniResult")
"Running in app process on port 8080 (${rootError.message ?: "root unavailable"}; $jniResult)"
}
}
private fun clearExistingOtgGadgetsIfEnabled() {
if (!HostSettings.getClearExistingOtg(this)) return
val command = """
root=/sys/kernel/config/usb_gadget
[ -d "${'$'}root" ] || exit 0
for gadget in "${'$'}root"/*; do
[ -d "${'$'}gadget" ] || continue
[ -w "${'$'}gadget/UDC" ] && echo "" > "${'$'}gadget/UDC" 2>/dev/null || true
find "${'$'}gadget/configs" -type l -delete 2>/dev/null || true
rm -rf "${'$'}gadget" 2>/dev/null || true
done
""".trimIndent()
runCatching {
ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
.redirectErrorStream(true)
.start()
.waitFor()
}.onSuccess { exit ->
LogStore.append("Existing OTG gadget cleanup finished with exit code $exit")
}.onFailure { err ->
LogStore.append("Existing OTG gadget cleanup failed: ${err.message ?: err::class.java.simpleName}")
}
}
private fun configureAlsaEnvironment(executable: File) {
val binDir = executable.parentFile
?: throw IllegalStateException("host binary has no parent directory")
val alsaConfigDir = File(binDir, "alsa")
val alsaConfigPath = File(alsaConfigDir, "alsa.conf")
NativeBridge.setEnv("ALSA_CONFIG_DIR", alsaConfigDir.absolutePath)
NativeBridge.setEnv("ALSA_CONFIG_PATH", alsaConfigPath.absolutePath)
}
private fun extractHostBinary(): File {
val abi = Build.SUPPORTED_ABIS.firstOrNull { it == "arm64-v8a" || it == "armeabi-v7a" }
?: throw IllegalStateException("unsupported ABI: ${Build.SUPPORTED_ABIS.joinToString()}")
val binDir = File(filesDir, "bin/$abi")
val target = File(binDir, "one-kvm-android-host")
copyAssetIfChanged("bin/$abi/one-kvm-android-host", target)
copyAssetIfChanged("bin/$abi/libc++_shared.so", File(binDir, "libc++_shared.so"))
copyAssetIfChanged("bin/$abi/libasound.so", File(binDir, "libasound.so"))
copyAssetIfChanged("bin/$abi/libopus.so", File(binDir, "libopus.so"))
copyAssetDirectoryIfChanged("bin/$abi/alsa", File(binDir, "alsa"))
if (!target.setExecutable(true, false)) {
throw IllegalStateException("cannot mark host binary executable")
}
return target
}
private fun copyAssetIfChanged(assetPath: String, target: File) {
val stamp = File(target.parentFile, "${target.name}.stamp")
@Suppress("DEPRECATION")
val packageInfo = packageManager.getPackageInfo(packageName, 0)
val expectedStamp = "${packageInfo.lastUpdateTime}:$assetPath"
if (target.exists() && stamp.exists() && stamp.readText() == expectedStamp) return
target.parentFile?.mkdirs()
assets.open(assetPath).use { input ->
target.outputStream().use { output -> input.copyTo(output) }
}
stamp.writeText(expectedStamp)
}
private fun copyAssetDirectoryIfChanged(assetDir: String, targetDir: File) {
@Suppress("DEPRECATION")
val packageInfo = packageManager.getPackageInfo(packageName, 0)
val stamp = File(targetDir, ".stamp")
val expectedStamp = "${packageInfo.lastUpdateTime}:$assetDir"
if (targetDir.exists() && stamp.exists() && stamp.readText() == expectedStamp) return
if (targetDir.exists()) targetDir.deleteRecursively()
copyAssetDirectory(assetDir, targetDir)
stamp.writeText(expectedStamp)
}
private fun copyAssetDirectory(assetDir: String, targetDir: File) {
targetDir.mkdirs()
val children = assets.list(assetDir)?.filter { it.isNotEmpty() }.orEmpty()
for (child in children) {
val childAsset = "$assetDir/$child"
val childTarget = File(targetDir, child)
val grandChildren = assets.list(childAsset)?.filter { it.isNotEmpty() }.orEmpty()
if (grandChildren.isEmpty()) {
copyAssetIfChanged(childAsset, childTarget)
} else {
copyAssetDirectory(childAsset, childTarget)
}
}
}
private fun startRootHost(
executable: File,
dataDir: File,
rustLog: String,
rustLogFile: File,
logLevel: String,
) {
stopRootHost(executable)
waitForPortRelease(8080, 2_000)
val libDir = executable.parentFile?.absolutePath
?: throw IllegalStateException("host binary has no parent directory")
val alsaConfigDir = File(executable.parentFile, "alsa")
val alsaConfigPath = File(alsaConfigDir, "alsa.conf")
val command =
"export LD_LIBRARY_PATH=${shellQuote(libDir)}:\${LD_LIBRARY_PATH:-}; " +
"export ALSA_CONFIG_DIR=${shellQuote(alsaConfigDir.absolutePath)}; " +
"export ALSA_CONFIG_PATH=${shellQuote(alsaConfigPath.absolutePath)}; " +
"export RUST_LOG=${shellQuote(rustLog)}; " +
"export ONE_KVM_FFMPEG_LOG=${shellQuote(ffmpegLogLevel(logLevel))}; " +
"export ONE_KVM_ANDROID_LOG_FILE=${shellQuote(rustLogFile.absolutePath)}; " +
"${shellQuote(executable.absolutePath)} ${shellQuote(dataDir.absolutePath)} 0.0.0.0 8080"
val process = ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
.redirectErrorStream(true)
.start()
rootProcess = process
Thread {
val readError = runCatching {
BufferedReader(InputStreamReader(process.inputStream)).useLines { lines ->
lines.forEach {
android.util.Log.i("OneKvmService", it)
}
}
}.exceptionOrNull()
if (readError != null && readError !is InterruptedIOException) {
android.util.Log.w("OneKvmService", "Root host log reader stopped", readError)
LogStore.append("Root host log reader stopped: ${readError.message ?: readError::class.java.simpleName}")
}
val exit = runCatching { process.waitFor() }.getOrNull()
if (rootProcess === process && exit != null) {
rootProcess = null
ServiceStatusStore.setError(this, "Root host exited with code $exit")
}
}.start()
Thread.sleep(500)
val exit = runCatching { process.exitValue() }.getOrNull()
if (exit != null) {
rootProcess = null
throw IllegalStateException("root host exited immediately: $exit")
}
}
private fun startForegroundCompat(id: Int, notification: Notification) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val invoked = runCatching {
val method = Service::class.java.getMethod(
"startForeground",
Int::class.javaPrimitiveType,
Notification::class.java,
Int::class.javaPrimitiveType,
)
method.invoke(this, id, notification, foregroundServiceTypeConnectedDevice())
}.isSuccess
if (invoked) return
}
super.startForeground(id, notification)
}
private fun foregroundServiceTypeConnectedDevice(): Int {
return try {
Service::class.java.getField("FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE").getInt(null)
} catch (_: ReflectiveOperationException) {
0
}
}
private fun stopRootHost(executable: File? = null) {
rootProcess?.destroy()
rootProcess = null
stopRootHostProcess(executable)
}
private fun stopRootHostProcess(executable: File? = null) {
val command = buildString {
append("pkill -TERM -f '[o]ne-kvm-android-host' 2>/dev/null || true; ")
append("for pid in $(pidof one-kvm-android-host 2>/dev/null); do kill -TERM \"${'$'}pid\" 2>/dev/null || true; done; ")
append("sleep 0.2; ")
append("pkill -KILL -f '[o]ne-kvm-android-host' 2>/dev/null || true; ")
append("for pid in $(pidof one-kvm-android-host 2>/dev/null); do kill -KILL \"${'$'}pid\" 2>/dev/null || true; done; ")
}
runCatching {
ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
.redirectErrorStream(true)
.start()
.waitFor()
}.onFailure { err ->
LogStore.append("Failed to stop stale root host: ${err.message ?: err::class.java.simpleName}")
}
}
private fun waitForPortRelease(port: Int, timeoutMs: Long) {
val deadline = System.currentTimeMillis() + timeoutMs
while (System.currentTimeMillis() < deadline) {
val inUse = isPortOpen(port, 100)
if (!inUse) return
Thread.sleep(100)
}
}
private fun isPortOpen(port: Int, timeoutMs: Int): Boolean {
return runCatching {
java.net.Socket().use { socket ->
socket.connect(java.net.InetSocketAddress("127.0.0.1", port), timeoutMs)
}
true
}.getOrDefault(false)
}
private fun shellQuote(value: String): String {
return "'" + value.replace("'", "'\\''") + "'"
}
private fun ffmpegLogLevel(level: String): String {
return when (level) {
"trace" -> "trace"
"debug" -> "debug"
"info" -> "info"
"warn" -> "warning"
else -> "error"
}
}
companion object {
private const val CHANNEL_ID = "one_kvm_host"
private const val NOTIFICATION_ID = 1001
const val ACTION_START = "cn.one_kvm.androidhost.START"
const val ACTION_STOP = "cn.one_kvm.androidhost.STOP"
fun start(context: Context) {
val intent = Intent(context, OneKvmService::class.java).setAction(ACTION_START)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
fun stop(context: Context) {
context.startService(Intent(context, OneKvmService::class.java).setAction(ACTION_STOP))
}
}
}

View File

@@ -0,0 +1,75 @@
package cn.one_kvm.androidhost
import android.content.Context
object ServiceStatusStore {
private const val PREFS = "one_kvm_android_status"
private const val KEY_STATE = "state"
private const val KEY_MESSAGE = "message"
private const val KEY_UPDATED_AT = "updated_at"
const val STATE_STOPPED = "stopped"
const val STATE_STARTING = "starting"
const val STATE_RUNNING = "running"
const val STATE_STOPPING = "stopping"
const val STATE_ERROR = "error"
data class Snapshot(
val state: String,
val message: String,
val updatedAt: Long,
) {
fun labelText(): String {
return when (state) {
STATE_STARTING -> "启动中"
STATE_RUNNING -> "运行中"
STATE_STOPPING -> "停止中"
STATE_ERROR -> "错误"
else -> "已停止"
}
}
fun displayText(): String {
val label = labelText()
return if (message.isBlank()) label else "$label$message"
}
}
fun setStarting(context: Context, message: String = "正在启动服务") {
write(context, STATE_STARTING, message)
}
fun setRunning(context: Context, message: String) {
write(context, STATE_RUNNING, message)
}
fun setStopping(context: Context, message: String = "正在停止服务") {
write(context, STATE_STOPPING, message)
}
fun setStopped(context: Context, message: String = "服务已停止") {
write(context, STATE_STOPPED, message)
}
fun setError(context: Context, message: String) {
write(context, STATE_ERROR, message)
}
fun snapshot(context: Context): Snapshot {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return Snapshot(
state = prefs.getString(KEY_STATE, STATE_STOPPED) ?: STATE_STOPPED,
message = prefs.getString(KEY_MESSAGE, "") ?: "",
updatedAt = prefs.getLong(KEY_UPDATED_AT, 0L),
)
}
private fun write(context: Context, state: String, message: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.edit()
.putString(KEY_STATE, state)
.putString(KEY_MESSAGE, message)
.putLong(KEY_UPDATED_AT, System.currentTimeMillis())
.apply()
}
}

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#1D7BF2"
android:pathData="M24,0h60a24,24 0,0 1,24 24v60a24,24 0,0 1,-24 24H24a24,24 0,0 1,-24 -24V24a24,24 0,0 1,24 -24z" />
<path
android:fillColor="#AED8E8"
android:pathData="M29,25h50a3,3 0,0 1,3 3v31a3,3 0,0 1,-3 3H29a3,3 0,0 1,-3 -3V28a3,3 0,0 1,3 -3z" />
<path
android:fillColor="#3F3F3D"
android:pathData="M31,30h46v27H31z" />
<path
android:fillColor="#E7F1F4"
android:pathData="M31,26h10a1.4,1.4 0,0 1,0 2.8H31a1.4,1.4 0,0 1,0 -2.8z" />
<path
android:fillColor="#8BBFD1"
android:pathData="M49,62h10l1.5,8h-13z" />
<path
android:fillColor="#9FCFE0"
android:pathData="M40,70a14,4.5 0,1 0,28 0a14,4.5 0,1 0,-28 0z" />
<path
android:fillColor="#E8F5F8"
android:pathData="M45,70a7,1.8 0,1 0,14 0a7,1.8 0,1 0,-14 0z" />
<path
android:fillColor="#BFE6F1"
android:pathData="M32,76h38l5,8H27z" />
<path
android:fillColor="#76ADC2"
android:pathData="M28,84h47v2H28z" />
<path
android:fillColor="#FFFFFF"
android:fillAlpha="0.82"
android:pathData="M37,79h6v2h-6zM46,79h5v2h-5zM54,79h5v2h-5zM62,79h6v2h-6zM34,82h7v2h-7zM44,82h6v2h-6zM53,82h11v2H53zM67,82h4v2h-4z" />
</vector>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4,5h16v10H4z" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M9,17h6v2h3v2H6v-2h3z" />
</vector>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">One-KVM Android Host</string>
</resources>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:colorAccent">#2563EB</item>
</style>
</resources>

3
android/build.gradle.kts Normal file
View File

@@ -0,0 +1,3 @@
plugins {
id("com.android.application") version "9.0.0" apply false
}

View File

@@ -0,0 +1,3 @@
android.useAndroidX=true
android.nonTransitiveRClass=true
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
android/gradlew vendored Executable file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

21
android/native/Cargo.toml Normal file
View File

@@ -0,0 +1,21 @@
[package]
name = "one-kvm-android-bootstrap"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "one_kvm_android_bootstrap"
crate-type = ["cdylib"]
[[bin]]
name = "one-kvm-android-host"
path = "src/bin/one-kvm-android-host.rs"
[dependencies]
jni = "0.22.4"
one-kvm = { path = "../..", default-features = false, features = ["android", "android-mediacodec"] }
rustls-platform-verifier = "0.7"
[features]
android-mediacodec = ["one-kvm/android-mediacodec"]

View File

@@ -0,0 +1,24 @@
use one_kvm::runtime::android::{self, AndroidRuntimeConfig};
fn main() {
let mut args = std::env::args().skip(1);
let data_dir = args
.next()
.unwrap_or_else(|| "/data/local/tmp/one-kvm".to_string());
let bind_address = args.next().unwrap_or_else(|| "0.0.0.0".to_string());
let port = args
.next()
.and_then(|value| value.parse::<u16>().ok())
.unwrap_or(8080);
one_kvm::runtime::android::init_rustls_provider();
if let Err(err) = android::run_foreground(AndroidRuntimeConfig {
data_dir,
bind_address,
port,
}) {
eprintln!("one-kvm android host failed: {err}");
std::process::exit(1);
}
}

182
android/native/src/lib.rs Normal file
View File

@@ -0,0 +1,182 @@
use jni::errors::{ErrorPolicy, ThrowRuntimeExAndDefault};
use jni::objects::{JClass, JObject, JString};
use jni::sys::{jint, jstring};
use jni::{Env, EnvOutcome, EnvUnowned};
use one_kvm::runtime::android::{self, AndroidRuntimeConfig};
#[derive(Debug)]
struct BridgeError(String);
impl From<jni::errors::Error> for BridgeError {
fn from(err: jni::errors::Error) -> Self {
Self(err.to_string())
}
}
impl From<String> for BridgeError {
fn from(err: String) -> Self {
Self(err)
}
}
impl std::fmt::Display for BridgeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Default)]
struct StatusPolicy;
impl ErrorPolicy<jint, BridgeError> for StatusPolicy {
type Captures<'unowned_env_local: 'native_method, 'native_method> = ();
fn on_error<'unowned_env_local: 'native_method, 'native_method>(
_env: &mut Env<'unowned_env_local>,
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
_err: BridgeError,
) -> jni::errors::Result<jint> {
Ok(-1)
}
fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
_env: &mut Env<'unowned_env_local>,
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
_payload: Box<dyn std::any::Any + Send + 'static>,
) -> jni::errors::Result<jint> {
Ok(-1)
}
}
#[derive(Debug, Default)]
struct StringResultPolicy;
impl ErrorPolicy<String, BridgeError> for StringResultPolicy {
type Captures<'unowned_env_local: 'native_method, 'native_method> = ();
fn on_error<'unowned_env_local: 'native_method, 'native_method>(
_env: &mut Env<'unowned_env_local>,
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
err: BridgeError,
) -> jni::errors::Result<String> {
Ok(format!("start failed: {err}"))
}
fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
_env: &mut Env<'unowned_env_local>,
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
_payload: Box<dyn std::any::Any + Send + 'static>,
) -> jni::errors::Result<String> {
Ok("start failed: panic in native bridge".to_string())
}
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_setEnv<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
name: JString<'local>,
value: JString<'local>,
) -> jint {
let outcome: EnvOutcome<'local, jint, BridgeError> = env.with_env_no_catch(|env| {
let name = name
.try_to_string(env)
.map_err(|err| BridgeError(format!("invalid env name: {err}")))?;
let value = value
.try_to_string(env)
.map_err(|err| BridgeError(format!("invalid env value: {err}")))?;
if name.contains('\0') || value.contains('\0') {
return Err(BridgeError("env contains NUL".to_string()));
}
std::env::set_var(name, value);
Ok(0)
});
outcome.resolve_with::<StatusPolicy, _>(|| ())
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_initTlsVerifier<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
context: JObject<'local>,
) -> jint {
let outcome: EnvOutcome<'local, jint, BridgeError> =
env.with_env_no_catch(|env| init_tls_verifier(env, context));
outcome.resolve_with::<StatusPolicy, _>(|| ())
}
#[cfg(target_os = "android")]
fn init_tls_verifier(env: &mut Env<'_>, context: JObject<'_>) -> Result<jint, BridgeError> {
rustls_platform_verifier::android::init_with_env(env, context)
.map_err(|err| BridgeError(format!("failed to initialize rustls platform verifier: {err}")))?;
Ok(0)
}
#[cfg(not(target_os = "android"))]
fn init_tls_verifier(_env: &mut Env<'_>, _context: JObject<'_>) -> Result<jint, BridgeError> {
Ok(0)
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_startHost<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
data_dir: JString<'local>,
bind_address: JString<'local>,
port: i32,
) -> jstring {
let outcome: EnvOutcome<'local, String, BridgeError> = env.with_env_no_catch(|env| {
let data_dir = data_dir
.try_to_string(env)
.map_err(|err| BridgeError(format!("invalid data dir: {err}")))?;
let bind_address = bind_address
.try_to_string(env)
.map_err(|err| BridgeError(format!("invalid bind address: {err}")))?;
let port = u16::try_from(port).map_err(|_| BridgeError("invalid port".to_string()))?;
android::start(AndroidRuntimeConfig {
data_dir,
bind_address,
port,
})
.map_err(BridgeError)
});
let result = outcome.resolve_with::<StringResultPolicy, _>(|| ());
env.with_env_no_catch(|env| env.new_string(result))
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
.into_raw()
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_stopHost<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
) -> jstring {
env.with_env_no_catch(|env| env.new_string(android::stop()))
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
.into_raw()
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_hostStatus<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
) -> jstring {
env.with_env_no_catch(|env| env.new_string(android::status()))
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
.into_raw()
}
#[no_mangle]
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_kernelVersion<'local>(
mut env: EnvUnowned<'local>,
_class: JClass<'local>,
) -> jstring {
env.with_env_no_catch(|env| env.new_string(env!("CARGO_PKG_VERSION")))
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
.into_raw()
}

View File

@@ -0,0 +1,18 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "OneKvmAndroidHost"
include(":app")

View File

@@ -64,25 +64,6 @@ fn generate_secrets() {
pub mod ice {
/// Google public STUN server URL (hardcoded)
pub const STUN_SERVER: &str = "stun:stun.l.google.com:19302";
/// TURN server URLs - not provided, users must configure their own
pub const TURN_URLS: &str = "";
/// TURN authentication username
pub const TURN_USERNAME: &str = "";
/// TURN authentication password
pub const TURN_PASSWORD: &str = "";
/// Always returns true since we have STUN
pub const fn is_configured() -> bool {
true
}
/// Always returns false since TURN is not provided
pub const fn has_turn() -> bool {
false
}
}
/// RustDesk public server configuration - NOT PROVIDED

View File

@@ -12,7 +12,8 @@ ARG TARGETPLATFORM
# Install runtime dependencies in a single layer
# All codec libraries (libx264, libx265, libopus) are now statically linked
# Only hardware acceleration drivers and core system libraries remain dynamic
RUN apt-get update && \
RUN sed -i 's/ main$/ main contrib non-free/' /etc/apt/sources.list && \
apt-get update && \
apt-get install -y --no-install-recommends \
# Core runtime (all platforms) - no codec libs needed
ca-certificates \
@@ -24,7 +25,8 @@ RUN apt-get update && \
# Platform-specific hardware acceleration
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
apt-get install -y --no-install-recommends \
libva2 libva-drm2 libva-x11-2 libx11-6 libxcb1 libxau6 libxdmcp6 libmfx1; \
libva2 libva-drm2 libva-x11-2 libx11-6 libxcb1 libxau6 libxdmcp6 libmfx1 \
i965-va-driver-shaders intel-media-va-driver-non-free vainfo; \
elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \
apt-get install -y --no-install-recommends \
libdrm2 libva2; \
@@ -39,7 +41,7 @@ RUN apt-get update && \
COPY --chmod=755 init.sh /init.sh
# Copy binaries (these are placed by the build script)
COPY --chmod=755 one-kvm ttyd gostc easytier-core /usr/bin/
COPY --chmod=755 one-kvm ttyd /usr/bin/
# Copy ventoy resources if they exist
COPY ventoy/ /etc/one-kvm/ventoy/

View File

@@ -0,0 +1,50 @@
# One-KVM Runtime Image (full)
# This Dockerfile only packages pre-compiled binaries (no compilation)
# Used after cross-compiling with `cross build`
# Using Debian 11 for maximum compatibility (GLIBC 2.31)
ARG TARGETPLATFORM=linux/amd64
FROM debian:11-slim
ARG TARGETPLATFORM
# Install runtime dependencies in a single layer
# All codec libraries (libx264, libx265, libopus) are now statically linked
# Only hardware acceleration drivers and core system libraries remain dynamic
RUN sed -i 's/ main$/ main contrib non-free/' /etc/apt/sources.list && \
apt-get update && \
apt-get install -y --no-install-recommends \
# Core runtime (all platforms) - no codec libs needed
ca-certificates \
libudev1 \
libasound2 \
# v4l2 is handled by kernel, minimal userspace needed
libv4l-0 \
&& \
# Platform-specific hardware acceleration
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
apt-get install -y --no-install-recommends \
libva2 libva-drm2 libva-x11-2 libx11-6 libxcb1 libxau6 libxdmcp6 libmfx1 \
i965-va-driver-shaders intel-media-va-driver-non-free vainfo; \
elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \
apt-get install -y --no-install-recommends \
libdrm2 libva2; \
elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \
apt-get install -y --no-install-recommends \
libdrm2 libva2; \
fi && \
rm -rf /var/lib/apt/lists/* && \
mkdir -p /etc/one-kvm/ventoy
# Copy init script
COPY --chmod=755 init.sh /init.sh
# Copy binaries (these are placed by the build script)
COPY --chmod=755 one-kvm ttyd gostc easytier-core /usr/bin/
# Copy ventoy resources if they exist
COPY ventoy/ /etc/one-kvm/ventoy/
# Entrypoint
CMD ["/init.sh"]

117
build/build-android.sh Normal file
View File

@@ -0,0 +1,117 @@
#!/usr/bin/env bash
# Build Android APKs using the Docker build image.
# Usage: ./build/build-android.sh [arm64|armv7|all|help]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DOCKERFILE="$PROJECT_ROOT/build/cross/Dockerfile.android"
IMAGE_NAME="${ONE_KVM_ANDROID_DOCKER_IMAGE:-one-kvm-android-build:cn}"
fail() {
echo "Error: $*" >&2
exit 1
}
build_android() {
local arch="$1"
local docker_build_args=()
local docker_mount_args=()
local gradle_distribution_url="${ONE_KVM_GRADLE_DISTRIBUTION_URL:-}"
local gradle_distribution_url_cn="${ONE_KVM_GRADLE_DISTRIBUTION_URL_CN:-https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip}"
local gradle_network_timeout="${ONE_KVM_GRADLE_NETWORK_TIMEOUT:-120000}"
local gradle_cache="${ONE_KVM_ANDROID_GRADLE_CACHE_DIR:-one-kvm-android-gradle-cache}"
local cargo_registry_cache="${ONE_KVM_ANDROID_CARGO_REGISTRY_CACHE_DIR:-one-kvm-android-cargo-registry}"
local cargo_git_cache="${ONE_KVM_ANDROID_CARGO_GIT_CACHE_DIR:-one-kvm-android-cargo-git}"
add_cache_mount() {
local source="$1"
local target="$2"
if [[ "$source" == /* || "$source" == ./* || "$source" == ../* ]]; then
mkdir -p "$source"
source="$(cd "$source" && pwd)"
fi
docker_mount_args+=("-v" "$source:$target")
}
if [[ "${CHINAMIRRO:-}" == "1" ]]; then
docker_build_args+=("--build-arg" "CHINAMIRRO=1")
if [[ -z "$gradle_distribution_url" ]]; then
gradle_distribution_url="$gradle_distribution_url_cn"
fi
fi
if [[ "${ONE_KVM_ANDROID_SKIP_DOCKER_BUILD:-0}" == "1" ]]; then
echo "=== Skipping Android image build: $IMAGE_NAME ==="
else
echo "=== Building Android image: $IMAGE_NAME ==="
docker build \
-f "$DOCKERFILE" \
-t "$IMAGE_NAME" \
"${docker_build_args[@]}" \
"$PROJECT_ROOT/build/cross"
fi
add_cache_mount "$gradle_cache" "/root/.gradle"
add_cache_mount "$cargo_registry_cache" "/root/.cargo/registry"
add_cache_mount "$cargo_git_cache" "/root/.cargo/git"
echo "=== Building Android APK: $arch ==="
docker run --rm \
-v "$PROJECT_ROOT:/workspace" \
"${docker_mount_args[@]}" \
-w /workspace \
-e "CHINAMIRRO=${CHINAMIRRO:-0}" \
-e "ONE_KVM_GRADLE_DISTRIBUTION_URL=$gradle_distribution_url" \
-e "ONE_KVM_GRADLE_DISTRIBUTION_URL_CN=$gradle_distribution_url_cn" \
-e "ONE_KVM_GRADLE_NETWORK_TIMEOUT=$gradle_network_timeout" \
"$IMAGE_NAME" \
"$arch"
}
[[ -f "$DOCKERFILE" ]] || fail "Android Dockerfile not found: $DOCKERFILE"
command -v docker >/dev/null 2>&1 || fail "docker is required"
case "${1:-all}" in
all)
build_android all
;;
arm64)
build_android arm64
;;
armv7)
build_android armv7
;;
help | --help | -h)
cat <<'EOF'
Usage: build/build-android.sh [arch|help]
Commands:
all (default) Build arm64 and armv7 APKs
arm64 Build only arm64 APK
armv7 Build only ARMv7 APK
help Show this help
Examples:
build/build-android.sh
build/build-android.sh arm64
CHINAMIRRO=1 build/build-android.sh all
CHINAMIRRO=1 ONE_KVM_GRADLE_DISTRIBUTION_URL=https://mirrors.aliyun.com/macports/distfiles/gradle/gradle-9.1.0-bin.zip build/build-android.sh all
Environment:
ONE_KVM_ANDROID_GRADLE_CACHE_DIR Host Gradle cache path or Docker volume name
ONE_KVM_ANDROID_CARGO_REGISTRY_CACHE_DIR Host Cargo registry cache path or Docker volume name
ONE_KVM_ANDROID_CARGO_GIT_CACHE_DIR Host Cargo git cache path or Docker volume name
ONE_KVM_ANDROID_SKIP_DOCKER_BUILD=1 Reuse an already loaded Docker image
APK output:
target/android/one-kvm_<version>_<arm32|arm64>.apk
EOF
;;
*)
fail "Unknown argument: $1"
;;
esac

View File

@@ -19,6 +19,23 @@ ARCH_MAP=(
build_arch() {
local rust_target="$1"
case "${CHINAMIRRO:-}" in
1|true|TRUE|yes|YES|on|ON)
local cross_build_opts="${CROSS_BUILD_OPTS:+$CROSS_BUILD_OPTS }--build-arg CHINAMIRRO=1"
echo "=== China mirror acceleration: enabled (Tsinghua) ==="
echo "=== Building: $rust_target (via cross with custom Dockerfile) ==="
env \
CROSS_BUILD_OPTS="$cross_build_opts" \
CARGO_SOURCE_CRATES_IO_REPLACE_WITH=tuna \
CARGO_SOURCE_TUNA_REGISTRY=sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/ \
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse \
RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup \
RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup \
cross build --release --target "$rust_target"
return
;;
esac
echo "=== Building: $rust_target (via cross with custom Dockerfile) ==="
cross build --release --target "$rust_target"
}
@@ -49,6 +66,7 @@ case "${1:-all}" in
echo "Examples:"
echo " $0 # Build all"
echo " $0 x86_64 # Build x86_64 only"
echo " CHINAMIRRO=1 $0 arm64 # Build with Tsinghua mirrors"
exit 0
;;
*)

View File

@@ -0,0 +1,309 @@
# Android build image for One-KVM
# Based on Debian 11 for stable toolchain/runtime compatibility
FROM debian:11
ARG CHINAMIRRO=0
ARG ANDROID_SDK_ROOT=/root/android-sdk
ARG ANDROID_CMDLINE_TOOLS_VERSION=11076708_latest
ARG ANDROID_NDK_VERSION=27.3.13750724
ARG ANDROID_PLATFORM=36
ARG ANDROID_BUILD_TOOLS=36.0.0
ARG CARGO_NDK_VERSION=4.1.2
ARG RUSTUP_DIST_SERVER_CN=https://mirrors.tuna.tsinghua.edu.cn/rustup
ARG RUSTUP_UPDATE_ROOT_CN=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup
ARG CARGO_REGISTRY_CN=sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/
ARG MAVEN_REPOSITORY_CN=https://maven.aliyun.com/repository/public
ARG GOOGLE_MAVEN_REPOSITORY_CN=https://maven.aliyun.com/repository/google
ARG GRADLE_DISTRIBUTION_URL_CN=https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip
ARG ANDROID_CMDLINE_TOOLS_URL=
ENV DEBIAN_FRONTEND=noninteractive
ENV ANDROID_HOME=${ANDROID_SDK_ROOT}
ENV ANDROID_SDK_ROOT=${ANDROID_SDK_ROOT}
ENV ANDROID_NDK_HOME=${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}
ENV ANDROID_NDK_ROOT=${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}
ENV ANDROID_BUILD_TOOLS=${ANDROID_BUILD_TOOLS}
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
ENV PATH=/root/.cargo/bin:${PATH}
ENV ONE_KVM_GRADLE_DISTRIBUTION_URL_CN=${GRADLE_DISTRIBUTION_URL_CN}
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
/etc/apt/sources.list; \
fi
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
wget \
unzip \
zip \
git \
bash \
build-essential \
pkg-config \
cmake \
ninja-build \
autoconf \
automake \
libtool \
nasm \
yasm \
python3 \
openjdk-17-jdk-headless \
libstdc++6 \
&& rm -rf /var/lib/apt/lists/*
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
mkdir -p /root/.cargo; \
printf '%s\n' \
'[source.crates-io]' \
"replace-with = 'tuna'" \
'[source.tuna]' \
"registry = '${CARGO_REGISTRY_CN}'" \
'[registries.tuna]' \
"index = '${CARGO_REGISTRY_CN}'" \
> /root/.cargo/config.toml; \
fi \
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable \
&& cargo install cargo-ndk --version ${CARGO_NDK_VERSION} --locked \
&& rustup target add armv7-linux-androideabi aarch64-linux-android
RUN mkdir -p /opt/android-cmdline-tools \
&& cd /tmp \
&& if [ -n "$ANDROID_CMDLINE_TOOLS_URL" ]; then \
wget -q "$ANDROID_CMDLINE_TOOLS_URL" -O cmdline-tools.zip; \
else \
wget -q https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS_VERSION}.zip -O cmdline-tools.zip; \
fi \
&& unzip -q cmdline-tools.zip -d /opt/android-cmdline-tools \
&& mkdir -p ${ANDROID_SDK_ROOT}/cmdline-tools/latest \
&& mv /opt/android-cmdline-tools/cmdline-tools/* ${ANDROID_SDK_ROOT}/cmdline-tools/latest/ \
&& rm -rf /tmp/cmdline-tools.zip /opt/android-cmdline-tools
RUN mkdir -p ${ANDROID_SDK_ROOT}/licenses \
&& yes | ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=${ANDROID_SDK_ROOT} --licenses >/dev/null \
&& ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=${ANDROID_SDK_ROOT} \
"platform-tools" \
"platforms;android-${ANDROID_PLATFORM}" \
"build-tools;${ANDROID_BUILD_TOOLS}" \
"ndk;${ANDROID_NDK_VERSION}" \
"cmake;3.22.1" \
&& mkdir -p ${ANDROID_NDK_HOME}
RUN if [ "$CHINAMIRRO" = "1" ]; then \
mkdir -p /root/.gradle; \
printf '%s\n' \
"beforeSettings { settings ->" \
" settings.pluginManagement.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
" settings.pluginManagement.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
" settings.dependencyResolutionManagement.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
" settings.dependencyResolutionManagement.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
"}" \
"allprojects {" \
" buildscript.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
" buildscript.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
"}" \
> /root/.gradle/init.gradle; \
fi
RUN apt-get update && apt-get install -y --no-install-recommends \
libclang-dev \
llvm \
&& rm -rf /var/lib/apt/lists/*
ENV LIBCLANG_PATH=/usr/lib/llvm-11/lib
RUN printf '%s\n' \
'#!/usr/bin/env bash' \
'set -euo pipefail' \
'' \
'PROJECT_ROOT="${ONE_KVM_ANDROID_PROJECT_ROOT:-/workspace}"' \
'ANDROID_DIR="${PROJECT_ROOT}/android"' \
'BUILD_TYPE="release"' \
'ARCH="${1:-all}"' \
'FFMPEG_ROOT="${ONE_KVM_ANDROID_FFMPEG_ROOT:-${PROJECT_ROOT}/dist/android-ffmpeg-mediacodec}"' \
'OUTPUT_DIR="${PROJECT_ROOT}/target/android"' \
'SIGNING_DIR="${PROJECT_ROOT}/target/android-signing"' \
'KEYSTORE_PATH="${SIGNING_DIR}/one-kvm-release.jks"' \
'KEY_ALIAS="one-kvm-release"' \
'KEY_PASSWORD="one-kvm-release"' \
'ANDROID_BUILD_TOOLS_DIR="${ANDROID_SDK_ROOT}/build-tools/${ANDROID_BUILD_TOOLS}"' \
'WRAPPER_PROPERTIES="$ANDROID_DIR/gradle/wrapper/gradle-wrapper.properties"' \
'GRADLE_DISTRIBUTION_URL="${ONE_KVM_GRADLE_DISTRIBUTION_URL:-}"' \
'GRADLE_DISTRIBUTION_URL_CN="${ONE_KVM_GRADLE_DISTRIBUTION_URL_CN:-https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip}"' \
'GRADLE_NETWORK_TIMEOUT="${ONE_KVM_GRADLE_NETWORK_TIMEOUT:-120000}"' \
'' \
'usage() {' \
' cat <<EOF' \
'Usage:' \
' docker run --rm -v "$PWD:/workspace" one-kvm-android-build:cn [arm64|armv7|all|help]' \
'' \
'Commands:' \
' all Build arm64 and armv7 APKs. Default.' \
' arm64 Build only arm64 APK.' \
' armv7 Build only ARMv7 APK.' \
' help Show this help.' \
'' \
'APK output:' \
' target/android/one-kvm_<version>_<arm32|arm64>.apk' \
'EOF' \
'}' \
'' \
'fail() {' \
' echo "Error: $*" >&2' \
' exit 1' \
'}' \
'' \
'read_project_version() {' \
' local version' \
' version="$(awk -F "\"" '"'"'/^version[[:space:]]*=/ { print $2; exit }'"'"' "$PROJECT_ROOT/Cargo.toml")"' \
' [[ -n "$version" ]] || fail "Failed to resolve version from $PROJECT_ROOT/Cargo.toml"' \
' printf "%s\n" "$version"' \
'}' \
'' \
'copy_apks() {' \
' local flavor="$1"' \
' local src_dir="$ANDROID_DIR/app/build/outputs/apk/$flavor/$BUILD_TYPE"' \
' local found=0' \
' mkdir -p "$OUTPUT_DIR"' \
' for apk in "$src_dir"/*.apk; do' \
' [[ -f "$apk" ]] || continue' \
' sign_apk "$apk" "$OUTPUT_DIR/one-kvm_${PROJECT_VERSION}_${flavor}.apk"' \
' found=1' \
' done' \
' [[ "$found" == "1" ]] || fail "No APK files found in: $src_dir"' \
'}' \
'' \
'ensure_keystore() {' \
' if [[ -f "$KEYSTORE_PATH" ]]; then' \
' return' \
' fi' \
' mkdir -p "$SIGNING_DIR"' \
' keytool -genkeypair -noprompt -keystore "$KEYSTORE_PATH" -storetype PKCS12 -alias "$KEY_ALIAS" -keyalg RSA -keysize 2048 -validity 10000 -storepass "$KEY_PASSWORD" -keypass "$KEY_PASSWORD" -dname "CN=One-KVM, OU=One-KVM, O=One-KVM, L=Local, S=Local, C=US" >/dev/null' \
'}' \
'' \
'sign_apk() {' \
' local input_apk="$1"' \
' local output_apk="$2"' \
' local aligned_apk' \
' aligned_apk="$(mktemp --suffix=.apk)"' \
' "$ANDROID_BUILD_TOOLS_DIR/zipalign" -f -p 4 "$input_apk" "$aligned_apk"' \
' "$ANDROID_BUILD_TOOLS_DIR/apksigner" sign --ks "$KEYSTORE_PATH" --ks-key-alias "$KEY_ALIAS" --ks-pass "pass:$KEY_PASSWORD" --key-pass "pass:$KEY_PASSWORD" --out "$output_apk" "$aligned_apk"' \
' "$ANDROID_BUILD_TOOLS_DIR/apksigner" verify --verbose "$output_apk" >/dev/null' \
' rm -f "$aligned_apk"' \
'}' \
'' \
'cd "$PROJECT_ROOT"' \
'' \
'case "$ARCH" in' \
'help | --help | -h)' \
' usage' \
' exit 0' \
' ;;' \
'esac' \
'' \
'[[ -d "$ANDROID_DIR" ]] || fail "Android project not found: $ANDROID_DIR"' \
'[[ -x "$ANDROID_DIR/gradlew" ]] || fail "Gradle wrapper is not executable: $ANDROID_DIR/gradlew"' \
'[[ -f "$WRAPPER_PROPERTIES" ]] || fail "Gradle wrapper properties not found: $WRAPPER_PROPERTIES"' \
'' \
'ORIGINAL_WRAPPER_PROPERTIES="$(mktemp)"' \
'cp "$WRAPPER_PROPERTIES" "$ORIGINAL_WRAPPER_PROPERTIES"' \
'cleanup_wrapper_properties() {' \
' cp "$ORIGINAL_WRAPPER_PROPERTIES" "$WRAPPER_PROPERTIES"' \
' rm -f "$ORIGINAL_WRAPPER_PROPERTIES"' \
'}' \
'trap cleanup_wrapper_properties EXIT' \
'' \
'if [[ "${CHINAMIRRO:-0}" == "1" && -z "$GRADLE_DISTRIBUTION_URL" ]]; then' \
' GRADLE_DISTRIBUTION_URL="$GRADLE_DISTRIBUTION_URL_CN"' \
'fi' \
'' \
'if [[ -n "$GRADLE_DISTRIBUTION_URL" ]]; then' \
' WRAPPER_PROPERTIES_TMP="$(mktemp)"' \
' awk -v url="$GRADLE_DISTRIBUTION_URL" -v timeout="$GRADLE_NETWORK_TIMEOUT" '"'"'' \
' BEGIN { seen_url = 0; seen_timeout = 0 }' \
' /^distributionUrl=/ { print "distributionUrl=" url; seen_url = 1; next }' \
' /^networkTimeout=/ { print "networkTimeout=" timeout; seen_timeout = 1; next }' \
' { print }' \
' END {' \
' if (!seen_url) print "distributionUrl=" url;' \
' if (!seen_timeout) print "networkTimeout=" timeout;' \
' }' \
' '"'"' "$WRAPPER_PROPERTIES" > "$WRAPPER_PROPERTIES_TMP"' \
' cp "$WRAPPER_PROPERTIES_TMP" "$WRAPPER_PROPERTIES"' \
' rm -f "$WRAPPER_PROPERTIES_TMP"' \
' find /root/.gradle/wrapper/dists -name "*.lck" -o -name "*.part" 2>/dev/null | xargs -r rm -f' \
'fi' \
'' \
'ensure_keystore' \
'' \
'case "$ARCH" in' \
'arm64)' \
' ANDROID_ABIS="arm64-v8a"' \
' GRADLE_TASK=":app:assembleArm64Release"' \
' APK_FLAVORS="arm64"' \
' ;;' \
'armv7)' \
' ANDROID_ABIS="armeabi-v7a"' \
' GRADLE_TASK=":app:assembleArm32Release"' \
' APK_FLAVORS="arm32"' \
' ;;' \
'all)' \
' ANDROID_ABIS="arm64-v8a,armeabi-v7a"' \
' GRADLE_TASK=":app:assembleRelease"' \
' APK_FLAVORS="arm64 arm32"' \
' ;;' \
'*) fail "Unsupported architecture: $ARCH (expected arm64, armv7, or all)" ;;' \
'esac' \
'' \
'printf "sdk.dir=%s\n" "$ANDROID_HOME" > "$ANDROID_DIR/local.properties"' \
'mkdir -p "$OUTPUT_DIR"' \
'PROJECT_VERSION="$(read_project_version)"' \
'' \
'export ONE_KVM_ANDROID_PROFILE="$BUILD_TYPE"' \
'export ONE_KVM_ANDROID_ABIS="$ANDROID_ABIS"' \
'export ONE_KVM_ANDROID_FFMPEG_ROOT="$FFMPEG_ROOT"' \
'export ANDROID_HOME' \
'export ANDROID_SDK_ROOT' \
'export ANDROID_NDK_HOME' \
'export ANDROID_NDK_ROOT' \
'' \
'echo "Building Android APK"' \
'echo " task: $GRADLE_TASK"' \
'echo " profile: $ONE_KVM_ANDROID_PROFILE"' \
'echo " version: $PROJECT_VERSION"' \
'echo " abis: $ONE_KVM_ANDROID_ABIS"' \
'echo " output: $OUTPUT_DIR"' \
'echo " sdk: $ANDROID_HOME"' \
'echo " ndk: $ANDROID_NDK_HOME"' \
'echo " build tools: $ANDROID_BUILD_TOOLS_DIR"' \
'echo " ffmpeg root: $ONE_KVM_ANDROID_FFMPEG_ROOT"' \
'if [[ -n "$GRADLE_DISTRIBUTION_URL" ]]; then' \
' echo " gradle distribution: $GRADLE_DISTRIBUTION_URL"' \
'fi' \
'' \
'(' \
' cd "$ANDROID_DIR"' \
' ./gradlew "$GRADLE_TASK"' \
')' \
'' \
'for flavor in $APK_FLAVORS; do' \
' copy_apks "$flavor"' \
'done' \
'' \
'echo' \
'echo "APK output:"' \
'ls -1 "$OUTPUT_DIR"' \
> /usr/local/bin/build-one-kvm-android \
&& chmod +x /usr/local/bin/build-one-kvm-android
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/build-one-kvm-android"]
CMD ["all"]

View File

@@ -3,15 +3,39 @@
FROM debian:11
# Set Rustup mirrors (Aliyun)
ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
# Optionally use Tsinghua mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
/etc/apt/sources.list; \
fi
# Install Rust toolchain
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable \
&& if [ "$CHINAMIRRO" = "1" ]; then \
mkdir -p /root/.cargo; \
printf '%s\n' \
'[source.crates-io]' \
"replace-with = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -31,7 +55,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
meson \
ninja-build \
wget \
xz-utils \
file \
rsync \
gcc-aarch64-linux-gnu \
g++-aarch64-linux-gnu \
libc6-dev-arm64-cross \
@@ -47,16 +73,29 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libv4l-dev:arm64 \
libudev-dev:arm64 \
zlib1g-dev:arm64 \
linux-libc-dev:arm64 \
# Note: libjpeg-turbo, libyuv, libvpx, libx264, libx265, libopus are built from source below for static linking
libdrm-dev:arm64 \
&& rm -rf /var/lib/apt/lists/*
# Install newer V4L2 headers for v4l2r bindgen
RUN mkdir -p /opt/v4l2-headers \
&& wget -q https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${LINUX_HEADERS_VERSION}.tar.xz -O /tmp/linux-headers.tar.xz \
&& if [ -n "$LINUX_HEADERS_SHA256" ]; then echo "$LINUX_HEADERS_SHA256 /tmp/linux-headers.tar.xz" | sha256sum -c -; fi \
&& tar -xf /tmp/linux-headers.tar.xz -C /tmp \
&& cd /tmp/linux-${LINUX_HEADERS_VERSION} \
&& make ARCH=arm64 headers_install INSTALL_HDR_PATH=/opt/v4l2-headers \
&& rm -rf /tmp/linux-${LINUX_HEADERS_VERSION} /tmp/linux-headers.tar.xz
ENV V4L2R_VIDEODEV2_H_PATH=/opt/v4l2-headers/include
# Build static libjpeg-turbo from source (cross-compile for ARM64)
RUN git clone --depth 1 https://github.com/libjpeg-turbo/libjpeg-turbo /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_INSTALL_PREFIX=/usr/aarch64-linux-gnu \
-DCMAKE_INSTALL_LIBDIR=lib \
-DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_SYSTEM_PROCESSOR=aarch64 \
-DCMAKE_C_COMPILER=aarch64-linux-gnu-gcc \
@@ -75,6 +114,11 @@ RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
-DCMAKE_SYSTEM_PROCESSOR=aarch64 \
-DCMAKE_C_COMPILER=aarch64-linux-gnu-gcc \
-DCMAKE_CXX_COMPILER=aarch64-linux-gnu-g++ \
-DJPEG_FOUND=TRUE \
-DJPEG_INCLUDE_DIR=/usr/aarch64-linux-gnu/include \
-DJPEG_LIBRARY=/usr/aarch64-linux-gnu/lib/libjpeg.a \
-DCMAKE_C_FLAGS="-DHAVE_JPEG -I/usr/aarch64-linux-gnu/include" \
-DCMAKE_CXX_FLAGS="-DHAVE_JPEG -I/usr/aarch64-linux-gnu/include" \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/libyuv
@@ -309,7 +353,11 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& rm -rf /tmp/ffmpeg-build /tmp/aarch64-cross.txt /tmp/aarch64-pkg-config
# Add Rust target
RUN rustup target add aarch64-unknown-linux-gnu
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& rustup target add aarch64-unknown-linux-gnu
# Configure environment for cross-compilation
ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \

View File

@@ -3,15 +3,39 @@
FROM debian:11
# Set Rustup mirrors (Aliyun)
ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
# Optionally use Tsinghua mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
/etc/apt/sources.list; \
fi
# Install Rust toolchain
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable \
&& if [ "$CHINAMIRRO" = "1" ]; then \
mkdir -p /root/.cargo; \
printf '%s\n' \
'[source.crates-io]' \
"replace-with = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -31,7 +55,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
meson \
ninja-build \
wget \
xz-utils \
file \
rsync \
gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf \
libc6-dev-armhf-cross \
@@ -46,16 +72,29 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libasound2-dev:armhf \
libv4l-dev:armhf \
libudev-dev:armhf \
linux-libc-dev:armhf \
zlib1g-dev:armhf \
libdrm-dev:armhf \
&& rm -rf /var/lib/apt/lists/*
# Install newer V4L2 headers for v4l2r bindgen
RUN mkdir -p /opt/v4l2-headers \
&& wget -q https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${LINUX_HEADERS_VERSION}.tar.xz -O /tmp/linux-headers.tar.xz \
&& if [ -n "$LINUX_HEADERS_SHA256" ]; then echo "$LINUX_HEADERS_SHA256 /tmp/linux-headers.tar.xz" | sha256sum -c -; fi \
&& tar -xf /tmp/linux-headers.tar.xz -C /tmp \
&& cd /tmp/linux-${LINUX_HEADERS_VERSION} \
&& make ARCH=arm headers_install INSTALL_HDR_PATH=/opt/v4l2-headers \
&& rm -rf /tmp/linux-${LINUX_HEADERS_VERSION} /tmp/linux-headers.tar.xz
ENV V4L2R_VIDEODEV2_H_PATH=/opt/v4l2-headers/include
# Build static libjpeg-turbo from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://github.com/libjpeg-turbo/libjpeg-turbo /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_INSTALL_PREFIX=/usr/arm-linux-gnueabihf \
-DCMAKE_INSTALL_LIBDIR=lib \
-DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_SYSTEM_PROCESSOR=arm \
-DCMAKE_C_COMPILER=arm-linux-gnueabihf-gcc \
@@ -74,6 +113,11 @@ RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
-DCMAKE_SYSTEM_PROCESSOR=arm \
-DCMAKE_C_COMPILER=arm-linux-gnueabihf-gcc \
-DCMAKE_CXX_COMPILER=arm-linux-gnueabihf-g++ \
-DJPEG_FOUND=TRUE \
-DJPEG_INCLUDE_DIR=/usr/arm-linux-gnueabihf/include \
-DJPEG_LIBRARY=/usr/arm-linux-gnueabihf/lib/libjpeg.a \
-DCMAKE_C_FLAGS="-DHAVE_JPEG -I/usr/arm-linux-gnueabihf/include" \
-DCMAKE_CXX_FLAGS="-DHAVE_JPEG -I/usr/arm-linux-gnueabihf/include" \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/libyuv
@@ -298,7 +342,11 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& rm -rf /tmp/ffmpeg-build /tmp/armhf-cross.txt /tmp/armhf-pkg-config
# Add Rust target
RUN rustup target add armv7-unknown-linux-gnueabihf
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& rustup target add armv7-unknown-linux-gnueabihf
# Configure environment for cross-compilation
ENV CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \

View File

@@ -3,15 +3,39 @@
FROM debian:11
# Set Rustup mirrors (Aliyun)
ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
# Optionally use Tsinghua mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
/etc/apt/sources.list; \
fi
# Install Rust toolchain
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable \
&& if [ "$CHINAMIRRO" = "1" ]; then \
mkdir -p /root/.cargo; \
printf '%s\n' \
'[source.crates-io]' \
"replace-with = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -29,6 +53,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libclang-dev \
llvm \
wget \
xz-utils \
rsync \
# Autotools for libopus (requires autoreconf)
autoconf \
automake \
@@ -37,6 +63,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libasound2-dev \
libv4l-dev \
libudev-dev \
linux-libc-dev \
zlib1g-dev \
# Note: libjpeg-turbo, libx264, libx265, libopus are built from source below for static linking
libva-dev \
@@ -49,11 +76,24 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libxdmcp-dev \
&& rm -rf /var/lib/apt/lists/*
# Install newer V4L2 headers for v4l2r bindgen
RUN mkdir -p /opt/v4l2-headers \
&& wget -q https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${LINUX_HEADERS_VERSION}.tar.xz -O /tmp/linux-headers.tar.xz \
&& if [ -n "$LINUX_HEADERS_SHA256" ]; then echo "$LINUX_HEADERS_SHA256 /tmp/linux-headers.tar.xz" | sha256sum -c -; fi \
&& tar -xf /tmp/linux-headers.tar.xz -C /tmp \
&& cd /tmp/linux-${LINUX_HEADERS_VERSION} \
&& make ARCH=x86 headers_install INSTALL_HDR_PATH=/opt/v4l2-headers \
&& rm -rf /tmp/linux-${LINUX_HEADERS_VERSION} /tmp/linux-headers.tar.xz
ENV V4L2R_VIDEODEV2_H_PATH=/opt/v4l2-headers/include
# Build static libjpeg-turbo from source (needed by libyuv)
RUN git clone --depth 1 https://github.com/libjpeg-turbo/libjpeg-turbo /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DCMAKE_INSTALL_LIBDIR=lib \
-DENABLE_SHARED=OFF -DENABLE_STATIC=ON \
&& make -j$(nproc) \
&& make install \
@@ -64,6 +104,11 @@ RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
&& cd /tmp/libyuv \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DJPEG_FOUND=TRUE \
-DJPEG_INCLUDE_DIR=/usr/local/include \
-DJPEG_LIBRARY=/usr/local/lib/libjpeg.a \
-DCMAKE_C_FLAGS="-DHAVE_JPEG -I/usr/local/include" \
-DCMAKE_CXX_FLAGS="-DHAVE_JPEG -I/usr/local/include" \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/libyuv
@@ -203,7 +248,11 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& rm -rf /tmp/ffmpeg-build
# Add Rust target
RUN rustup target add x86_64-unknown-linux-gnu
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
fi \
&& rustup target add x86_64-unknown-linux-gnu
# Configure environment for static linking
ENV PKG_CONFIG_ALLOW_CROSS=1\

View File

@@ -4,36 +4,106 @@
set -e
# Start one-kvm with default options
# Additional options can be passed via environment variables
EXTRA_ARGS="-d /etc/one-kvm"
detect_intel_libva_driver() {
if [ -n "${LIBVA_DRIVER_NAME:-}" ]; then
echo "[INFO] Using preconfigured LIBVA_DRIVER_NAME=$LIBVA_DRIVER_NAME"
return
fi
if [ "$(uname -m)" != "x86_64" ]; then
return
fi
local devices=()
if [ -n "${LIBVA_DEVICE:-}" ]; then
devices=("$LIBVA_DEVICE")
else
shopt -s nullglob
devices=(/dev/dri/renderD*)
shopt -u nullglob
fi
if [ ${#devices[@]} -eq 0 ]; then
return
fi
local device=""
local node=""
local vendor=""
local driver=""
for device in "${devices[@]}"; do
if [ ! -e "$device" ]; then
continue
fi
node="$(basename "$device")"
vendor=""
if [ -r "/sys/class/drm/$node/device/vendor" ]; then
vendor="$(cat "/sys/class/drm/$node/device/vendor")"
fi
if [ -n "$vendor" ] && [ "$vendor" != "0x8086" ]; then
echo "[INFO] Skipping VA-API probe for $device (vendor=$vendor)"
continue
fi
for driver in iHD i965; do
if LIBVA_DRIVER_NAME="$driver" vainfo --display drm --device "$device" >/dev/null 2>&1; then
export LIBVA_DRIVER_NAME="$driver"
if [ -n "$vendor" ]; then
echo "[INFO] Detected Intel VA-API driver '$driver' on $device (vendor=$vendor)"
else
echo "[INFO] Detected Intel VA-API driver '$driver' on $device"
fi
return
fi
done
done
echo "[WARN] Unable to auto-detect an Intel VA-API driver; leaving LIBVA_DRIVER_NAME unset"
}
detect_intel_libva_driver
# Start one-kvm with default options.
# Additional options can be passed via environment variables.
# Data directory (prefer DATA_DIR, keep ONE_KVM_DATA_DIR for backward compatibility)
DATA_DIR="${DATA_DIR:-${ONE_KVM_DATA_DIR:-/etc/one-kvm}}"
ARGS=(-d "$DATA_DIR")
# Enable HTTPS if requested
if [ "${ENABLE_HTTPS:-false}" = "true" ]; then
EXTRA_ARGS="$EXTRA_ARGS --enable-https"
ARGS+=(--enable-https)
fi
# Custom bind address
if [ -n "$BIND_ADDRESS" ]; then
EXTRA_ARGS="$EXTRA_ARGS -a $BIND_ADDRESS"
ARGS+=(-a "$BIND_ADDRESS")
fi
# Custom port
if [ -n "$HTTP_PORT" ]; then
EXTRA_ARGS="$EXTRA_ARGS -p $HTTP_PORT"
ARGS+=(-p "$HTTP_PORT")
fi
# Custom HTTPS port
if [ -n "$HTTPS_PORT" ]; then
ARGS+=(--https-port "$HTTPS_PORT")
fi
# Verbosity level
if [ -n "$VERBOSE" ]; then
case "$VERBOSE" in
1) EXTRA_ARGS="$EXTRA_ARGS -v" ;;
2) EXTRA_ARGS="$EXTRA_ARGS -vv" ;;
3) EXTRA_ARGS="$EXTRA_ARGS -vvv" ;;
1) ARGS+=(-v) ;;
2) ARGS+=(-vv) ;;
3) ARGS+=(-vvv) ;;
esac
fi
echo "[INFO] Starting one-kvm..."
echo "[INFO] Extra arguments: $EXTRA_ARGS"
echo "[INFO] Arguments: ${ARGS[*]}"
# Execute one-kvm
exec /usr/bin/one-kvm $EXTRA_ARGS
exec /usr/bin/one-kvm "${ARGS[@]}"

View File

@@ -7,6 +7,8 @@ Wants=network-online.target
[Service]
Type=simple
User=root
# Example for older Intel GPUs:
# Environment=LIBVA_DRIVER_NAME=i965
ExecStart=/usr/bin/one-kvm
Restart=on-failure
RestartSec=5

View File

@@ -126,7 +126,7 @@ EOF
# Create control file
BASE_DEPS="libc6 (>= 2.31), libgcc-s1, libstdc++6, libasound2 (>= 1.1), libdrm2 (>= 2.4)"
AMD64_DEPS="libva2 (>= 2.0), libva-drm2 (>= 2.10), libva-x11-2 (>= 2.10), libmfx1 (>= 21.1), libx11-6 (>= 1.6), libxcb1 (>= 1.14)"
AMD64_DEPS="libva2 (>= 2.0), libva-drm2 (>= 2.10), libva-x11-2 (>= 2.10), libmfx1 (>= 21.1), libx11-6 (>= 1.6), libxcb1 (>= 1.14), i965-va-driver-shaders (>= 2.4), intel-media-va-driver-non-free (>= 21.1)"
DEPS="$BASE_DEPS"
if [ "$DEB_ARCH" = "amd64" ]; then
DEPS="$DEPS, $AMD64_DEPS"

View File

@@ -25,11 +25,13 @@ echo_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# Configuration
REGISTRY="${REGISTRY:-}" # e.g., docker.io/username or ghcr.io/username
IMAGE_NAME="${IMAGE_NAME:-one-kvm}"
IMAGE_NAME="${IMAGE_NAME:-}"
TAG="${TAG:-latest}"
VARIANT="${VARIANT:-minimal}"
INCLUDE_THIRD_PARTY=false
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
STAGING_DIR="$PROJECT_ROOT/build-staging"
BASE_STAGING_DIR="$PROJECT_ROOT/build-staging"
# Full image name with registry
get_full_image_name() {
@@ -77,6 +79,18 @@ while [[ $# -gt 0 ]]; do
REGISTRY="$2"
shift 2
;;
--image-name)
IMAGE_NAME="$2"
shift 2
;;
--variant)
VARIANT="$2"
shift 2
;;
--full)
VARIANT="full"
shift
;;
--build)
BUILD_BINARY=true
shift
@@ -91,9 +105,12 @@ while [[ $# -gt 0 ]]; do
echo " Use comma to specify multiple: linux/amd64,linux/arm64"
echo " Default: $DEFAULT_PLATFORM"
echo " --registry REGISTRY Container registry (e.g., docker.io/user, ghcr.io/user)"
echo " --image-name NAME Override image name (default: one-kvm or one-kvm-full)"
echo " --push Push image to registry"
echo " --load Load image to local Docker (single platform only)"
echo " --tag TAG Image tag (default: latest)"
echo " --variant VARIANT Image variant: minimal or full (default: minimal)"
echo " --full Shortcut for --variant full"
echo " --build Also build the binary with cross (optional)"
echo " --help Show this help"
echo ""
@@ -101,6 +118,9 @@ while [[ $# -gt 0 ]]; do
echo " # Build for current platform and load locally"
echo " $0 --platform linux/arm64 --load"
echo ""
echo " # Build full image (includes gostc + easytier)"
echo " $0 --variant full --platform linux/arm64 --load"
echo ""
echo " # Build and push single platform"
echo " $0 --platform linux/arm64 --registry docker.io/user --push"
echo ""
@@ -115,6 +135,28 @@ while [[ $# -gt 0 ]]; do
esac
done
# Normalize variant and image name
case "$VARIANT" in
minimal)
INCLUDE_THIRD_PARTY=false
;;
full)
INCLUDE_THIRD_PARTY=true
;;
*)
echo_error "Unknown variant: $VARIANT (expected: minimal or full)"
exit 1
;;
esac
if [ -z "$IMAGE_NAME" ]; then
if [ "$VARIANT" = "full" ]; then
IMAGE_NAME="one-kvm-full"
else
IMAGE_NAME="one-kvm"
fi
fi
# Default platform
if [ -z "$PLATFORMS" ]; then
PLATFORMS="$DEFAULT_PLATFORM"
@@ -176,21 +218,23 @@ download_tools() {
chmod +x "$staging/ttyd"
fi
# gostc
if [ ! -f "$staging/gostc" ]; then
curl -fsSL "$GOSTC_URL" -o /tmp/gostc.tar.gz
tar -xzf /tmp/gostc.tar.gz -C "$staging"
chmod +x "$staging/gostc"
rm /tmp/gostc.tar.gz
fi
if [ "$INCLUDE_THIRD_PARTY" = true ]; then
# gostc
if [ ! -f "$staging/gostc" ]; then
curl -fsSL "$GOSTC_URL" -o /tmp/gostc.tar.gz
tar -xzf /tmp/gostc.tar.gz -C "$staging"
chmod +x "$staging/gostc"
rm /tmp/gostc.tar.gz
fi
# easytier
if [ ! -f "$staging/easytier-core" ]; then
curl -fsSL "$EASYTIER_URL" -o /tmp/easytier.zip
unzip -o /tmp/easytier.zip -d /tmp/easytier
cp "/tmp/easytier/$EASYTIER_DIR/easytier-core" "$staging/easytier-core"
chmod +x "$staging/easytier-core"
rm -rf /tmp/easytier.zip /tmp/easytier
# easytier
if [ ! -f "$staging/easytier-core" ]; then
curl -fsSL "$EASYTIER_URL" -o /tmp/easytier.zip
unzip -o /tmp/easytier.zip -d /tmp/easytier
cp "/tmp/easytier/$EASYTIER_DIR/easytier-core" "$staging/easytier-core"
chmod +x "$staging/easytier-core"
rm -rf /tmp/easytier.zip /tmp/easytier
fi
fi
}
@@ -198,13 +242,14 @@ download_tools() {
build_for_platform() {
local platform="$1"
local target=$(platform_to_target "$platform")
local staging="$STAGING_DIR/$target"
local staging="$BASE_STAGING_DIR/$VARIANT/$target"
echo_info "=========================================="
echo_info "Processing: $platform ($target)"
echo_info "=========================================="
# Create staging directory
rm -rf "$staging"
mkdir -p "$staging/ventoy"
# Build binary if requested
@@ -252,7 +297,11 @@ build_for_platform() {
fi
# Copy Dockerfile
cp "$PROJECT_ROOT/build/Dockerfile.runtime" "$staging/Dockerfile"
local dockerfile="$PROJECT_ROOT/build/Dockerfile.runtime"
if [ "$INCLUDE_THIRD_PARTY" = true ]; then
dockerfile="$PROJECT_ROOT/build/Dockerfile.runtime-full"
fi
cp "$dockerfile" "$staging/Dockerfile"
# Build Docker image
echo_info "Building Docker image..."
@@ -292,6 +341,7 @@ main() {
echo_info "One-KVM Docker Image Builder"
echo_info "Image: $full_image:$TAG"
echo_info "Variant: $VARIANT"
echo_info "Platforms: $PLATFORMS"
if [ -n "$REGISTRY" ]; then
echo_info "Registry: $REGISTRY"

87
build/windows/build.ps1 Normal file
View File

@@ -0,0 +1,87 @@
param(
[string]$Configuration = "debug",
[string]$Target = "x86_64-pc-windows-msvc",
[string]$Triplet = "x64-windows-static",
[string]$VcpkgRoot = $env:VCPKG_ROOT,
[string]$VcpkgInstalledRoot = $env:VCPKG_INSTALLED_DIR,
[switch]$NoDefaultFeatures,
[string[]]$Features = @(),
[switch]$Package,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$CargoArgs = @()
)
$ErrorActionPreference = "Stop"
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..")
Set-Location $repoRoot
if ([string]::IsNullOrWhiteSpace($VcpkgRoot)) {
$VcpkgRoot = Join-Path (Split-Path $repoRoot -Parent) "vcpkg"
}
$VcpkgRoot = [System.IO.Path]::GetFullPath($VcpkgRoot)
if ([string]::IsNullOrWhiteSpace($VcpkgInstalledRoot)) {
$VcpkgInstalledRoot = Join-Path $VcpkgRoot "installed"
}
$VcpkgInstalledRoot = [System.IO.Path]::GetFullPath($VcpkgInstalledRoot)
$vcpkgTripletRoot = Join-Path $VcpkgInstalledRoot $Triplet
$turbojpegLibDir = Join-Path $vcpkgTripletRoot "lib"
$turbojpegIncludeDir = Join-Path $vcpkgTripletRoot "include"
if (-not (Test-Path $VcpkgRoot)) {
throw "VCPKG_ROOT does not exist: $VcpkgRoot. Run build/windows/bootstrap-vcpkg.ps1 first."
}
if (-not (Test-Path $turbojpegLibDir) -or -not (Test-Path $turbojpegIncludeDir)) {
throw "vcpkg triplet is not installed at $vcpkgTripletRoot. Run build/windows/bootstrap-vcpkg.ps1 first."
}
$env:VCPKG_ROOT = $VcpkgRoot
$env:VCPKG_DEFAULT_TRIPLET = $Triplet
$env:VCPKG_INSTALLED_DIR = $VcpkgInstalledRoot
$env:TURBOJPEG_SOURCE = "explicit"
$env:TURBOJPEG_LIB_DIR = $turbojpegLibDir
$env:TURBOJPEG_INCLUDE_DIR = $turbojpegIncludeDir
$cargoCommand = @("build", "--target", $Target)
if ($Configuration -eq "release") {
$cargoCommand += "--release"
} elseif ($Configuration -ne "debug") {
throw "Unsupported configuration '$Configuration'. Use 'debug' or 'release'."
}
if ($NoDefaultFeatures) {
$cargoCommand += "--no-default-features"
}
if ($Features.Count -gt 0) {
$cargoCommand += "--features"
$cargoCommand += ($Features -join ",")
}
$cargoCommand += $CargoArgs
cargo @cargoCommand
if ($Package) {
$metadata = cargo metadata --no-deps --format-version 1 | ConvertFrom-Json
$packageInfo = $metadata.packages | Where-Object { $_.name -eq "one-kvm" } | Select-Object -First 1
if ($null -eq $packageInfo -or [string]::IsNullOrWhiteSpace($packageInfo.version)) {
throw "Failed to resolve version from Cargo metadata"
}
$sourcePath = Join-Path $repoRoot "target/$Target/release/one-kvm.exe"
$targetName = "one-kvm_{0}_amd64.exe" -f $packageInfo.version
$targetPath = Join-Path $repoRoot "target/$Target/release/$targetName"
if (-not (Test-Path $sourcePath)) {
throw "Windows binary not found: $sourcePath"
}
Copy-Item $sourcePath $targetPath
Write-Host $targetPath
}

View File

@@ -1,130 +0,0 @@
# One-KVM 技术文档
本目录包含 One-KVM 项目的完整技术文档。
## 文档结构
```
docs/
├── README.md # 本文件 - 文档索引
├── system-architecture.md # 系统架构文档
├── tech-stack.md # 技术栈文档
└── modules/ # 模块文档
├── video.md # 视频模块
├── hid.md # HID 模块
├── otg.md # OTG 模块
├── msd.md # MSD 模块
├── atx.md # ATX 模块
├── audio.md # 音频模块
├── webrtc.md # WebRTC 模块
├── rustdesk.md # RustDesk 模块
├── auth.md # 认证模块
├── config.md # 配置模块
├── events.md # 事件模块
└── web.md # Web 模块
```
## 快速导航
### 核心文档
| 文档 | 描述 |
|------|------|
| [系统架构](./system-architecture.md) | 整体架构设计、数据流、模块依赖 |
| [技术栈](./tech-stack.md) | 使用的技术、库和开发规范 |
### 功能模块
| 模块 | 描述 | 关键文件 |
|------|------|---------|
| [Video](./modules/video.md) | 视频采集和编码 | `src/video/` |
| [HID](./modules/hid.md) | 键盘鼠标控制 | `src/hid/` |
| [OTG](./modules/otg.md) | USB Gadget 管理 | `src/otg/` |
| [MSD](./modules/msd.md) | 虚拟存储设备 | `src/msd/` |
| [ATX](./modules/atx.md) | 电源控制 | `src/atx/` |
| [Audio](./modules/audio.md) | 音频采集编码 | `src/audio/` |
| [WebRTC](./modules/webrtc.md) | WebRTC 流媒体 | `src/webrtc/` |
| [RustDesk](./modules/rustdesk.md) | RustDesk 协议集成 | `src/rustdesk/` |
### 基础设施
| 模块 | 描述 | 关键文件 |
|------|------|---------|
| [Auth](./modules/auth.md) | 认证和会话 | `src/auth/` |
| [Config](./modules/config.md) | 配置管理 | `src/config/` |
| [Events](./modules/events.md) | 事件系统 | `src/events/` |
| [Web](./modules/web.md) | HTTP API | `src/web/` |
## 架构概览
```
┌─────────────────────────────────────────────────────────────────┐
│ One-KVM System │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Web Frontend (Vue3) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Axum Web Server │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ AppState │ │
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
│ │ │ Video │ │ HID │ │ MSD │ │ ATX │ │ │
│ │ │ Module │ │ Module │ │ Module │ │ Module │ │ │
│ │ └────────┘ └────────┘ └────────┘ └────────┘ │ │
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
│ │ │ Audio │ │ WebRTC │ │RustDesk│ │ Events │ │ │
│ │ │ Module │ │ Module │ │ Module │ │ Bus │ │ │
│ │ └────────┘ └────────┘ └────────┘ └────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Hardware Layer │ │
│ │ V4L2 │ USB OTG │ GPIO │ ALSA │ Network │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## 关键特性
- **单一二进制**: Web UI + 后端一体化部署
- **双流模式**: WebRTC (H264/H265/VP8/VP9) + MJPEG
- **USB OTG**: 虚拟键鼠、虚拟存储
- **硬件加速**: VAAPI/RKMPP/V4L2 M2M
- **RustDesk**: 跨平台远程访问
- **无配置文件**: SQLite 配置存储
## 目标平台
| 平台 | 架构 | 用途 |
|------|------|------|
| aarch64-unknown-linux-gnu | ARM64 | 主要目标 |
| armv7-unknown-linux-gnueabihf | ARMv7 | 备选 |
| x86_64-unknown-linux-gnu | x86-64 | 开发/测试 |
## 快速开始
```bash
# 构建前端
cd web && npm install && npm run build && cd ..
# 构建后端
cargo build --release
# 运行
./target/release/one-kvm --enable-https
```
## 相关链接
- [项目仓库](https://github.com/mofeng-git/One-KVM)
- [开发计划](./DEVELOPMENT_PLAN.md)
- [项目目标](./PROJECT_GOALS.md)

View File

@@ -1,484 +0,0 @@
# ATX 模块文档
## 1. 模块概述
ATX 模块提供电源控制功能,通过 GPIO 或 USB 继电器控制目标计算机的电源和重置按钮。
### 1.1 主要功能
- 电源按钮控制
- 重置按钮控制
- 电源 LED 状态监视
- Wake-on-LAN 支持
- 多后端支持 (GPIO/USB 继电器)
### 1.2 文件结构
```
src/atx/
├── mod.rs # 模块导出
├── controller.rs # AtxController (11KB)
├── executor.rs # 动作执行器 (10KB)
├── types.rs # 类型定义 (7KB)
├── led.rs # LED 监视 (5KB)
└── wol.rs # Wake-on-LAN (5KB)
```
---
## 2. 架构设计
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ ATX Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
Web API
┌─────────────────┐
│ AtxController │
│ (controller.rs) │
└────────┬────────┘
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ Power │ │ Reset │ │ LED │
│Executor│ │Executor│ │Monitor │
└───┬────┘ └───┬────┘ └───┬────┘
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ GPIO │ │ GPIO │ │ GPIO │
│ or USB │ │ or USB │ │ Input │
│ Relay │ │ Relay │ │ │
└───┬────┘ └───┬────┘ └───┬────┘
│ │ │
└───────────┼─────────────┘
┌───────────────┐
│ Target PC │
│ (ATX Header) │
└───────────────┘
```
---
## 3. 核心组件
### 3.1 AtxController (controller.rs)
```rust
pub struct AtxController {
/// 电源按钮配置
power: Arc<AtxButton>,
/// 重置按钮配置
reset: Arc<AtxButton>,
/// LED 监视器
led_monitor: Arc<RwLock<Option<LedMonitor>>>,
/// WoL 控制器
wol: Arc<RwLock<Option<WolController>>>,
/// 当前状态
state: Arc<RwLock<AtxState>>,
/// 事件总线
events: Arc<EventBus>,
}
impl AtxController {
/// 创建控制器
pub fn new(config: &AtxConfig, events: Arc<EventBus>) -> Result<Self>;
/// 短按电源按钮 (开机/正常关机)
pub async fn power_short_press(&self) -> Result<()>;
/// 长按电源按钮 (强制关机)
pub async fn power_long_press(&self) -> Result<()>;
/// 按重置按钮
pub async fn reset_press(&self) -> Result<()>;
/// 获取电源状态
pub fn power_state(&self) -> PowerState;
/// 发送 WoL 魔术包
pub async fn wake_on_lan(&self, mac: &str) -> Result<()>;
/// 获取状态
pub fn state(&self) -> AtxState;
/// 重新加载配置
pub async fn reload(&self, config: &AtxConfig) -> Result<()>;
}
pub struct AtxState {
/// 是否可用
pub available: bool,
/// 电源是否开启
pub power_on: bool,
/// 最后操作时间
pub last_action: Option<DateTime<Utc>>,
/// 错误信息
pub error: Option<String>,
}
pub enum PowerState {
On,
Off,
Unknown,
}
```
### 3.2 AtxButton (executor.rs)
```rust
pub struct AtxButton {
/// 按钮名称
name: String,
/// 驱动类型
driver: AtxDriverType,
/// GPIO 句柄
gpio: Option<LineHandle>,
/// USB 继电器句柄
relay: Option<UsbRelay>,
/// 配置
config: AtxKeyConfig,
}
impl AtxButton {
/// 创建按钮
pub fn new(name: &str, config: &AtxKeyConfig) -> Result<Self>;
/// 短按 (100ms)
pub async fn short_press(&self) -> Result<()>;
/// 长按 (3000ms)
pub async fn long_press(&self) -> Result<()>;
/// 自定义按压时间
pub async fn press(&self, duration: Duration) -> Result<()>;
/// 设置输出状态
fn set_output(&self, high: bool) -> Result<()>;
}
pub enum AtxDriverType {
/// GPIO 直连
Gpio,
/// USB 继电器
UsbRelay,
/// 禁用
None,
}
```
### 3.3 LedMonitor (led.rs)
```rust
pub struct LedMonitor {
/// GPIO 引脚
pin: u32,
/// GPIO 句柄
line: LineHandle,
/// 当前状态
state: Arc<AtomicBool>,
/// 监视任务
monitor_task: Option<JoinHandle<()>>,
}
impl LedMonitor {
/// 创建监视器
pub fn new(config: &AtxLedConfig) -> Result<Self>;
/// 启动监视
pub fn start(&mut self, events: Arc<EventBus>) -> Result<()>;
/// 停止监视
pub fn stop(&mut self);
/// 获取当前状态
pub fn state(&self) -> bool;
}
```
### 3.4 WolController (wol.rs)
```rust
pub struct WolController {
/// 网络接口
interface: String,
/// 广播地址
broadcast_addr: SocketAddr,
}
impl WolController {
/// 创建控制器
pub fn new(interface: Option<&str>) -> Result<Self>;
/// 发送 WoL 魔术包
pub async fn wake(&self, mac: &str) -> Result<()>;
/// 构建魔术包
fn build_magic_packet(mac: &[u8; 6]) -> [u8; 102];
/// 解析 MAC 地址
fn parse_mac(mac: &str) -> Result<[u8; 6]>;
}
```
---
## 4. 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct AtxConfig {
/// 是否启用
pub enabled: bool,
/// 电源按钮配置
pub power: AtxKeyConfig,
/// 重置按钮配置
pub reset: AtxKeyConfig,
/// LED 监视配置
pub led: AtxLedConfig,
/// WoL 配置
pub wol: WolConfig,
}
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct AtxKeyConfig {
/// 驱动类型
pub driver: AtxDriverType,
/// GPIO 芯片 (如 /dev/gpiochip0)
pub gpio_chip: Option<String>,
/// GPIO 引脚号
pub gpio_pin: Option<u32>,
/// USB 继电器设备
pub relay_device: Option<String>,
/// 继电器通道
pub relay_channel: Option<u8>,
/// 激活电平
pub active_level: ActiveLevel,
}
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct AtxLedConfig {
/// 是否启用
pub enabled: bool,
/// GPIO 芯片
pub gpio_chip: Option<String>,
/// GPIO 引脚号
pub gpio_pin: Option<u32>,
/// 激活电平
pub active_level: ActiveLevel,
}
pub enum ActiveLevel {
High,
Low,
}
impl Default for AtxConfig {
fn default() -> Self {
Self {
enabled: false,
power: AtxKeyConfig::default(),
reset: AtxKeyConfig::default(),
led: AtxLedConfig::default(),
wol: WolConfig::default(),
}
}
}
```
---
## 5. API 端点
| 端点 | 方法 | 描述 |
|------|------|------|
| `/api/atx/status` | GET | 获取 ATX 状态 |
| `/api/atx/power/short` | POST | 短按电源 |
| `/api/atx/power/long` | POST | 长按电源 |
| `/api/atx/reset` | POST | 按重置 |
| `/api/atx/wol` | POST | 发送 WoL |
### 响应格式
```json
// GET /api/atx/status
{
"available": true,
"power_on": true,
"last_action": "2024-01-15T10:30:00Z",
"error": null
}
// POST /api/atx/wol
// Request: { "mac": "00:11:22:33:44:55" }
{
"success": true
}
```
---
## 6. 硬件连接
### 6.1 GPIO 直连
```
One-KVM Device Target PC
┌─────────────┐ ┌─────────────┐
│ GPIO Pin │───────────────│ Power SW │
│ (Output) │ │ │
└─────────────┘ └─────────────┘
接线说明:
- GPIO 引脚连接到 ATX 电源按钮
- 使用光耦或继电器隔离 (推荐)
- 注意电平匹配
```
### 6.2 USB 继电器
```
One-KVM Device USB Relay Target PC
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ USB │───────────────│ Relay │──────────│ Power SW │
│ │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────┘
优点:
- 完全隔离
- 无需担心电平问题
- 更安全
```
---
## 7. 事件
```rust
pub enum SystemEvent {
AtxStateChanged {
power_on: bool,
last_action: Option<String>,
error: Option<String>,
},
AtxActionPerformed {
action: String, // "power_short" | "power_long" | "reset" | "wol"
success: bool,
},
}
```
---
## 8. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum AtxError {
#[error("ATX not available")]
NotAvailable,
#[error("GPIO error: {0}")]
GpioError(String),
#[error("Relay error: {0}")]
RelayError(String),
#[error("WoL error: {0}")]
WolError(String),
#[error("Invalid MAC address: {0}")]
InvalidMac(String),
#[error("Operation in progress")]
Busy,
}
```
---
## 9. 使用示例
```rust
let atx = AtxController::new(&config, events)?;
// 开机
atx.power_short_press().await?;
// 检查状态
tokio::time::sleep(Duration::from_secs(5)).await;
if atx.power_state() == PowerState::On {
println!("PC is now on");
}
// 强制关机
atx.power_long_press().await?;
// 重置
atx.reset_press().await?;
// Wake-on-LAN
atx.wake_on_lan("00:11:22:33:44:55").await?;
```
---
## 10. 常见问题
### Q: GPIO 无法控制?
1. 检查引脚配置
2. 检查权限 (`/dev/gpiochip*`)
3. 检查接线
### Q: LED 状态不正确?
1. 检查 active_level 配置
2. 检查 GPIO 输入模式
### Q: WoL 不工作?
1. 检查目标 PC BIOS 设置
2. 检查网卡支持
3. 检查网络广播

View File

@@ -1,463 +0,0 @@
# Audio 模块文档
## 1. 模块概述
Audio 模块负责音频采集和编码,支持 ALSA 采集和 Opus 编码。
### 1.1 主要功能
- ALSA 音频采集
- Opus 编码
- 多质量配置
- WebSocket/WebRTC 传输
### 1.2 文件结构
```
src/audio/
├── mod.rs # 模块导出
├── controller.rs # AudioController (15KB)
├── capture.rs # ALSA 采集 (12KB)
├── encoder.rs # Opus 编码 (8KB)
├── shared_pipeline.rs # 共享管道 (15KB)
├── monitor.rs # 健康监视 (11KB)
└── device.rs # 设备枚举 (8KB)
```
---
## 2. 架构设计
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Audio Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
ALSA Device (hw:0,0)
│ PCM 48kHz/16bit/Stereo
┌─────────────────┐
│ AudioCapturer │
│ (capture.rs) │
└────────┬────────┘
┌─────────────────────────────────────────┐
│ SharedAudioPipeline │
│ ┌─────────────────────────────────┐ │
│ │ Opus Encoder │ │
│ │ 48kHz → 24-96 kbps │ │
│ └─────────────────────────────────┘ │
└────────────────┬────────────────────────┘
┌─────────┴─────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ WebSocket │ │ WebRTC │
│ Stream │ │ Audio Track │
└─────────────┘ └─────────────┘
```
---
## 3. 核心组件
### 3.1 AudioController (controller.rs)
```rust
pub struct AudioController {
/// 采集器
capturer: Arc<RwLock<Option<AudioCapturer>>>,
/// 共享管道
pipeline: Arc<SharedAudioPipeline>,
/// 配置
config: Arc<RwLock<AudioConfig>>,
/// 状态
state: Arc<RwLock<AudioState>>,
/// 事件总线
events: Arc<EventBus>,
}
impl AudioController {
/// 创建控制器
pub fn new(config: &AudioConfig, events: Arc<EventBus>) -> Result<Self>;
/// 启动音频
pub async fn start(&self) -> Result<()>;
/// 停止音频
pub async fn stop(&self) -> Result<()>;
/// 订阅音频帧
pub fn subscribe(&self) -> broadcast::Receiver<AudioFrame>;
/// 获取状态
pub fn status(&self) -> AudioStatus;
/// 设置质量
pub fn set_quality(&self, quality: AudioQuality) -> Result<()>;
/// 列出设备
pub fn list_devices(&self) -> Vec<AudioDeviceInfo>;
/// 重新加载配置
pub async fn reload(&self, config: &AudioConfig) -> Result<()>;
}
pub struct AudioStatus {
pub enabled: bool,
pub streaming: bool,
pub device: Option<String>,
pub sample_rate: u32,
pub channels: u16,
pub bitrate: u32,
pub error: Option<String>,
}
```
### 3.2 AudioCapturer (capture.rs)
```rust
pub struct AudioCapturer {
/// PCM 句柄
pcm: PCM,
/// 设备名
device: String,
/// 采样率
sample_rate: u32,
/// 通道数
channels: u16,
/// 帧大小
frame_size: usize,
/// 运行状态
running: AtomicBool,
}
impl AudioCapturer {
/// 打开设备
pub fn open(device: &str, config: &CaptureConfig) -> Result<Self>;
/// 读取音频帧
pub fn read_frame(&self) -> Result<Vec<i16>>;
/// 启动采集
pub fn start(&self) -> Result<()>;
/// 停止采集
pub fn stop(&self);
/// 是否运行中
pub fn is_running(&self) -> bool;
}
pub struct CaptureConfig {
pub sample_rate: u32, // 48000
pub channels: u16, // 2
pub frame_size: usize, // 960 (20ms)
pub buffer_size: usize, // 4800
}
```
### 3.3 OpusEncoder (encoder.rs)
```rust
pub struct OpusEncoder {
/// Opus 编码器
encoder: audiopus::Encoder,
/// 采样率
sample_rate: u32,
/// 通道数
channels: u16,
/// 帧大小
frame_size: usize,
/// 码率
bitrate: u32,
}
impl OpusEncoder {
/// 创建编码器
pub fn new(quality: AudioQuality) -> Result<Self>;
/// 编码 PCM 数据
pub fn encode(&mut self, pcm: &[i16]) -> Result<Vec<u8>>;
/// 设置码率
pub fn set_bitrate(&mut self, bitrate: u32) -> Result<()>;
/// 获取码率
pub fn bitrate(&self) -> u32;
/// 重置编码器
pub fn reset(&mut self) -> Result<()>;
}
```
### 3.4 SharedAudioPipeline (shared_pipeline.rs)
```rust
pub struct SharedAudioPipeline {
/// 采集器
capturer: Arc<RwLock<Option<AudioCapturer>>>,
/// 编码器
encoder: Arc<Mutex<OpusEncoder>>,
/// 广播通道
tx: broadcast::Sender<AudioFrame>,
/// 采集任务
capture_task: Arc<RwLock<Option<JoinHandle<()>>>>,
/// 配置
config: Arc<RwLock<AudioConfig>>,
}
impl SharedAudioPipeline {
/// 创建管道
pub fn new(config: &AudioConfig) -> Result<Self>;
/// 启动管道
pub async fn start(&self) -> Result<()>;
/// 停止管道
pub async fn stop(&self) -> Result<()>;
/// 订阅音频帧
pub fn subscribe(&self) -> broadcast::Receiver<AudioFrame>;
/// 获取统计
pub fn stats(&self) -> PipelineStats;
}
pub struct AudioFrame {
/// Opus 数据
pub data: Bytes,
/// 时间戳
pub timestamp: u64,
/// 帧序号
pub sequence: u64,
}
```
---
## 4. 音频质量
```rust
pub enum AudioQuality {
/// 24 kbps - 最低带宽
VeryLow,
/// 48 kbps - 低带宽
Low,
/// 64 kbps - 中等
Medium,
/// 96 kbps - 高质量
High,
}
impl AudioQuality {
pub fn bitrate(&self) -> u32 {
match self {
Self::VeryLow => 24000,
Self::Low => 48000,
Self::Medium => 64000,
Self::High => 96000,
}
}
}
```
---
## 5. 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct AudioConfig {
/// 是否启用
pub enabled: bool,
/// 设备名
pub device: Option<String>,
/// 音频质量
pub quality: AudioQuality,
/// 自动启动
pub auto_start: bool,
}
impl Default for AudioConfig {
fn default() -> Self {
Self {
enabled: true,
device: None, // 使用默认设备
quality: AudioQuality::Medium,
auto_start: false,
}
}
}
```
---
## 6. API 端点
| 端点 | 方法 | 描述 |
|------|------|------|
| `/api/audio/status` | GET | 获取音频状态 |
| `/api/audio/start` | POST | 启动音频 |
| `/api/audio/stop` | POST | 停止音频 |
| `/api/audio/devices` | GET | 列出设备 |
| `/api/audio/quality` | GET | 获取质量 |
| `/api/audio/quality` | POST | 设置质量 |
| `/api/ws/audio` | WS | 音频流 |
### 响应格式
```json
// GET /api/audio/status
{
"enabled": true,
"streaming": true,
"device": "hw:0,0",
"sample_rate": 48000,
"channels": 2,
"bitrate": 64000,
"error": null
}
// GET /api/audio/devices
{
"devices": [
{
"name": "hw:0,0",
"description": "USB Audio Device",
"is_default": true
}
]
}
```
---
## 7. WebSocket 音频流
```javascript
// 连接 WebSocket
const ws = new WebSocket('/api/ws/audio');
ws.binaryType = 'arraybuffer';
// 初始化 Opus 解码器
const decoder = new OpusDecoder();
// 接收音频帧
ws.onmessage = (event) => {
const frame = new Uint8Array(event.data);
const pcm = decoder.decode(frame);
audioContext.play(pcm);
};
```
---
## 8. 事件
```rust
pub enum SystemEvent {
AudioStateChanged {
enabled: bool,
streaming: bool,
device: Option<String>,
error: Option<String>,
},
}
```
---
## 9. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum AudioError {
#[error("Device not found: {0}")]
DeviceNotFound(String),
#[error("Device busy: {0}")]
DeviceBusy(String),
#[error("ALSA error: {0}")]
AlsaError(String),
#[error("Encoder error: {0}")]
EncoderError(String),
#[error("Not streaming")]
NotStreaming,
}
```
---
## 10. 使用示例
```rust
let controller = AudioController::new(&config, events)?;
// 启动音频
controller.start().await?;
// 订阅音频帧
let mut rx = controller.subscribe();
while let Ok(frame) = rx.recv().await {
// 处理 Opus 数据
send_to_client(frame.data);
}
// 停止
controller.stop().await?;
```
---
## 11. 常见问题
### Q: 找不到音频设备?
1. 检查 ALSA 配置
2. 运行 `arecord -l`
3. 检查权限
### Q: 音频延迟高?
1. 减小帧大小
2. 降低质量
3. 检查网络
### Q: 音频断断续续?
1. 增大缓冲区
2. 检查 CPU 负载
3. 使用更低质量

View File

@@ -1,340 +0,0 @@
# Auth 模块文档
## 1. 模块概述
Auth 模块提供用户认证和会话管理功能。
### 1.1 主要功能
- 用户管理
- 密码哈希 (Argon2)
- 会话管理
- 认证中间件
- 权限控制
### 1.2 文件结构
```
src/auth/
├── mod.rs # 模块导出
├── user.rs # 用户管理 (5KB)
├── session.rs # 会话管理 (4KB)
├── password.rs # 密码哈希 (1KB)
└── middleware.rs # 中间件 (4KB)
```
---
## 2. 核心组件
### 2.1 UserStore (user.rs)
```rust
pub struct UserStore {
db: Pool<Sqlite>,
}
impl UserStore {
/// 创建存储
pub async fn new(db: Pool<Sqlite>) -> Result<Self>;
/// 创建用户
pub async fn create_user(&self, user: &CreateUser) -> Result<User>;
/// 获取用户
pub async fn get_user(&self, id: &str) -> Result<Option<User>>;
/// 按用户名获取
pub async fn get_by_username(&self, username: &str) -> Result<Option<User>>;
/// 更新用户
pub async fn update_user(&self, id: &str, update: &UpdateUser) -> Result<()>;
/// 删除用户
pub async fn delete_user(&self, id: &str) -> Result<()>;
/// 列出用户
pub async fn list_users(&self) -> Result<Vec<User>>;
/// 验证密码
pub async fn verify_password(&self, username: &str, password: &str) -> Result<Option<User>>;
/// 更新密码
pub async fn update_password(&self, id: &str, new_password: &str) -> Result<()>;
/// 检查是否需要初始化
pub async fn needs_setup(&self) -> Result<bool>;
}
pub struct User {
pub id: String,
pub username: String,
pub role: UserRole,
pub created_at: DateTime<Utc>,
}
pub enum UserRole {
Admin,
User,
}
pub struct CreateUser {
pub username: String,
pub password: String,
pub role: UserRole,
}
```
### 2.2 SessionStore (session.rs)
```rust
pub struct SessionStore {
/// 会话映射
sessions: RwLock<HashMap<String, Session>>,
/// 会话超时
timeout: Duration,
}
impl SessionStore {
/// 创建存储
pub fn new(timeout: Duration) -> Self;
/// 创建会话
pub fn create_session(&self, user: &User) -> String;
/// 获取会话
pub fn get_session(&self, token: &str) -> Option<Session>;
/// 删除会话
pub fn delete_session(&self, token: &str);
/// 清理过期会话
pub fn cleanup_expired(&self);
/// 刷新会话
pub fn refresh_session(&self, token: &str) -> bool;
}
pub struct Session {
pub token: String,
pub user_id: String,
pub username: String,
pub role: UserRole,
pub created_at: Instant,
pub last_active: Instant,
}
```
### 2.3 密码哈希 (password.rs)
```rust
/// 哈希密码
pub fn hash_password(password: &str) -> Result<String> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let hash = argon2
.hash_password(password.as_bytes(), &salt)?
.to_string();
Ok(hash)
}
/// 验证密码
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
let parsed_hash = PasswordHash::new(hash)?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok())
}
```
### 2.4 认证中间件 (middleware.rs)
```rust
pub async fn auth_middleware(
State(state): State<Arc<AppState>>,
cookies: Cookies,
request: Request,
next: Next,
) -> Response {
// 获取 session token
let token = cookies
.get("session_id")
.map(|c| c.value().to_string());
// 验证会话
let session = token
.and_then(|t| state.sessions.get_session(&t));
if let Some(session) = session {
// 将用户信息注入请求
let mut request = request;
request.extensions_mut().insert(session);
next.run(request).await
} else {
StatusCode::UNAUTHORIZED.into_response()
}
}
pub async fn admin_middleware(
session: Extension<Session>,
request: Request,
next: Next,
) -> Response {
if session.role == UserRole::Admin {
next.run(request).await
} else {
StatusCode::FORBIDDEN.into_response()
}
}
```
---
## 3. API 端点
| 端点 | 方法 | 权限 | 描述 |
|------|------|------|------|
| `/api/auth/login` | POST | Public | 登录 |
| `/api/auth/logout` | POST | User | 登出 |
| `/api/auth/check` | GET | User | 检查认证 |
| `/api/auth/password` | POST | User | 修改密码 |
| `/api/users` | GET | Admin | 列出用户 |
| `/api/users` | POST | Admin | 创建用户 |
| `/api/users/:id` | DELETE | Admin | 删除用户 |
| `/api/setup/init` | POST | Public | 初始化设置 |
### 请求/响应格式
```json
// POST /api/auth/login
// Request:
{
"username": "admin",
"password": "password123"
}
// Response:
{
"user": {
"id": "uuid",
"username": "admin",
"role": "admin"
}
}
// GET /api/auth/check
{
"authenticated": true,
"user": {
"id": "uuid",
"username": "admin",
"role": "admin"
}
}
```
---
## 4. 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct AuthConfig {
/// 会话超时 (秒)
pub session_timeout_secs: u64,
/// 是否启用认证
pub enabled: bool,
}
impl Default for AuthConfig {
fn default() -> Self {
Self {
session_timeout_secs: 86400, // 24 小时
enabled: true,
}
}
}
```
---
## 5. 安全特性
### 5.1 密码存储
- Argon2id 哈希
- 随机盐值
- 不可逆
### 5.2 会话安全
- 随机 token (UUID v4)
- HTTPOnly Cookie
- 会话超时
- 自动清理
### 5.3 权限控制
- 两级权限: Admin / User
- 中间件检查
- 敏感操作需 Admin
---
## 6. 使用示例
```rust
// 创建用户
let user = users.create_user(&CreateUser {
username: "admin".to_string(),
password: "password123".to_string(),
role: UserRole::Admin,
}).await?;
// 验证密码
if let Some(user) = users.verify_password("admin", "password123").await? {
// 创建会话
let token = sessions.create_session(&user);
// 设置 Cookie
cookies.add(Cookie::build("session_id", token)
.http_only(true)
.path("/")
.finish());
}
// 获取会话
if let Some(session) = sessions.get_session(&token) {
println!("User: {}", session.username);
}
```
---
## 7. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error("Invalid credentials")]
InvalidCredentials,
#[error("User not found")]
UserNotFound,
#[error("User already exists")]
UserExists,
#[error("Session expired")]
SessionExpired,
#[error("Permission denied")]
PermissionDenied,
#[error("Setup required")]
SetupRequired,
}
```

View File

@@ -1,755 +0,0 @@
# Config 模块文档
## 1. 模块概述
Config 模块提供配置管理功能,所有配置存储在 SQLite 数据库中,使用 ArcSwap 实现无锁读取,提供高性能配置访问。
### 1.1 主要功能
- SQLite 配置存储(持久化)
- 无锁配置读取ArcSwap
- 类型安全的配置结构
- 配置变更通知broadcast channel
- TypeScript 类型生成typeshare
- RESTful API按功能域分离
### 1.2 文件结构
```
src/config/
├── mod.rs # 模块导出
├── schema.rs # 配置结构定义(包含所有子配置)
└── store.rs # SQLite 存储与无锁缓存
```
---
## 2. 核心组件
### 2.1 ConfigStore (store.rs)
配置存储使用 **ArcSwap** 实现无锁读取,提供接近零成本的配置访问性能:
```rust
pub struct ConfigStore {
pool: Pool<Sqlite>,
/// 无锁缓存,使用 ArcSwap 实现零成本读取
cache: Arc<ArcSwap<AppConfig>>,
/// 配置变更通知通道
change_tx: broadcast::Sender<ConfigChange>,
}
impl ConfigStore {
/// 创建存储
pub async fn new(db_path: &Path) -> Result<Self>;
/// 获取当前配置(无锁,零拷贝)
///
/// 返回 Arc<AppConfig>,高效共享无需克隆
/// 这是一个无锁操作,开销极小
pub fn get(&self) -> Arc<AppConfig>;
/// 设置完整配置
pub async fn set(&self, config: AppConfig) -> Result<()>;
/// 使用闭包更新配置
///
/// 读-修改-写模式。并发更新时,最后的写入获胜。
/// 对于不频繁的用户触发配置更改来说是可接受的。
pub async fn update<F>(&self, f: F) -> Result<()>
where
F: FnOnce(&mut AppConfig);
/// 订阅配置变更事件
pub fn subscribe(&self) -> broadcast::Receiver<ConfigChange>;
/// 检查系统是否已初始化(无锁)
pub fn is_initialized(&self) -> bool;
/// 获取数据库连接池(用于会话管理)
pub fn pool(&self) -> &Pool<Sqlite>;
}
```
**性能特点**
- `get()` 是无锁读取操作,返回 `Arc<AppConfig>`,无需克隆
- 配置读取频率远高于写入ArcSwap 优化了读取路径
- 写入操作先持久化到数据库,再原子性更新内存缓存
- 使用 broadcast channel 通知配置变更,支持多订阅者
**数据库连接池配置**
```rust
SqlitePoolOptions::new()
.max_connections(2) // SQLite 单写模式2 个连接足够
.acquire_timeout(Duration::from_secs(5))
.idle_timeout(Duration::from_secs(300))
```
### 2.2 AppConfig (schema.rs)
主应用配置结构,包含所有子系统的配置:
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct AppConfig {
/// 初始设置是否完成
pub initialized: bool,
/// 认证配置
pub auth: AuthConfig,
/// 视频采集配置
pub video: VideoConfig,
/// HID键盘/鼠标)配置
pub hid: HidConfig,
/// MSD大容量存储配置
pub msd: MsdConfig,
/// ATX 电源控制配置
pub atx: AtxConfig,
/// 音频配置
pub audio: AudioConfig,
/// 流媒体配置
pub stream: StreamConfig,
/// Web 服务器配置
pub web: WebConfig,
/// 扩展配置ttyd, gostc, easytier
pub extensions: ExtensionsConfig,
/// RustDesk 远程访问配置
pub rustdesk: RustDeskConfig,
}
```
### 2.3 主要子配置结构
#### AuthConfig - 认证配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct AuthConfig {
/// 会话超时时间(秒)
pub session_timeout_secs: u32, // 默认 8640024小时
/// 启用双因素认证
pub totp_enabled: bool,
/// TOTP 密钥(加密存储)
pub totp_secret: Option<String>,
}
```
#### VideoConfig - 视频采集配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[typeshare]
pub struct VideoConfig {
/// 视频设备路径(如 /dev/video0
pub device: Option<String>,
/// 像素格式(如 "MJPEG", "YUYV", "NV12"
pub format: Option<String>,
/// 分辨率宽度
pub width: u32, // 默认 1920
/// 分辨率高度
pub height: u32, // 默认 1080
/// 帧率
pub fps: u32, // 默认 30
/// JPEG 质量1-100
pub quality: u32, // 默认 80
}
```
#### HidConfig - HID 配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[typeshare]
pub struct HidConfig {
/// HID 后端类型
pub backend: HidBackend, // Otg | Ch9329 | None
/// OTG 键盘设备路径
pub otg_keyboard: String, // 默认 "/dev/hidg0"
/// OTG 鼠标设备路径
pub otg_mouse: String, // 默认 "/dev/hidg1"
/// OTG UDCUSB 设备控制器)名称
pub otg_udc: Option<String>,
/// OTG USB 设备描述符配置
pub otg_descriptor: OtgDescriptorConfig,
/// CH9329 串口路径
pub ch9329_port: String, // 默认 "/dev/ttyUSB0"
/// CH9329 波特率
pub ch9329_baudrate: u32, // 默认 9600
/// 鼠标模式:绝对定位或相对定位
pub mouse_absolute: bool, // 默认 true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[typeshare]
pub struct OtgDescriptorConfig {
pub vendor_id: u16, // 默认 0x1d6bLinux Foundation
pub product_id: u16, // 默认 0x0104
pub manufacturer: String, // 默认 "One-KVM"
pub product: String, // 默认 "One-KVM USB Device"
pub serial_number: Option<String>,
}
```
#### StreamConfig - 流媒体配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct StreamConfig {
/// 流模式WebRTC | Mjpeg
pub mode: StreamMode,
/// 编码器类型
pub encoder: EncoderType, // Auto | Software | Vaapi | Nvenc | Qsv | Amf | Rkmpp | V4l2m2m
/// 码率预设Speed | Balanced | Quality
pub bitrate_preset: BitratePreset,
/// 自定义 STUN 服务器
pub stun_server: Option<String>, // 默认 "stun:stun.l.google.com:19302"
/// 自定义 TURN 服务器
pub turn_server: Option<String>,
/// TURN 用户名
pub turn_username: Option<String>,
/// TURN 密码(加密存储,不通过 API 暴露)
pub turn_password: Option<String>,
/// 无客户端时自动暂停
#[typeshare(skip)]
pub auto_pause_enabled: bool,
/// 自动暂停延迟(秒)
#[typeshare(skip)]
pub auto_pause_delay_secs: u64,
/// 客户端超时清理(秒)
#[typeshare(skip)]
pub client_timeout_secs: u64,
}
```
#### MsdConfig - 大容量存储配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct MsdConfig {
/// 启用 MSD 功能
pub enabled: bool, // 默认 true
/// ISO/IMG 镜像存储路径
pub images_path: String, // 默认 "./data/msd/images"
/// Ventoy 启动驱动器文件路径
pub drive_path: String, // 默认 "./data/msd/ventoy.img"
/// 虚拟驱动器大小MB最小 1024
pub virtual_drive_size_mb: u32, // 默认 1638416GB
}
```
#### AtxConfig - ATX 电源控制配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct AtxConfig {
/// 启用 ATX 功能
pub enabled: bool,
/// 电源按钮配置(短按和长按共用)
pub power: AtxKeyConfig,
/// 重置按钮配置
pub reset: AtxKeyConfig,
/// LED 检测配置(可选)
pub led: AtxLedConfig,
/// WOL 数据包使用的网络接口(空字符串 = 自动)
pub wol_interface: String,
}
```
#### AudioConfig - 音频配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct AudioConfig {
/// 启用音频采集
pub enabled: bool, // 默认 false
/// ALSA 设备名称
pub device: String, // 默认 "default"
/// 音频质量预设:"voice" | "balanced" | "high"
pub quality: String, // 默认 "balanced"
}
```
**注意**:采样率固定为 48000Hz声道固定为 2立体声这是 Opus 编码和 WebRTC 的最佳配置。
#### WebConfig - Web 服务器配置
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[typeshare]
pub struct WebConfig {
/// HTTP 端口
pub http_port: u16, // 默认 8080
/// HTTPS 端口
pub https_port: u16, // 默认 8443
/// 绑定地址
pub bind_address: String, // 默认 "0.0.0.0"
/// 启用 HTTPS
pub https_enabled: bool, // 默认 false
/// 自定义 SSL 证书路径
pub ssl_cert_path: Option<String>,
/// 自定义 SSL 密钥路径
pub ssl_key_path: Option<String>,
}
```
---
## 3. TypeScript 类型生成
使用 `#[typeshare]` 属性自动生成 TypeScript 类型:
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct VideoConfig {
pub device: Option<String>,
pub width: u32,
pub height: u32,
}
```
生成的 TypeScript
```typescript
export interface VideoConfig {
device?: string;
width: number;
height: number;
}
```
生成命令:
```bash
./scripts/generate-types.sh
# 或
typeshare src --lang=typescript --output-file=web/src/types/generated.ts
```
---
## 4. API 端点
所有配置端点均需要 **Admin** 权限,采用 RESTful 设计,按功能域分离。
### 4.1 全局配置
| 端点 | 方法 | 权限 | 描述 |
|------|------|------|------|
| `/api/config` | GET | Admin | 获取完整配置(敏感信息已过滤) |
| `/api/config` | POST | Admin | 更新完整配置(已废弃,请使用按域 PATCH |
### 4.2 分域配置端点
| 端点 | 方法 | 权限 | 描述 |
|------|------|------|------|
| `/api/config/video` | GET | Admin | 获取视频配置 |
| `/api/config/video` | PATCH | Admin | 更新视频配置(部分更新) |
| `/api/config/stream` | GET | Admin | 获取流配置 |
| `/api/config/stream` | PATCH | Admin | 更新流配置(部分更新) |
| `/api/config/hid` | GET | Admin | 获取 HID 配置 |
| `/api/config/hid` | PATCH | Admin | 更新 HID 配置(部分更新) |
| `/api/config/msd` | GET | Admin | 获取 MSD 配置 |
| `/api/config/msd` | PATCH | Admin | 更新 MSD 配置(部分更新) |
| `/api/config/atx` | GET | Admin | 获取 ATX 配置 |
| `/api/config/atx` | PATCH | Admin | 更新 ATX 配置(部分更新) |
| `/api/config/audio` | GET | Admin | 获取音频配置 |
| `/api/config/audio` | PATCH | Admin | 更新音频配置(部分更新) |
| `/api/config/web` | GET | Admin | 获取 Web 服务器配置 |
| `/api/config/web` | PATCH | Admin | 更新 Web 服务器配置(部分更新) |
### 4.3 RustDesk 配置端点
| 端点 | 方法 | 权限 | 描述 |
|------|------|------|------|
| `/api/config/rustdesk` | GET | Admin | 获取 RustDesk 配置 |
| `/api/config/rustdesk` | PATCH | Admin | 更新 RustDesk 配置 |
| `/api/config/rustdesk/status` | GET | Admin | 获取 RustDesk 服务状态 |
| `/api/config/rustdesk/password` | GET | Admin | 获取设备密码 |
| `/api/config/rustdesk/regenerate-id` | POST | Admin | 重新生成设备 ID |
| `/api/config/rustdesk/regenerate-password` | POST | Admin | 重新生成设备密码 |
### 4.4 请求/响应示例
#### 获取视频配置
```bash
GET /api/config/video
```
响应:
```json
{
"device": "/dev/video0",
"format": "MJPEG",
"width": 1920,
"height": 1080,
"fps": 30,
"quality": 80
}
```
#### 部分更新视频配置
```bash
PATCH /api/config/video
Content-Type: application/json
{
"width": 1280,
"height": 720,
"fps": 60
}
```
响应:更新后的完整 VideoConfig
```json
{
"device": "/dev/video0",
"format": "MJPEG",
"width": 1280,
"height": 720,
"fps": 60,
"quality": 80
}
```
**注意**
- 所有 PATCH 请求都支持部分更新,只需要提供要修改的字段
- 未提供的字段保持原有值不变
- 更新后返回完整的配置对象
- 配置变更会自动触发相关组件重载
---
## 5. 配置变更通知
ConfigStore 提供 broadcast channel 用于配置变更通知:
```rust
/// 配置变更事件
#[derive(Debug, Clone)]
pub struct ConfigChange {
pub key: String,
}
// 订阅配置变更
let mut rx = config_store.subscribe();
// 监听变更事件
while let Ok(change) = rx.recv().await {
println!("配置 {} 已更新", change.key);
// 重载相关组件
}
```
**工作流程**
1. 调用 `config_store.set()``config_store.update()`
2. 配置写入数据库(持久化)
3. 原子性更新内存缓存ArcSwap
4. 发送 `ConfigChange` 事件到 broadcast channel
5. 各组件的订阅者接收事件并执行重载逻辑
**组件重载示例**
```rust
// VideoStreamManager 监听配置变更
let mut config_rx = config_store.subscribe();
tokio::spawn(async move {
while let Ok(change) = config_rx.recv().await {
if change.key == "app_config" {
video_manager.reload().await;
}
}
});
```
---
## 6. 数据库结构
ConfigStore 使用 SQLite 存储配置和其他系统数据:
### 6.1 配置表
```sql
CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
```
配置以 JSON 格式存储:
```sql
-- 应用配置
key: 'app_config'
value: '{"initialized": true, "video": {...}, "hid": {...}, ...}'
```
### 6.2 用户表
```sql
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
is_admin INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
```
### 6.3 会话表
```sql
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
data TEXT
);
```
### 6.4 API 令牌表
```sql
CREATE TABLE IF NOT EXISTS api_tokens (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
token_hash TEXT NOT NULL,
permissions TEXT NOT NULL,
expires_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_used TEXT
);
```
**存储特点**
- 所有配置存储在单个 JSON 文本中(`app_config` key
- 每次配置更新都更新整个 JSON简化事务处理
- 使用 `ON CONFLICT` 实现 upsert 操作
- 连接池大小为 21 读 + 1 写),适合嵌入式环境
---
## 7. 使用示例
### 7.1 基本用法
```rust
use crate::config::ConfigStore;
use std::path::Path;
// 创建配置存储
let config_store = ConfigStore::new(Path::new("./data/config.db")).await?;
// 获取配置(无锁,零拷贝)
let config = config_store.get();
println!("视频设备: {:?}", config.video.device);
println!("是否已初始化: {}", config.initialized);
// 检查是否已初始化
if !config_store.is_initialized() {
println!("系统尚未初始化,请完成初始设置");
}
```
### 7.2 更新配置
```rust
// 方式 1: 使用闭包更新(推荐)
config_store.update(|config| {
config.video.width = 1280;
config.video.height = 720;
config.video.fps = 60;
}).await?;
// 方式 2: 整体替换
let mut new_config = (*config_store.get()).clone();
new_config.stream.mode = StreamMode::WebRTC;
new_config.stream.encoder = EncoderType::Rkmpp;
config_store.set(new_config).await?;
```
### 7.3 订阅配置变更
```rust
// 在组件中监听配置变更
let config_store = state.config.clone();
let mut rx = config_store.subscribe();
tokio::spawn(async move {
while let Ok(change) = rx.recv().await {
tracing::info!("配置 {} 已变更", change.key);
// 重新加载配置
let config = config_store.get();
// 执行重载逻辑
if let Err(e) = reload_component(&config).await {
tracing::error!("重载组件失败: {}", e);
}
}
});
```
### 7.4 在 Handler 中使用
```rust
use axum::{extract::State, Json};
use std::sync::Arc;
use crate::config::VideoConfig;
use crate::state::AppState;
// 获取视频配置
pub async fn get_video_config(
State(state): State<Arc<AppState>>
) -> Json<VideoConfig> {
let config = state.config.get();
Json(config.video.clone())
}
// 更新视频配置
pub async fn update_video_config(
State(state): State<Arc<AppState>>,
Json(update): Json<VideoConfig>,
) -> Result<Json<VideoConfig>> {
// 更新配置
state.config.update(|config| {
config.video = update;
}).await?;
// 返回更新后的配置
let config = state.config.get();
Ok(Json(config.video.clone()))
}
```
### 7.5 访问数据库连接池
```rust
// ConfigStore 还提供数据库连接池访问
// 用于用户管理、会话管理等功能
let pool = config_store.pool();
// 查询用户
let user: Option<User> = sqlx::query_as(
"SELECT * FROM users WHERE username = ?"
)
.bind(username)
.fetch_optional(pool)
.await?;
```
---
## 8. 默认配置
系统首次运行时会自动创建默认配置:
```rust
impl Default for AppConfig {
fn default() -> Self {
Self {
initialized: false, // 需要通过初始设置向导完成
auth: AuthConfig {
session_timeout_secs: 86400, // 24小时
totp_enabled: false,
totp_secret: None,
},
video: VideoConfig {
device: None, // 自动检测
format: None, // 自动检测或使用 MJPEG
width: 1920,
height: 1080,
fps: 30,
quality: 80,
},
stream: StreamConfig {
mode: StreamMode::Mjpeg,
encoder: EncoderType::Auto,
bitrate_preset: BitratePreset::Balanced,
stun_server: Some("stun:stun.l.google.com:19302".to_string()),
turn_server: None,
turn_username: None,
turn_password: None,
auto_pause_enabled: false,
auto_pause_delay_secs: 10,
client_timeout_secs: 30,
},
hid: HidConfig {
backend: HidBackend::None, // 需要用户手动启用
otg_keyboard: "/dev/hidg0".to_string(),
otg_mouse: "/dev/hidg1".to_string(),
otg_udc: None, // 自动检测
otg_descriptor: OtgDescriptorConfig::default(),
ch9329_port: "/dev/ttyUSB0".to_string(),
ch9329_baudrate: 9600,
mouse_absolute: true,
},
msd: MsdConfig {
enabled: true,
images_path: "./data/msd/images".to_string(),
drive_path: "./data/msd/ventoy.img".to_string(),
virtual_drive_size_mb: 16384, // 16GB
},
atx: AtxConfig {
enabled: false, // 需要用户配置硬件绑定
power: AtxKeyConfig::default(),
reset: AtxKeyConfig::default(),
led: AtxLedConfig::default(),
wol_interface: String::new(), // 自动检测
},
audio: AudioConfig {
enabled: false,
device: "default".to_string(),
quality: "balanced".to_string(),
},
web: WebConfig {
http_port: 8080,
https_port: 8443,
bind_address: "0.0.0.0".to_string(),
https_enabled: false,
ssl_cert_path: None,
ssl_key_path: None,
},
extensions: ExtensionsConfig::default(),
rustdesk: RustDeskConfig::default(),
}
}
}
```
**配置初始化流程**
1. 用户首次访问 Web UI系统检测到 `initialized = false`
2. 重定向到初始设置向导(`/setup`
3. 用户设置管理员账户、选择视频设备等
4. 完成设置后,`initialized` 设为 `true`
5. 后续可通过设置页面(`/settings`)修改各项配置

View File

@@ -1,353 +0,0 @@
# Events 模块文档
## 1. 模块概述
Events 模块提供事件总线功能,用于模块间通信和状态广播。
### 1.1 主要功能
- 事件发布/订阅
- 多订阅者广播
- WebSocket 事件推送
- 状态变更通知
### 1.2 文件结构
```
src/events/
└── mod.rs # EventBus 实现
```
---
## 2. 架构设计
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Event System │
└─────────────────────────────────────────────────────────────────────────────┘
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ Video │ │ HID │ │ Audio │
│ Module │ │ Module │ │ Module │
└───────┬────────┘ └───────┬────────┘ └───────┬────────┘
│ │ │
│ publish() │ publish() │ publish()
└──────────────────┼──────────────────┘
┌─────────────────────┐
│ EventBus │
│ (broadcast channel) │
└──────────┬──────────┘
┌─────────────────┼─────────────────┐
│ │ │
│ subscribe() │ subscribe() │
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ WebSocket │ │ DeviceInfo │ │ Internal │
│ Handler │ │ Broadcaster │ │ Tasks │
└────────────────┘ └────────────────┘ └────────────────┘
```
---
## 3. 核心组件
### 3.1 EventBus
```rust
pub struct EventBus {
/// 广播发送器
tx: broadcast::Sender<SystemEvent>,
}
impl EventBus {
/// 创建事件总线
pub fn new() -> Self {
let (tx, _) = broadcast::channel(1024);
Self { tx }
}
/// 发布事件
pub fn publish(&self, event: SystemEvent) {
let _ = self.tx.send(event);
}
/// 订阅事件
pub fn subscribe(&self) -> broadcast::Receiver<SystemEvent> {
self.tx.subscribe()
}
}
```
### 3.2 SystemEvent
```rust
#[derive(Clone, Debug, Serialize)]
pub enum SystemEvent {
// 视频事件
StreamStateChanged {
state: String,
device: Option<String>,
resolution: Option<Resolution>,
fps: Option<f32>,
},
VideoDeviceChanged {
added: Vec<String>,
removed: Vec<String>,
},
// HID 事件
HidStateChanged {
backend: String,
initialized: bool,
keyboard_connected: bool,
mouse_connected: bool,
mouse_mode: String,
error: Option<String>,
},
// MSD 事件
MsdStateChanged {
mode: String,
connected: bool,
image: Option<String>,
error: Option<String>,
},
MsdDownloadProgress {
download_id: String,
downloaded: u64,
total: u64,
speed: u64,
},
// ATX 事件
AtxStateChanged {
power_on: bool,
last_action: Option<String>,
error: Option<String>,
},
// 音频事件
AudioStateChanged {
enabled: bool,
streaming: bool,
device: Option<String>,
error: Option<String>,
},
// 配置事件
ConfigChanged {
section: String,
},
// 设备信息汇总
DeviceInfo {
video: VideoInfo,
hid: HidInfo,
msd: MsdInfo,
atx: AtxInfo,
audio: AudioInfo,
},
// 系统错误
SystemError {
module: String,
severity: String,
message: String,
},
// RustDesk 事件
RustDeskStatusChanged {
status: String,
device_id: Option<String>,
error: Option<String>,
},
RustDeskConnectionOpened {
connection_id: String,
peer_id: String,
},
RustDeskConnectionClosed {
connection_id: String,
peer_id: String,
reason: String,
},
}
```
---
## 4. 设备信息广播器
`main.rs` 中启动的后台任务:
```rust
pub fn spawn_device_info_broadcaster(
state: Arc<AppState>,
events: Arc<EventBus>,
) -> JoinHandle<()> {
tokio::spawn(async move {
let mut rx = events.subscribe();
let mut debounce = tokio::time::interval(Duration::from_millis(100));
let mut pending = false;
loop {
tokio::select! {
// 收到事件
result = rx.recv() => {
if result.is_ok() {
pending = true;
}
}
// 防抖定时器
_ = debounce.tick() => {
if pending {
pending = false;
// 收集设备信息
let device_info = state.get_device_info().await;
// 广播
events.publish(SystemEvent::DeviceInfo(device_info));
}
}
}
}
})
}
```
---
## 5. WebSocket 事件推送
```rust
pub async fn ws_handler(
ws: WebSocketUpgrade,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| handle_ws(socket, state))
}
async fn handle_ws(mut socket: WebSocket, state: Arc<AppState>) {
let mut rx = state.events.subscribe();
loop {
tokio::select! {
// 发送事件给客户端
result = rx.recv() => {
if let Ok(event) = result {
let json = serde_json::to_string(&event).unwrap();
if socket.send(Message::Text(json)).await.is_err() {
break;
}
}
}
// 接收客户端消息
msg = socket.recv() => {
match msg {
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
}
```
---
## 6. 使用示例
### 6.1 发布事件
```rust
// 视频模块发布状态变更
events.publish(SystemEvent::StreamStateChanged {
state: "streaming".to_string(),
device: Some("/dev/video0".to_string()),
resolution: Some(Resolution { width: 1920, height: 1080 }),
fps: Some(30.0),
});
// HID 模块发布状态变更
events.publish(SystemEvent::HidStateChanged {
backend: "otg".to_string(),
initialized: true,
keyboard_connected: true,
mouse_connected: true,
mouse_mode: "absolute".to_string(),
error: None,
});
```
### 6.2 订阅事件
```rust
let mut rx = events.subscribe();
loop {
match rx.recv().await {
Ok(SystemEvent::StreamStateChanged { state, .. }) => {
println!("Stream state: {}", state);
}
Ok(SystemEvent::HidStateChanged { backend, .. }) => {
println!("HID backend: {}", backend);
}
Err(_) => break,
}
}
```
---
## 7. 前端事件处理
```typescript
// 连接 WebSocket
const ws = new WebSocket('/api/ws');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'StreamStateChanged':
updateStreamStatus(data);
break;
case 'HidStateChanged':
updateHidStatus(data);
break;
case 'MsdStateChanged':
updateMsdStatus(data);
break;
case 'DeviceInfo':
updateAllDevices(data);
break;
}
};
```
---
## 8. 最佳实践
### 8.1 事件粒度
- 使用细粒度事件便于精确更新
- DeviceInfo 用于初始化和定期同步
### 8.2 防抖
- 使用 100ms 防抖避免事件风暴
- 合并多个快速变更
### 8.3 错误处理
- 发布失败静默忽略 (fire-and-forget)
- 订阅者断开自动清理

File diff suppressed because it is too large Load Diff

View File

@@ -1,617 +0,0 @@
# MSD 模块文档
## 1. 模块概述
MSD (Mass Storage Device) 模块提供虚拟存储设备功能,允许将 ISO/IMG 镜像作为 USB 存储设备挂载到目标计算机。
### 1.1 主要功能
- ISO/IMG 镜像挂载
- 镜像下载管理
- Ventoy 多 ISO 启动盘
- 热插拔支持
- 下载进度追踪
### 1.2 文件结构
```
src/msd/
├── mod.rs # 模块导出
├── controller.rs # MsdController (20KB)
├── image.rs # 镜像管理 (21KB)
├── ventoy_drive.rs # Ventoy 驱动 (24KB)
├── monitor.rs # 健康监视 (9KB)
└── types.rs # 类型定义 (6KB)
```
---
## 2. 架构设计
### 2.1 整体架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ MSD Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
Web API
┌─────────────────┐
│ MsdController │
│ (controller.rs) │
└────────┬────────┘
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌───────────┐ ┌───────────┐
│ Image │ │ Ventoy │ │ OTG │
│ Manager │ │ Drive │ │ Service │
│ (image.rs) │ │(ventoy.rs)│ │ │
└──────┬──────┘ └─────┬─────┘ └─────┬─────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌───────────┐ ┌───────────┐
│ /data/ │ │ exFAT │ │ MSD │
│ images/ │ │ Drive │ │ Function │
└─────────────┘ └───────────┘ └───────────┘
┌───────────────┐
│ Target PC │
│ (USB Drive) │
└───────────────┘
```
### 2.2 MSD 模式
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ MSD Modes │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Image Mode │
│ ┌───────────┐ │
│ │ ISO/IMG │ ──► MSD LUN ──► Target PC sees single drive │
│ │ File │ │
│ └───────────┘ │
│ 特点: │
│ - 单个镜像文件 │
│ - 直接挂载 │
│ - 适合系统安装 │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Ventoy Mode │
│ ┌───────────┐ │
│ │ ISO 1 │ │
│ ├───────────┤ ┌───────────┐ │
│ │ ISO 2 │ ──► │ Ventoy │ ──► Target PC sees bootable drive │
│ ├───────────┤ │ Drive │ with ISO selection menu │
│ │ ISO 3 │ └───────────┘ │
│ └───────────┘ │
│ 特点: │
│ - 多个 ISO 文件 │
│ - exFAT 文件系统 │
│ - 启动菜单选择 │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 3. 核心组件
### 3.1 MsdController (controller.rs)
MSD 控制器主类。
```rust
pub struct MsdController {
/// 当前状态
state: Arc<RwLock<MsdState>>,
/// 镜像管理器
image_manager: Arc<ImageManager>,
/// Ventoy 驱动器
ventoy_drive: Arc<RwLock<Option<VentoyDrive>>>,
/// OTG 服务
otg_service: Arc<OtgService>,
/// MSD 函数句柄
msd_function: Arc<RwLock<Option<MsdFunction>>>,
/// 事件总线
events: Arc<EventBus>,
/// 数据目录
data_dir: PathBuf,
}
impl MsdController {
/// 创建控制器
pub async fn new(
otg_service: Arc<OtgService>,
data_dir: PathBuf,
events: Arc<EventBus>,
) -> Result<Arc<Self>>;
/// 获取状态
pub fn state(&self) -> MsdState;
/// 连接 MSD
pub async fn connect(&self) -> Result<()>;
/// 断开 MSD
pub async fn disconnect(&self) -> Result<()>;
/// 切换到镜像模式
pub async fn set_image(&self, image_id: &str) -> Result<()>;
/// 切换到 Ventoy 模式
pub async fn set_ventoy(&self) -> Result<()>;
/// 清除当前挂载
pub async fn clear(&self) -> Result<()>;
/// 列出镜像
pub fn list_images(&self) -> Vec<ImageInfo>;
/// 上传镜像
pub async fn upload_image(&self, name: &str, data: Bytes) -> Result<ImageInfo>;
/// 从 URL 下载镜像
pub async fn download_image(&self, url: &str) -> Result<String>;
/// 删除镜像
pub async fn delete_image(&self, image_id: &str) -> Result<()>;
/// 获取下载进度
pub fn get_download_progress(&self, download_id: &str) -> Option<DownloadProgress>;
}
pub struct MsdState {
/// 是否可用
pub available: bool,
/// 当前模式
pub mode: MsdMode,
/// 是否已连接
pub connected: bool,
/// 当前镜像信息
pub current_image: Option<ImageInfo>,
/// 驱动器信息
pub drive_info: Option<DriveInfo>,
/// 错误信息
pub error: Option<String>,
}
pub enum MsdMode {
/// 未激活
None,
/// 单镜像模式
Image,
/// Ventoy 模式
Drive,
}
```
### 3.2 ImageManager (image.rs)
镜像文件管理器。
```rust
pub struct ImageManager {
/// 镜像目录
images_dir: PathBuf,
/// 镜像列表缓存
images: RwLock<HashMap<String, ImageInfo>>,
/// 下载任务
downloads: RwLock<HashMap<String, DownloadTask>>,
/// HTTP 客户端
http_client: reqwest::Client,
}
impl ImageManager {
/// 创建管理器
pub fn new(images_dir: PathBuf) -> Result<Self>;
/// 扫描镜像目录
pub fn scan_images(&self) -> Result<Vec<ImageInfo>>;
/// 获取镜像信息
pub fn get_image(&self, id: &str) -> Option<ImageInfo>;
/// 添加镜像
pub async fn add_image(&self, name: &str, data: Bytes) -> Result<ImageInfo>;
/// 删除镜像
pub fn delete_image(&self, id: &str) -> Result<()>;
/// 开始下载
pub async fn start_download(&self, url: &str) -> Result<String>;
/// 取消下载
pub fn cancel_download(&self, download_id: &str) -> Result<()>;
/// 获取下载进度
pub fn get_download_progress(&self, download_id: &str) -> Option<DownloadProgress>;
/// 验证镜像文件
fn validate_image(path: &Path) -> Result<ImageFormat>;
}
pub struct ImageInfo {
/// 唯一 ID
pub id: String,
/// 文件名
pub name: String,
/// 文件大小
pub size: u64,
/// 格式
pub format: ImageFormat,
/// 创建时间
pub created_at: DateTime<Utc>,
/// 下载状态
pub download_status: Option<DownloadStatus>,
}
pub enum ImageFormat {
/// ISO 光盘镜像
Iso,
/// 原始磁盘镜像
Img,
/// 未知格式
Unknown,
}
pub struct DownloadProgress {
/// 已下载字节
pub downloaded: u64,
/// 总字节数
pub total: u64,
/// 下载速度 (bytes/sec)
pub speed: u64,
/// 预计剩余时间
pub eta_secs: u64,
/// 状态
pub status: DownloadStatus,
}
pub enum DownloadStatus {
Pending,
Downloading,
Completed,
Failed(String),
Cancelled,
}
```
### 3.3 VentoyDrive (ventoy_drive.rs)
Ventoy 可启动驱动器管理。
```rust
pub struct VentoyDrive {
/// 驱动器路径
drive_path: PathBuf,
/// 镜像路径
images: Vec<PathBuf>,
/// 容量
capacity: u64,
/// 已用空间
used: u64,
}
impl VentoyDrive {
/// 创建 Ventoy 驱动器
pub fn create(drive_path: PathBuf, capacity: u64) -> Result<Self>;
/// 添加 ISO
pub fn add_iso(&mut self, iso_path: &Path) -> Result<()>;
/// 移除 ISO
pub fn remove_iso(&mut self, name: &str) -> Result<()>;
/// 列出 ISO
pub fn list_isos(&self) -> Vec<String>;
/// 获取驱动器信息
pub fn info(&self) -> DriveInfo;
/// 获取驱动器路径
pub fn path(&self) -> &Path;
}
pub struct DriveInfo {
/// 容量
pub capacity: u64,
/// 已用空间
pub used: u64,
/// 可用空间
pub available: u64,
/// ISO 列表
pub isos: Vec<String>,
}
```
---
## 4. 类型定义
### 4.1 MSD 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct MsdConfig {
/// 是否启用 MSD
pub enabled: bool,
/// 镜像目录
pub images_dir: Option<String>,
/// 默认模式
pub default_mode: MsdMode,
/// Ventoy 容量 (MB)
pub ventoy_capacity_mb: u32,
}
impl Default for MsdConfig {
fn default() -> Self {
Self {
enabled: true,
images_dir: None,
default_mode: MsdMode::None,
ventoy_capacity_mb: 4096, // 4GB
}
}
}
```
---
## 5. API 端点
| 端点 | 方法 | 描述 |
|------|------|------|
| `/api/msd/status` | GET | 获取 MSD 状态 |
| `/api/msd/connect` | POST | 连接 MSD |
| `/api/msd/disconnect` | POST | 断开 MSD |
| `/api/msd/images` | GET | 列出镜像 |
| `/api/msd/images` | POST | 上传镜像 |
| `/api/msd/images/:id` | DELETE | 删除镜像 |
| `/api/msd/images/download` | POST | 从 URL 下载 |
| `/api/msd/images/download/:id` | GET | 获取下载进度 |
| `/api/msd/images/download/:id` | DELETE | 取消下载 |
| `/api/msd/set-image` | POST | 设置当前镜像 |
| `/api/msd/set-ventoy` | POST | 设置 Ventoy 模式 |
| `/api/msd/clear` | POST | 清除挂载 |
### 响应格式
```json
// GET /api/msd/status
{
"available": true,
"mode": "image",
"connected": true,
"current_image": {
"id": "abc123",
"name": "ubuntu-22.04.iso",
"size": 4700000000,
"format": "iso"
},
"drive_info": null,
"error": null
}
// GET /api/msd/images
{
"images": [
{
"id": "abc123",
"name": "ubuntu-22.04.iso",
"size": 4700000000,
"format": "iso",
"created_at": "2024-01-15T10:30:00Z"
}
]
}
// POST /api/msd/images/download
// Request: { "url": "https://example.com/image.iso" }
// Response: { "download_id": "xyz789" }
// GET /api/msd/images/download/xyz789
{
"downloaded": 1234567890,
"total": 4700000000,
"speed": 12345678,
"eta_secs": 280,
"status": "downloading"
}
```
---
## 6. 事件
```rust
pub enum SystemEvent {
MsdStateChanged {
mode: MsdMode,
connected: bool,
image: Option<String>,
error: Option<String>,
},
MsdDownloadProgress {
download_id: String,
progress: DownloadProgress,
},
MsdDownloadComplete {
download_id: String,
image_id: String,
success: bool,
error: Option<String>,
},
}
```
---
## 7. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum MsdError {
#[error("MSD not available")]
NotAvailable,
#[error("Already connected")]
AlreadyConnected,
#[error("Not connected")]
NotConnected,
#[error("Image not found: {0}")]
ImageNotFound(String),
#[error("Invalid image format: {0}")]
InvalidFormat(String),
#[error("Download failed: {0}")]
DownloadFailed(String),
#[error("Storage full")]
StorageFull,
#[error("OTG error: {0}")]
OtgError(String),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
}
```
---
## 8. 使用示例
### 8.1 挂载 ISO 镜像
```rust
let msd = MsdController::new(otg_service, data_dir, events).await?;
// 列出镜像
let images = msd.list_images();
println!("Available images: {:?}", images);
// 设置镜像
msd.set_image("abc123").await?;
// 连接到目标 PC
msd.connect().await?;
// 目标 PC 现在可以看到 USB 驱动器...
// 断开连接
msd.disconnect().await?;
```
### 8.2 从 URL 下载
```rust
// 开始下载
let download_id = msd.download_image("https://example.com/ubuntu.iso").await?;
// 监控进度
loop {
if let Some(progress) = msd.get_download_progress(&download_id) {
println!("Progress: {}%", progress.downloaded * 100 / progress.total);
if matches!(progress.status, DownloadStatus::Completed) {
break;
}
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
```
### 8.3 使用 Ventoy 模式
```rust
// 切换到 Ventoy 模式
msd.set_ventoy().await?;
// 获取驱动器信息
let state = msd.state();
if let Some(drive_info) = state.drive_info {
println!("Capacity: {} MB", drive_info.capacity / 1024 / 1024);
println!("ISOs: {:?}", drive_info.isos);
}
// 连接
msd.connect().await?;
```
---
## 9. 常见问题
### Q: 镜像无法挂载?
1. 检查镜像文件完整性
2. 确认文件格式正确
3. 检查存储空间
### Q: 目标 PC 不识别?
1. 检查 USB 连接
2. 尝试重新连接
3. 查看目标 PC 的设备管理器
### Q: 下载速度慢?
1. 检查网络连接
2. 使用更近的镜像源
3. 检查磁盘 I/O
### Q: Ventoy 启动失败?
1. 检查目标 PC BIOS 设置
2. 尝试不同的启动模式
3. 确认 ISO 文件支持 Ventoy

View File

@@ -1,667 +0,0 @@
# OTG 模块文档
## 1. 模块概述
OTG (On-The-Go) 模块负责管理 Linux USB Gadget为 HID 和 MSD 功能提供统一的 USB 设备管理。
### 1.1 主要功能
- USB Gadget 生命周期管理
- HID 函数配置 (键盘、鼠标)
- MSD 函数配置 (虚拟存储)
- ConfigFS 操作
- UDC 绑定/解绑
### 1.2 文件结构
```
src/otg/
├── mod.rs # 模块导出
├── service.rs # OtgService (17KB)
├── manager.rs # OtgGadgetManager (12KB)
├── hid.rs # HID Function (7KB)
├── msd.rs # MSD Function (14KB)
├── configfs.rs # ConfigFS 操作 (4KB)
├── endpoint.rs # 端点分配 (2KB)
└── report_desc.rs # HID 报告描述符 (6KB)
```
---
## 2. 架构设计
### 2.1 设计目标
解决 HID 和 MSD 共享同一个 USB Gadget 的所有权问题:
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ OTG Ownership Model │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────┐
│ OtgService │ ◄── 唯一所有者
│ (service.rs) │
└────────┬────────┘
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
enable_hid() enable_msd() 状态查询
│ │
└──────┬──────┘
┌─────────────────┐
│OtgGadgetManager │
│ (manager.rs) │
└────────┬────────┘
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌───────┐ ┌───────┐ ┌───────┐
│ HID │ │ MSD │ │ UDC │
│ Func │ │ Func │ │ Bind │
└───────┘ └───────┘ └───────┘
```
### 2.2 ConfigFS 结构
```
/sys/kernel/config/usb_gadget/one-kvm/
├── idVendor # 0x05ac (Apple)
├── idProduct # 0x0001
├── bcdDevice # 0x0100
├── bcdUSB # 0x0200
├── bMaxPacketSize0 # 64
├── strings/
│ └── 0x409/ # English
│ ├── manufacturer # "One-KVM"
│ ├── product # "KVM Device"
│ └── serialnumber # UUID
├── configs/
│ └── c.1/
│ ├── MaxPower # 500
│ ├── strings/
│ │ └── 0x409/
│ │ └── configuration # "Config 1"
│ └── (function symlinks)
├── functions/
│ ├── hid.usb0/ # 键盘
│ │ ├── protocol # 1 (keyboard)
│ │ ├── subclass # 1 (boot)
│ │ ├── report_length # 8
│ │ └── report_desc # (binary)
│ │
│ ├── hid.usb1/ # 相对鼠标
│ │ ├── protocol # 2 (mouse)
│ │ ├── subclass # 1 (boot)
│ │ ├── report_length # 4
│ │ └── report_desc # (binary)
│ │
│ ├── hid.usb2/ # 绝对鼠标
│ │ ├── protocol # 2 (mouse)
│ │ ├── subclass # 0 (none)
│ │ ├── report_length # 6
│ │ └── report_desc # (binary)
│ │
│ └── mass_storage.usb0/ # 虚拟存储
│ ├── stall # 1
│ └── lun.0/
│ ├── cdrom # 1 (ISO mode)
│ ├── ro # 1 (read-only)
│ ├── removable # 1
│ ├── nofua # 1
│ └── file # /path/to/image.iso
└── UDC # UDC 设备名
```
---
## 3. 核心组件
### 3.1 OtgService (service.rs)
OTG 服务主类,提供统一的 USB Gadget 管理接口。
```rust
pub struct OtgService {
/// Gadget 管理器
manager: Arc<Mutex<OtgGadgetManager>>,
/// 当前状态
state: Arc<RwLock<OtgServiceState>>,
/// HID 函数句柄
hid_function: Arc<RwLock<Option<HidFunction>>>,
/// MSD 函数句柄
msd_function: Arc<RwLock<Option<MsdFunction>>>,
/// 请求计数器 (lock-free)
pending_requests: AtomicU8,
}
impl OtgService {
/// 创建服务
pub fn new() -> Result<Self>;
/// 启用 HID 功能
pub async fn enable_hid(&self) -> Result<HidDevicePaths>;
/// 禁用 HID 功能
pub async fn disable_hid(&self) -> Result<()>;
/// 启用 MSD 功能
pub async fn enable_msd(&self) -> Result<MsdFunction>;
/// 禁用 MSD 功能
pub async fn disable_msd(&self) -> Result<()>;
/// 获取状态
pub fn state(&self) -> OtgServiceState;
/// 检查 HID 是否启用
pub fn is_hid_enabled(&self) -> bool;
/// 检查 MSD 是否启用
pub fn is_msd_enabled(&self) -> bool;
}
pub struct OtgServiceState {
/// Gadget 是否激活
pub gadget_active: bool,
/// HID 是否启用
pub hid_enabled: bool,
/// MSD 是否启用
pub msd_enabled: bool,
/// HID 设备路径
pub hid_paths: Option<HidDevicePaths>,
/// 错误信息
pub error: Option<String>,
}
pub struct HidDevicePaths {
pub keyboard: PathBuf, // /dev/hidg0
pub mouse_relative: PathBuf, // /dev/hidg1
pub mouse_absolute: PathBuf, // /dev/hidg2
}
```
### 3.2 OtgGadgetManager (manager.rs)
Gadget 生命周期管理器。
```rust
pub struct OtgGadgetManager {
/// Gadget 路径
gadget_path: PathBuf,
/// UDC 设备名
udc_name: Option<String>,
/// 是否已创建
created: bool,
/// 是否已绑定
bound: bool,
/// 端点分配器
endpoint_allocator: EndpointAllocator,
}
impl OtgGadgetManager {
/// 创建管理器
pub fn new() -> Result<Self>;
/// 创建 Gadget
pub fn create_gadget(&mut self, config: &GadgetConfig) -> Result<()>;
/// 销毁 Gadget
pub fn destroy_gadget(&mut self) -> Result<()>;
/// 绑定 UDC
pub fn bind_udc(&mut self) -> Result<()>;
/// 解绑 UDC
pub fn unbind_udc(&mut self) -> Result<()>;
/// 添加函数
pub fn add_function(&mut self, func: &dyn GadgetFunction) -> Result<()>;
/// 移除函数
pub fn remove_function(&mut self, func: &dyn GadgetFunction) -> Result<()>;
/// 链接函数到配置
pub fn link_function(&self, func: &dyn GadgetFunction) -> Result<()>;
/// 取消链接函数
pub fn unlink_function(&self, func: &dyn GadgetFunction) -> Result<()>;
/// 检测可用 UDC
fn detect_udc() -> Result<String>;
}
pub struct GadgetConfig {
pub name: String, // "one-kvm"
pub vendor_id: u16, // 0x05ac
pub product_id: u16, // 0x0001
pub manufacturer: String, // "One-KVM"
pub product: String, // "KVM Device"
pub serial: String, // UUID
}
```
### 3.3 HID Function (hid.rs)
```rust
pub struct HidFunction {
/// 键盘函数
keyboard: HidFunctionConfig,
/// 相对鼠标函数
mouse_relative: HidFunctionConfig,
/// 绝对鼠标函数
mouse_absolute: HidFunctionConfig,
}
pub struct HidFunctionConfig {
/// 函数名
pub name: String, // "hid.usb0"
/// 协议
pub protocol: u8, // 1=keyboard, 2=mouse
/// 子类
pub subclass: u8, // 1=boot, 0=none
/// 报告长度
pub report_length: u8,
/// 报告描述符
pub report_desc: Vec<u8>,
}
impl HidFunction {
/// 创建 HID 函数
pub fn new() -> Self;
/// 获取键盘报告描述符
pub fn keyboard_report_desc() -> Vec<u8>;
/// 获取相对鼠标报告描述符
pub fn mouse_relative_report_desc() -> Vec<u8>;
/// 获取绝对鼠标报告描述符
pub fn mouse_absolute_report_desc() -> Vec<u8>;
}
impl GadgetFunction for HidFunction {
fn name(&self) -> &str;
fn function_type(&self) -> &str; // "hid"
fn configure(&self, path: &Path) -> Result<()>;
}
```
### 3.4 MSD Function (msd.rs)
```rust
pub struct MsdFunction {
/// 函数名
name: String,
/// LUN 配置
luns: Vec<MsdLun>,
}
pub struct MsdLun {
/// LUN 编号
pub lun_id: u8,
/// 镜像文件路径
pub file: Option<PathBuf>,
/// 是否 CD-ROM 模式
pub cdrom: bool,
/// 是否只读
pub readonly: bool,
/// 是否可移除
pub removable: bool,
}
impl MsdFunction {
/// 创建 MSD 函数
pub fn new() -> Self;
/// 设置镜像文件
pub fn set_image(&mut self, path: &Path, cdrom: bool) -> Result<()>;
/// 清除镜像
pub fn clear_image(&mut self) -> Result<()>;
/// 弹出介质
pub fn eject(&mut self) -> Result<()>;
}
impl GadgetFunction for MsdFunction {
fn name(&self) -> &str;
fn function_type(&self) -> &str; // "mass_storage"
fn configure(&self, path: &Path) -> Result<()>;
}
```
### 3.5 ConfigFS 操作 (configfs.rs)
```rust
pub struct ConfigFs;
impl ConfigFs {
/// ConfigFS 根路径
const ROOT: &'static str = "/sys/kernel/config/usb_gadget";
/// 创建目录
pub fn mkdir(path: &Path) -> Result<()>;
/// 删除目录
pub fn rmdir(path: &Path) -> Result<()>;
/// 写入文件
pub fn write_file(path: &Path, content: &str) -> Result<()>;
/// 写入二进制文件
pub fn write_binary(path: &Path, data: &[u8]) -> Result<()>;
/// 读取文件
pub fn read_file(path: &Path) -> Result<String>;
/// 创建符号链接
pub fn symlink(target: &Path, link: &Path) -> Result<()>;
/// 删除符号链接
pub fn unlink(path: &Path) -> Result<()>;
/// 列出目录
pub fn list_dir(path: &Path) -> Result<Vec<String>>;
}
```
### 3.6 端点分配 (endpoint.rs)
```rust
pub struct EndpointAllocator {
/// 已使用的端点
used_endpoints: HashSet<u8>,
/// 最大端点数
max_endpoints: u8,
}
impl EndpointAllocator {
/// 创建分配器
pub fn new(max_endpoints: u8) -> Self;
/// 分配端点
pub fn allocate(&mut self, count: u8) -> Result<Vec<u8>>;
/// 释放端点
pub fn release(&mut self, endpoints: &[u8]);
/// 检查可用端点数
pub fn available(&self) -> u8;
}
```
### 3.7 报告描述符 (report_desc.rs)
```rust
pub struct ReportDescriptor;
impl ReportDescriptor {
/// 标准键盘报告描述符
pub fn keyboard() -> Vec<u8> {
vec![
0x05, 0x01, // Usage Page (Generic Desktop)
0x09, 0x06, // Usage (Keyboard)
0xA1, 0x01, // Collection (Application)
0x05, 0x07, // Usage Page (Key Codes)
0x19, 0xE0, // Usage Minimum (224)
0x29, 0xE7, // Usage Maximum (231)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x01, // Logical Maximum (1)
0x75, 0x01, // Report Size (1)
0x95, 0x08, // Report Count (8)
0x81, 0x02, // Input (Data, Variable, Absolute)
0x95, 0x01, // Report Count (1)
0x75, 0x08, // Report Size (8)
0x81, 0x01, // Input (Constant)
0x95, 0x06, // Report Count (6)
0x75, 0x08, // Report Size (8)
0x15, 0x00, // Logical Minimum (0)
0x25, 0x65, // Logical Maximum (101)
0x05, 0x07, // Usage Page (Key Codes)
0x19, 0x00, // Usage Minimum (0)
0x29, 0x65, // Usage Maximum (101)
0x81, 0x00, // Input (Data, Array)
0xC0, // End Collection
]
}
/// 相对鼠标报告描述符
pub fn mouse_relative() -> Vec<u8>;
/// 绝对鼠标报告描述符
pub fn mouse_absolute() -> Vec<u8>;
}
```
---
## 4. 生命周期管理
### 4.1 初始化流程
```
OtgService::new()
├── 检测 UDC 设备
│ └── 读取 /sys/class/udc/
├── 创建 OtgGadgetManager
└── 初始化状态
enable_hid()
├── 检查 Gadget 是否存在
│ └── 如不存在,创建 Gadget
├── 创建 HID 函数
│ ├── hid.usb0 (键盘)
│ ├── hid.usb1 (相对鼠标)
│ └── hid.usb2 (绝对鼠标)
├── 配置函数
│ └── 写入报告描述符
├── 链接函数到配置
├── 绑定 UDC (如未绑定)
└── 等待设备节点出现
└── /dev/hidg0, hidg1, hidg2
```
### 4.2 清理流程
```
disable_hid()
├── 检查是否有其他函数使用
├── 如果只有 HID解绑 UDC
├── 取消链接 HID 函数
└── 删除 HID 函数目录
disable_msd()
├── 同上...
└── 如果没有任何函数,销毁 Gadget
```
---
## 5. 配置
### 5.1 OTG 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct OtgConfig {
/// 是否启用 OTG
pub enabled: bool,
/// 厂商 ID
pub vendor_id: u16,
/// 产品 ID
pub product_id: u16,
/// 厂商名称
pub manufacturer: String,
/// 产品名称
pub product: String,
}
impl Default for OtgConfig {
fn default() -> Self {
Self {
enabled: true,
vendor_id: 0x05ac, // Apple
product_id: 0x0001,
manufacturer: "One-KVM".to_string(),
product: "KVM Device".to_string(),
}
}
}
```
---
## 6. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum OtgError {
#[error("No UDC device found")]
NoUdcDevice,
#[error("Gadget already exists")]
GadgetExists,
#[error("Gadget not found")]
GadgetNotFound,
#[error("Function already exists: {0}")]
FunctionExists(String),
#[error("UDC busy")]
UdcBusy,
#[error("ConfigFS error: {0}")]
ConfigFsError(String),
#[error("Permission denied: {0}")]
PermissionDenied(String),
#[error("Device node not found: {0}")]
DeviceNodeNotFound(String),
}
```
---
## 7. 使用示例
### 7.1 启用 HID
```rust
let otg = OtgService::new()?;
// 启用 HID
let paths = otg.enable_hid().await?;
println!("Keyboard: {:?}", paths.keyboard);
println!("Mouse relative: {:?}", paths.mouse_relative);
println!("Mouse absolute: {:?}", paths.mouse_absolute);
// 使用设备...
// 禁用 HID
otg.disable_hid().await?;
```
### 7.2 启用 MSD
```rust
let otg = OtgService::new()?;
// 启用 MSD
let mut msd = otg.enable_msd().await?;
// 挂载 ISO
msd.set_image(Path::new("/data/ubuntu.iso"), true)?;
// 弹出
msd.eject()?;
// 禁用 MSD
otg.disable_msd().await?;
```
---
## 8. 常见问题
### Q: 找不到 UDC 设备?
1. 检查内核是否支持 USB Gadget
2. 加载必要的内核模块:
```bash
modprobe libcomposite
modprobe usb_f_hid
modprobe usb_f_mass_storage
```
3. 检查 `/sys/class/udc/` 目录
### Q: 权限错误?
1. 以 root 运行
2. 或配置 udev 规则
### Q: 设备节点不出现?
1. 检查 UDC 是否正确绑定
2. 查看 `dmesg` 日志
3. 检查 ConfigFS 配置
### Q: 目标 PC 不识别?
1. 检查 USB 线缆
2. 检查报告描述符
3. 使用 `lsusb` 确认设备

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,428 +0,0 @@
# Web 模块文档
## 1. 模块概述
Web 模块提供 HTTP API 和静态文件服务。
### 1.1 主要功能
- REST API
- WebSocket
- 静态文件服务
- 认证中间件
- CORS 支持
### 1.2 文件结构
```
src/web/
├── mod.rs # 模块导出
├── routes.rs # 路由定义 (9KB)
├── ws.rs # WebSocket (8KB)
├── audio_ws.rs # 音频 WebSocket (8KB)
├── static_files.rs # 静态文件 (6KB)
└── handlers/ # API 处理器
├── mod.rs
└── config/
├── mod.rs
├── apply.rs
├── types.rs
└── rustdesk.rs
```
---
## 2. 路由结构
### 2.1 公共路由 (无认证)
| 路由 | 方法 | 描述 |
|------|------|------|
| `/health` | GET | 健康检查 |
| `/auth/login` | POST | 登录 |
| `/setup` | GET | 获取设置状态 |
| `/setup/init` | POST | 初始化设置 |
### 2.2 用户路由 (需认证)
| 路由 | 方法 | 描述 |
|------|------|------|
| `/info` | GET | 系统信息 |
| `/devices` | GET | 设备列表 |
| `/stream/*` | * | 流控制 |
| `/webrtc/*` | * | WebRTC 信令 |
| `/hid/*` | * | HID 控制 |
| `/audio/*` | * | 音频控制 |
| `/ws` | WS | 事件 WebSocket |
| `/ws/audio` | WS | 音频 WebSocket |
### 2.3 管理员路由 (需 Admin)
| 路由 | 方法 | 描述 |
|------|------|------|
| `/config/*` | * | 配置管理 |
| `/msd/*` | * | MSD 操作 |
| `/atx/*` | * | ATX 控制 |
| `/extensions/*` | * | 扩展管理 |
| `/rustdesk/*` | * | RustDesk |
| `/users/*` | * | 用户管理 |
---
## 3. 路由定义
```rust
pub fn create_router(state: Arc<AppState>) -> Router {
Router::new()
// 公共路由
.route("/health", get(handlers::health))
.route("/auth/login", post(handlers::login))
.route("/setup", get(handlers::setup_status))
.route("/setup/init", post(handlers::setup_init))
// 用户路由
.nest("/api", user_routes())
// 管理员路由
.nest("/api/admin", admin_routes())
// 静态文件
.fallback(static_files::serve)
// 中间件
.layer(CorsLayer::permissive())
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http())
// 状态
.with_state(state)
}
fn user_routes() -> Router {
Router::new()
.route("/info", get(handlers::system_info))
.route("/devices", get(handlers::list_devices))
// 流控制
.route("/stream/status", get(handlers::stream_status))
.route("/stream/start", post(handlers::stream_start))
.route("/stream/stop", post(handlers::stream_stop))
.route("/stream/mjpeg", get(handlers::mjpeg_stream))
// WebRTC
.route("/webrtc/session", post(handlers::webrtc_create_session))
.route("/webrtc/offer", post(handlers::webrtc_offer))
.route("/webrtc/ice", post(handlers::webrtc_ice))
.route("/webrtc/close", post(handlers::webrtc_close))
// HID
.route("/hid/status", get(handlers::hid_status))
.route("/hid/reset", post(handlers::hid_reset))
// WebSocket
.route("/ws", get(handlers::ws_handler))
.route("/ws/audio", get(handlers::audio_ws_handler))
// 认证中间件
.layer(middleware::from_fn(auth_middleware))
}
fn admin_routes() -> Router {
Router::new()
// 配置
.route("/config", get(handlers::config::get_config))
.route("/config", patch(handlers::config::update_config))
// MSD
.route("/msd/status", get(handlers::msd_status))
.route("/msd/connect", post(handlers::msd_connect))
// ATX
.route("/atx/status", get(handlers::atx_status))
.route("/atx/power/short", post(handlers::atx_power_short))
// 认证中间件
.layer(middleware::from_fn(auth_middleware))
.layer(middleware::from_fn(admin_middleware))
}
```
---
## 4. 静态文件服务
```rust
#[derive(RustEmbed)]
#[folder = "web/dist"]
#[include = "*.html"]
#[include = "*.js"]
#[include = "*.css"]
#[include = "assets/*"]
struct Assets;
pub async fn serve(uri: Uri) -> impl IntoResponse {
let path = uri.path().trim_start_matches('/');
// 尝试获取文件
if let Some(content) = Assets::get(path) {
let mime = mime_guess::from_path(path)
.first_or_octet_stream();
return (
[(header::CONTENT_TYPE, mime.as_ref())],
content.data.into_owned(),
).into_response();
}
// SPA 回退到 index.html
if let Some(content) = Assets::get("index.html") {
return (
[(header::CONTENT_TYPE, "text/html")],
content.data.into_owned(),
).into_response();
}
StatusCode::NOT_FOUND.into_response()
}
```
---
## 5. WebSocket 处理
### 5.1 事件 WebSocket (ws.rs)
```rust
pub async fn ws_handler(
ws: WebSocketUpgrade,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| handle_ws(socket, state))
}
async fn handle_ws(mut socket: WebSocket, state: Arc<AppState>) {
// 发送初始设备信息
let device_info = state.get_device_info().await;
let json = serde_json::to_string(&device_info).unwrap();
let _ = socket.send(Message::Text(json)).await;
// 订阅事件
let mut rx = state.events.subscribe();
loop {
tokio::select! {
// 发送事件
result = rx.recv() => {
if let Ok(event) = result {
let json = serde_json::to_string(&event).unwrap();
if socket.send(Message::Text(json)).await.is_err() {
break;
}
}
}
// 接收消息 (心跳/关闭)
msg = socket.recv() => {
match msg {
Some(Ok(Message::Ping(data))) => {
let _ = socket.send(Message::Pong(data)).await;
}
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
}
```
### 5.2 音频 WebSocket (audio_ws.rs)
```rust
pub async fn audio_ws_handler(
ws: WebSocketUpgrade,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| handle_audio_ws(socket, state))
}
async fn handle_audio_ws(mut socket: WebSocket, state: Arc<AppState>) {
// 订阅音频帧
let mut rx = state.audio.subscribe();
loop {
tokio::select! {
// 发送音频帧
result = rx.recv() => {
if let Ok(frame) = result {
if socket.send(Message::Binary(frame.data.to_vec())).await.is_err() {
break;
}
}
}
// 处理关闭
msg = socket.recv() => {
match msg {
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
}
```
---
## 6. MJPEG 流
```rust
pub async fn mjpeg_stream(
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
let boundary = "frame";
// 订阅视频帧
let rx = state.stream_manager.subscribe_mjpeg();
// 创建流
let stream = async_stream::stream! {
let mut rx = rx;
while let Ok(frame) = rx.recv().await {
let header = format!(
"--{}\r\nContent-Type: image/jpeg\r\nContent-Length: {}\r\n\r\n",
boundary,
frame.data.len()
);
yield Ok::<_, std::io::Error>(Bytes::from(header));
yield Ok(frame.data.clone());
yield Ok(Bytes::from("\r\n"));
}
};
(
[(
header::CONTENT_TYPE,
format!("multipart/x-mixed-replace; boundary={}", boundary),
)],
Body::from_stream(stream),
)
}
```
---
## 7. 错误处理
```rust
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::AuthError => (StatusCode::UNAUTHORIZED, "Authentication failed"),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized"),
AppError::Forbidden => (StatusCode::FORBIDDEN, "Forbidden"),
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.as_str()),
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.as_str()),
AppError::Internal(err) => {
tracing::error!("Internal error: {:?}", err);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
}
// ...
};
(status, Json(json!({ "error": message }))).into_response()
}
}
```
---
## 8. 请求提取器
```rust
// 从 Cookie 获取会话
pub struct AuthUser(pub Session);
#[async_trait]
impl<S> FromRequestParts<S> for AuthUser
where
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let cookies = Cookies::from_request_parts(parts, state).await?;
let token = cookies
.get("session_id")
.map(|c| c.value().to_string())
.ok_or(AppError::Unauthorized)?;
let state = parts.extensions.get::<Arc<AppState>>().unwrap();
let session = state.sessions
.get_session(&token)
.ok_or(AppError::Unauthorized)?;
Ok(AuthUser(session))
}
}
```
---
## 9. 中间件
### 9.1 认证中间件
```rust
pub async fn auth_middleware(
State(state): State<Arc<AppState>>,
cookies: Cookies,
mut request: Request,
next: Next,
) -> Response {
let token = cookies
.get("session_id")
.map(|c| c.value().to_string());
if let Some(session) = token.and_then(|t| state.sessions.get_session(&t)) {
request.extensions_mut().insert(session);
next.run(request).await
} else {
StatusCode::UNAUTHORIZED.into_response()
}
}
```
### 9.2 Admin 中间件
```rust
pub async fn admin_middleware(
Extension(session): Extension<Session>,
request: Request,
next: Next,
) -> Response {
if session.role == UserRole::Admin {
next.run(request).await
} else {
StatusCode::FORBIDDEN.into_response()
}
}
```
---
## 10. HTTPS 支持
```rust
// 使用 axum-server 提供 TLS
let tls_config = RustlsConfig::from_pem_file(cert_path, key_path).await?;
axum_server::bind_rustls(addr, tls_config)
.serve(app.into_make_service())
.await?;
// 或自动生成自签名证书
let (cert, key) = generate_self_signed_cert()?;
let tls_config = RustlsConfig::from_pem(cert, key).await?;
```

View File

@@ -1,789 +0,0 @@
# WebRTC 模块文档
## 1. 模块概述
WebRTC 模块提供低延迟的实时音视频流传输,支持多种视频编码格式和 DataChannel HID 控制。
### 1.1 主要功能
- WebRTC 会话管理
- 多编码器支持 (H264/H265/VP8/VP9)
- 音频轨道 (Opus)
- DataChannel HID
- ICE/STUN/TURN 支持
### 1.2 文件结构
```
src/webrtc/
├── mod.rs # 模块导出
├── webrtc_streamer.rs # 统一管理器 (35KB)
├── universal_session.rs # 会话管理 (32KB)
├── unified_video_track.rs # 统一视频轨道 (15KB)
├── video_track.rs # 视频轨道 (19KB)
├── rtp.rs # RTP 打包 (24KB)
├── h265_payloader.rs # H265 RTP (15KB)
├── peer.rs # PeerConnection (17KB)
├── config.rs # 配置 (3KB)
├── signaling.rs # 信令 (5KB)
├── session.rs # 会话基类 (8KB)
└── track.rs # 轨道基类 (11KB)
```
---
## 2. 架构设计
### 2.1 整体架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ WebRTC Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
Browser
│ HTTP Signaling
┌─────────────────┐
│ WebRtcStreamer │
│(webrtc_streamer)│
└────────┬────────┘
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Session │ │Session │ │Session │
│ 1 │ │ 2 │ │ N │
└───┬────┘ └───┬────┘ └───┬────┘
│ │ │
├───────────┼─────────────┤
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────┐
│ SharedVideoPipeline │
│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │
│ │H264 │ │H265 │ │VP8 │ │VP9 │ │
│ └─────┘ └─────┘ └─────┘ └─────┘ │
└─────────────────────────────────────┘
┌────────────────┐
│ VideoCapturer │
└────────────────┘
```
### 2.2 会话生命周期
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Session Lifecycle │
└─────────────────────────────────────────────────────────────────────────────┘
1. 创建会话
POST /webrtc/session
┌─────────────────┐
│ Create Session │
│ Generate ID │
└────────┬────────┘
{ session_id: "..." }
2. 发送 Offer
POST /webrtc/offer
{ session_id, codec, offer_sdp }
┌─────────────────┐
│ Process Offer │
│ Create Answer │
│ Setup Tracks │
└────────┬────────┘
{ answer_sdp, ice_candidates }
3. ICE 候选
POST /webrtc/ice
{ session_id, candidate }
┌─────────────────┐
│ Add ICE │
│ Candidate │
└─────────────────┘
4. 连接建立
┌─────────────────┐
│ DTLS Handshake │
│ SRTP Setup │
│ DataChannel │
└────────┬────────┘
开始传输视频/音频
5. 关闭会话
POST /webrtc/close
{ session_id }
┌─────────────────┐
│ Cleanup │
│ Release │
└─────────────────┘
```
---
## 3. 核心组件
### 3.1 WebRtcStreamer (webrtc_streamer.rs)
WebRTC 服务主类。
```rust
pub struct WebRtcStreamer {
/// 会话映射
sessions: Arc<RwLock<HashMap<String, Arc<UniversalSession>>>>,
/// 共享视频管道
video_pipeline: Arc<SharedVideoPipeline>,
/// 共享音频管道
audio_pipeline: Arc<SharedAudioPipeline>,
/// HID 控制器
hid: Arc<HidController>,
/// 配置
config: WebRtcConfig,
/// 事件总线
events: Arc<EventBus>,
}
impl WebRtcStreamer {
/// 创建流服务
pub async fn new(
video_pipeline: Arc<SharedVideoPipeline>,
audio_pipeline: Arc<SharedAudioPipeline>,
hid: Arc<HidController>,
config: WebRtcConfig,
events: Arc<EventBus>,
) -> Result<Self>;
/// 创建会话
pub async fn create_session(&self) -> Result<String>;
/// 处理 Offer
pub async fn process_offer(
&self,
session_id: &str,
offer: &str,
codec: VideoCodec,
) -> Result<OfferResponse>;
/// 添加 ICE 候选
pub async fn add_ice_candidate(
&self,
session_id: &str,
candidate: &str,
) -> Result<()>;
/// 关闭会话
pub async fn close_session(&self, session_id: &str) -> Result<()>;
/// 获取会话列表
pub fn list_sessions(&self) -> Vec<SessionInfo>;
/// 获取统计信息
pub fn get_stats(&self) -> WebRtcStats;
}
pub struct OfferResponse {
pub answer_sdp: String,
pub ice_candidates: Vec<String>,
}
pub struct WebRtcStats {
pub active_sessions: usize,
pub total_bytes_sent: u64,
pub avg_bitrate: u32,
}
```
### 3.2 UniversalSession (universal_session.rs)
单个 WebRTC 会话。
```rust
pub struct UniversalSession {
/// 会话 ID
id: String,
/// PeerConnection
peer: Arc<RTCPeerConnection>,
/// 视频轨道
video_track: Arc<UniversalVideoTrack>,
/// 音频轨道
audio_track: Option<Arc<dyn TrackLocal>>,
/// HID DataChannel
hid_channel: Arc<RwLock<Option<Arc<RTCDataChannel>>>>,
/// HID 处理器
hid_handler: Arc<HidDataChannelHandler>,
/// 状态
state: Arc<RwLock<SessionState>>,
/// 编码器类型
codec: VideoCodec,
}
impl UniversalSession {
/// 创建会话
pub async fn new(
id: String,
config: &WebRtcConfig,
video_pipeline: Arc<SharedVideoPipeline>,
audio_pipeline: Arc<SharedAudioPipeline>,
hid_handler: Arc<HidDataChannelHandler>,
codec: VideoCodec,
) -> Result<Self>;
/// 处理 Offer SDP
pub async fn handle_offer(&self, offer_sdp: &str) -> Result<String>;
/// 添加 ICE 候选
pub async fn add_ice_candidate(&self, candidate: &str) -> Result<()>;
/// 获取 ICE 候选
pub fn get_ice_candidates(&self) -> Vec<String>;
/// 关闭会话
pub async fn close(&self) -> Result<()>;
/// 获取状态
pub fn state(&self) -> SessionState;
/// 获取统计
pub fn stats(&self) -> SessionStats;
}
pub enum SessionState {
New,
Connecting,
Connected,
Disconnected,
Failed,
Closed,
}
pub struct SessionStats {
pub bytes_sent: u64,
pub packets_sent: u64,
pub bitrate: u32,
pub frame_rate: f32,
pub round_trip_time: Duration,
}
```
### 3.3 VideoTrack (video_track.rs)
视频轨道封装。
```rust
pub struct UniversalVideoTrack {
/// 轨道 ID
id: String,
/// 编码类型
codec: VideoCodec,
/// RTP 发送器
rtp_sender: Arc<RtpSender>,
/// 帧计数
frame_count: AtomicU64,
/// 统计
stats: Arc<RwLock<TrackStats>>,
}
impl UniversalVideoTrack {
/// 创建轨道
pub fn new(id: &str, codec: VideoCodec) -> Result<Self>;
/// 发送编码帧
pub async fn send_frame(&self, frame: &EncodedFrame) -> Result<()>;
/// 获取 RTP 参数
pub fn rtp_params(&self) -> RtpParameters;
/// 获取统计
pub fn stats(&self) -> TrackStats;
}
pub struct TrackStats {
pub frames_sent: u64,
pub bytes_sent: u64,
pub packets_sent: u64,
pub packet_loss: f32,
}
```
### 3.4 RTP 打包 (rtp.rs)
RTP 协议实现。
```rust
pub struct RtpPacketizer {
/// SSRC
ssrc: u32,
/// 序列号
sequence: u16,
/// 时间戳
timestamp: u32,
/// 负载类型
payload_type: u8,
/// 时钟频率
clock_rate: u32,
}
impl RtpPacketizer {
/// 创建打包器
pub fn new(codec: VideoCodec) -> Self;
/// 打包 H264 帧
pub fn packetize_h264(&mut self, frame: &[u8], keyframe: bool) -> Vec<Vec<u8>>;
/// 打包 VP8 帧
pub fn packetize_vp8(&mut self, frame: &[u8], keyframe: bool) -> Vec<Vec<u8>>;
/// 打包 VP9 帧
pub fn packetize_vp9(&mut self, frame: &[u8], keyframe: bool) -> Vec<Vec<u8>>;
/// 打包 Opus 帧
pub fn packetize_opus(&mut self, frame: &[u8]) -> Vec<u8>;
}
/// H264 NAL 单元分片
pub struct H264Fragmenter;
impl H264Fragmenter {
/// 分片大于 MTU 的 NAL
pub fn fragment(nal: &[u8], mtu: usize) -> Vec<Vec<u8>>;
/// 创建 STAP-A 聚合
pub fn aggregate(nals: &[&[u8]]) -> Vec<u8>;
}
```
### 3.5 H265 打包器 (h265_payloader.rs)
H265/HEVC RTP 打包。
```rust
pub struct H265Payloader {
/// MTU 大小
mtu: usize,
}
impl H265Payloader {
/// 创建打包器
pub fn new(mtu: usize) -> Self;
/// 打包 H265 帧
pub fn packetize(&self, frame: &[u8]) -> Vec<Vec<u8>>;
/// 分析 NAL 单元类型
fn get_nal_type(nal: &[u8]) -> u8;
/// 是否需要分片
fn needs_fragmentation(&self, nal: &[u8]) -> bool;
}
```
---
## 4. 信令协议
### 4.1 创建会话
```
POST /api/webrtc/session
Content-Type: application/json
{}
Response:
{
"session_id": "abc123-def456"
}
```
### 4.2 发送 Offer
```
POST /api/webrtc/offer
Content-Type: application/json
{
"session_id": "abc123-def456",
"video_codec": "h264",
"enable_audio": true,
"offer_sdp": "v=0\r\no=- ..."
}
Response:
{
"answer_sdp": "v=0\r\no=- ...",
"ice_candidates": [
"candidate:1 1 UDP ...",
"candidate:2 1 TCP ..."
]
}
```
### 4.3 ICE 候选
```
POST /api/webrtc/ice
Content-Type: application/json
{
"session_id": "abc123-def456",
"candidate": "candidate:1 1 UDP ..."
}
Response:
{
"success": true
}
```
### 4.4 关闭会话
```
POST /api/webrtc/close
Content-Type: application/json
{
"session_id": "abc123-def456"
}
Response:
{
"success": true
}
```
---
## 5. 配置
```rust
#[derive(Serialize, Deserialize)]
#[typeshare]
pub struct WebRtcConfig {
/// STUN 服务器
pub stun_servers: Vec<String>,
/// TURN 服务器
pub turn_servers: Vec<TurnServer>,
/// 默认编码器
pub default_codec: VideoCodec,
/// 码率 (kbps)
pub bitrate_kbps: u32,
/// GOP 大小
pub gop_size: u32,
/// 启用音频
pub enable_audio: bool,
/// 启用 DataChannel HID
pub enable_datachannel_hid: bool,
}
pub struct TurnServer {
pub url: String,
pub username: String,
pub password: String,
}
impl Default for WebRtcConfig {
fn default() -> Self {
Self {
stun_servers: vec!["stun:stun.l.google.com:19302".to_string()],
turn_servers: vec![],
default_codec: VideoCodec::H264,
bitrate_kbps: 2000,
gop_size: 60,
enable_audio: true,
enable_datachannel_hid: true,
}
}
}
```
---
## 6. DataChannel HID
### 6.1 消息格式
```javascript
// 键盘事件
{
"type": "keyboard",
"keys": ["KeyA", "KeyB"],
"modifiers": {
"ctrl": false,
"shift": true,
"alt": false,
"meta": false
}
}
// 鼠标事件
{
"type": "mouse",
"x": 16384,
"y": 16384,
"button": "left",
"event": "press"
}
// 鼠标模式
{
"type": "mouse_mode",
"mode": "absolute"
}
```
### 6.2 处理流程
```
DataChannel Message
┌─────────────────┐
│Parse JSON Event │
└────────┬────────┘
┌─────────────────┐
│HidDataChannel │
│ Handler │
└────────┬────────┘
┌─────────────────┐
│ HidController │
└────────┬────────┘
USB/Serial
```
---
## 7. 支持的编码器
| 编码器 | RTP 负载类型 | 时钟频率 | 硬件加速 |
|--------|-------------|---------|---------|
| H264 | 96 (动态) | 90000 | VAAPI/RKMPP/V4L2 |
| H265 | 97 (动态) | 90000 | VAAPI |
| VP8 | 98 (动态) | 90000 | VAAPI |
| VP9 | 99 (动态) | 90000 | VAAPI |
| Opus | 111 (动态) | 48000 | 无 (软件) |
---
## 8. 错误处理
```rust
#[derive(Debug, thiserror::Error)]
pub enum WebRtcError {
#[error("Session not found: {0}")]
SessionNotFound(String),
#[error("Session already exists")]
SessionExists,
#[error("Invalid SDP: {0}")]
InvalidSdp(String),
#[error("Codec not supported: {0}")]
CodecNotSupported(String),
#[error("ICE failed")]
IceFailed,
#[error("DTLS failed")]
DtlsFailed,
#[error("Track error: {0}")]
TrackError(String),
#[error("Connection closed")]
ConnectionClosed,
}
```
---
## 9. 使用示例
### 9.1 创建会话
```rust
let streamer = WebRtcStreamer::new(
video_pipeline,
audio_pipeline,
hid,
WebRtcConfig::default(),
events,
).await?;
// 创建会话
let session_id = streamer.create_session().await?;
// 处理 Offer
let response = streamer.process_offer(
&session_id,
&offer_sdp,
VideoCodec::H264,
).await?;
println!("Answer: {}", response.answer_sdp);
```
### 9.2 前端连接
```javascript
// 创建 PeerConnection
const pc = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});
// 创建 DataChannel
const hidChannel = pc.createDataChannel('hid');
// 创建 Offer
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// 发送到服务器
const response = await fetch('/api/webrtc/offer', {
method: 'POST',
body: JSON.stringify({
session_id,
video_codec: 'h264',
offer_sdp: offer.sdp
})
});
const { answer_sdp, ice_candidates } = await response.json();
// 设置 Answer
await pc.setRemoteDescription({ type: 'answer', sdp: answer_sdp });
// 添加 ICE 候选
for (const candidate of ice_candidates) {
await pc.addIceCandidate({ candidate });
}
```
---
## 10. 管道重启机制
当码率或编码器配置变更时视频管道需要重启。WebRTC 模块实现了自动重连机制:
### 10.1 重启流程
```
用户修改码率/编码器
┌─────────────────────┐
│ set_bitrate_preset │
│ 1. 保存 frame_tx │ ← 关键:在停止前保存
│ 2. 停止旧管道 │
│ 3. 等待清理 │
│ 4. 恢复 frame_tx │
│ 5. 创建新管道 │
│ 6. 重连所有会话 │
└─────────────────────┘
所有 WebRTC 会话自动恢复
```
### 10.2 关键代码
```rust
pub async fn set_bitrate_preset(self: &Arc<Self>, preset: BitratePreset) -> Result<()> {
// 保存 frame_tx (监控任务会在管道停止后清除它)
let saved_frame_tx = self.video_frame_tx.read().await.clone();
// 停止管道
pipeline.stop();
tokio::time::sleep(Duration::from_millis(100)).await;
// 恢复 frame_tx 并重建管道
if let Some(tx) = saved_frame_tx {
*self.video_frame_tx.write().await = Some(tx.clone());
let pipeline = self.ensure_video_pipeline(tx).await?;
// 重连所有会话
for session in sessions {
session.start_from_video_pipeline(pipeline.subscribe(), ...).await;
}
}
}
```
---
## 11. 常见问题
### Q: 连接超时?
1. 检查 STUN/TURN 配置
2. 检查防火墙设置
3. 尝试使用 TURN 中继
### Q: 视频卡顿?
1. 降低分辨率/码率
2. 检查网络带宽
3. 使用硬件编码
### Q: 音频不同步?
1. 检查时间戳同步
2. 调整缓冲区大小
3. 使用 NTP 同步
### Q: 切换码率后视频静止?
1. 检查管道重启逻辑是否正确保存了 `video_frame_tx`
2. 确认会话重连成功
3. 查看日志中是否有 "Reconnecting session" 信息

View File

@@ -1,477 +0,0 @@
# hwcodec 技术架构报告
## 1. 项目概述
hwcodec 是一个基于 FFmpeg 的硬件视频编解码库,来源于 RustDesk 项目并针对 One-KVM 进行了深度定制优化。该库专注于 IP-KVM 场景,提供 Windows 和 Linux 平台的 GPU 加速视频编码能力。
### 1.1 项目位置
```
libs/hwcodec/
├── src/ # Rust 源代码
└── cpp/ # C++ 源代码
```
### 1.2 核心特性
- **多编解码格式支持**: H.264, H.265 (HEVC), VP8, VP9, MJPEG
- **硬件加速**: NVENC, AMF, Intel QSV (Windows), VAAPI, RKMPP, V4L2 M2M (Linux)
- **跨平台**: Windows, Linux (x86_64, ARM64, ARMv7)
- **低延迟优化**: 专为实时流媒体场景设计
- **Rust/C++ 混合架构**: Rust 提供安全的上层 APIC++ 实现底层编解码逻辑
- **IP-KVM 专用**: 解码仅支持 MJPEG采集卡输出格式编码支持多种硬件加速
## 2. 架构设计
### 2.1 整体架构图
```
┌─────────────────────────────────────────────────────────────┐
│ Rust API Layer │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ ffmpeg_ram module ││
│ │ (encode.rs + decode.rs) ││
│ └──────────────────────────┬──────────────────────────────┘│
├─────────────────────────────┼───────────────────────────────┤
│ │ │
│ FFI Bindings (bindgen) │
│ ▼ │
├─────────────────────────────────────────────────────────────┤
│ C++ Core Layer │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ ffmpeg_ram (encode/decode) ││
│ └──────────────────────────┬──────────────────────────────┘│
├─────────────────────────────┼───────────────────────────────┤
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ FFmpeg Libraries │ │
│ │ libavcodec │ libavutil │ libavformat │ libswscale │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
├─────────────────────────────┼───────────────────────────────┤
│ Hardware Acceleration Backends │
│ ┌────────┐ ┌─────┐ ┌─────┐ ┌───────┐ ┌───────┐ ┌───────┐ │
│ │ NVENC │ │ AMF │ │ QSV │ │ VAAPI │ │ RKMPP │ │V4L2M2M│ │
│ └────────┘ └─────┘ └─────┘ └───────┘ └───────┘ └───────┘ │
└─────────────────────────────────────────────────────────────┘
```
### 2.2 模块职责
| 模块 | 职责 | 关键文件 |
|------|------|----------|
| `ffmpeg_ram` | 基于 RAM 的软件/硬件编解码 | `src/ffmpeg_ram/` |
| `common` | 公共定义和 GPU 检测 | `src/common.rs` |
| `ffmpeg` | FFmpeg 日志和初始化 | `src/ffmpeg.rs` |
## 3. 模块详细分析
### 3.1 库入口 (lib.rs)
```rust
// libs/hwcodec/src/lib.rs
pub mod common;
pub mod ffmpeg;
pub mod ffmpeg_ram;
```
**功能**:
- 导出所有子模块
- 提供 C 日志回调函数
### 3.2 公共模块 (common.rs)
**核心类型**:
```rust
pub enum Driver {
NV, // NVIDIA
AMF, // AMD
MFX, // Intel
FFMPEG, // 软件编码
}
```
**GPU 检测函数**:
| 平台 | 检测函数 | 检测方式 |
|------|----------|----------|
| Linux | `linux_support_nv()` | 加载 libcuda.so + libnvidia-encode.so |
| Linux | `linux_support_amd()` | 检查 `libamfrt64.so.1` |
| Linux | `linux_support_intel()` | 检查 `libvpl.so`/`libmfx.so` |
| Linux | `linux_support_rkmpp()` | 检查 `/dev/mpp_service` |
| Linux | `linux_support_v4l2m2m()` | 检查 `/dev/video*` 设备 |
### 3.3 FFmpeg RAM 编码模块
#### 3.3.1 Rust 层 (src/ffmpeg_ram/)
**CodecInfo 结构体**:
```rust
pub struct CodecInfo {
pub name: String, // 编码器名称如 "h264_nvenc"
pub mc_name: Option<String>, // MediaCodec 名称 (Android)
pub format: DataFormat, // H264/H265/VP8/VP9/MJPEG
pub priority: i32, // 优先级 (Best=0, Good=1, Normal=2, Soft=3, Bad=4)
pub hwdevice: AVHWDeviceType, // 硬件设备类型
}
```
**EncodeContext 结构体**:
```rust
pub struct EncodeContext {
pub name: String, // 编码器名称
pub width: i32, // 视频宽度
pub height: i32, // 视频高度
pub pixfmt: AVPixelFormat, // 像素格式 (NV12/YUV420P)
pub align: i32, // 内存对齐
pub fps: i32, // 帧率
pub gop: i32, // GOP 大小
pub rc: RateControl, // 码率控制模式
pub quality: Quality, // 质量级别
pub kbs: i32, // 目标码率 (kbps)
pub q: i32, // 量化参数
pub thread_count: i32, // 线程数
}
```
**Encoder 类**:
```rust
pub struct Encoder {
codec: *mut c_void, // C++ 编码器指针
frames: *mut Vec<EncodeFrame>, // 编码输出帧
pub ctx: EncodeContext,
pub linesize: Vec<i32>, // 行大小
pub offset: Vec<i32>, // 平面偏移
pub length: i32, // 总数据长度
}
```
**核心方法**:
| 方法 | 功能 |
|------|------|
| `Encoder::new()` | 创建编码器实例 |
| `Encoder::encode()` | 编码一帧 YUV 数据 |
| `Encoder::set_bitrate()` | 动态调整码率 |
| `Encoder::request_keyframe()` | 请求下一帧为关键帧 |
| `Encoder::available_encoders()` | 检测系统可用编码器 |
#### 3.3.2 C++ 层 (cpp/ffmpeg_ram/)
**FFmpegRamEncoder 类** (ffmpeg_ram_encode.cpp):
```cpp
class FFmpegRamEncoder {
AVCodecContext *c_ = NULL; // FFmpeg 编码上下文
AVFrame *frame_ = NULL; // 输入帧
AVPacket *pkt_ = NULL; // 编码输出包
AVBufferRef *hw_device_ctx_; // 硬件设备上下文
AVFrame *hw_frame_ = NULL; // 硬件帧
bool force_keyframe_ = false; // 强制关键帧标志
// 主要方法
bool init(int *linesize, int *offset, int *length);
int encode(const uint8_t *data, int length, const void *obj, uint64_t ms);
int do_encode(AVFrame *frame, const void *obj, int64_t ms);
int set_hwframe_ctx(); // 设置硬件帧上下文
};
```
**编码流程**:
```
输入 YUV 数据
fill_frame() - 填充 AVFrame 数据指针
├──▶ (软件编码) 直接使用 frame_
└──▶ (硬件编码) av_hwframe_transfer_data() 传输到 GPU
使用 hw_frame_
avcodec_send_frame() - 发送帧到编码器
avcodec_receive_packet() - 获取编码数据
callback() - 回调输出
```
### 3.4 FFmpeg RAM 解码模块
**IP-KVM 专用设计**: 解码器仅支持 MJPEG 软件解码,因为 IP-KVM 场景中视频采集卡输出的是 MJPEG 格式。
**Decoder 类**:
```rust
pub struct Decoder {
codec: *mut c_void,
frames: *mut Vec<DecodeFrame>,
pub ctx: DecodeContext,
}
pub struct DecodeFrame {
pub pixfmt: AVPixelFormat,
pub width: i32,
pub height: i32,
pub data: Vec<Vec<u8>>, // Y, U, V 平面数据
pub linesize: Vec<i32>,
pub key: bool,
}
```
**available_decoders()**: 仅返回 MJPEG 软件解码器
```rust
pub fn available_decoders() -> Vec<CodecInfo> {
vec![CodecInfo {
name: "mjpeg".to_owned(),
format: MJPEG,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Best as _,
..Default::default()
}]
}
```
**C++ 实现** (ffmpeg_ram_decode.cpp):
```cpp
class FFmpegRamDecoder {
AVCodecContext *c_ = NULL;
AVFrame *frame_ = NULL; // 解码输出帧
AVPacket *pkt_ = NULL;
int do_decode(const void *obj);
};
```
**解码流程**:
```
输入 MJPEG 数据
avcodec_send_packet() - 发送数据到解码器
avcodec_receive_frame() - 获取解码帧 (YUV420P)
callback() - 回调输出
```
## 4. 硬件加速支持
### 4.1 支持的硬件加速后端
| 后端 | 厂商 | 平台 | 编码器名称 |
|------|------|------|-----------|
| NVENC | NVIDIA | Windows/Linux | h264_nvenc, hevc_nvenc |
| AMF | AMD | Windows/Linux | h264_amf, hevc_amf |
| QSV | Intel | Windows | h264_qsv, hevc_qsv |
| VAAPI | 通用 | Linux | h264_vaapi, hevc_vaapi, vp8_vaapi, vp9_vaapi |
| RKMPP | Rockchip | Linux | h264_rkmpp, hevc_rkmpp |
| V4L2 M2M | ARM SoC | Linux | h264_v4l2m2m, hevc_v4l2m2m |
### 4.2 硬件检测逻辑 (Linux)
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
// NVIDIA 检测 - 简化的动态库检测
int linux_support_nv() {
void *handle = dlopen("libcuda.so.1", RTLD_LAZY);
if (!handle) handle = dlopen("libcuda.so", RTLD_LAZY);
if (!handle) return -1;
dlclose(handle);
handle = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
if (!handle) handle = dlopen("libnvidia-encode.so", RTLD_LAZY);
if (!handle) return -1;
dlclose(handle);
return 0;
}
// AMD 检测 - 检查 AMF 运行时库
int linux_support_amd() {
void *handle = dlopen("libamfrt64.so.1", RTLD_LAZY);
if (!handle) return -1;
dlclose(handle);
return 0;
}
// Intel 检测 - 检查 VPL/MFX 库
int linux_support_intel() {
const char *libs[] = {"libvpl.so", "libmfx.so", ...};
// 任一成功加载则返回 0
}
// Rockchip MPP 检测 - 检查设备节点
int linux_support_rkmpp() {
if (access("/dev/mpp_service", F_OK) == 0) return 0;
if (access("/dev/rga", F_OK) == 0) return 0;
return -1;
}
// V4L2 M2M 检测 - 检查视频设备
int linux_support_v4l2m2m() {
const char *devices[] = {"/dev/video10", "/dev/video11", ...};
// 任一设备可打开则返回 0
}
```
### 4.3 编码器优先级系统
```rust
pub enum Priority {
Best = 0, // 最高优先级 (硬件加速)
Good = 1, // 良好 (VAAPI, 部分硬件)
Normal = 2, // 普通
Soft = 3, // 软件编码
Bad = 4, // 最低优先级
}
```
**优先级分配**:
| 编码器 | 优先级 |
|--------|--------|
| h264_nvenc, hevc_nvenc | Best (0) |
| h264_amf, hevc_amf | Best (0) |
| h264_qsv, hevc_qsv | Best (0) |
| h264_rkmpp, hevc_rkmpp | Best (0) |
| h264_vaapi, hevc_vaapi | Good (1) |
| h264_v4l2m2m, hevc_v4l2m2m | Good (1) |
| h264 (x264), hevc (x265) | Soft (3) |
### 4.4 低延迟优化配置
```cpp
// libs/hwcodec/cpp/common/util.cpp
bool set_lantency_free(void *priv_data, const std::string &name) {
// NVENC: 禁用延迟缓冲
if (name.find("nvenc") != std::string::npos) {
av_opt_set(priv_data, "delay", "0", 0);
}
// AMF: 设置查询超时
if (name.find("amf") != std::string::npos) {
av_opt_set(priv_data, "query_timeout", "1000", 0);
}
// QSV/VAAPI: 设置异步深度为 1
if (name.find("qsv") != std::string::npos ||
name.find("vaapi") != std::string::npos) {
av_opt_set(priv_data, "async_depth", "1", 0);
}
// libvpx: 实时模式
if (name.find("libvpx") != std::string::npos) {
av_opt_set(priv_data, "deadline", "realtime", 0);
av_opt_set_int(priv_data, "cpu-used", 6, 0);
av_opt_set_int(priv_data, "lag-in-frames", 0, 0);
}
return true;
}
```
## 5. 构建系统
### 5.1 Cargo.toml 配置
```toml
[package]
name = "hwcodec"
version = "0.8.0"
edition = "2021"
description = "Hardware video codec for IP-KVM (Windows/Linux)"
[features]
default = []
[dependencies]
log = "0.4"
serde_derive = "1.0"
serde = "1.0"
serde_json = "1.0"
[build-dependencies]
cc = "1.0" # C++ 编译
bindgen = "0.59" # FFI 绑定生成
```
### 5.2 构建流程 (build.rs)
```
build.rs
├── build_common()
│ ├── 生成 common_ffi.rs (bindgen)
│ ├── 编译平台相关 C++ 代码
│ └── 链接系统库 (stdc++)
└── ffmpeg::build_ffmpeg()
├── 生成 ffmpeg_ffi.rs
├── 链接 FFmpeg 库 (VCPKG 或 pkg-config)
└── build_ffmpeg_ram()
└── 编译 ffmpeg_ram_encode.cpp, ffmpeg_ram_decode.cpp
```
### 5.3 FFmpeg 链接方式
| 方式 | 平台 | 条件 |
|------|------|------|
| VCPKG 静态链接 | 跨平台 | 设置 `VCPKG_ROOT` 环境变量 |
| pkg-config 动态链接 | Linux | 默认方式 |
## 6. 与原版 hwcodec 的区别
针对 One-KVM IP-KVM 场景,对原版 RustDesk hwcodec 进行了以下简化:
### 6.1 移除的功能
| 移除项 | 原因 |
|--------|------|
| VRAM 模块 | IP-KVM 不需要 GPU 显存直接编解码 |
| Mux 模块 | IP-KVM 不需要录制到文件 |
| macOS 支持 | IP-KVM 目标平台不包含 macOS |
| Android 支持 | IP-KVM 目标平台不包含 Android |
| 外部 SDK | 简化构建,减少依赖 |
| 多格式解码 | IP-KVM 仅需 MJPEG 解码 |
### 6.2 保留的功能
| 保留项 | 用途 |
|--------|------|
| FFmpeg RAM 编码 | WebRTC 视频编码 |
| FFmpeg RAM 解码 | MJPEG 采集卡解码 |
| 硬件加速编码 | 低延迟高效编码 |
| 软件编码后备 | 无硬件加速时的兜底方案 |
### 6.3 代码量对比
| 指标 | 原版 | 简化版 | 减少 |
|------|------|--------|------|
| 外部 SDK | ~9MB | 0 | 100% |
| C++ 文件 | ~30 | ~10 | ~67% |
| Rust 模块 | 6 | 3 | 50% |
## 7. 总结
hwcodec 库通过 Rust/C++ 混合架构,在保证内存安全的同时实现了高性能的视频编解码。针对 One-KVM IP-KVM 场景的优化设计特点包括:
1. **精简的编解码器 API**: 解码仅支持 MJPEG编码支持多种硬件加速
2. **自动硬件检测**: 运行时自动检测并选择最优的硬件加速后端
3. **优先级系统**: 基于质量和性能为不同编码器分配优先级
4. **低延迟优化**: 针对实时流媒体场景进行了专门优化
5. **简化的构建系统**: 无需外部 SDK仅依赖系统 FFmpeg
6. **Windows/Linux 跨平台**: 支持 x86_64、ARM64、ARMv7 架构

View File

@@ -1,481 +0,0 @@
# hwcodec 编解码器 API 详解
## 1. 编码器 API
### 1.1 编码器初始化
#### EncodeContext 参数
```rust
pub struct EncodeContext {
pub name: String, // 编码器名称
pub mc_name: Option<String>, // MediaCodec 名称 (保留字段)
pub width: i32, // 视频宽度 (必须为偶数)
pub height: i32, // 视频高度 (必须为偶数)
pub pixfmt: AVPixelFormat, // 像素格式
pub align: i32, // 内存对齐 (通常为 0 或 32)
pub fps: i32, // 帧率
pub gop: i32, // GOP 大小 (关键帧间隔)
pub rc: RateControl, // 码率控制模式
pub quality: Quality, // 编码质量
pub kbs: i32, // 目标码率 (kbps)
pub q: i32, // 量化参数 (CQ 模式)
pub thread_count: i32, // 编码线程数
}
```
#### 参数说明
| 参数 | 类型 | 说明 | 推荐值 |
|------|------|------|--------|
| `name` | String | FFmpeg 编码器名称 | 见下表 |
| `width` | i32 | 视频宽度 | 1920 |
| `height` | i32 | 视频高度 | 1080 |
| `pixfmt` | AVPixelFormat | 像素格式 | NV12 / YUV420P |
| `align` | i32 | 内存对齐 | 0 (自动) |
| `fps` | i32 | 帧率 | 30 |
| `gop` | i32 | GOP 大小 | 30 (1秒) |
| `rc` | RateControl | 码率控制 | CBR / VBR |
| `quality` | Quality | 质量级别 | Medium |
| `kbs` | i32 | 码率 (kbps) | 2000-8000 |
| `thread_count` | i32 | 线程数 | 4 |
#### 编码器名称对照表
| 名称 | 格式 | 加速 | 平台 |
|------|------|------|------|
| `h264_nvenc` | H.264 | NVIDIA GPU | Windows/Linux |
| `hevc_nvenc` | H.265 | NVIDIA GPU | Windows/Linux |
| `h264_amf` | H.264 | AMD GPU | Windows/Linux |
| `hevc_amf` | H.265 | AMD GPU | Windows/Linux |
| `h264_qsv` | H.264 | Intel QSV | Windows |
| `hevc_qsv` | H.265 | Intel QSV | Windows |
| `h264_vaapi` | H.264 | VAAPI | Linux |
| `hevc_vaapi` | H.265 | VAAPI | Linux |
| `vp8_vaapi` | VP8 | VAAPI | Linux |
| `vp9_vaapi` | VP9 | VAAPI | Linux |
| `h264_rkmpp` | H.264 | Rockchip MPP | Linux |
| `hevc_rkmpp` | H.265 | Rockchip MPP | Linux |
| `h264_v4l2m2m` | H.264 | V4L2 M2M | Linux |
| `hevc_v4l2m2m` | H.265 | V4L2 M2M | Linux |
| `h264` | H.264 | 软件 (x264) | 全平台 |
| `hevc` | H.265 | 软件 (x265) | 全平台 |
| `libvpx` | VP8 | 软件 | 全平台 |
| `libvpx-vp9` | VP9 | 软件 | 全平台 |
| `mjpeg` | MJPEG | 软件 | 全平台 |
### 1.2 创建编码器
```rust
use hwcodec::ffmpeg_ram::encode::{Encoder, EncodeContext};
use hwcodec::ffmpeg::{AVPixelFormat};
use hwcodec::common::{RateControl, Quality};
let ctx = EncodeContext {
name: "h264_vaapi".to_string(),
mc_name: None,
width: 1920,
height: 1080,
pixfmt: AVPixelFormat::AV_PIX_FMT_NV12,
align: 0,
fps: 30,
gop: 30,
rc: RateControl::RC_CBR,
quality: Quality::Quality_Medium,
kbs: 4000,
q: 0,
thread_count: 4,
};
let encoder = Encoder::new(ctx)?;
println!("Linesize: {:?}", encoder.linesize);
println!("Offset: {:?}", encoder.offset);
println!("Buffer length: {}", encoder.length);
```
### 1.3 编码帧
```rust
// 准备 YUV 数据
let yuv_data: Vec<u8> = prepare_yuv_frame();
// 编码
let pts_ms: i64 = 0; // 时间戳 (毫秒)
match encoder.encode(&yuv_data, pts_ms) {
Ok(frames) => {
for frame in frames.iter() {
println!("Encoded: {} bytes, pts={}, key={}",
frame.data.len(), frame.pts, frame.key);
// 发送 frame.data
}
}
Err(code) => {
eprintln!("Encode error: {}", code);
}
}
```
### 1.4 动态调整码率
```rust
// 动态调整到 6000 kbps
encoder.set_bitrate(6000)?;
```
### 1.5 请求关键帧
```rust
// 下一帧强制编码为 IDR 帧
encoder.request_keyframe();
```
### 1.6 检测可用编码器
```rust
use hwcodec::ffmpeg_ram::encode::{Encoder, EncodeContext};
use hwcodec::ffmpeg_ram::CodecInfo;
let ctx = EncodeContext {
name: String::new(),
mc_name: None,
width: 1920,
height: 1080,
pixfmt: AVPixelFormat::AV_PIX_FMT_NV12,
align: 0,
fps: 30,
gop: 30,
rc: RateControl::RC_DEFAULT,
quality: Quality::Quality_Default,
kbs: 4000,
q: 0,
thread_count: 4,
};
let available_encoders = Encoder::available_encoders(ctx, None);
for encoder in available_encoders {
println!("Available: {} (format: {:?}, priority: {})",
encoder.name, encoder.format, encoder.priority);
}
```
## 2. 解码器 API
### 2.1 IP-KVM 专用设计
在 One-KVM IP-KVM 场景中,解码器仅支持 MJPEG 软件解码。这是因为视频采集卡输出的格式是 MJPEG不需要其他格式的硬件解码支持。
### 2.2 解码器初始化
#### DecodeContext 参数
```rust
pub struct DecodeContext {
pub name: String, // 解码器名称 ("mjpeg")
pub device_type: AVHWDeviceType, // 硬件设备类型 (NONE)
pub thread_count: i32, // 解码线程数
}
```
### 2.3 创建解码器
```rust
use hwcodec::ffmpeg_ram::decode::{Decoder, DecodeContext};
use hwcodec::ffmpeg::AVHWDeviceType;
let ctx = DecodeContext {
name: "mjpeg".to_string(),
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
thread_count: 4,
};
let decoder = Decoder::new(ctx)?;
```
### 2.4 解码帧
```rust
// 输入 MJPEG 编码数据
let mjpeg_data: Vec<u8> = receive_mjpeg_frame();
match decoder.decode(&mjpeg_data) {
Ok(frames) => {
for frame in frames.iter() {
println!("Decoded: {}x{}, format={:?}, key={}",
frame.width, frame.height, frame.pixfmt, frame.key);
// 访问 YUV 数据
let y_plane = &frame.data[0];
let u_plane = &frame.data[1];
let v_plane = &frame.data[2];
}
}
Err(code) => {
eprintln!("Decode error: {}", code);
}
}
```
### 2.5 DecodeFrame 结构体
```rust
pub struct DecodeFrame {
pub pixfmt: AVPixelFormat, // 输出像素格式
pub width: i32, // 帧宽度
pub height: i32, // 帧高度
pub data: Vec<Vec<u8>>, // 平面数据 [Y, U, V] 或 [Y, UV]
pub linesize: Vec<i32>, // 每个平面的行字节数
pub key: bool, // 是否为关键帧
}
```
#### 像素格式与平面布局
| 像素格式 | 平面数 | data[0] | data[1] | data[2] |
|----------|--------|---------|---------|---------|
| `YUV420P` | 3 | Y | U | V |
| `YUVJ420P` | 3 | Y | U | V |
| `YUV422P` | 3 | Y | U | V |
| `NV12` | 2 | Y | UV (交错) | - |
| `NV21` | 2 | Y | VU (交错) | - |
### 2.6 获取可用解码器
```rust
use hwcodec::ffmpeg_ram::decode::Decoder;
let available_decoders = Decoder::available_decoders();
for decoder in available_decoders {
println!("Available: {} (format: {:?}, hwdevice: {:?})",
decoder.name, decoder.format, decoder.hwdevice);
}
// 输出:
// Available: mjpeg (format: MJPEG, hwdevice: AV_HWDEVICE_TYPE_NONE)
```
## 3. 码率控制模式
### 3.1 RateControl 枚举
```rust
pub enum RateControl {
RC_DEFAULT, // 使用编码器默认
RC_CBR, // 恒定码率
RC_VBR, // 可变码率
RC_CQ, // 恒定质量 (需设置 q 参数)
}
```
### 3.2 模式说明
| 模式 | 说明 | 适用场景 |
|------|------|----------|
| `RC_CBR` | 码率恒定,质量随场景变化 | 网络带宽受限 |
| `RC_VBR` | 质量优先,码率波动 | 本地存储 |
| `RC_CQ` | 恒定质量,码率波动大 | 质量敏感场景 |
### 3.3 各编码器支持情况
| 编码器 | CBR | VBR | CQ |
|--------|-----|-----|-----|
| nvenc | ✓ | ✓ | ✓ |
| amf | ✓ | ✓ (低延迟) | ✗ |
| qsv | ✓ | ✓ | ✗ |
| vaapi | ✓ | ✓ | ✗ |
## 4. 质量等级
### 4.1 Quality 枚举
```rust
pub enum Quality {
Quality_Default, // 使用编码器默认
Quality_High, // 高质量 (慢速)
Quality_Medium, // 中等质量 (平衡)
Quality_Low, // 低质量 (快速)
}
```
### 4.2 编码器预设映射
| 质量 | nvenc | amf | qsv |
|------|-------|-----|-----|
| High | - | quality | veryslow |
| Medium | p4 | balanced | medium |
| Low | p1 | speed | veryfast |
## 5. 错误处理
### 5.1 错误码
| 错误码 | 常量 | 说明 |
|--------|------|------|
| 0 | `HWCODEC_SUCCESS` | 成功 |
| -1 | `HWCODEC_ERR_COMMON` | 通用错误 |
| -2 | `HWCODEC_ERR_HEVC_COULD_NOT_FIND_POC` | HEVC 解码参考帧丢失 |
### 5.2 常见错误处理
```rust
match encoder.encode(&yuv_data, pts) {
Ok(frames) => {
// 处理编码帧
}
Err(-1) => {
eprintln!("编码失败,可能是输入数据格式错误");
}
Err(code) => {
eprintln!("未知错误: {}", code);
}
}
```
## 6. 最佳实践
### 6.1 编码器选择策略
```rust
fn select_best_encoder(
width: i32,
height: i32,
format: DataFormat
) -> Option<String> {
let ctx = EncodeContext {
width,
height,
pixfmt: AVPixelFormat::AV_PIX_FMT_NV12,
// ... 其他参数
};
let encoders = Encoder::available_encoders(ctx, None);
// 按优先级排序,选择最佳
encoders.into_iter()
.filter(|e| e.format == format)
.min_by_key(|e| e.priority)
.map(|e| e.name)
}
```
### 6.2 帧内存布局
```rust
// 获取 NV12 帧布局信息
let (linesize, offset, length) = ffmpeg_linesize_offset_length(
AVPixelFormat::AV_PIX_FMT_NV12,
1920,
1080,
0, // align
)?;
// 分配缓冲区
let mut buffer = vec![0u8; length as usize];
// 填充 Y 平面: buffer[0..offset[0]]
// 填充 UV 平面: buffer[offset[0]..length]
```
### 6.3 关键帧控制
```rust
let mut frame_count = 0;
loop {
// 每 30 帧强制一个关键帧
if frame_count % 30 == 0 {
encoder.request_keyframe();
}
encoder.encode(&yuv_data, pts)?;
frame_count += 1;
}
```
### 6.4 线程安全
```rust
// Decoder 实现了 Send + Sync
unsafe impl Send for Decoder {}
unsafe impl Sync for Decoder {}
// 可以安全地在多线程间传递
let decoder = Arc::new(Mutex::new(Decoder::new(ctx)?));
```
## 7. IP-KVM 典型使用场景
### 7.1 视频采集和转码流程
```
USB 采集卡 (MJPEG)
┌─────────────────┐
│ MJPEG Decoder │ ◄── Decoder::new("mjpeg")
│ (软件解码) │
└────────┬────────┘
│ YUV420P
┌─────────────────┐
│ H264 Encoder │ ◄── Encoder::new("h264_vaapi")
│ (硬件加速) │
└────────┬────────┘
│ H264 NAL
WebRTC 传输
```
### 7.2 完整示例
```rust
use hwcodec::ffmpeg_ram::decode::{Decoder, DecodeContext};
use hwcodec::ffmpeg_ram::encode::{Encoder, EncodeContext};
use hwcodec::ffmpeg::AVHWDeviceType;
// 创建 MJPEG 解码器
let decode_ctx = DecodeContext {
name: "mjpeg".to_string(),
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
thread_count: 4,
};
let mut decoder = Decoder::new(decode_ctx)?;
// 检测并选择最佳编码器
let encode_ctx = EncodeContext {
name: String::new(),
width: 1920,
height: 1080,
// ...
};
let available = Encoder::available_encoders(encode_ctx.clone(), None);
let best_h264 = available.iter()
.filter(|e| e.format == DataFormat::H264)
.min_by_key(|e| e.priority)
.expect("No H264 encoder available");
// 使用最佳编码器创建实例
let encode_ctx = EncodeContext {
name: best_h264.name.clone(),
..encode_ctx
};
let mut encoder = Encoder::new(encode_ctx)?;
// 处理循环
loop {
let mjpeg_frame = capture_frame();
// 解码 MJPEG -> YUV
let decoded = decoder.decode(&mjpeg_frame)?;
// 编码 YUV -> H264
for frame in decoded {
let yuv_data = frame.data.concat();
let encoded = encoder.encode(&yuv_data, pts)?;
// 发送编码数据
for packet in encoded {
send_to_webrtc(packet.data);
}
}
}
```

View File

@@ -1,561 +0,0 @@
# hwcodec 硬件加速详解
## 1. 硬件加速架构
### 1.1 整体流程
```
┌─────────────────────────────────────────────────────────────┐
│ 应用层 (Rust) │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ Encoder::available_encoders() → 自动检测可用硬件编码器 ││
│ └─────────────────────────────────────────────────────────┘│
└────────────────────────────┬────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 硬件检测层 (C++) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐│
│ │linux_ │ │linux_ │ │linux_ │ │linux_support_ ││
│ │support_nv│ │support_ │ │support_ │ │rkmpp/v4l2m2m ││
│ └────┬─────┘ │amd │ │intel │ └─────────┬────────┘│
│ │ └────┬─────┘ └────┬─────┘ │ │
└───────┼────────────┼────────────┼─────────────────┼─────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────────────┐
│ CUDA/ │ │ AMF │ │ VPL/MFX │ │ 设备节点检测 │
│ NVENC │ │ Runtime │ │ Library │ │ /dev/mpp_service │
│ 动态库 │ │ 动态库 │ │ 动态库 │ │ /dev/video* │
└───────────┘ └───────────┘ └───────────┘ └───────────────────┘
```
### 1.2 编码器测试验证
每个检测到的硬件编码器都会进行实际编码测试:
```rust
// libs/hwcodec/src/ffmpeg_ram/encode.rs
// 生成测试用 YUV 数据
let yuv = Encoder::dummy_yuv(ctx.clone())?;
// 尝试创建编码器并编码测试帧
match Encoder::new(c) {
Ok(mut encoder) => {
let start = std::time::Instant::now();
match encoder.encode(&yuv, 0) {
Ok(frames) => {
let elapsed = start.elapsed().as_millis();
// 验证: 必须产生 1 帧且为关键帧,且在超时时间内完成
if frames.len() == 1 && frames[0].key == 1
&& elapsed < TEST_TIMEOUT_MS {
res.push(codec);
}
}
Err(_) => { /* 编码失败,跳过 */ }
}
}
Err(_) => { /* 创建失败,跳过 */ }
}
```
## 2. NVIDIA NVENC/NVDEC
### 2.1 检测机制 (Linux)
使用简化的动态库检测方法,无需 CUDA SDK 依赖:
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
int linux_support_nv() {
// 检测 CUDA 运行时库
void *handle = dlopen("libcuda.so.1", RTLD_LAZY);
if (!handle) {
handle = dlopen("libcuda.so", RTLD_LAZY);
}
if (!handle) {
LOG_TRACE("NVIDIA: libcuda.so not found");
return -1;
}
dlclose(handle);
// 检测 NVENC 编码库
handle = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
if (!handle) {
handle = dlopen("libnvidia-encode.so", RTLD_LAZY);
}
if (!handle) {
LOG_TRACE("NVIDIA: libnvidia-encode.so not found");
return -1;
}
dlclose(handle);
LOG_TRACE("NVIDIA: driver support detected");
return 0;
}
```
### 2.2 编码配置
```cpp
// libs/hwcodec/cpp/common/util.cpp
// NVENC 低延迟配置
if (name.find("nvenc") != std::string::npos) {
// 禁用编码延迟
av_opt_set(priv_data, "delay", "0", 0);
}
// GPU 选择
if (name.find("nvenc") != std::string::npos) {
av_opt_set_int(priv_data, "gpu", gpu_index, 0);
}
// 质量预设
switch (quality) {
case Quality_Medium:
av_opt_set(priv_data, "preset", "p4", 0);
break;
case Quality_Low:
av_opt_set(priv_data, "preset", "p1", 0);
break;
}
// 码率控制
av_opt_set(priv_data, "rc", "cbr", 0); // 或 "vbr"
```
### 2.3 环境变量
| 变量 | 说明 |
|------|------|
| `RUSTDESK_HWCODEC_NVENC_GPU` | 指定使用的 GPU 索引 (-1 = 自动) |
### 2.4 依赖库
- `libcuda.so` / `libcuda.so.1` - CUDA 运行时
- `libnvidia-encode.so` / `libnvidia-encode.so.1` - NVENC 编码器
## 3. AMD AMF
### 3.1 检测机制 (Linux)
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
int linux_support_amd() {
#if defined(__x86_64__) || defined(__aarch64__)
#define AMF_DLL_NAMEA "libamfrt64.so.1"
#else
#define AMF_DLL_NAMEA "libamfrt32.so.1"
#endif
void *handle = dlopen(AMF_DLL_NAMEA, RTLD_LAZY);
if (!handle) {
return -1; // AMF 不可用
}
dlclose(handle);
return 0; // AMF 可用
}
```
### 3.2 编码配置
```cpp
// libs/hwcodec/cpp/common/util.cpp
// AMF 低延迟配置
if (name.find("amf") != std::string::npos) {
av_opt_set(priv_data, "query_timeout", "1000", 0);
}
// 质量预设
switch (quality) {
case Quality_High:
av_opt_set(priv_data, "quality", "quality", 0);
break;
case Quality_Medium:
av_opt_set(priv_data, "quality", "balanced", 0);
break;
case Quality_Low:
av_opt_set(priv_data, "quality", "speed", 0);
break;
}
// 码率控制
av_opt_set(priv_data, "rc", "cbr", 0); // 恒定码率
av_opt_set(priv_data, "rc", "vbr_latency", 0); // 低延迟 VBR
```
### 3.3 依赖库
- `libamfrt64.so.1` (64位) 或 `libamfrt32.so.1` (32位)
## 4. Intel QSV/MFX
### 4.1 检测机制 (Linux)
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
int linux_support_intel() {
const char *libs[] = {
"libvpl.so", // oneVPL (新版)
"libmfx.so", // Media SDK
"libmfx-gen.so.1.2", // 新驱动
"libmfxhw64.so.1" // 旧版驱动
};
for (size_t i = 0; i < sizeof(libs) / sizeof(libs[0]); i++) {
void *handle = dlopen(libs[i], RTLD_LAZY);
if (handle) {
dlclose(handle);
return 0; // 找到可用库
}
}
return -1; // Intel MFX 不可用
}
```
### 4.2 编码配置
```cpp
// libs/hwcodec/cpp/common/util.cpp
// QSV 低延迟配置
if (name.find("qsv") != std::string::npos) {
av_opt_set(priv_data, "async_depth", "1", 0);
}
// QSV 特殊码率配置
if (name.find("qsv") != std::string::npos) {
c->rc_max_rate = c->bit_rate;
c->bit_rate--; // 实现 CBR 效果
}
// 质量预设
switch (quality) {
case Quality_High:
av_opt_set(priv_data, "preset", "veryslow", 0);
break;
case Quality_Medium:
av_opt_set(priv_data, "preset", "medium", 0);
break;
case Quality_Low:
av_opt_set(priv_data, "preset", "veryfast", 0);
break;
}
// 严格标准兼容性 (用于某些特殊设置)
c->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
```
### 4.3 限制
- QSV 不支持 `YUV420P` 像素格式,必须使用 `NV12`
- 在 One-KVM 简化版中仅 Windows 平台完全支持
## 5. VAAPI (Linux)
### 5.1 工作原理
VAAPI (Video Acceleration API) 是 Linux 上的通用硬件视频加速接口:
```
┌─────────────────────────────────────────────────────────────┐
│ Application │
├─────────────────────────────────────────────────────────────┤
│ FFmpeg libavcodec │
├─────────────────────────────────────────────────────────────┤
│ VAAPI (libva) │
├──────────────┬──────────────┬──────────────┬────────────────┤
│ Intel i965 │ Intel iHD │ AMD radeonsi │ NVIDIA VDPAU │
│ (Gen8-) │ (Gen9+) │ │ (via wrapper) │
├──────────────┴──────────────┴──────────────┴────────────────┤
│ Kernel DRM Driver │
├──────────────┬──────────────┬──────────────┬────────────────┤
│ i915 │ amdgpu │ nvidia │ ... │
└──────────────┴──────────────┴──────────────┴────────────────┘
```
### 5.2 编码配置
```cpp
// libs/hwcodec/cpp/common/util.cpp
// VAAPI 低延迟配置
if (name.find("vaapi") != std::string::npos) {
av_opt_set(priv_data, "async_depth", "1", 0);
}
```
### 5.3 硬件上下文初始化
```cpp
// libs/hwcodec/cpp/ffmpeg_ram/ffmpeg_ram_encode.cpp
// 检测 VAAPI 编码器
if (name_.find("vaapi") != std::string::npos) {
hw_device_type_ = AV_HWDEVICE_TYPE_VAAPI;
hw_pixfmt_ = AV_PIX_FMT_VAAPI;
}
// 创建硬件设备上下文
ret = av_hwdevice_ctx_create(&hw_device_ctx_, hw_device_type_,
NULL, // 使用默认设备
NULL, 0);
// 设置硬件帧上下文
set_hwframe_ctx();
// 分配硬件帧
hw_frame_ = av_frame_alloc();
av_hwframe_get_buffer(c_->hw_frames_ctx, hw_frame_, 0);
```
### 5.4 编码流程
```
输入 YUV (CPU 内存)
av_hwframe_transfer_data(hw_frame_, frame_, 0) // CPU → GPU
avcodec_send_frame(c_, hw_frame_) // 发送 GPU 帧
avcodec_receive_packet(c_, pkt_) // 获取编码数据
编码数据 (CPU 内存)
```
### 5.5 依赖库
- `libva.so` - VAAPI 核心库
- `libva-drm.so` - DRM 后端
- `libva-x11.so` - X11 后端 (可选)
## 6. Rockchip MPP
### 6.1 检测机制
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
int linux_support_rkmpp() {
// 检测 MPP 服务设备
if (access("/dev/mpp_service", F_OK) == 0) {
LOG_TRACE("RKMPP: Found /dev/mpp_service");
return 0; // MPP 可用
}
// 备用: 检测 RGA 设备
if (access("/dev/rga", F_OK) == 0) {
LOG_TRACE("RKMPP: Found /dev/rga");
return 0; // MPP 可能可用
}
LOG_TRACE("RKMPP: No Rockchip MPP device found");
return -1; // MPP 不可用
}
```
### 6.2 支持的编码器
| 编码器 | 优先级 | 说明 |
|--------|--------|------|
| `h264_rkmpp` | Best (0) | H.264 硬件编码 |
| `hevc_rkmpp` | Best (0) | H.265 硬件编码 |
### 6.3 适用设备
- Rockchip RK3328 (Onecloud, Chainedbox)
- Rockchip RK3399/RK3588 系列
- 其他 Rockchip SoC
## 7. V4L2 M2M
### 7.1 检测机制
```cpp
// libs/hwcodec/cpp/common/platform/linux/linux.cpp
int linux_support_v4l2m2m() {
const char *m2m_devices[] = {
"/dev/video10", // 常见 M2M 编码设备
"/dev/video11", // 常见 M2M 解码设备
"/dev/video0", // 某些 SoC 使用
};
for (size_t i = 0; i < sizeof(m2m_devices) / sizeof(m2m_devices[0]); i++) {
if (access(m2m_devices[i], F_OK) == 0) {
int fd = open(m2m_devices[i], O_RDWR | O_NONBLOCK);
if (fd >= 0) {
close(fd);
LOG_TRACE("V4L2 M2M: Found device " + m2m_devices[i]);
return 0; // V4L2 M2M 可用
}
}
}
LOG_TRACE("V4L2 M2M: No M2M device found");
return -1;
}
```
### 7.2 支持的编码器
| 编码器 | 优先级 | 说明 |
|--------|--------|------|
| `h264_v4l2m2m` | Good (1) | H.264 V4L2 编码 |
| `hevc_v4l2m2m` | Good (1) | H.265 V4L2 编码 |
### 7.3 适用设备
- 通用 ARM SoC (Allwinner, Amlogic 等)
- 支持 V4L2 M2M API 的设备
## 8. 硬件加速优先级
### 8.1 优先级定义
```rust
pub enum Priority {
Best = 0, // 专用硬件编码器
Good = 1, // 通用硬件加速
Normal = 2, // 基本硬件支持
Soft = 3, // 软件编码
Bad = 4, // 最低优先级
}
```
### 8.2 各编码器优先级
| 优先级 | 编码器 |
|--------|--------|
| Best (0) | nvenc, amf, qsv, rkmpp |
| Good (1) | vaapi, v4l2m2m |
| Soft (3) | x264, x265, libvpx |
### 8.3 选择策略
```rust
// libs/hwcodec/src/ffmpeg_ram/mod.rs
pub fn prioritized(coders: Vec<CodecInfo>) -> CodecInfos {
// 对于每种格式,选择优先级最高的编码器
for coder in coders {
match coder.format {
DataFormat::H264 => {
if h264.is_none() || h264.priority > coder.priority {
h264 = Some(coder);
}
}
// ... 其他格式类似
}
}
}
```
## 9. 故障排除
### 9.1 NVIDIA
```bash
# 检查 NVIDIA 驱动
nvidia-smi
# 检查 NVENC 支持
ls /dev/nvidia*
# 检查 CUDA 库
ldconfig -p | grep cuda
ldconfig -p | grep nvidia-encode
```
### 9.2 AMD
```bash
# 检查 AMD 驱动
lspci | grep AMD
# 检查 AMF 库
ldconfig -p | grep amf
```
### 9.3 Intel
```bash
# 检查 Intel 驱动
vainfo
# 检查 MFX 库
ldconfig -p | grep mfx
ldconfig -p | grep vpl
```
### 9.4 VAAPI
```bash
# 安装 vainfo
sudo apt install vainfo
# 检查 VAAPI 支持
vainfo
# 输出示例:
# libva info: VA-API version 1.14.0
# libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so
# vainfo: Driver version: Intel iHD driver for Intel(R) Gen Graphics
# vainfo: Supported profile and entrypoints
# VAProfileH264Main : VAEntrypointVLD
# VAProfileH264Main : VAEntrypointEncSlice
# ...
```
### 9.5 Rockchip MPP
```bash
# 检查 MPP 设备
ls -la /dev/mpp_service
ls -la /dev/rga
# 检查 MPP 库
ldconfig -p | grep rockchip_mpp
```
### 9.6 V4L2 M2M
```bash
# 列出 V4L2 设备
v4l2-ctl --list-devices
# 检查设备能力
v4l2-ctl -d /dev/video10 --all
```
## 10. 性能优化建议
### 10.1 编码器选择
1. **优先使用硬件编码**: NVENC > AMF > QSV > VAAPI > V4L2 M2M > 软件
2. **ARM 设备**: 优先检测 RKMPP其次 V4L2 M2M
3. **x86 设备**: 根据 GPU 厂商自动选择
### 10.2 低延迟配置
所有硬件编码器都启用了低延迟优化:
| 编码器 | 配置 |
|--------|------|
| NVENC | `delay=0` |
| AMF | `query_timeout=1000` |
| QSV | `async_depth=1` |
| VAAPI | `async_depth=1` |
| libvpx | `deadline=realtime`, `cpu-used=6` |
### 10.3 码率控制
- **实时流**: 推荐 CBR 模式,保证稳定码率
- **GOP 大小**: 建议 30-60 帧 (1-2秒),平衡延迟和压缩效率

View File

@@ -1,477 +0,0 @@
# hwcodec 构建系统与集成指南
## 1. 项目结构
```
libs/hwcodec/
├── Cargo.toml # 包配置
├── Cargo.lock # 依赖锁定
├── build.rs # 构建脚本
└── src/ # Rust 源码
├── lib.rs # 库入口
├── common.rs # 公共定义
├── ffmpeg.rs # FFmpeg 集成
└── ffmpeg_ram/ # RAM 编解码
├── mod.rs
├── encode.rs
└── decode.rs
└── cpp/ # C++ 源码
├── common/ # 公共代码
│ ├── log.cpp
│ ├── log.h
│ ├── util.cpp
│ ├── util.h
│ ├── callback.h
│ ├── common.h
│ └── platform/
│ ├── linux/
│ │ ├── linux.cpp
│ │ └── linux.h
│ └── win/
│ ├── win.cpp
│ └── win.h
├── ffmpeg_ram/ # FFmpeg RAM 实现
│ ├── ffmpeg_ram_encode.cpp
│ ├── ffmpeg_ram_decode.cpp
│ └── ffmpeg_ram_ffi.h
└── yuv/ # YUV 处理
└── yuv.cpp
```
## 2. Cargo 配置
### 2.1 Cargo.toml
```toml
[package]
name = "hwcodec"
version = "0.8.0"
edition = "2021"
description = "Hardware video codec for IP-KVM (Windows/Linux)"
[features]
default = []
[dependencies]
log = "0.4" # 日志
serde_derive = "1.0" # 序列化派生宏
serde = "1.0" # 序列化
serde_json = "1.0" # JSON 序列化
[build-dependencies]
cc = "1.0" # C++ 编译
bindgen = "0.59" # FFI 绑定生成
[dev-dependencies]
env_logger = "0.10" # 日志输出
```
### 2.2 与原版的区别
| 特性 | 原版 (RustDesk) | 简化版 (One-KVM) |
|------|-----------------|------------------|
| `vram` feature | ✓ | ✗ (已移除) |
| 外部 SDK | 需要 | 不需要 |
| 版本号 | 0.7.1 | 0.8.0 |
| 目标平台 | Windows/Linux/macOS/Android | Windows/Linux |
### 2.3 使用方式
```toml
# 在 One-KVM 项目中使用
[dependencies]
hwcodec = { path = "libs/hwcodec" }
```
## 3. 构建脚本详解 (build.rs)
### 3.1 主入口
```rust
fn main() {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut builder = Build::new();
// 1. 构建公共模块
build_common(&mut builder);
// 2. 构建 FFmpeg 相关模块
ffmpeg::build_ffmpeg(&mut builder);
// 3. 编译生成静态库
builder.static_crt(true).compile("hwcodec");
}
```
### 3.2 公共模块构建
```rust
fn build_common(builder: &mut Build) {
let common_dir = manifest_dir.join("cpp").join("common");
// 生成 FFI 绑定
bindgen::builder()
.header(common_dir.join("common.h"))
.header(common_dir.join("callback.h"))
.rustified_enum("*")
.generate()
.write_to_file(OUT_DIR.join("common_ffi.rs"));
// 平台相关代码
#[cfg(windows)]
builder.file(common_dir.join("platform/win/win.cpp"));
#[cfg(target_os = "linux")]
builder.file(common_dir.join("platform/linux/linux.cpp"));
// 工具代码
builder.files([
common_dir.join("log.cpp"),
common_dir.join("util.cpp"),
]);
}
```
### 3.3 FFmpeg 模块构建
```rust
mod ffmpeg {
pub fn build_ffmpeg(builder: &mut Build) {
// 生成 FFmpeg FFI 绑定
ffmpeg_ffi();
// 链接 FFmpeg 库
if let Ok(vcpkg_root) = std::env::var("VCPKG_ROOT") {
link_vcpkg(builder, vcpkg_root.into());
} else {
link_system_ffmpeg(builder); // pkg-config
}
// 链接系统库
link_os();
// 构建 FFmpeg RAM 模块
build_ffmpeg_ram(builder);
}
}
```
### 3.4 FFmpeg 链接方式
#### VCPKG (跨平台静态链接)
```rust
fn link_vcpkg(builder: &mut Build, path: PathBuf) -> PathBuf {
// 目标平台识别
let target = match (target_os, target_arch) {
("windows", "x86_64") => "x64-windows-static",
("linux", arch) => format!("{}-linux", arch),
_ => panic!("unsupported platform"),
};
let lib_path = path.join("installed").join(target).join("lib");
// 链接 FFmpeg 静态库
println!("cargo:rustc-link-search=native={}", lib_path);
["avcodec", "avutil", "avformat"].iter()
.for_each(|lib| println!("cargo:rustc-link-lib=static={}", lib));
}
```
#### pkg-config (Linux 动态链接)
```rust
fn link_system_ffmpeg(builder: &mut Build) {
let libs = ["libavcodec", "libavutil", "libavformat", "libswscale"];
for lib in &libs {
// 获取编译标志
let cflags = Command::new("pkg-config")
.args(["--cflags", lib])
.output()?;
// 获取链接标志
let libs = Command::new("pkg-config")
.args(["--libs", lib])
.output()?;
// 解析并应用
for flag in libs.split_whitespace() {
if flag.starts_with("-L") {
println!("cargo:rustc-link-search=native={}", &flag[2..]);
} else if flag.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &flag[2..]);
}
}
}
}
```
### 3.5 系统库链接
```rust
fn link_os() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let libs: Vec<&str> = match target_os.as_str() {
"windows" => vec!["User32", "bcrypt", "ole32", "advapi32"],
"linux" => vec!["drm", "X11", "stdc++", "z"],
_ => panic!("unsupported os"),
};
for lib in libs {
println!("cargo:rustc-link-lib={}", lib);
}
}
```
## 4. FFI 绑定生成
### 4.1 bindgen 配置
```rust
bindgen::builder()
.header("path/to/header.h")
.rustified_enum("*") // 生成 Rust 枚举
.parse_callbacks(Box::new(Callbacks)) // 自定义回调
.generate()
.write_to_file(OUT_DIR.join("ffi.rs"));
```
### 4.2 自定义派生
```rust
#[derive(Debug)]
struct CommonCallbacks;
impl bindgen::callbacks::ParseCallbacks for CommonCallbacks {
fn add_derives(&self, name: &str) -> Vec<String> {
// 为特定类型添加序列化支持
match name {
"DataFormat" | "SurfaceFormat" | "API" => {
vec!["Serialize".to_string(), "Deserialize".to_string()]
}
_ => vec![],
}
}
}
```
### 4.3 生成的文件
| 文件 | 来源 | 内容 |
|------|------|------|
| `common_ffi.rs` | `common.h`, `callback.h` | 枚举、常量、回调类型 |
| `ffmpeg_ffi.rs` | `ffmpeg_ffi.h` | FFmpeg 日志级别、函数 |
| `ffmpeg_ram_ffi.rs` | `ffmpeg_ram_ffi.h` | 编解码器函数 |
## 5. 平台构建指南
### 5.1 Linux 构建
```bash
# 安装 FFmpeg 开发库
sudo apt install libavcodec-dev libavformat-dev libavutil-dev libswscale-dev
# 安装其他依赖
sudo apt install libdrm-dev libx11-dev pkg-config
# 安装 clang (bindgen 需要)
sudo apt install clang libclang-dev
# 构建
cargo build --release -p hwcodec
```
### 5.2 Windows 构建 (VCPKG)
```powershell
# 安装 VCPKG
git clone https://github.com/microsoft/vcpkg
cd vcpkg
./bootstrap-vcpkg.bat
# 安装 FFmpeg
./vcpkg install ffmpeg:x64-windows-static
# 设置环境变量
$env:VCPKG_ROOT = "C:\path\to\vcpkg"
# 构建
cargo build --release -p hwcodec
```
### 5.3 交叉编译
```bash
# 安装 cross
cargo install cross --git https://github.com/cross-rs/cross
# ARM64 Linux
cross build --release -p hwcodec --target aarch64-unknown-linux-gnu
# ARMv7 Linux
cross build --release -p hwcodec --target armv7-unknown-linux-gnueabihf
```
## 6. 集成到 One-KVM
### 6.1 依赖配置
```toml
# Cargo.toml
[dependencies]
hwcodec = { path = "libs/hwcodec" }
```
### 6.2 使用示例
```rust
use hwcodec::ffmpeg_ram::encode::{Encoder, EncodeContext};
use hwcodec::ffmpeg_ram::decode::{Decoder, DecodeContext};
use hwcodec::ffmpeg::{AVPixelFormat, AVHWDeviceType};
// 检测可用编码器
let encoders = Encoder::available_encoders(ctx, None);
// 创建编码器
let encoder = Encoder::new(EncodeContext {
name: "h264_vaapi".to_string(),
width: 1920,
height: 1080,
pixfmt: AVPixelFormat::AV_PIX_FMT_NV12,
fps: 30,
gop: 30,
kbs: 4000,
// ...
})?;
// 编码
let frames = encoder.encode(&yuv_data, pts_ms)?;
// 创建 MJPEG 解码器 (IP-KVM 专用)
let decoder = Decoder::new(DecodeContext {
name: "mjpeg".to_string(),
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
thread_count: 4,
})?;
// 解码
let frames = decoder.decode(&mjpeg_data)?;
```
### 6.3 日志集成
```rust
// hwcodec 使用 log crate与 One-KVM 日志系统兼容
use log::{debug, info, warn, error};
// C++ 层日志通过回调传递到 Rust
#[no_mangle]
pub extern "C" fn hwcodec_av_log_callback(level: i32, message: *const c_char) {
// 转发到 Rust log 系统
match level {
AV_LOG_ERROR => error!("{}", message),
AV_LOG_WARNING => warn!("{}", message),
AV_LOG_INFO => info!("{}", message),
AV_LOG_DEBUG => debug!("{}", message),
_ => {}
}
}
```
## 7. 故障排除
### 7.1 编译错误
**FFmpeg 未找到**:
```
error: pkg-config failed for libavcodec
```
解决: 安装 FFmpeg 开发库
```bash
sudo apt install libavcodec-dev libavformat-dev libavutil-dev libswscale-dev
```
**bindgen 错误**:
```
error: failed to run custom build command for `hwcodec`
```
解决: 安装 clang
```bash
sudo apt install clang libclang-dev
```
### 7.2 链接错误
**符号未定义**:
```
undefined reference to `av_log_set_level'
```
解决: 检查 FFmpeg 库链接顺序,确保 pkg-config 正确配置
**动态库未找到**:
```
error while loading shared libraries: libavcodec.so.59
```
解决:
```bash
sudo ldconfig
# 或设置 LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
```
### 7.3 运行时错误
**硬件编码器不可用**:
```
Encoder h264_vaapi test failed
```
检查:
1. 驱动是否正确安装: `vainfo`
2. 权限是否足够: `ls -la /dev/dri/`
3. 用户是否在 video 组: `groups`
**解码失败**:
```
avcodec_receive_frame failed, ret = -11
```
解决: 这通常表示需要更多输入数据 (EAGAIN),是正常行为
## 8. 与原版 RustDesk hwcodec 的构建差异
### 8.1 移除的构建步骤
| 步骤 | 原因 |
|------|------|
| `build_mux()` | 移除了 Mux 模块 |
| `build_ffmpeg_vram()` | 移除了 VRAM 模块 |
| `sdk::build_sdk()` | 移除了外部 SDK 依赖 |
| macOS 框架链接 | 移除了 macOS 支持 |
| Android NDK 链接 | 移除了 Android 支持 |
### 8.2 简化的构建流程
```
原版构建流程:
build.rs
├── build_common()
├── ffmpeg::build_ffmpeg()
│ ├── build_ffmpeg_ram()
│ ├── build_ffmpeg_vram() [已移除]
│ └── build_mux() [已移除]
└── sdk::build_sdk() [已移除]
简化版构建流程:
build.rs
├── build_common()
└── ffmpeg::build_ffmpeg()
└── build_ffmpeg_ram()
```
### 8.3 优势
1. **更快的编译**: 无需编译外部 SDK 代码
2. **更少的依赖**: 无需下载 ~9MB 的外部 SDK
3. **更简单的维护**: 代码量减少约 67%
4. **更小的二进制**: 不包含未使用的功能

View File

@@ -1,69 +0,0 @@
# RustDesk 通信协议技术报告
## 概述
本报告详细分析 RustDesk 远程桌面软件的客户端与服务器之间的通信协议,包括 Rendezvous 服务器hbbs、Relay 服务器hbbr以及客户端之间的 P2P 连接机制。
## 文档结构
| 文档 | 内容 |
|------|------|
| [01-architecture.md](01-architecture.md) | 整体架构设计 |
| [02-rendezvous-protocol.md](02-rendezvous-protocol.md) | Rendezvous 服务器协议 |
| [03-relay-protocol.md](03-relay-protocol.md) | Relay 服务器协议 |
| [04-p2p-connection.md](04-p2p-connection.md) | P2P 连接流程 |
| [05-message-format.md](05-message-format.md) | 消息格式定义 |
| [06-encryption.md](06-encryption.md) | 加密机制 |
| [07-nat-traversal.md](07-nat-traversal.md) | NAT 穿透技术 |
| [08-onekvm-comparison.md](08-onekvm-comparison.md) | **One-KVM 实现对比分析** |
## 核心组件
### 1. Rendezvous Server (hbbs)
- **功能**: ID 注册、Peer 发现、NAT 类型检测、连接协调
- **端口**: 21116 (TCP/UDP), 21115 (NAT 测试), 21118 (WebSocket)
- **源文件**: `rustdesk-server/src/rendezvous_server.rs`
### 2. Relay Server (hbbr)
- **功能**: 当 P2P 连接失败时提供数据中转
- **端口**: 21117 (TCP), 21119 (WebSocket)
- **源文件**: `rustdesk-server/src/relay_server.rs`
### 3. 客户端 (RustDesk)
- **功能**: 远程桌面控制、文件传输、屏幕共享
- **核心模块**:
- `rendezvous_mediator.rs` - 与 Rendezvous 服务器通信
- `client.rs` - 客户端连接逻辑
- `server/connection.rs` - 被控端连接处理
## 协议栈
```
┌─────────────────────────────────────────┐
│ Application Layer │
│ (Video/Audio/Keyboard/Mouse/File) │
├─────────────────────────────────────────┤
│ Message Layer │
│ (Protobuf Messages) │
├─────────────────────────────────────────┤
│ Security Layer │
│ (Sodium: X25519 + ChaCha20) │
├─────────────────────────────────────────┤
│ Transport Layer │
│ (TCP/UDP/WebSocket/KCP) │
└─────────────────────────────────────────┘
```
## 关键技术特点
1. **混合连接模式**: 优先尝试 P2P 直连,失败后自动切换到 Relay 中转
2. **多协议支持**: TCP、UDP、WebSocket、KCP
3. **端到端加密**: 使用 libsodium 实现的 X25519 密钥交换和 ChaCha20-Poly1305 对称加密
4. **NAT 穿透**: 支持 UDP 打洞和 TCP 打洞技术
5. **服务器签名**: 可选的服务器公钥签名验证,防止中间人攻击
## 版本信息
- 分析基于 RustDesk 最新版本源码
- Protocol Buffer 版本: proto3
- 加密库: libsodium (sodiumoxide)

View File

@@ -1,218 +0,0 @@
# RustDesk 架构设计
## 系统架构图
```
┌──────────────────────┐
│ Rendezvous Server │
│ (hbbs) │
│ Port: 21116 │
└──────────┬───────────┘
┌──────────────────────────┼──────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Client A │ │ Client B │ │ Client C │
│ (控制端) │ │ (被控端) │ │ (被控端) │
└───────┬───────┘ └───────┬───────┘ └───────────────┘
│ │
│ P2P Connection │
│◄────────────────────────►│
│ │
│ (如果 P2P 失败) │
│ │ │
│ ▼ │
│ ┌───────────────┐ │
└─►│ Relay Server │◄──────┘
│ (hbbr) │
│ Port: 21117 │
└───────────────┘
```
## 服务器组件详解
### Rendezvous Server (hbbs)
**监听端口:**
| 端口 | 协议 | 用途 |
|------|------|------|
| 21116 | TCP | 主要通信端口,处理 punch hole 请求 |
| 21116 | UDP | Peer 注册、NAT 类型检测 |
| 21115 | TCP | NAT 测试专用端口 |
| 21118 | WebSocket | Web 客户端支持 |
**核心数据结构:**
```rust
// rustdesk-server/src/rendezvous_server.rs:64-83
pub struct RendezvousServer {
tcp_punch: Arc<Mutex<HashMap<SocketAddr, Sink>>>, // TCP punch hole 连接
pm: PeerMap, // Peer 映射表
tx: Sender, // 消息发送通道
relay_servers: Arc<RelayServers>, // 可用 Relay 服务器列表
relay_servers0: Arc<RelayServers>, // 原始 Relay 服务器列表
rendezvous_servers: Arc<Vec<String>>, // Rendezvous 服务器列表
inner: Arc<Inner>, // 内部配置
}
struct Inner {
serial: i32, // 配置序列号
version: String, // 软件版本
software_url: String, // 软件更新 URL
mask: Option<Ipv4Network>, // LAN 掩码
local_ip: String, // 本地 IP
sk: Option<sign::SecretKey>, // 服务器签名密钥
}
```
**Peer 数据结构:**
```rust
// rustdesk-server/src/peer.rs:32-42
pub struct Peer {
pub socket_addr: SocketAddr, // 最后注册的地址
pub last_reg_time: Instant, // 最后注册时间
pub guid: Vec<u8>, // 数据库 GUID
pub uuid: Bytes, // 设备 UUID
pub pk: Bytes, // 公钥
pub info: PeerInfo, // Peer 信息
pub reg_pk: (u32, Instant), // 注册频率限制
}
```
### Relay Server (hbbr)
**监听端口:**
| 端口 | 协议 | 用途 |
|------|------|------|
| 21117 | TCP | 主要中转端口 |
| 21119 | WebSocket | Web 客户端支持 |
**核心特性:**
```rust
// rustdesk-server/src/relay_server.rs:40-44
static DOWNGRADE_THRESHOLD_100: AtomicUsize = AtomicUsize::new(66); // 降级阈值
static DOWNGRADE_START_CHECK: AtomicUsize = AtomicUsize::new(1_800_000); // 检测开始时间(ms)
static LIMIT_SPEED: AtomicUsize = AtomicUsize::new(32 * 1024 * 1024); // 限速(bit/s)
static TOTAL_BANDWIDTH: AtomicUsize = AtomicUsize::new(1024 * 1024 * 1024);// 总带宽
static SINGLE_BANDWIDTH: AtomicUsize = AtomicUsize::new(128 * 1024 * 1024);// 单连接带宽
```
## 客户端架构
### 核心模块
```
rustdesk/src/
├── rendezvous_mediator.rs # Rendezvous 服务器通信
├── client.rs # 控制端核心逻辑
├── server/
│ ├── mod.rs # 被控端服务
│ ├── connection.rs # 连接处理
│ ├── video_service.rs # 视频服务
│ ├── audio_service.rs # 音频服务
│ └── input_service.rs # 输入服务
├── common.rs # 通用函数(加密、解密)
└── platform/ # 平台特定代码
```
### RendezvousMediator
```rust
// rustdesk/src/rendezvous_mediator.rs:44-50
pub struct RendezvousMediator {
addr: TargetAddr<'static>, // 服务器地址
host: String, // 服务器主机名
host_prefix: String, // 主机前缀
keep_alive: i32, // 保活间隔
}
```
**两种连接模式:**
1. **UDP 模式** (默认):
- 用于 Peer 注册和心跳
- 更低延迟
- 可能被某些防火墙阻止
2. **TCP 模式**:
- 用于代理环境
- WebSocket 模式
- 更可靠
## 连接流程概述
### 被控端启动流程
```
1. 生成设备 ID 和密钥对
2. 连接 Rendezvous Server
3. 发送 RegisterPeer 消息
4. 如果需要,发送 RegisterPk 注册公钥
5. 定期发送心跳保持在线状态
6. 等待 PunchHole 或 RequestRelay 请求
```
### 控制端连接流程
```
1. 输入目标设备 ID
2. 连接 Rendezvous Server
3. 发送 PunchHoleRequest 消息
4. 根据响应决定连接方式:
a. 直连 (P2P): 使用 PunchHole 信息尝试打洞
b. 局域网: 使用 LocalAddr 信息直连
c. 中转: 通过 Relay Server 连接
5. 建立安全加密通道
6. 发送 LoginRequest 进行身份验证
7. 开始远程控制会话
```
## 数据流
### 视频流
```
被控端 控制端
│ │
│ VideoFrame (H264/VP9/...) │
├─────────────────────────────────►│
│ │
│ 加密 → 传输 → 解密 → 解码 → 显示 │
```
### 输入流
```
控制端 被控端
│ │
│ MouseEvent/KeyEvent │
├─────────────────────────────────►│
│ │
│ 加密 → 传输 → 解密 → 模拟输入 │
```
## 高可用设计
### 多服务器支持
- 客户端可配置多个 Rendezvous Server
- 自动选择延迟最低的服务器
- 连接失败时自动切换备用服务器
### Relay Server 选择
- 支持配置多个 Relay Server
- 轮询算法分配负载
- 定期检查 Relay Server 可用性
### 重连机制
```rust
// 连接超时和重试参数
const REG_INTERVAL: i64 = 12_000; // 注册间隔 12 秒
const REG_TIMEOUT: i32 = 30_000; // 注册超时 30 秒
const CONNECT_TIMEOUT: u64 = 18_000; // 连接超时 18 秒
```

View File

@@ -1,438 +0,0 @@
# Rendezvous 服务器协议
## 概述
Rendezvous Serverhbbs是 RustDesk 的核心协调服务器,负责:
- Peer ID 注册和发现
- 公钥存储和分发
- NAT 类型检测
- P2P 连接协调(打洞辅助)
- Relay Server 分配
## 协议消息定义
所有消息使用 Protocol Buffers 定义在 `protos/rendezvous.proto`
```protobuf
message RendezvousMessage {
oneof union {
RegisterPeer register_peer = 6;
RegisterPeerResponse register_peer_response = 7;
PunchHoleRequest punch_hole_request = 8;
PunchHole punch_hole = 9;
PunchHoleSent punch_hole_sent = 10;
PunchHoleResponse punch_hole_response = 11;
FetchLocalAddr fetch_local_addr = 12;
LocalAddr local_addr = 13;
ConfigUpdate configure_update = 14;
RegisterPk register_pk = 15;
RegisterPkResponse register_pk_response = 16;
SoftwareUpdate software_update = 17;
RequestRelay request_relay = 18;
RelayResponse relay_response = 19;
TestNatRequest test_nat_request = 20;
TestNatResponse test_nat_response = 21;
PeerDiscovery peer_discovery = 22;
OnlineRequest online_request = 23;
OnlineResponse online_response = 24;
KeyExchange key_exchange = 25;
HealthCheck hc = 26;
}
}
```
## 核心流程
### 1. Peer 注册流程
**客户端 → 服务器RegisterPeer**
```protobuf
message RegisterPeer {
string id = 1; // Peer ID (如 "123456789")
int32 serial = 2; // 配置序列号
}
```
**服务器处理逻辑:**
```rust
// rustdesk-server/src/rendezvous_server.rs:318-333
Some(rendezvous_message::Union::RegisterPeer(rp)) => {
if !rp.id.is_empty() {
log::trace!("New peer registered: {:?} {:?}", &rp.id, &addr);
self.update_addr(rp.id, addr, socket).await?;
// 如果服务器配置更新,发送 ConfigUpdate
if self.inner.serial > rp.serial {
let mut msg_out = RendezvousMessage::new();
msg_out.set_configure_update(ConfigUpdate {
serial: self.inner.serial,
rendezvous_servers: (*self.rendezvous_servers).clone(),
..Default::default()
});
socket.send(&msg_out, addr).await?;
}
}
}
```
**服务器 → 客户端RegisterPeerResponse**
```protobuf
message RegisterPeerResponse {
bool request_pk = 2; // 是否需要注册公钥
}
```
### 2. 公钥注册流程
当服务器检测到 Peer 的公钥为空或 IP 变化时,会请求注册公钥。
**客户端 → 服务器RegisterPk**
```protobuf
message RegisterPk {
string id = 1; // Peer ID
bytes uuid = 2; // 设备 UUID
bytes pk = 3; // Ed25519 公钥
string old_id = 4; // 旧 ID如果更换
}
```
**服务器处理逻辑:**
```rust
// rustdesk-server/src/rendezvous_server.rs:334-418
Some(rendezvous_message::Union::RegisterPk(rk)) => {
// 验证 UUID 和公钥
if rk.uuid.is_empty() || rk.pk.is_empty() {
return Ok(());
}
let id = rk.id;
let ip = addr.ip().to_string();
// ID 长度检查
if id.len() < 6 {
return send_rk_res(socket, addr, UUID_MISMATCH).await;
}
// IP 封锁检查
if !self.check_ip_blocker(&ip, &id).await {
return send_rk_res(socket, addr, TOO_FREQUENT).await;
}
// UUID 匹配验证
let peer = self.pm.get_or(&id).await;
// ... UUID 验证逻辑 ...
// 更新数据库
if changed {
self.pm.update_pk(id, peer, addr, rk.uuid, rk.pk, ip).await;
}
// 发送成功响应
msg_out.set_register_pk_response(RegisterPkResponse {
result: register_pk_response::Result::OK.into(),
..Default::default()
});
}
```
**服务器 → 客户端RegisterPkResponse**
```protobuf
message RegisterPkResponse {
enum Result {
OK = 0;
UUID_MISMATCH = 2;
ID_EXISTS = 3;
TOO_FREQUENT = 4;
INVALID_ID_FORMAT = 5;
NOT_SUPPORT = 6;
SERVER_ERROR = 7;
}
Result result = 1;
int32 keep_alive = 2; // 心跳间隔
}
```
### 3. Punch Hole 请求流程
当控制端要连接被控端时,首先发送 PunchHoleRequest。
**控制端 → 服务器PunchHoleRequest**
```protobuf
message PunchHoleRequest {
string id = 1; // 目标 Peer ID
NatType nat_type = 2; // 请求方的 NAT 类型
string licence_key = 3; // 许可证密钥
ConnType conn_type = 4; // 连接类型
string token = 5; // 认证令牌
string version = 6; // 客户端版本
}
enum NatType {
UNKNOWN_NAT = 0;
ASYMMETRIC = 1;
SYMMETRIC = 2;
}
enum ConnType {
DEFAULT_CONN = 0;
FILE_TRANSFER = 1;
PORT_FORWARD = 2;
RDP = 3;
VIEW_CAMERA = 4;
}
```
**服务器处理逻辑:**
```rust
// rustdesk-server/src/rendezvous_server.rs:674-765
async fn handle_punch_hole_request(...) {
// 1. 验证许可证密钥
if !key.is_empty() && ph.licence_key != key {
return Ok((PunchHoleResponse { failure: LICENSE_MISMATCH }, None));
}
// 2. 查找目标 Peer
if let Some(peer) = self.pm.get(&id).await {
let (elapsed, peer_addr) = peer.read().await;
// 3. 检查在线状态
if elapsed >= REG_TIMEOUT {
return Ok((PunchHoleResponse { failure: OFFLINE }, None));
}
// 4. 判断是否同一局域网
let same_intranet = (peer_is_lan && is_lan) ||
(peer_addr.ip() == addr.ip());
if same_intranet {
// 请求获取本地地址
msg_out.set_fetch_local_addr(FetchLocalAddr {
socket_addr: AddrMangle::encode(addr).into(),
relay_server,
});
} else {
// 发送 Punch Hole 请求给被控端
msg_out.set_punch_hole(PunchHole {
socket_addr: AddrMangle::encode(addr).into(),
nat_type: ph.nat_type,
relay_server,
});
}
return Ok((msg_out, Some(peer_addr)));
}
// Peer 不存在
Ok((PunchHoleResponse { failure: ID_NOT_EXIST }, None))
}
```
**服务器 → 被控端PunchHole 或 FetchLocalAddr**
```protobuf
message PunchHole {
bytes socket_addr = 1; // 控制端地址(编码)
string relay_server = 2; // Relay 服务器地址
NatType nat_type = 3; // 控制端 NAT 类型
}
message FetchLocalAddr {
bytes socket_addr = 1; // 控制端地址(编码)
string relay_server = 2; // Relay 服务器地址
}
```
### 4. 被控端响应流程
**被控端 → 服务器PunchHoleSent 或 LocalAddr**
```protobuf
message PunchHoleSent {
bytes socket_addr = 1; // 控制端地址
string id = 2; // 被控端 ID
string relay_server = 3; // Relay 服务器
NatType nat_type = 4; // 被控端 NAT 类型
string version = 5; // 客户端版本
}
message LocalAddr {
bytes socket_addr = 1; // 控制端地址
bytes local_addr = 2; // 被控端本地地址
string relay_server = 3; // Relay 服务器
string id = 4; // 被控端 ID
string version = 5; // 客户端版本
}
```
**服务器 → 控制端PunchHoleResponse**
```protobuf
message PunchHoleResponse {
bytes socket_addr = 1; // 被控端地址
bytes pk = 2; // 被控端公钥(已签名)
enum Failure {
ID_NOT_EXIST = 0;
OFFLINE = 2;
LICENSE_MISMATCH = 3;
LICENSE_OVERUSE = 4;
}
Failure failure = 3;
string relay_server = 4;
oneof union {
NatType nat_type = 5;
bool is_local = 6; // 是否为局域网连接
}
string other_failure = 7;
int32 feedback = 8;
}
```
### 5. Relay 请求流程
当 P2P 连接失败或 NAT 类型不支持打洞时,使用 Relay。
**客户端 → 服务器RequestRelay**
```protobuf
message RequestRelay {
string id = 1; // 目标 Peer ID
string uuid = 2; // 连接 UUID用于配对
bytes socket_addr = 3; // 本端地址
string relay_server = 4; // 指定的 Relay 服务器
bool secure = 5; // 是否使用加密
string licence_key = 6; // 许可证密钥
ConnType conn_type = 7; // 连接类型
string token = 8; // 认证令牌
}
```
**服务器 → 客户端RelayResponse**
```protobuf
message RelayResponse {
bytes socket_addr = 1; // 对端地址
string uuid = 2; // 连接 UUID
string relay_server = 3; // Relay 服务器地址
oneof union {
string id = 4; // 对端 ID
bytes pk = 5; // 对端公钥
}
string refuse_reason = 6; // 拒绝原因
string version = 7; // 版本
int32 feedback = 9;
}
```
## NAT 类型检测
**客户端 → 服务器TestNatRequest**
```protobuf
message TestNatRequest {
int32 serial = 1; // 配置序列号
}
```
**服务器 → 客户端TestNatResponse**
```protobuf
message TestNatResponse {
int32 port = 1; // 观测到的源端口
ConfigUpdate cu = 2; // 配置更新
}
```
NAT 检测原理:
1. 客户端同时向主端口21116和 NAT 测试端口21115发送请求
2. 比较两次响应中观测到的源端口
3. 如果端口一致,则为 ASYMMETRIC NAT适合打洞
4. 如果端口不一致,则为 SYMMETRIC NAT需要 Relay
## 地址编码
RustDesk 使用 `AddrMangle` 对 SocketAddr 进行编码:
```rust
// 编码示例
// IPv4: 4 bytes IP + 2 bytes port = 6 bytes
// IPv6: 16 bytes IP + 2 bytes port = 18 bytes
pub fn encode(addr: SocketAddr) -> Vec<u8>;
pub fn decode(bytes: &[u8]) -> SocketAddr;
```
## 安全机制
### 服务器签名
当服务器配置了私钥时,会对 Peer 的公钥进行签名:
```rust
// rustdesk-server/src/rendezvous_server.rs:1160-1182
async fn get_pk(&mut self, version: &str, id: String) -> Bytes {
if version.is_empty() || self.inner.sk.is_none() {
Bytes::new()
} else {
match self.pm.get(&id).await {
Some(peer) => {
let pk = peer.read().await.pk.clone();
// 使用服务器私钥签名 IdPk
sign::sign(
&IdPk { id, pk, ..Default::default() }
.write_to_bytes()
.unwrap_or_default(),
self.inner.sk.as_ref().unwrap(),
).into()
}
_ => Bytes::new(),
}
}
}
```
### IP 封锁
服务器实现了 IP 封锁机制防止滥用:
```rust
// rustdesk-server/src/rendezvous_server.rs:866-894
async fn check_ip_blocker(&self, ip: &str, id: &str) -> bool {
let mut lock = IP_BLOCKER.lock().await;
if let Some(old) = lock.get_mut(ip) {
// 每秒请求超过 30 次则封锁
if counter.0 > 30 {
return false;
}
// 每天超过 300 个不同 ID 则封锁
if counter.0.len() > 300 {
return !is_new;
}
}
true
}
```
## 时序图
### 完整连接建立流程
```
控制端 Rendezvous Server 被控端
│ │ │
│ PunchHoleRequest │ │
├──────────────────────►│ │
│ │ PunchHole │
│ ├──────────────────────►│
│ │ │
│ │ PunchHoleSent │
│ │◄──────────────────────┤
│ PunchHoleResponse │ │
│◄──────────────────────┤ │
│ │ │
│ ─────────── P2P Connection ──────────────────│
│◄─────────────────────────────────────────────►│
```

View File

@@ -1,318 +0,0 @@
# Relay 服务器协议
## 概述
Relay Serverhbbr是 RustDesk 的数据中转服务器,当 P2P 连接无法建立时(如双方都在 Symmetric NAT 后面),所有通信数据通过 Relay Server 转发。
## 服务器架构
### 监听端口
| 端口 | 协议 | 用途 |
|------|------|------|
| 21117 | TCP | 主要中转端口 |
| 21119 | WebSocket | Web 客户端支持 |
### 核心配置
```rust
// rustdesk-server/src/relay_server.rs:40-46
static DOWNGRADE_THRESHOLD_100: AtomicUsize = AtomicUsize::new(66); // 0.66
static DOWNGRADE_START_CHECK: AtomicUsize = AtomicUsize::new(1_800_000); // 30分钟 (ms)
static LIMIT_SPEED: AtomicUsize = AtomicUsize::new(32 * 1024 * 1024); // 32 Mb/s
static TOTAL_BANDWIDTH: AtomicUsize = AtomicUsize::new(1024 * 1024 * 1024);// 1024 Mb/s
static SINGLE_BANDWIDTH: AtomicUsize = AtomicUsize::new(128 * 1024 * 1024);// 128 Mb/s
const BLACKLIST_FILE: &str = "blacklist.txt";
const BLOCKLIST_FILE: &str = "blocklist.txt";
```
## 连接配对机制
### 配对原理
Relay Server 使用 UUID 来配对两个客户端的连接:
1. 第一个客户端连接并发送 `RequestRelay` 消息(包含 UUID
2. 服务器将该连接存储在等待队列中
3. 第二个客户端使用相同的 UUID 连接
4. 服务器将两个连接配对,开始转发数据
### 配对流程
```rust
// rustdesk-server/src/relay_server.rs:425-462
async fn make_pair_(stream: impl StreamTrait, addr: SocketAddr, key: &str, limiter: Limiter) {
let mut stream = stream;
if let Ok(Some(Ok(bytes))) = timeout(30_000, stream.recv()).await {
if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) {
if let Some(rendezvous_message::Union::RequestRelay(rf)) = msg_in.union {
// 验证许可证密钥
if !key.is_empty() && rf.licence_key != key {
log::warn!("Relay authentication failed from {}", addr);
return;
}
if !rf.uuid.is_empty() {
// 尝试查找配对
let mut peer = PEERS.lock().await.remove(&rf.uuid);
if let Some(peer) = peer.as_mut() {
// 找到配对,开始中转
log::info!("Relay request {} got paired", rf.uuid);
relay(addr, &mut stream, peer, limiter).await;
} else {
// 没找到,存储等待配对
log::info!("New relay request {} from {}", rf.uuid, addr);
PEERS.lock().await.insert(rf.uuid.clone(), Box::new(stream));
sleep(30.).await; // 等待 30 秒
PEERS.lock().await.remove(&rf.uuid); // 超时移除
}
}
}
}
}
}
```
## 数据转发
### 转发逻辑
```rust
// rustdesk-server/src/relay_server.rs:464-566
async fn relay(
addr: SocketAddr,
stream: &mut impl StreamTrait,
peer: &mut Box<dyn StreamTrait>,
total_limiter: Limiter,
) -> ResultType<()> {
let limiter = <Limiter>::new(SINGLE_BANDWIDTH.load(Ordering::SeqCst) as f64);
let blacklist_limiter = <Limiter>::new(LIMIT_SPEED.load(Ordering::SeqCst) as _);
loop {
tokio::select! {
// 从 peer 接收数据,发送给 stream
res = peer.recv() => {
if let Some(Ok(bytes)) = res {
// 带宽限制
if blacked || downgrade {
blacklist_limiter.consume(bytes.len() * 8).await;
} else {
limiter.consume(bytes.len() * 8).await;
}
total_limiter.consume(bytes.len() * 8).await;
stream.send_raw(bytes.into()).await?;
} else {
break;
}
},
// 从 stream 接收数据,发送给 peer
res = stream.recv() => {
if let Some(Ok(bytes)) = res {
// 带宽限制
limiter.consume(bytes.len() * 8).await;
total_limiter.consume(bytes.len() * 8).await;
peer.send_raw(bytes.into()).await?;
} else {
break;
}
},
_ = timer.tick() => {
// 超时检测
if last_recv_time.elapsed().as_secs() > 30 {
bail!("Timeout");
}
}
}
// 降级检测
if elapsed > DOWNGRADE_START_CHECK && total > elapsed * downgrade_threshold {
downgrade = true;
log::info!("Downgrade {}, exceed threshold", id);
}
}
Ok(())
}
```
### 原始模式
当两端都支持原始模式时,跳过 protobuf 解析以提高性能:
```rust
// rustdesk-server/src/relay_server.rs:440-444
if !stream.is_ws() && !peer.is_ws() {
peer.set_raw();
stream.set_raw();
log::info!("Both are raw");
}
```
## 带宽控制
### 多级限速
1. **总带宽限制**:整个服务器的总带宽
2. **单连接限制**:每个中转连接的带宽
3. **黑名单限速**:对黑名单 IP 的特殊限制
### 降级机制
当连接持续占用高带宽时,会触发降级:
```rust
// 条件:
// 1. 连接时间 > DOWNGRADE_START_CHECK (30分钟)
// 2. 平均带宽 > SINGLE_BANDWIDTH * 0.66
// 降级后使用 LIMIT_SPEED (32 Mb/s) 限速
if elapsed > DOWNGRADE_START_CHECK.load(Ordering::SeqCst)
&& !downgrade
&& total > elapsed * downgrade_threshold
{
downgrade = true;
}
```
## 安全控制
### 黑名单
用于限速特定 IP
```
# blacklist.txt
192.168.1.100
10.0.0.50
```
### 封锁名单
用于完全拒绝特定 IP
```
# blocklist.txt
1.2.3.4
5.6.7.8
```
### 运行时管理命令
通过本地 TCP 连接(仅限 localhost发送命令
```rust
// rustdesk-server/src/relay_server.rs:152-324
match fds.next() {
Some("h") => // 帮助
Some("blacklist-add" | "ba") => // 添加黑名单
Some("blacklist-remove" | "br") => // 移除黑名单
Some("blacklist" | "b") => // 查看黑名单
Some("blocklist-add" | "Ba") => // 添加封锁名单
Some("blocklist-remove" | "Br") => // 移除封锁名单
Some("blocklist" | "B") => // 查看封锁名单
Some("downgrade-threshold" | "dt") => // 设置降级阈值
Some("downgrade-start-check" | "t") => // 设置降级检测时间
Some("limit-speed" | "ls") => // 设置限速
Some("total-bandwidth" | "tb") => // 设置总带宽
Some("single-bandwidth" | "sb") => // 设置单连接带宽
Some("usage" | "u") => // 查看使用统计
}
```
## 协议消息
### RequestRelay
用于建立中转连接的请求消息:
```protobuf
message RequestRelay {
string id = 1; // 目标 Peer ID
string uuid = 2; // 连接 UUID配对用
bytes socket_addr = 3; // 本端地址
string relay_server = 4; // Relay 服务器
bool secure = 5; // 是否加密
string licence_key = 6; // 许可证密钥
ConnType conn_type = 7; // 连接类型
string token = 8; // 认证令牌
}
```
## 时序图
### 中转连接建立
```
客户端 A Relay Server 客户端 B
│ │ │
│ RequestRelay(uuid) │ │
├─────────────────────────►│ │
│ │ │
│ │ (存储等待配对) │
│ │ │
│ │ RequestRelay(uuid) │
│ │◄───────────────────────────┤
│ │ │
│ │ (配对成功) │
│ │ │
│ ◄────────── 数据转发 ─────────────────────────────────►│
│ │ │
```
### 数据转发
```
客户端 A Relay Server 客户端 B
│ │ │
│ ────[数据]───────► │ │
│ │ ────[数据]───────► │
│ │ │
│ │ ◄───[数据]──────── │
│ ◄───[数据]──────── │ │
│ │ │
```
## 性能优化
### 零拷贝
使用 `Bytes` 类型减少内存拷贝:
```rust
async fn send_raw(&mut self, bytes: Bytes) -> ResultType<()>;
```
### WebSocket 支持
支持 WebSocket 协议以穿越防火墙:
```rust
#[async_trait]
impl StreamTrait for tokio_tungstenite::WebSocketStream<TcpStream> {
async fn recv(&mut self) -> Option<Result<BytesMut, Error>> {
if let Some(msg) = self.next().await {
match msg {
Ok(tungstenite::Message::Binary(bytes)) => {
Some(Ok(bytes[..].into()))
}
// ...
}
}
}
}
```
## 监控指标
服务器跟踪以下指标:
| 指标 | 说明 |
|------|------|
| elapsed | 连接持续时间 (ms) |
| total | 总传输数据量 (bit) |
| highest | 最高瞬时速率 (kb/s) |
| speed | 当前速率 (kb/s) |
通过 `usage` 命令查看:
```
192.168.1.100:12345: 3600s 1024.00MB 50000kb/s 45000kb/s 42000kb/s
```

View File

@@ -1,424 +0,0 @@
# P2P 连接流程
## 概述
RustDesk 优先尝试建立 P2P 直连,只有在直连失败时才使用 Relay 中转。P2P 连接支持多种方式:
- TCP 打洞
- UDP 打洞KCP
- 局域网直连
- IPv6 直连
## 连接决策流程
```
开始连接
┌──────────────┐
│ 是否强制 Relay
└──────┬───────┘
是 │ 否
┌─────────┴─────────┐
▼ ▼
使用 Relay 检查 NAT 类型
┌──────────────┴──────────────┐
│ │
▼ ▼
双方都是对称 NAT 有一方是可穿透 NAT
│ │
是 │ │
▼ ▼
使用 Relay 尝试 P2P 连接
┌─────────────┴─────────────┐
│ │
▼ ▼
同一局域网? 不同网络
│ │
是 │ │
▼ ▼
局域网直连 尝试打洞
┌──────────────┴──────────────┐
│ │
▼ ▼
TCP 打洞成功? UDP 打洞成功?
│ │
是 │ 否 是 │ 否
▼ │ ▼ │
TCP P2P 连接 └───────────► KCP P2P 连接 │
使用 Relay
```
## 客户端连接入口
```rust
// rustdesk/src/client.rs:188-230
impl Client {
pub async fn start(
peer: &str,
key: &str,
token: &str,
conn_type: ConnType,
interface: impl Interface,
) -> ResultType<...> {
// 检查是否为 IP 直连
if hbb_common::is_ip_str(peer) {
return connect_tcp_local(check_port(peer, RELAY_PORT + 1), None, CONNECT_TIMEOUT).await;
}
// 检查是否为域名:端口格式
if hbb_common::is_domain_port_str(peer) {
return connect_tcp_local(peer, None, CONNECT_TIMEOUT).await;
}
// 通过 Rendezvous Server 连接
let (rendezvous_server, servers, _) = crate::get_rendezvous_server(1_000).await;
Self::_start_inner(peer, key, token, conn_type, interface, rendezvous_server, servers).await
}
}
```
## 被控端处理连接请求
### 处理 PunchHole 消息
```rust
// rustdesk/src/rendezvous_mediator.rs:554-619
async fn handle_punch_hole(&self, ph: PunchHole, server: ServerPtr) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&ph.socket_addr);
let relay_server = self.get_relay_server(ph.relay_server);
// 判断是否需要 Relay
if ph.nat_type.enum_value() == Ok(NatType::SYMMETRIC)
|| Config::get_nat_type() == NatType::SYMMETRIC as i32
|| relay
{
// 使用 Relay
let uuid = Uuid::new_v4().to_string();
return self.create_relay(ph.socket_addr, relay_server, uuid, server, true, true).await;
}
// 尝试 UDP 打洞
if ph.udp_port > 0 {
peer_addr.set_port(ph.udp_port as u16);
self.punch_udp_hole(peer_addr, server, msg_punch).await?;
return Ok(());
}
// 尝试 TCP 打洞
log::debug!("Punch tcp hole to {:?}", peer_addr);
let socket = {
let socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// 关键步骤:尝试连接对方,让 NAT 建立映射
allow_err!(socket_client::connect_tcp_local(peer_addr, Some(local_addr), 30).await);
socket
};
// 发送 PunchHoleSent 告知 Rendezvous Server
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(PunchHoleSent {
socket_addr: ph.socket_addr,
id: Config::get_id(),
relay_server,
nat_type: nat_type.into(),
version: crate::VERSION.to_owned(),
});
socket.send_raw(msg_out.write_to_bytes()?).await?;
// 接受控制端连接
crate::accept_connection(server.clone(), socket, peer_addr, true).await;
Ok(())
}
```
### 处理 FetchLocalAddr局域网连接
```rust
// rustdesk/src/rendezvous_mediator.rs:481-552
async fn handle_intranet(&self, fla: FetchLocalAddr, server: ServerPtr) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&fla.socket_addr);
let relay_server = self.get_relay_server(fla.relay_server.clone());
// 尝试局域网直连
if is_ipv4(&self.addr) && !relay && !config::is_disable_tcp_listen() {
if let Err(err) = self.handle_intranet_(fla.clone(), server.clone(), relay_server.clone()).await {
log::debug!("Failed to handle intranet: {:?}, will try relay", err);
} else {
return Ok(());
}
}
// 局域网直连失败,使用 Relay
let uuid = Uuid::new_v4().to_string();
self.create_relay(fla.socket_addr, relay_server, uuid, server, true, true).await
}
async fn handle_intranet_(&self, fla: FetchLocalAddr, server: ServerPtr, relay_server: String) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&fla.socket_addr);
let mut socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// 发送本地地址给 Rendezvous Server
let mut msg_out = Message::new();
msg_out.set_local_addr(LocalAddr {
id: Config::get_id(),
socket_addr: AddrMangle::encode(peer_addr).into(),
local_addr: AddrMangle::encode(local_addr).into(),
relay_server,
version: crate::VERSION.to_owned(),
});
socket.send_raw(msg_out.write_to_bytes()?).await?;
// 接受连接
crate::accept_connection(server.clone(), socket, peer_addr, true).await;
Ok(())
}
```
## UDP 打洞 (KCP)
### 打洞原理
UDP 打洞利用 NAT 的端口映射特性:
1. A 向 Rendezvous Server 注册NAT 创建映射 `A_internal:port1 → A_external:port2`
2. B 同样注册,创建映射 `B_internal:port3 → B_external:port4`
3. A 向 B 的外部地址发送 UDP 包A 的 NAT 创建到 B 的映射
4. B 向 A 的外部地址发送 UDP 包B 的 NAT 创建到 A 的映射
5. 如果 NAT 不是 Symmetric 类型,双方的包可以到达对方
```rust
// rustdesk/src/rendezvous_mediator.rs:621-642
async fn punch_udp_hole(
&self,
peer_addr: SocketAddr,
server: ServerPtr,
msg_punch: PunchHoleSent,
) -> ResultType<()> {
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(msg_punch);
let (socket, addr) = new_direct_udp_for(&self.host).await?;
let data = msg_out.write_to_bytes()?;
// 发送到 Rendezvous Server
socket.send_to(&data, addr).await?;
// 多次尝试发送以增加成功率
let socket_cloned = socket.clone();
tokio::spawn(async move {
for _ in 0..2 {
let tm = (hbb_common::time_based_rand() % 20 + 10) as f32 / 1000.;
hbb_common::sleep(tm).await;
socket.send_to(&data, addr).await.ok();
}
});
// 等待对方连接
udp_nat_listen(socket_cloned.clone(), peer_addr, peer_addr, server).await?;
Ok(())
}
```
### KCP 协议
RustDesk 在 UDP 上使用 KCP 协议提供可靠传输:
```rust
// rustdesk/src/rendezvous_mediator.rs:824-851
async fn udp_nat_listen(
socket: Arc<tokio::net::UdpSocket>,
peer_addr: SocketAddr,
peer_addr_v4: SocketAddr,
server: ServerPtr,
) -> ResultType<()> {
socket.connect(peer_addr).await?;
// 执行 UDP 打洞
let res = crate::punch_udp(socket.clone(), true).await?;
// 建立 KCP 流
let stream = crate::kcp_stream::KcpStream::accept(
socket,
Duration::from_millis(CONNECT_TIMEOUT as _),
res,
).await?;
// 创建连接
crate::server::create_tcp_connection(server, stream.1, peer_addr_v4, true).await?;
Ok(())
}
```
## TCP 打洞
### 原理
TCP 打洞比 UDP 更难,因为 TCP 需要三次握手。基本思路:
1. A 和 B 都尝试同时向对方发起连接
2. 第一个 SYN 包会被对方的 NAT 丢弃(因为没有映射)
3. 但这个 SYN 包会在 A 的 NAT 上创建映射
4. 当 B 的 SYN 包到达 A 的 NAT 时,由于已有映射,会被转发给 A
5. 连接建立
### 实现
```rust
// rustdesk/src/rendezvous_mediator.rs:604-617
log::debug!("Punch tcp hole to {:?}", peer_addr);
let mut socket = {
let socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// 关键:使用相同的本地地址尝试连接对方
// 这会在 NAT 上创建映射,使对方的连接请求能够到达
allow_err!(socket_client::connect_tcp_local(peer_addr, Some(local_addr), 30).await);
socket
};
```
## Relay 连接
当 P2P 失败时,使用 Relay
```rust
// rustdesk/src/rendezvous_mediator.rs:434-479
async fn create_relay(
&self,
socket_addr: Vec<u8>,
relay_server: String,
uuid: String,
server: ServerPtr,
secure: bool,
initiate: bool,
) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&socket_addr);
log::info!(
"create_relay requested from {:?}, relay_server: {}, uuid: {}, secure: {}",
peer_addr, relay_server, uuid, secure,
);
// 连接 Rendezvous Server 发送 RelayResponse
let mut socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let mut msg_out = Message::new();
let mut rr = RelayResponse {
socket_addr: socket_addr.into(),
version: crate::VERSION.to_owned(),
..Default::default()
};
if initiate {
rr.uuid = uuid.clone();
rr.relay_server = relay_server.clone();
rr.set_id(Config::get_id());
}
msg_out.set_relay_response(rr);
socket.send(&msg_out).await?;
// 连接 Relay Server
crate::create_relay_connection(
server,
relay_server,
uuid,
peer_addr,
secure,
is_ipv4(&self.addr),
).await;
Ok(())
}
```
## IPv6 支持
RustDesk 优先尝试 IPv6 连接:
```rust
// rustdesk/src/rendezvous_mediator.rs:808-822
async fn start_ipv6(
peer_addr_v6: SocketAddr,
peer_addr_v4: SocketAddr,
server: ServerPtr,
) -> bytes::Bytes {
crate::test_ipv6().await;
if let Some((socket, local_addr_v6)) = crate::get_ipv6_socket().await {
let server = server.clone();
tokio::spawn(async move {
allow_err!(udp_nat_listen(socket.clone(), peer_addr_v6, peer_addr_v4, server).await);
});
return local_addr_v6;
}
Default::default()
}
```
## 连接状态机
```
┌─────────────────────────────────────────┐
│ │
▼ │
┌───────────┐ ┌────┴────┐
│ 等待连接 │──────PunchHoleRequest──────►│正在连接 │
└───────────┘ └────┬────┘
┌──────────────────────────────┼──────────────────────────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌─────────────┐ ┌─────────────┐
│ P2P TCP │ │ P2P UDP/KCP │ │ Relay │
│ 连接中 │ │ 连接中 │ │ 连接中 │
└─────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
成功 │ 失败 成功 │ 失败 成功 │ 失败
│ │ │ │ │ │
▼ │ ▼ │ ▼ │
┌──────────┐│ ┌──────────┐│ ┌──────────┐│
│已连接 ││ │已连接 ││ │已连接 ││
│(直连) ││ │(UDP) ││ │(中转) ││
└──────────┘│ └──────────┘│ └──────────┘│
│ │ │
└──────────────►尝试 Relay◄───┘ │
│ │
└────────────────────────────────────────┘
```
## 直接连接模式
用户可以配置允许直接 TCP 连接(不经过 Rendezvous Server
```rust
// rustdesk/src/rendezvous_mediator.rs:727-792
async fn direct_server(server: ServerPtr) {
let mut listener = None;
let mut port = get_direct_port(); // 默认 21118
loop {
let disabled = !option2bool(OPTION_DIRECT_SERVER, &Config::get_option(OPTION_DIRECT_SERVER));
if !disabled && listener.is_none() {
match hbb_common::tcp::listen_any(port as _).await {
Ok(l) => {
listener = Some(l);
log::info!("Direct server listening on: {:?}", l.local_addr());
}
Err(err) => {
log::error!("Failed to start direct server: {}", err);
}
}
}
if let Some(l) = listener.as_mut() {
if let Ok(Ok((stream, addr))) = hbb_common::timeout(1000, l.accept()).await {
stream.set_nodelay(true).ok();
log::info!("direct access from {}", addr);
let server = server.clone();
tokio::spawn(async move {
crate::server::create_tcp_connection(server, stream, addr, false).await
});
}
}
}
}
```

View File

@@ -1,574 +0,0 @@
# 消息格式定义
## 概述
RustDesk 使用 Protocol Buffers (protobuf) 定义所有网络消息格式。主要有两个 proto 文件:
- `rendezvous.proto` - Rendezvous/Relay 服务器通信消息
- `message.proto` - 客户端之间通信消息
## Rendezvous 消息 (rendezvous.proto)
### 顶层消息
```protobuf
message RendezvousMessage {
oneof union {
RegisterPeer register_peer = 6;
RegisterPeerResponse register_peer_response = 7;
PunchHoleRequest punch_hole_request = 8;
PunchHole punch_hole = 9;
PunchHoleSent punch_hole_sent = 10;
PunchHoleResponse punch_hole_response = 11;
FetchLocalAddr fetch_local_addr = 12;
LocalAddr local_addr = 13;
ConfigUpdate configure_update = 14;
RegisterPk register_pk = 15;
RegisterPkResponse register_pk_response = 16;
SoftwareUpdate software_update = 17;
RequestRelay request_relay = 18;
RelayResponse relay_response = 19;
TestNatRequest test_nat_request = 20;
TestNatResponse test_nat_response = 21;
PeerDiscovery peer_discovery = 22;
OnlineRequest online_request = 23;
OnlineResponse online_response = 24;
KeyExchange key_exchange = 25;
HealthCheck hc = 26;
}
}
```
### 注册相关
```protobuf
// Peer 注册
message RegisterPeer {
string id = 1; // Peer ID
int32 serial = 2; // 配置序列号
}
message RegisterPeerResponse {
bool request_pk = 2; // 是否需要注册公钥
}
// 公钥注册
message RegisterPk {
string id = 1; // Peer ID
bytes uuid = 2; // 设备 UUID
bytes pk = 3; // Ed25519 公钥
string old_id = 4; // 旧 ID
}
message RegisterPkResponse {
enum Result {
OK = 0;
UUID_MISMATCH = 2;
ID_EXISTS = 3;
TOO_FREQUENT = 4;
INVALID_ID_FORMAT = 5;
NOT_SUPPORT = 6;
SERVER_ERROR = 7;
}
Result result = 1;
int32 keep_alive = 2;
}
```
### 连接协调相关
```protobuf
// 连接类型
enum ConnType {
DEFAULT_CONN = 0;
FILE_TRANSFER = 1;
PORT_FORWARD = 2;
RDP = 3;
VIEW_CAMERA = 4;
}
// NAT 类型
enum NatType {
UNKNOWN_NAT = 0;
ASYMMETRIC = 1; // 可打洞
SYMMETRIC = 2; // 需要中转
}
// Punch Hole 请求
message PunchHoleRequest {
string id = 1; // 目标 Peer ID
NatType nat_type = 2;
string licence_key = 3;
ConnType conn_type = 4;
string token = 5;
string version = 6;
}
// Punch Hole 响应
message PunchHoleResponse {
bytes socket_addr = 1; // 目标地址
bytes pk = 2; // 公钥(已签名)
enum Failure {
ID_NOT_EXIST = 0;
OFFLINE = 2;
LICENSE_MISMATCH = 3;
LICENSE_OVERUSE = 4;
}
Failure failure = 3;
string relay_server = 4;
oneof union {
NatType nat_type = 5;
bool is_local = 6;
}
string other_failure = 7;
int32 feedback = 8;
}
// 服务器转发给被控端
message PunchHole {
bytes socket_addr = 1; // 控制端地址
string relay_server = 2;
NatType nat_type = 3;
}
// 被控端发送给服务器
message PunchHoleSent {
bytes socket_addr = 1;
string id = 2;
string relay_server = 3;
NatType nat_type = 4;
string version = 5;
}
```
### Relay 相关
```protobuf
// Relay 请求
message RequestRelay {
string id = 1;
string uuid = 2; // 配对 UUID
bytes socket_addr = 3;
string relay_server = 4;
bool secure = 5;
string licence_key = 6;
ConnType conn_type = 7;
string token = 8;
}
// Relay 响应
message RelayResponse {
bytes socket_addr = 1;
string uuid = 2;
string relay_server = 3;
oneof union {
string id = 4;
bytes pk = 5;
}
string refuse_reason = 6;
string version = 7;
int32 feedback = 9;
}
```
## 会话消息 (message.proto)
### 顶层消息
```protobuf
message Message {
oneof union {
SignedId signed_id = 3;
PublicKey public_key = 4;
TestDelay test_delay = 5;
VideoFrame video_frame = 6;
LoginRequest login_request = 7;
LoginResponse login_response = 8;
Hash hash = 9;
MouseEvent mouse_event = 10;
AudioFrame audio_frame = 11;
CursorData cursor_data = 12;
CursorPosition cursor_position = 13;
uint64 cursor_id = 14;
KeyEvent key_event = 15;
Clipboard clipboard = 16;
FileAction file_action = 17;
FileResponse file_response = 18;
Misc misc = 19;
Cliprdr cliprdr = 20;
MessageBox message_box = 21;
SwitchSidesResponse switch_sides_response = 22;
VoiceCallRequest voice_call_request = 23;
VoiceCallResponse voice_call_response = 24;
PeerInfo peer_info = 25;
PointerDeviceEvent pointer_device_event = 26;
Auth2FA auth_2fa = 27;
MultiClipboards multi_clipboards = 28;
}
}
```
### 认证相关
```protobuf
// ID 和公钥
message IdPk {
string id = 1;
bytes pk = 2;
}
// 密钥交换
message PublicKey {
bytes asymmetric_value = 1; // X25519 公钥
bytes symmetric_value = 2; // 加密的对称密钥
}
// 签名的 ID
message SignedId {
bytes id = 1; // 签名的 IdPk
}
// 密码哈希挑战
message Hash {
string salt = 1;
string challenge = 2;
}
// 登录请求
message LoginRequest {
string username = 1;
bytes password = 2; // 加密的密码
string my_id = 4;
string my_name = 5;
OptionMessage option = 6;
oneof union {
FileTransfer file_transfer = 7;
PortForward port_forward = 8;
ViewCamera view_camera = 15;
}
bool video_ack_required = 9;
uint64 session_id = 10;
string version = 11;
OSLogin os_login = 12;
string my_platform = 13;
bytes hwid = 14;
}
// 登录响应
message LoginResponse {
oneof union {
string error = 1;
PeerInfo peer_info = 2;
}
bool enable_trusted_devices = 3;
}
// 2FA 认证
message Auth2FA {
string code = 1;
bytes hwid = 2;
}
```
### 视频相关
```protobuf
// 编码后的视频帧
message EncodedVideoFrame {
bytes data = 1;
bool key = 2; // 是否关键帧
int64 pts = 3; // 时间戳
}
message EncodedVideoFrames {
repeated EncodedVideoFrame frames = 1;
}
// 视频帧
message VideoFrame {
oneof union {
EncodedVideoFrames vp9s = 6;
RGB rgb = 7;
YUV yuv = 8;
EncodedVideoFrames h264s = 10;
EncodedVideoFrames h265s = 11;
EncodedVideoFrames vp8s = 12;
EncodedVideoFrames av1s = 13;
}
int32 display = 14; // 显示器索引
}
// 显示信息
message DisplayInfo {
sint32 x = 1;
sint32 y = 2;
int32 width = 3;
int32 height = 4;
string name = 5;
bool online = 6;
bool cursor_embedded = 7;
Resolution original_resolution = 8;
double scale = 9;
}
```
### 输入相关
```protobuf
// 鼠标事件
message MouseEvent {
int32 mask = 1; // 按钮掩码
sint32 x = 2;
sint32 y = 3;
repeated ControlKey modifiers = 4;
}
// 键盘事件
message KeyEvent {
bool down = 1; // 按下/释放
bool press = 2; // 单击
oneof union {
ControlKey control_key = 3;
uint32 chr = 4; // 字符码
uint32 unicode = 5; // Unicode
string seq = 6; // 字符序列
uint32 win2win_hotkey = 7;
}
repeated ControlKey modifiers = 8;
KeyboardMode mode = 9;
}
// 键盘模式
enum KeyboardMode {
Legacy = 0;
Map = 1;
Translate = 2;
Auto = 3;
}
// 控制键枚举(部分)
enum ControlKey {
Unknown = 0;
Alt = 1;
Backspace = 2;
CapsLock = 3;
Control = 4;
Delete = 5;
// ... 更多按键
CtrlAltDel = 100;
LockScreen = 101;
}
```
### 音频相关
```protobuf
// 音频格式
message AudioFormat {
uint32 sample_rate = 1;
uint32 channels = 2;
}
// 音频帧
message AudioFrame {
bytes data = 1; // Opus 编码数据
}
```
### 剪贴板相关
```protobuf
// 剪贴板格式
enum ClipboardFormat {
Text = 0;
Rtf = 1;
Html = 2;
ImageRgba = 21;
ImagePng = 22;
ImageSvg = 23;
Special = 31;
}
// 剪贴板内容
message Clipboard {
bool compress = 1;
bytes content = 2;
int32 width = 3;
int32 height = 4;
ClipboardFormat format = 5;
string special_name = 6;
}
message MultiClipboards {
repeated Clipboard clipboards = 1;
}
```
### 文件传输相关
```protobuf
// 文件操作
message FileAction {
oneof union {
ReadDir read_dir = 1;
FileTransferSendRequest send = 2;
FileTransferReceiveRequest receive = 3;
FileDirCreate create = 4;
FileRemoveDir remove_dir = 5;
FileRemoveFile remove_file = 6;
ReadAllFiles all_files = 7;
FileTransferCancel cancel = 8;
FileTransferSendConfirmRequest send_confirm = 9;
FileRename rename = 10;
ReadEmptyDirs read_empty_dirs = 11;
}
}
// 文件响应
message FileResponse {
oneof union {
FileDirectory dir = 1;
FileTransferBlock block = 2;
FileTransferError error = 3;
FileTransferDone done = 4;
FileTransferDigest digest = 5;
ReadEmptyDirsResponse empty_dirs = 6;
}
}
// 文件传输块
message FileTransferBlock {
int32 id = 1;
sint32 file_num = 2;
bytes data = 3;
bool compressed = 4;
uint32 blk_id = 5;
}
// 文件条目
message FileEntry {
FileType entry_type = 1;
string name = 2;
bool is_hidden = 3;
uint64 size = 4;
uint64 modified_time = 5;
}
```
### 杂项消息
```protobuf
message Misc {
oneof union {
ChatMessage chat_message = 4;
SwitchDisplay switch_display = 5;
PermissionInfo permission_info = 6;
OptionMessage option = 7;
AudioFormat audio_format = 8;
string close_reason = 9;
bool refresh_video = 10;
bool video_received = 12;
BackNotification back_notification = 13;
bool restart_remote_device = 14;
// ... 更多选项
}
}
// Peer 信息
message PeerInfo {
string username = 1;
string hostname = 2;
string platform = 3;
repeated DisplayInfo displays = 4;
int32 current_display = 5;
bool sas_enabled = 6;
string version = 7;
Features features = 9;
SupportedEncoding encoding = 10;
SupportedResolutions resolutions = 11;
string platform_additions = 12;
WindowsSessions windows_sessions = 13;
}
// 选项消息
message OptionMessage {
enum BoolOption {
NotSet = 0;
No = 1;
Yes = 2;
}
ImageQuality image_quality = 1;
BoolOption lock_after_session_end = 2;
BoolOption show_remote_cursor = 3;
BoolOption privacy_mode = 4;
BoolOption block_input = 5;
int32 custom_image_quality = 6;
BoolOption disable_audio = 7;
BoolOption disable_clipboard = 8;
BoolOption enable_file_transfer = 9;
SupportedDecoding supported_decoding = 10;
int32 custom_fps = 11;
// ... 更多选项
}
```
## 消息编码
### 长度前缀
TCP 传输时使用长度前缀编码:
```rust
// hbb_common/src/bytes_codec.rs
pub struct BytesCodec {
state: DecodeState,
raw: bool,
}
impl Decoder for BytesCodec {
type Item = BytesMut;
type Error = std::io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<BytesMut>, Self::Error> {
if self.raw {
// 原始模式:直接返回数据
if buf.is_empty() {
Ok(None)
} else {
Ok(Some(buf.split()))
}
} else {
// 标准模式4 字节长度前缀 + 数据
match self.state {
DecodeState::Head => {
if buf.len() < 4 {
return Ok(None);
}
let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
buf.advance(4);
self.state = DecodeState::Data(len);
self.decode(buf)
}
DecodeState::Data(len) => {
if buf.len() < len {
return Ok(None);
}
let data = buf.split_to(len);
self.state = DecodeState::Head;
Ok(Some(data))
}
}
}
}
}
```
### 加密模式
当启用加密时,消息结构为:
```
┌─────────────┬─────────────┬─────────────────────────┐
│ Length(4) │ Nonce(8) │ Encrypted Data(N) │
└─────────────┴─────────────┴─────────────────────────┘
```

View File

@@ -1,342 +0,0 @@
# 加密机制
## 概述
RustDesk 使用 libsodium (sodiumoxide) 库实现端到端加密,主要包含:
- **Ed25519**: 用于身份签名和验证
- **X25519**: 用于密钥交换
- **ChaCha20-Poly1305**: 用于对称加密
## 密钥类型
### 1. 身份密钥对 (Ed25519)
用于 Peer 身份认证和签名:
```rust
// 生成密钥对
use sodiumoxide::crypto::sign;
let (pk, sk) = sign::gen_keypair();
// pk: sign::PublicKey (32 bytes)
// sk: sign::SecretKey (64 bytes)
```
### 2. 服务器签名密钥
Rendezvous Server 可以配置签名密钥,用于签名 Peer 公钥:
```rust
// rustdesk-server/src/rendezvous_server.rs:1185-1210
fn get_server_sk(key: &str) -> (String, Option<sign::SecretKey>) {
let mut out_sk = None;
let mut key = key.to_owned();
// 如果是 base64 编码的私钥
if let Ok(sk) = base64::decode(&key) {
if sk.len() == sign::SECRETKEYBYTES {
log::info!("The key is a crypto private key");
key = base64::encode(&sk[(sign::SECRETKEYBYTES / 2)..]); // 公钥部分
let mut tmp = [0u8; sign::SECRETKEYBYTES];
tmp[..].copy_from_slice(&sk);
out_sk = Some(sign::SecretKey(tmp));
}
}
// 如果是占位符,生成新密钥对
if key.is_empty() || key == "-" || key == "_" {
let (pk, sk) = crate::common::gen_sk(0);
out_sk = sk;
if !key.is_empty() {
key = pk;
}
}
if !key.is_empty() {
log::info!("Key: {}", key);
}
(key, out_sk)
}
```
### 3. 会话密钥 (X25519 + ChaCha20)
用于客户端之间的加密通信:
```rust
// hbb_common/src/tcp.rs:27-28
#[derive(Clone)]
pub struct Encrypt(pub Key, pub u64, pub u64);
// Key: secretbox::Key (32 bytes)
// u64: 发送计数器
// u64: 接收计数器
```
## 密钥交换流程
### 1. 身份验证
客户端首先交换签名的身份:
```protobuf
message IdPk {
string id = 1; // Peer ID
bytes pk = 2; // Ed25519 公钥
}
message SignedId {
bytes id = 1; // 签名的 IdPk (by server or self)
}
```
### 2. X25519 密钥交换
使用 X25519 ECDH 生成共享密钥:
```rust
// 生成临时密钥对
use sodiumoxide::crypto::box_;
let (our_pk, our_sk) = box_::gen_keypair();
// 计算共享密钥
let shared_secret = box_::curve25519xsalsa20poly1305::scalarmult(&our_sk, &their_pk);
// 派生对称密钥
let symmetric_key = secretbox::Key::from_slice(&shared_secret[..32]).unwrap();
```
### 3. 对称密钥消息
```protobuf
message PublicKey {
bytes asymmetric_value = 1; // X25519 公钥
bytes symmetric_value = 2; // 加密的对称密钥(用于额外安全)
}
```
## 会话加密
### 加密实现
```rust
// hbb_common/src/tcp.rs
impl Encrypt {
pub fn new(key: Key) -> Self {
Self(key, 0, 0) // 初始化计数器为 0
}
// 加密
pub fn enc(&mut self, data: &[u8]) -> Vec<u8> {
self.1 += 1; // 递增发送计数器
let nonce = self.get_nonce(self.1);
let encrypted = secretbox::seal(data, &nonce, &self.0);
// 格式: nonce (8 bytes) + encrypted data
let mut result = Vec::with_capacity(8 + encrypted.len());
result.extend_from_slice(&self.1.to_le_bytes());
result.extend_from_slice(&encrypted);
result
}
// 解密
pub fn dec(&mut self, data: &mut BytesMut) -> io::Result<()> {
if data.len() < 8 + secretbox::MACBYTES {
return Err(io::Error::new(io::ErrorKind::InvalidData, "too short"));
}
// 提取 nonce
let counter = u64::from_le_bytes(data[..8].try_into().unwrap());
// 防重放攻击检查
if counter <= self.2 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "replay attack"));
}
self.2 = counter;
let nonce = self.get_nonce(counter);
let plaintext = secretbox::open(&data[8..], &nonce, &self.0)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "decrypt failed"))?;
data.clear();
data.extend_from_slice(&plaintext);
Ok(())
}
fn get_nonce(&self, counter: u64) -> Nonce {
let mut nonce = [0u8; 24];
nonce[..8].copy_from_slice(&counter.to_le_bytes());
Nonce(nonce)
}
}
```
### 消息格式
加密后的消息结构:
```
┌──────────────────┬─────────────────────────────────────────┐
│ Counter (8B) │ Encrypted Data + MAC (N+16 bytes) │
└──────────────────┴─────────────────────────────────────────┘
```
## 密码验证
### 挑战-响应机制
被控端生成随机盐和挑战,控制端计算哈希响应:
```protobuf
message Hash {
string salt = 1; // 随机盐
string challenge = 2; // 随机挑战
}
```
### 密码处理
```rust
// 客户端计算密码哈希
fn get_password_hash(password: &str, salt: &str) -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.update(password.as_bytes());
hasher.update(salt.as_bytes());
hasher.finalize().to_vec()
}
// 发送加密的密码(使用对称密钥加密)
fn encrypt_password(password_hash: &[u8], symmetric_key: &Key) -> Vec<u8> {
secretbox::seal(password_hash, &nonce, symmetric_key)
}
```
## 服务器公钥验证
### 签名验证
如果 Rendezvous Server 配置了密钥,会签名 Peer 公钥:
```rust
// 服务器签名 IdPk
let signed_id_pk = sign::sign(
&IdPk { id, pk, ..Default::default() }
.write_to_bytes()?,
&server_sk,
);
// 客户端验证
fn verify_server_signature(signed_pk: &[u8], server_pk: &sign::PublicKey) -> Option<IdPk> {
if let Ok(verified) = sign::verify(signed_pk, server_pk) {
return IdPk::parse_from_bytes(&verified).ok();
}
None
}
```
### 客户端获取服务器公钥
```rust
pub async fn get_rs_pk(id: &str) -> ResultType<(String, sign::PublicKey)> {
// 从配置或 Rendezvous Server 获取公钥
let key = Config::get_option("key");
if !key.is_empty() {
if let Ok(pk) = base64::decode(&key) {
if pk.len() == sign::PUBLICKEYBYTES {
return Ok((key, sign::PublicKey::from_slice(&pk).unwrap()));
}
}
}
// ... 从服务器获取
}
```
## TCP 连接加密
### 安全 TCP 握手
```rust
// rustdesk/src/common.rs
pub async fn secure_tcp(conn: &mut Stream, key: &str) -> ResultType<()> {
// 1. 生成临时 X25519 密钥对
let (our_pk, our_sk) = box_::gen_keypair();
// 2. 发送我们的公钥
let mut msg = Message::new();
msg.set_public_key(PublicKey {
asymmetric_value: our_pk.0.to_vec().into(),
..Default::default()
});
conn.send(&msg).await?;
// 3. 接收对方公钥
let msg = conn.next_timeout(CONNECT_TIMEOUT).await?
.ok_or_else(|| anyhow!("timeout"))?;
let their_pk = msg.get_public_key();
// 4. 计算共享密钥
let shared = box_::curve25519xsalsa20poly1305::scalarmult(
&our_sk,
&box_::PublicKey::from_slice(&their_pk.asymmetric_value)?,
);
// 5. 设置加密
conn.set_key(secretbox::Key::from_slice(&shared[..32]).unwrap());
Ok(())
}
```
## 安全特性
### 1. 前向保密
每个会话使用临时密钥对,即使长期密钥泄露,历史会话仍然安全。
### 2. 重放攻击防护
使用递增计数器作为 nonce 的一部分,拒绝旧的或重复的消息。
### 3. 中间人攻击防护
- 服务器签名 Peer 公钥
- 可配置服务器公钥验证
### 4. 密码暴力破解防护
- 使用盐和多次哈希
- 服务器端限流
## 加密算法参数
| 算法 | 密钥大小 | Nonce 大小 | MAC 大小 |
|------|----------|------------|----------|
| Ed25519 | 64 bytes (private), 32 bytes (public) | N/A | 64 bytes |
| X25519 | 32 bytes | N/A | N/A |
| ChaCha20-Poly1305 | 32 bytes | 24 bytes | 16 bytes |
## 密钥生命周期
```
┌─────────────────────────────────────────────────────────────┐
│ 长期密钥 (Ed25519) │
│ ┌─────────────────┐ │
│ │ 设备首次启动时生成 │ │
│ │ 存储在配置文件中 │ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 会话密钥 (X25519) │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 每次连接时生成 │───►│ 用于密钥协商 │ │
│ │ 临时密钥对 │ │ 派生对称密钥 │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 对称密钥 (ChaCha20-Poly1305) │ │
│ │ 用于会话中的所有消息加密 │ │
│ │ 会话结束时销毁 │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

View File

@@ -1,410 +0,0 @@
# NAT 穿透技术
## 概述
RustDesk 实现了多种 NAT 穿透技术,以在不同网络环境下建立 P2P 连接:
- NAT 类型检测
- UDP 打洞
- TCP 打洞
- Relay 中转(作为后备)
## NAT 类型
### 分类
```protobuf
enum NatType {
UNKNOWN_NAT = 0; // 未知
ASYMMETRIC = 1; // 非对称 NAT (Cone NAT) - 可打洞
SYMMETRIC = 2; // 对称 NAT - 通常需要 Relay
}
```
### NAT 类型说明
| 类型 | 描述 | 可打洞 |
|------|------|--------|
| Full Cone | 外部端口固定,任何外部主机可访问 | ✅ 最容易 |
| Restricted Cone | 外部端口固定,仅允许曾发送过数据的 IP | ✅ 容易 |
| Port Restricted Cone | 外部端口固定,仅允许曾发送过数据的 IP:Port | ✅ 可能 |
| Symmetric | 每个目标地址使用不同外部端口 | ❌ 困难 |
## NAT 类型检测
### 检测原理
RustDesk 使用双端口检测法:
1. 客户端向 Rendezvous Server 的主端口 (21116) 发送 TestNatRequest
2. 同时向 NAT 测试端口 (21115) 发送 TestNatRequest
3. 比较两次响应中观测到的源端口
```
客户端 Rendezvous Server
│ │
│ TestNatRequest ────────►│ Port 21116
│ │
│ TestNatRequest ────────►│ Port 21115
│ │
│◄──────── TestNatResponse │ (包含观测到的源端口)
│ │
│ │
│ 比较两次源端口 │
│ 相同 → ASYMMETRIC │
│ 不同 → SYMMETRIC │
```
### 实现代码
**客户端发送检测请求:**
```rust
// rustdesk/src/lib.rs
pub fn test_nat_type() {
tokio::spawn(async move {
let rendezvous_server = Config::get_rendezvous_servers().first().cloned();
if let Some(host) = rendezvous_server {
// 连接主端口
let host = check_port(&host, RENDEZVOUS_PORT);
// 连接 NAT 测试端口
let host2 = crate::increase_port(&host, -1);
// 发送测试请求
let mut msg = RendezvousMessage::new();
msg.set_test_nat_request(TestNatRequest {
serial: Config::get_serial(),
});
// 收集两次响应的端口
let port1 = send_and_get_port(&host, &msg).await;
let port2 = send_and_get_port(&host2, &msg).await;
// 判断 NAT 类型
let nat_type = if port1 == port2 {
NatType::ASYMMETRIC // 可打洞
} else {
NatType::SYMMETRIC // 需要 Relay
};
Config::set_nat_type(nat_type as i32);
}
});
}
```
**服务器响应:**
```rust
// rustdesk-server/src/rendezvous_server.rs:1080-1087
Some(rendezvous_message::Union::TestNatRequest(_)) => {
let mut msg_out = RendezvousMessage::new();
msg_out.set_test_nat_response(TestNatResponse {
port: addr.port() as _, // 返回观测到的源端口
..Default::default()
});
stream.send(&msg_out).await.ok();
}
```
## UDP 打洞
### 原理
UDP 打洞利用 NAT 的端口映射机制:
```
A (内网) B (内网)
│ │
│ ──► NAT_A ──► Internet ──► NAT_B ──► (丢弃) │
│ │
│ │
│ (NAT_A 创建了映射 A:port → A_ext:port_a) │
│ │
│ │
│ (丢弃) ◄── NAT_A ◄── Internet ◄── NAT_B ◄── │
│ │
│ │
│ (NAT_B 创建了映射 B:port → B_ext:port_b) │
│ │
│ ──► NAT_A ──► Internet ──► NAT_B ──► │
│ (NAT_A 的映射存在,包被转发) │
│ │
│ ◄── NAT_A ◄── Internet ◄── NAT_B ◄── │
│ (NAT_B 的映射存在,包被转发) │
│ │
│ ◄───────── 双向通信建立 ──────────► │
```
### 实现
**被控端打洞:**
```rust
// rustdesk/src/rendezvous_mediator.rs:621-642
async fn punch_udp_hole(
&self,
peer_addr: SocketAddr,
server: ServerPtr,
msg_punch: PunchHoleSent,
) -> ResultType<()> {
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(msg_punch);
// 创建 UDP socket
let (socket, addr) = new_direct_udp_for(&self.host).await?;
let data = msg_out.write_to_bytes()?;
// 发送到 Rendezvous Server会转发给控制端
socket.send_to(&data, addr).await?;
// 多次发送以增加成功率
let socket_cloned = socket.clone();
tokio::spawn(async move {
for _ in 0..2 {
let tm = (hbb_common::time_based_rand() % 20 + 10) as f32 / 1000.;
hbb_common::sleep(tm).await;
socket.send_to(&data, addr).await.ok();
}
});
// 等待对方连接
udp_nat_listen(socket_cloned, peer_addr, peer_addr, server).await?;
Ok(())
}
```
**UDP 监听和 KCP 建立:**
```rust
// rustdesk/src/rendezvous_mediator.rs:824-851
async fn udp_nat_listen(
socket: Arc<tokio::net::UdpSocket>,
peer_addr: SocketAddr,
peer_addr_v4: SocketAddr,
server: ServerPtr,
) -> ResultType<()> {
// 连接到对方地址
socket.connect(peer_addr).await?;
// 执行 UDP 打洞
let res = crate::punch_udp(socket.clone(), true).await?;
// 建立 KCP 可靠传输层
let stream = crate::kcp_stream::KcpStream::accept(
socket,
Duration::from_millis(CONNECT_TIMEOUT as _),
res,
).await?;
// 创建连接
crate::server::create_tcp_connection(server, stream.1, peer_addr_v4, true).await?;
Ok(())
}
```
### KCP 协议
RustDesk 在 UDP 上使用 KCP 提供可靠传输KCP 特点:
- 更激进的重传策略
- 更低的延迟
- 可配置的可靠性级别
## TCP 打洞
### 原理
TCP 打洞比 UDP 困难,因为 TCP 需要三次握手。技巧是让双方同时发起连接:
```
A NAT_A NAT_B B
│ │ │ │
│ ─── SYN ───────────────►│─────────│────► (丢弃,无映射) │
│ │ │ │
│ (NAT_A 创建到 B 的映射) │ │ │
│ │ │ │
│ (丢弃,无映射) ◄─────────│─────────│◄─── SYN ───────────── │
│ │ │ │
│ │ │ (NAT_B 创建到 A 的映射) │
│ │ │ │
│ ─── SYN ───────────────►│─────────│────► SYN ───────────► │
│ │ │ (映射存在,转发成功) │
│ │ │ │
│ ◄─── SYN+ACK ──────────│─────────│◄─── SYN+ACK ───────── │
│ │ │ │
│ ─── ACK ───────────────►│─────────│────► ACK ───────────► │
│ │ │ │
│ ◄─────────── 连接建立 ─────────────────────────────────────►│
```
### 实现
```rust
// rustdesk/src/rendezvous_mediator.rs:604-617
log::debug!("Punch tcp hole to {:?}", peer_addr);
let mut socket = {
// 1. 先连接 Rendezvous Server 获取本地地址
let socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// 2. 用相同的本地地址尝试连接对方
// 这会在 NAT 上创建映射
// 虽然连接会失败,但映射已建立
allow_err!(socket_client::connect_tcp_local(peer_addr, Some(local_addr), 30).await);
socket
};
// 3. 发送 PunchHoleSent 通知服务器
// 服务器会转发给控制端
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(msg_punch);
socket.send_raw(msg_out.write_to_bytes()?).await?;
// 4. 等待控制端连接
// 由于已有映射,控制端的连接可以成功
crate::accept_connection(server.clone(), socket, peer_addr, true).await;
```
## 局域网直连
### 检测同一局域网
```rust
// rustdesk-server/src/rendezvous_server.rs:721-728
let same_intranet: bool = !ws
&& (peer_is_lan && is_lan || {
match (peer_addr, addr) {
(SocketAddr::V4(a), SocketAddr::V4(b)) => a.ip() == b.ip(),
(SocketAddr::V6(a), SocketAddr::V6(b)) => a.ip() == b.ip(),
_ => false,
}
});
```
### 局域网连接流程
```
控制端 Rendezvous Server 被控端
│ │ │
│ PunchHoleRequest ────►│ │
│ │ │
│ │ (检测到同一局域网) │
│ │ │
│ │ FetchLocalAddr ──────►│
│ │ │
│ │◄────── LocalAddr ────────│
│ │ (包含被控端内网地址) │
│ │ │
│◄─ PunchHoleResponse ──│ │
│ (is_local=true) │ │
│ (socket_addr=内网地址)│ │
│ │ │
│ ─────────── 直接连接内网地址 ────────────────────►│
```
## IPv6 支持
IPv6 通常不需要 NAT 穿透,但 RustDesk 仍支持 IPv6 打洞以处理有状态防火墙:
```rust
// rustdesk/src/rendezvous_mediator.rs:808-822
async fn start_ipv6(
peer_addr_v6: SocketAddr,
peer_addr_v4: SocketAddr,
server: ServerPtr,
) -> bytes::Bytes {
crate::test_ipv6().await;
if let Some((socket, local_addr_v6)) = crate::get_ipv6_socket().await {
let server = server.clone();
tokio::spawn(async move {
allow_err!(udp_nat_listen(socket.clone(), peer_addr_v6, peer_addr_v4, server).await);
});
return local_addr_v6;
}
Default::default()
}
```
## 连接策略决策树
```
开始连接
┌───────────────┐
│ NAT 类型检测 │
└───────┬───────┘
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
ASYMMETRIC UNKNOWN SYMMETRIC
│ │ │
▼ ▼ │
┌──────────┐ ┌──────────┐ │
│ 尝试 UDP │ │ 尝试 TCP │ │
│ 打洞 │ │ 打洞 │ │
└────┬─────┘ └────┬─────┘ │
│ │ │
成功 │ 失败 成功 │ 失败 │
▼ │ ▼ │ │
┌────────┐│ ┌────────┐│ │
│UDP P2P ││ │TCP P2P ││ │
└────────┘│ └────────┘│ │
│ │ │
└───────┬───────┘ │
│ │
▼ │
┌───────────────┐ │
│ 使用 Relay │◄─────────┘
└───────────────┘
```
## 性能优化
### 多路径尝试
RustDesk 同时尝试多种连接方式,选择最快成功的:
```rust
// rustdesk/src/client.rs:342-364
let mut connect_futures = Vec::new();
// 同时尝试 UDP 和 TCP
if udp.0.is_some() {
connect_futures.push(Self::_start_inner(..., udp).boxed());
}
connect_futures.push(Self::_start_inner(..., (None, None)).boxed());
// 使用 select_ok 选择第一个成功的
match select_ok(connect_futures).await {
Ok(conn) => Ok(conn),
Err(e) => Err(e),
}
```
### 超时控制
```rust
const CONNECT_TIMEOUT: u64 = 18_000; // 18 秒
const REG_TIMEOUT: i32 = 30_000; // 30 秒
// 连接超时处理
if let Ok(Ok((stream, addr))) = timeout(CONNECT_TIMEOUT, socket.accept()).await {
// 连接成功
} else {
// 超时,尝试其他方式
}
```
## 常见问题和解决方案
| 问题 | 原因 | 解决方案 |
|------|------|----------|
| 双 Symmetric NAT | 两端都是对称 NAT | 使用 Relay |
| 防火墙阻止 UDP | 企业防火墙 | 使用 TCP 或 WebSocket |
| 端口预测失败 | NAT 端口分配不规律 | 多次尝试或使用 Relay |
| IPv6 不通 | ISP 或防火墙问题 | 回退到 IPv4 |

View File

@@ -1,401 +0,0 @@
# RustDesk 协议 vs One-KVM 实现对比分析
本文档对比分析 RustDesk 原始协议与 One-KVM 的实现差异。
## 1. 概述
One-KVM 作为 IP-KVM 解决方案,只实现了 RustDesk 协议的**被控端Controlled** 功能不实现控制端Controller功能。这是设计决策因为 KVM 设备只需要接收远程控制,不需要控制其他设备。
### 架构差异
| 方面 | RustDesk 原版 | One-KVM |
|------|---------------|---------|
| 角色 | 双向(控制端+被控端) | 单向(仅被控端) |
| 连接方式 | P2P + Relay | 仅 Relay (TCP) |
| NAT 穿透 | UDP/TCP 打洞 + TURN | 不支持 |
| 传输协议 | UDP/TCP | 仅 TCP |
## 2. 已实现功能
### 2.1 Rendezvous 协议 (hbbs 通信)
| 消息类型 | 实现状态 | 备注 |
|----------|----------|------|
| RegisterPeer | ✅ 已实现 | 注册设备到服务器 |
| RegisterPeerResponse | ✅ 已实现 | 处理注册响应 |
| RegisterPk | ✅ 已实现 | 注册公钥 |
| RegisterPkResponse | ✅ 已实现 | 处理公钥注册响应 |
| PunchHoleSent | ✅ 已实现 | 响应打洞请求 |
| FetchLocalAddr | ✅ 已实现 | 获取本地地址 |
| LocalAddr | ✅ 已实现 | 返回本地地址 |
| RequestRelay | ✅ 已实现 | 请求中继连接 |
| RelayResponse | ✅ 已实现 | 处理中继响应 |
| ConfigUpdate | ✅ 已实现 | 接收配置更新 |
**实现文件**: `src/rustdesk/rendezvous.rs` (~829 行)
```rust
// 核心结构
pub struct RendezvousMediator {
config: RustDeskConfig,
key_pair: KeyPair,
signing_key: SigningKeyPair,
socket: UdpSocket,
status: Arc<RwLock<RendezvousStatus>>,
// ...
}
```
### 2.2 连接协议 (客户端连接)
| 消息类型 | 实现状态 | 备注 |
|----------|----------|------|
| SignedId | ✅ 已实现 | 签名身份验证 |
| PublicKey | ✅ 已实现 | 公钥交换 |
| Hash | ✅ 已实现 | 哈希挑战响应 |
| LoginRequest | ✅ 已实现 | 登录认证 |
| LoginResponse | ✅ 已实现 | 登录响应 |
| TestDelay | ✅ 已实现 | 延迟测试 |
| VideoFrame | ✅ 已实现 | 视频帧发送 |
| AudioFrame | ✅ 已实现 | 音频帧发送 |
| CursorData | ✅ 已实现 | 光标图像 |
| CursorPosition | ✅ 已实现 | 光标位置 |
| MouseEvent | ✅ 已实现 | 鼠标事件接收 |
| KeyEvent | ✅ 已实现 | 键盘事件接收 |
**实现文件**: `src/rustdesk/connection.rs` (~1349 行)
```rust
// 连接状态机
pub enum ConnectionState {
WaitingForSignedId,
WaitingForPublicKey,
WaitingForHash,
WaitingForLogin,
Authenticated,
Streaming,
}
```
### 2.3 加密模块
| 功能 | 实现状态 | 备注 |
|------|----------|------|
| Curve25519 密钥对 | ✅ 已实现 | 用于加密 |
| Ed25519 签名密钥对 | ✅ 已实现 | 用于签名 |
| Ed25519 → Curve25519 转换 | ✅ 已实现 | 密钥派生 |
| XSalsa20-Poly1305 | ✅ 已实现 | 会话加密 (secretbox) |
| 密码哈希 | ✅ 已实现 | 单重/双重 SHA256 |
| 会话密钥协商 | ✅ 已实现 | 对称密钥派生 |
**实现文件**: `src/rustdesk/crypto.rs` (~468 行)
```rust
// 密钥对结构
pub struct KeyPair {
secret_key: [u8; 32], // Curve25519 私钥
public_key: [u8; 32], // Curve25519 公钥
}
pub struct SigningKeyPair {
secret_key: [u8; 64], // Ed25519 私钥
public_key: [u8; 32], // Ed25519 公钥
}
```
### 2.4 视频/音频流
| 编码格式 | 实现状态 | 备注 |
|----------|----------|------|
| H.264 | ✅ 已实现 | 主要格式 |
| H.265/HEVC | ✅ 已实现 | 高效编码 |
| VP8 | ✅ 已实现 | WebRTC 兼容 |
| VP9 | ✅ 已实现 | 高质量 |
| AV1 | ✅ 已实现 | 新一代编码 |
| Opus 音频 | ✅ 已实现 | 低延迟音频 |
**实现文件**: `src/rustdesk/frame_adapters.rs` (~316 行)
### 2.5 HID 事件
| 功能 | 实现状态 | 备注 |
|------|----------|------|
| 鼠标移动 | ✅ 已实现 | 绝对/相对坐标 |
| 鼠标按键 | ✅ 已实现 | 左/中/右键 |
| 鼠标滚轮 | ✅ 已实现 | 垂直滚动 |
| 键盘按键 | ✅ 已实现 | 按下/释放 |
| 控制键映射 | ✅ 已实现 | ControlKey → USB HID |
| X11 键码映射 | ✅ 已实现 | X11 → USB HID |
**实现文件**: `src/rustdesk/hid_adapter.rs` (~386 行)
### 2.6 协议帧编码
| 功能 | 实现状态 | 备注 |
|------|----------|------|
| BytesCodec | ✅ 已实现 | 变长帧编码 |
| 1-4 字节头 | ✅ 已实现 | 根据长度自动选择 |
| 最大 1GB 消息 | ✅ 已实现 | 与原版一致 |
**实现文件**: `src/rustdesk/bytes_codec.rs` (~253 行)
## 3. 未实现功能
### 3.1 NAT 穿透相关
| 功能 | 原因 |
|------|------|
| UDP 打洞 | One-KVM 仅使用 TCP 中继 |
| TCP 打洞 | 同上 |
| STUN/TURN | 不需要 NAT 类型检测 |
| TestNat | 同上 |
| P2P 直连 | 设计简化,仅支持中继 |
### 3.2 客户端发起功能
| 功能 | 原因 |
|------|------|
| PunchHole (发起) | KVM 只接收连接 |
| RelayRequest | 同上 |
| ConnectPeer | 同上 |
| OnlineRequest | 不需要查询其他设备 |
### 3.3 文件传输
| 功能 | 原因 |
|------|------|
| FileTransfer | 超出 KVM 功能范围 |
| FileAction | 同上 |
| FileResponse | 同上 |
| FileTransferBlock | 同上 |
### 3.4 高级功能
| 功能 | 原因 |
|------|------|
| 剪贴板同步 | 超出 KVM 功能范围 |
| 多显示器切换 | One-KVM 使用单一视频源 |
| 虚拟显示器 | 不适用 |
| 端口转发 | 超出 KVM 功能范围 |
| 语音通话 | 不需要 |
| RDP 输入 | 不需要 |
| 插件系统 | 不支持 |
| 软件更新 | One-KVM 有自己的更新机制 |
### 3.5 权限协商
| 功能 | 原因 |
|------|------|
| Option 消息 | One-KVM 假设完全控制权限 |
| 权限请求 | 同上 |
| PermissionInfo | 同上 |
## 4. 实现差异
### 4.1 连接模式
**RustDesk 原版:**
```
客户端 ──UDP打洞──> 被控端 (P2P 优先)
└──Relay──> 被控端 (回退)
```
**One-KVM:**
```
RustDesk客户端 ──TCP中继──> hbbr服务器 ──> One-KVM设备
```
One-KVM 只支持 TCP 中继连接,不支持 P2P 直连。这简化了实现,但可能增加延迟。
### 4.2 会话加密
**RustDesk 原版:**
- 支持 ChaCha20-Poly1305 (流式)
- 支持 XSalsa20-Poly1305 (secretbox)
- 动态协商加密方式
**One-KVM:**
- 仅支持 XSalsa20-Poly1305 (secretbox)
- 使用序列号作为 nonce
```rust
// One-KVM 的加密实现
fn encrypt_message(&mut self, plaintext: &[u8]) -> Vec<u8> {
let nonce = make_nonce(&self.send_nonce);
self.send_nonce = self.send_nonce.wrapping_add(1);
secretbox::seal(plaintext, &nonce, &self.session_key)
}
```
### 4.3 视频流方向
**RustDesk 原版:**
- 双向视频流(可控制和被控制)
- 远程桌面捕获
**One-KVM:**
- 单向视频流(仅发送)
- 从 V4L2 设备捕获
- 集成到 One-KVM 的 VideoStreamManager
```rust
// One-KVM 视频流集成
pub async fn start_video_stream(&self, state: &AppState) {
let stream_manager = &state.video_stream_manager;
// 从 One-KVM 的视频管理器获取帧
}
```
### 4.4 HID 事件处理
**RustDesk 原版:**
- 转发到远程系统的输入子系统
- 使用 enigo 或 uinput
**One-KVM:**
- 转发到 USB OTG/HID 设备
- 控制物理 KVM 目标机器
```rust
// One-KVM HID 适配
pub fn convert_mouse_event(event: &RustDeskMouseEvent) -> Option<OneKvmMouseEvent> {
// 转换 RustDesk 鼠标事件到 One-KVM HID 事件
}
pub fn convert_key_event(event: &RustDeskKeyEvent) -> Option<OneKvmKeyEvent> {
// 转换 RustDesk 键盘事件到 One-KVM HID 事件
}
```
### 4.5 配置管理
**RustDesk 原版:**
- 使用 TOML/JSON 配置文件
- 硬编码默认值
**One-KVM:**
- 集成到 SQLite 配置系统
- Web UI 管理
- 使用 typeshare 生成 TypeScript 类型
```rust
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustDeskConfig {
pub enabled: bool,
pub rendezvous_server: String,
pub device_id: String,
// ...
}
```
### 4.6 设备 ID 生成
**RustDesk 原版:**
- 基于 MAC 地址和硬件信息
- 固定便携式 ID
**One-KVM:**
- 随机生成 9 位数字
- 存储在配置中
```rust
pub fn generate_device_id() -> String {
let mut rng = rand::thread_rng();
let id: u32 = rng.gen_range(100_000_000..999_999_999);
id.to_string()
}
```
## 5. 协议兼容性
### 5.1 完全兼容
| 功能 | 说明 |
|------|------|
| Rendezvous 注册 | 可与官方 hbbs 服务器通信 |
| 中继连接 | 可通过官方 hbbr 服务器中继 |
| 加密握手 | 与 RustDesk 客户端兼容 |
| 视频编码 | 支持所有主流编码格式 |
| HID 事件 | 接收标准 RustDesk 输入事件 |
### 5.2 部分兼容
| 功能 | 说明 |
|------|------|
| 密码认证 | 仅支持设备密码,不支持一次性密码 |
| 会话加密 | 仅 XSalsa20-Poly1305 |
### 5.3 不兼容
| 功能 | 说明 |
|------|------|
| P2P 连接 | 客户端必须通过中继连接 |
| 文件传输 | 不支持 |
| 剪贴板 | 不支持 |
## 6. 代码结构对比
### RustDesk 原版结构
```
rustdesk/
├── libs/hbb_common/ # 公共库
│ ├── protos/ # Protobuf 定义
│ └── src/
├── src/
│ ├── server/ # 被控端服务
│ ├── client/ # 控制端
│ ├── ui/ # 用户界面
│ └── rendezvous_mediator.rs
```
### One-KVM 结构
```
src/rustdesk/
├── mod.rs # 模块导出
├── config.rs # 配置类型 (~164 行)
├── crypto.rs # 加密模块 (~468 行)
├── bytes_codec.rs # 帧编码 (~253 行)
├── protocol.rs # 消息辅助 (~170 行)
├── rendezvous.rs # Rendezvous 中介 (~829 行)
├── connection.rs # 连接处理 (~1349 行)
├── hid_adapter.rs # HID 转换 (~386 行)
└── frame_adapters.rs # 视频/音频适配 (~316 行)
```
**总计**: ~3935 行代码
## 7. 总结
### 实现率统计
| 类别 | RustDesk 功能数 | One-KVM 实现数 | 实现率 |
|------|-----------------|----------------|--------|
| Rendezvous 协议 | 15+ | 10 | ~67% |
| 连接协议 | 30+ | 12 | ~40% |
| 加密功能 | 8 | 6 | 75% |
| 视频/音频 | 6 | 6 | 100% |
| HID 功能 | 6 | 6 | 100% |
### 设计理念
One-KVM 的 RustDesk 实现专注于 **IP-KVM 核心功能**:
1. **精简**: 只实现必要的被控端功能
2. **可靠**: 使用 TCP 中继保证连接稳定性
3. **集成**: 与 One-KVM 现有视频/HID 系统无缝集成
4. **安全**: 完整实现加密和认证机制
### 客户端兼容性
One-KVM 可与标准 RustDesk 客户端配合使用:
- RustDesk 桌面客户端 (Windows/macOS/Linux)
- RustDesk 移动客户端 (Android/iOS)
- RustDesk Web 客户端
只需确保:
1. 配置相同的 Rendezvous 服务器
2. 使用设备 ID 和密码连接
3. 客户端支持中继连接

View File

@@ -1,920 +0,0 @@
# One-KVM 系统架构文档
## 1. 项目概述
One-KVM 是一个用 Rust 编写的轻量级、开源 IP-KVM 解决方案。它提供 BIOS 级别的远程服务器管理能力,支持视频流、键鼠控制、虚拟存储、电源管理和音频等功能。
### 1.1 核心特性
- **单一二进制部署**Web UI + 后端一体化,无需额外配置文件
- **双流模式**:支持 WebRTCH264/H265/VP8/VP9和 MJPEG 两种流模式
- **USB OTG**:虚拟键鼠、虚拟存储、虚拟网卡
- **ATX 电源控制**GPIO/USB 继电器
- **RustDesk 协议集成**:支持跨平台访问
- **Vue3 SPA 前端**:支持中文/英文
- **SQLite 配置存储**:无需配置文件
### 1.2 目标平台
| 平台 | 架构 | 用途 |
|------|------|------|
| aarch64-unknown-linux-gnu | ARM64 | 主要目标Rockchip RK3328 等) |
| armv7-unknown-linux-gnueabihf | ARMv7 | 备选平台 |
| x86_64-unknown-linux-gnu | x86-64 | 开发/测试环境 |
---
## 2. 系统架构图
### 2.1 整体架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ One-KVM System │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Web Frontend (Vue3) │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Console │ │ Settings │ │ Login │ │ Setup │ │ Virtual │ │ │
│ │ │ View │ │ View │ │ View │ │ View │ │ Keyboard │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ │ │ │ │
│ │ ┌─────────────────┴─────────────────┐ │ │
│ │ │ Pinia State Store │ │ │
│ │ └─────────────────┬─────────────────┘ │ │
│ │ │ │ │
│ │ ┌──────────────────────────────────────────────────────────────┐ │ │
│ │ │ API Client Layer │ │ │
│ │ │ HTTP REST │ WebSocket │ WebRTC Signaling │ MJPEG │ │ │
│ │ └──────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ HTTP/WS/WebRTC │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Axum Web Server (routes.rs) │ │
│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │
│ │ │ Public │ │ User │ │ Admin │ │ Static │ │ │
│ │ │ Routes │ │ Routes │ │ Routes │ │ Files │ │ │
│ │ └───────────┘ └───────────┘ └───────────┘ └───────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ AppState (state.rs) │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ Central State Hub │ │ │
│ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ │
│ │ │ │ConfigStore │ │SessionStore│ │ UserStore │ │ │ │
│ │ │ │ (SQLite) │ │ (Memory) │ │ (SQLite) │ │ │ │
│ │ │ └────────────┘ └────────────┘ └────────────┘ │ │ │
│ │ │ │ │ │
│ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ │
│ │ │ │ EventBus │ │ OtgService │ │ Extensions │ │ │ │
│ │ │ │ (Broadcast)│ │ (USB) │ │ Manager │ │ │ │
│ │ │ └────────────┘ └────────────┘ └────────────┘ │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────┼─────────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ Video │ │ HID │ │ Audio │ │
│ │ Module │ │ Module │ │ Module │ │
│ ├────────────┤ ├────────────┤ ├────────────┤ │
│ │ Capture │ │ Controller │ │ Capture │ │
│ │ Encoder │ │ OTG Backend│ │ Encoder │ │
│ │ Streamer │ │ CH9329 │ │ Pipeline │ │
│ │ Pipeline │ │ Monitor │ │ (Opus) │ │
│ │ Manager │ │ DataChan │ │ Shared │ │
│ └────────────┘ └────────────┘ └────────────┘ │
│ │ │ │ │
│ └───────────────────────────┼──────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────┼─────────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ MSD │ │ ATX │ │ RustDesk │ │
│ │ Module │ │ Module │ │ Module │ │
│ ├────────────┤ ├────────────┤ ├────────────┤ │
│ │ Controller │ │ Controller │ │ Service │ │
│ │ Image Mgr │ │ Executor │ │ Rendezvous │ │
│ │ Ventoy │ │ LED Monitor│ │ Connection │ │
│ │ Drive │ │ WOL │ │ Protocol │ │
│ └────────────┘ └────────────┘ └────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Hardware Layer │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ V4L2 Video │ │ USB OTG │ │ GPIO │ │ ALSA │ │
│ │ Device │ │ Gadget │ │ Sysfs │ │ Audio │ │
│ │/dev/video* │ │ ConfigFS │ │ │ │ │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 2.2 数据流架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Data Flow Overview │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────┐
│ Target PC │
└────────┬────────┘
┌────────────────────────┼────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ HDMI Capture │ │ USB Port │ │ GPIO/Relay │
│ Card │ │ (OTG Mode) │ │ (ATX) │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ /dev/video0 │ │ /dev/hidg* │ │ /sys/class/ │
│ (V4L2) │ │ (USB Gadget) │ │ gpio/gpio* │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ One-KVM Application │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Video │ │ HID │ │ ATX │ │
│ │ Pipeline │ │ Controller │ │ Controller │ │
│ └─────┬───────┘ └─────┬───────┘ └─────┬───────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Event Bus │ │
│ │ (tokio broadcast channel) │ │
│ └───────────────────────────────────────────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Web Server (Axum) │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ MJPEG │ │ WebRTC │ │WebSocket │ │ │
│ │ │ Stream │ │ Stream │ │ Events │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ Client Browser │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Video │ │ Input │ │ Control │ │
│ │ Display │ │ Events │ │ Panel │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
---
## 3. 模块依赖关系
### 3.1 模块层次图
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Application Layer │
├─────────────────────────────────────────────────────────────────────────────┤
│ main.rs ──► state.rs ──► web/routes.rs │
│ │ │
│ ┌───────────┼───────────┬───────────┬───────────┬───────────┐ │
│ │ │ │ │ │ │ │
│ ▼ ▼ ▼ ▼ ▼ ▼ │
│ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │video/│ │ hid/ │ │ msd/ │ │ atx/ │ │audio/│ │webrtc│ │
│ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ │
│ │ │ │ │ │ │ │
│ │ └──────────┼──────────┘ │ │ │
│ │ │ │ │ │
│ │ ┌─────▼─────┐ │ │ │
│ │ │ otg/ │ │ │ │
│ │ │ (OtgSvc) │ │ │ │
│ │ └───────────┘ │ │ │
│ │ │ │ │
│ └──────────────────────────────────────────┼──────────┘ │
│ │ │
├─────────────────────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ config/ │ │ auth/ │ │ events/ │ │extensions│ │
│ │(ConfigSt)│ │(Session) │ │(EventBus)│ │(ExtMgr) │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ rustdesk/ (RustDeskService) │ │
│ │ connection.rs │ rendezvous.rs │ crypto.rs │ protocol.rs │ │
│ └───────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 3.2 依赖矩阵
| 模块 | 依赖的模块 |
|------|-----------|
| `main.rs` | state, config, auth, video, hid, msd, atx, audio, webrtc, web, rustdesk, events |
| `state.rs` | config, auth, video, hid, msd, atx, audio, webrtc, rustdesk, events, otg |
| `video/` | events, hwcodec (外部) |
| `hid/` | otg, events |
| `msd/` | otg, events |
| `atx/` | events |
| `audio/` | events |
| `webrtc/` | video, audio, hid, events |
| `web/` | state, auth, config, video, hid, msd, atx, audio, webrtc, events |
| `rustdesk/` | video, audio, hid, events |
| `otg/` | (无内部依赖) |
| `config/` | (无内部依赖) |
| `auth/` | config |
| `events/` | (无内部依赖) |
---
## 4. 核心组件详解
### 4.1 AppState (state.rs)
AppState 是整个应用的状态中枢,通过 `Arc` 包装的方式在所有 handler 之间共享。
```rust
pub struct AppState {
// 配置和存储
config: ConfigStore, // SQLite 配置存储
sessions: SessionStore, // 会话存储(内存)
users: UserStore, // SQLite 用户存储
// 核心服务
otg_service: Arc<OtgService>, // USB Gadget 统一管理HID/MSD 生命周期协调者)
stream_manager: Arc<VideoStreamManager>, // 视频流管理器MJPEG/WebRTC
hid: Arc<HidController>, // HID 控制器(键鼠控制)
msd: Arc<RwLock<Option<MsdController>>>, // MSD 控制器可选虚拟U盘
atx: Arc<RwLock<Option<AtxController>>>, // ATX 控制器(可选,电源控制)
audio: Arc<AudioController>, // 音频控制器ALSA + Opus
rustdesk: Arc<RwLock<Option<Arc<RustDeskService>>>>, // RustDesk可选远程访问
extensions: Arc<ExtensionManager>,// 扩展管理器ttyd, gostc, easytier
// 通信和生命周期
events: Arc<EventBus>, // 事件总线tokio broadcast channel
shutdown_tx: broadcast::Sender<()>, // 关闭信号
data_dir: PathBuf, // 数据目录
}
```
### 4.2 视频流管道
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Video Pipeline Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
┌───────────────────┐
│ V4L2 Device │
│ /dev/video0 │
└─────────┬─────────┘
│ Raw MJPEG/YUYV/NV12
┌───────────────────┐
│ VideoCapturer │ ◄─── src/video/capture.rs
│ (capture.rs) │
└─────────┬─────────┘
│ VideoFrame
┌───────────────────────────────────────────────────────────────────────────┐
│ SharedVideoPipeline │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Decode Stage │ │
│ │ ┌─────────────┐ │ │
│ │ │ MJPEG → YUV │ turbojpeg / VAAPI │ │
│ │ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Convert Stage │ │
│ │ ┌─────────────┐ │ │
│ │ │YUV → Target │ libyuv (SIMD accelerated) │ │
│ │ │ Format │ │ │
│ │ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Encode Stage │ │
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
│ │ │ H264 │ │ H265 │ │ VP8 │ │ VP9 │ │ │
│ │ │Encoder │ │Encoder │ │Encoder │ │Encoder │ │ │
│ │ └────────┘ └────────┘ └────────┘ └────────┘ │ │
│ │ │ (VAAPI/RKMPP/V4L2 M2M/Software) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────────────┘
├──────────────────────────────┬──────────────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
│ MJPEG Streamer │ │ WebRTC Streamer │ │ RustDesk Service │
│ (HTTP Stream) │ │ (RTP Packets) │ │ (P2P Stream) │
│ │ │ │ │ │
│ - HTTP/1.1 │ │ - DataChannel │ │ - TCP/UDP Relay │
│ - multipart/x- │ │ - SRTP │ │ - NaCl Encrypted │
│ mixed-replace │ │ - ICE/STUN/TURN │ │ - Rendezvous │
└───────────────────┘ └───────────────────┘ └───────────────────┘
│ │ │
▼ ▼ ▼
┌───────────────────────────────────────────────────────────────────────────┐
│ Clients │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Browser │ │ Browser │ │ RustDesk Client │ │
│ │ (MJPEG) │ │ (WebRTC) │ │ (Desktop/Mobile) │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└───────────────────────────────────────────────────────────────────────────┘
```
### 4.3 OTG 服务架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ OTG Service Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ OtgService (service.rs) │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Public Interface │ │
│ │ enable_hid() │ disable_hid() │ enable_msd() │ disable_msd() │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ OtgGadgetManager (manager.rs) │ │
│ │ ┌───────────────────────────────────────────────────────────────┐ │ │
│ │ │ Gadget Lifecycle │ │ │
│ │ │ create_gadget() │ destroy_gadget() │ bind_udc() │ unbind() │ │ │
│ │ └───────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────┼────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ HID Function │ │ MSD Function │ │ Endpoint Alloc │ │
│ │ (hid.rs) │ │ (msd.rs) │ │ (endpoint.rs) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ ConfigFS Operations │ │
│ │ /sys/kernel/config/usb_gadget/one-kvm/ │ │
│ │ ├── idVendor, idProduct, strings/ │ │
│ │ ├── configs/c.1/ │ │
│ │ │ └── functions/ (symlinks) │ │
│ │ └── functions/ │ │
│ │ ├── hid.usb0, hid.usb1, hid.usb2 │ │
│ │ └── mass_storage.usb0 │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Linux Kernel │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ /dev/hidg* │ │ Mass Storage │ │
│ │ (HID devices) │ │ Backend │ │
│ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 4.4 事件系统架构
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Event System Architecture │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Event Producers │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Video │ │ HID │ │ MSD │ │ ATX │ │ Audio │ │
│ │ Module │ │ Module │ │ Module │ │ Module │ │ Module │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ └────────────┴────────────┼────────────┴────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ EventBus │ │
│ │ (tokio broadcast channel) │ │
│ │ ┌───────────────────────────────────────────────────────────────┐ │ │
│ │ │ SystemEvent Enum │ │ │
│ │ │ StreamStateChanged │ HidStateChanged │ MsdStateChanged │ │ │
│ │ │ AtxStateChanged │ AudioStateChanged │ DeviceInfo │ Error │ │ │
│ │ └───────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────┼─────────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │WebSocket │ │ DeviceInfo│ │ Internal │ │
│ │ Clients │ │Broadcaster│ │ Tasks │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 5. 初始化流程
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Application Startup Flow │
└─────────────────────────────────────────────────────────────────────────────┘
main()
├──► Parse CLI Arguments (clap)
│ - address, port, data_dir
│ - enable_https, ssl_cert, ssl_key
│ - verbosity (-v, -vv, -vvv)
├──► Initialize Logging (tracing)
├──► Create/Open SQLite Database
│ └─► ConfigStore::new()
│ └─► UserStore::new()
│ └─► SessionStore::new()
├──► Initialize Core Services
│ │
│ ├──► EventBus::new()
│ │ └─► Create tokio broadcast channel
│ │
│ ├──► OtgService::new()
│ │ └─► Detect UDC device (/sys/class/udc)
│ │ └─► Initialize OtgGadgetManager
│ │
│ ├──► HidController::new()
│ │ └─► Detect backend type (OTG/CH9329/None)
│ │ └─► Create controller with optional OtgService
│ │
│ ├──► HidController::init()
│ │ └─► Request HID function from OtgService
│ │ └─► Create HID devices (/dev/hidg0-3)
│ │ └─► Open device files with O_NONBLOCK
│ │ └─► Initialize HidHealthMonitor
│ │
│ ├──► MsdController::init() (if configured)
│ │ └─► Request MSD function from OtgService
│ │ └─► Create mass storage device
│ │ └─► Initialize Ventoy drive (if available)
│ │
│ ├──► AtxController::init() (if configured)
│ │ └─► Setup GPIO pins or USB relay
│ │
│ ├──► AudioController::init()
│ │ └─► Open ALSA device
│ │ └─► Initialize Opus encoder
│ │
│ ├──► VideoStreamManager::new()
│ │ └─► Initialize SharedVideoPipeline
│ │ └─► Setup encoder registry (H264/H265/VP8/VP9)
│ │ └─► Detect hardware acceleration (VAAPI/RKMPP/V4L2 M2M)
│ │
│ └──► RustDeskService::new() (if configured)
│ └─► Load/generate device ID and keys
│ └─► Connect to rendezvous server
├──► Create AppState
│ └─► Wrap all services in Arc<>
├──► Spawn Background Tasks
│ ├──► spawn_device_info_broadcaster()
│ ├──► extension_health_check_task()
│ └──► rustdesk_reconnect_task()
├──► Create Axum Router
│ └─► create_router(app_state)
└──► Start HTTP/HTTPS Server
└─► axum::serve() or axum_server with TLS
```
---
## 6. 目录结构
```
One-KVM-RUST/
├── src/ # Rust 源代码
│ ├── main.rs # 应用入口点
│ ├── lib.rs # 库导出
│ ├── state.rs # AppState 定义
│ ├── error.rs # 错误类型定义
│ │
│ ├── video/ # 视频模块
│ │ ├── mod.rs
│ │ ├── capture.rs # V4L2 采集
│ │ ├── streamer.rs # 视频流服务
│ │ ├── stream_manager.rs # 流管理器
│ │ ├── shared_video_pipeline.rs # 共享视频管道
│ │ ├── format.rs # 像素格式
│ │ ├── frame.rs # 视频帧
│ │ ├── convert.rs # 格式转换
│ │ └── encoder/ # 编码器
│ │ ├── mod.rs
│ │ ├── traits.rs
│ │ ├── h264.rs
│ │ ├── h265.rs
│ │ ├── vp8.rs
│ │ ├── vp9.rs
│ │ └── jpeg.rs
│ │
│ ├── hid/ # HID 模块
│ │ ├── mod.rs # HidController主控制器
│ │ ├── backend.rs # HidBackend trait 和 HidBackendType
│ │ ├── otg.rs # OTG 后端USB Gadget HID
│ │ ├── ch9329.rs # CH9329 串口后端
│ │ ├── consumer.rs # Consumer Control usage codes
│ │ ├── keymap.rs # JS keyCode → USB HID 转换表
│ │ ├── types.rs # 事件类型定义
│ │ ├── monitor.rs # HidHealthMonitor错误跟踪与恢复
│ │ ├── datachannel.rs # DataChannel 二进制协议解析
│ │ └── websocket.rs # WebSocket 二进制协议适配
│ │
│ ├── otg/ # USB OTG 模块
│ │ ├── mod.rs
│ │ ├── service.rs # OtgService
│ │ ├── manager.rs # GadgetManager
│ │ ├── hid.rs # HID Function
│ │ ├── msd.rs # MSD Function
│ │ ├── configfs.rs # ConfigFS 操作
│ │ ├── endpoint.rs # 端点分配
│ │ └── report_desc.rs # HID 报告描述符
│ │
│ ├── msd/ # MSD 模块
│ │ ├── mod.rs
│ │ ├── controller.rs # MsdController
│ │ ├── image.rs # 镜像管理
│ │ ├── ventoy_drive.rs # Ventoy 驱动
│ │ ├── monitor.rs # 健康监视
│ │ └── types.rs # 类型定义
│ │
│ ├── atx/ # ATX 模块
│ │ ├── mod.rs
│ │ ├── controller.rs # AtxController
│ │ ├── executor.rs # 动作执行器
│ │ ├── types.rs # 类型定义
│ │ ├── led.rs # LED 监视
│ │ └── wol.rs # Wake-on-LAN
│ │
│ ├── audio/ # 音频模块
│ │ ├── mod.rs
│ │ ├── controller.rs # AudioController
│ │ ├── capture.rs # ALSA 采集
│ │ ├── encoder.rs # Opus 编码
│ │ ├── shared_pipeline.rs # 共享管道
│ │ ├── monitor.rs # 健康监视
│ │ └── device.rs # 设备枚举
│ │
│ ├── webrtc/ # WebRTC 模块
│ │ ├── mod.rs
│ │ ├── webrtc_streamer.rs # WebRTC 管理器
│ │ ├── universal_session.rs # 会话管理
│ │ ├── video_track.rs # 视频轨道
│ │ ├── rtp.rs # RTP 打包
│ │ ├── h265_payloader.rs # H265 RTP
│ │ ├── peer.rs # PeerConnection
│ │ ├── config.rs # 配置
│ │ ├── signaling.rs # 信令
│ │ └── track.rs # 轨道基类
│ │
│ ├── auth/ # 认证模块
│ │ ├── mod.rs
│ │ ├── user.rs # 用户管理
│ │ ├── session.rs # 会话管理
│ │ ├── password.rs # 密码哈希
│ │ └── middleware.rs # Axum 中间件
│ │
│ ├── config/ # 配置模块
│ │ ├── mod.rs
│ │ ├── schema.rs # 配置结构定义
│ │ └── store.rs # SQLite 存储
│ │
│ ├── events/ # 事件模块
│ │ └── mod.rs # EventBus
│ │
│ ├── rustdesk/ # RustDesk 模块
│ │ ├── mod.rs # RustDeskService
│ │ ├── connection.rs # 连接管理
│ │ ├── rendezvous.rs # 渲染服务器通信
│ │ ├── crypto.rs # NaCl 加密
│ │ ├── config.rs # 配置
│ │ ├── hid_adapter.rs # HID 适配
│ │ ├── frame_adapters.rs # 帧格式转换
│ │ ├── protocol.rs # 协议包装
│ │ └── bytes_codec.rs # 帧编码
│ │
│ ├── extensions/ # 扩展模块
│ │ └── mod.rs # ExtensionManager
│ │
│ ├── web/ # Web 模块
│ │ ├── mod.rs
│ │ ├── routes.rs # 路由定义
│ │ ├── ws.rs # WebSocket
│ │ ├── audio_ws.rs # 音频 WebSocket
│ │ ├── static_files.rs # 静态文件
│ │ └── handlers/ # API 处理器
│ │ ├── mod.rs
│ │ └── config/
│ │
│ ├── stream/ # MJPEG 流
│ │ └── mod.rs
│ │
│ └── utils/ # 工具函数
│ └── mod.rs
├── web/ # Vue3 前端
│ ├── src/
│ │ ├── views/ # 页面组件
│ │ ├── components/ # UI 组件
│ │ ├── api/ # API 客户端
│ │ ├── stores/ # Pinia 状态
│ │ ├── router/ # 路由配置
│ │ ├── i18n/ # 国际化
│ │ └── types/ # TypeScript 类型
│ └── package.json
├── libs/ # 外部库
│ ├── hwcodec/ # 硬件视频编码
│ └── ventoy-img-rs/ # Ventoy 支持
├── protos/ # Protobuf 定义
│ ├── message.proto # RustDesk 消息
│ └── rendezvous.proto # RustDesk 渲染
├── docs/ # 文档
├── scripts/ # 脚本
├── Cargo.toml # Rust 配置
├── build.rs # 构建脚本
└── README.md
```
---
## 7. 安全架构
### 7.1 认证流程
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Authentication Flow │
└─────────────────────────────────────────────────────────────────────────────┘
┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
│ Client │ │ Axum │ │ Auth │ │ SQLite │
│ Browser │ │ Server │ │ Module │ │ Database │
└─────┬─────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘
│ │ │ │
│ POST /auth/login │ │ │
│ {username, pass} │ │ │
│───────────────────►│ │ │
│ │ verify_user() │ │
│ │───────────────────►│ │
│ │ │ SELECT user │
│ │ │───────────────────►│
│ │ │◄───────────────────│
│ │ │ │
│ │ │ Argon2 verify │
│ │ │ ────────────► │
│ │ │ │
│ │ session_token │ │
│ │◄───────────────────│ │
│ │ │ │
│ Set-Cookie: │ │ │
│ session_id=token │ │ │
│◄───────────────────│ │ │
│ │ │ │
│ GET /api/... │ │ │
│ Cookie: session │ │ │
│───────────────────►│ │ │
│ │ validate_session()│ │
│ │───────────────────►│ │
│ │ user_info │ │
│ │◄───────────────────│ │
│ │ │ │
│ Response │ │ │
│◄───────────────────│ │ │
```
### 7.2 权限层级
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Permission Levels │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ Public (No Auth) │
│ ├── GET /health │
│ ├── POST /auth/login │
│ ├── GET /setup │
│ └── POST /setup/init │
├─────────────────────────────────────────────────────────────────────────────┤
│ User (Authenticated) │
│ ├── GET /info (系统信息) │
│ ├── GET /devices (设备列表) │
│ ├── GET/POST /stream/* (流控制) │
│ ├── POST /webrtc/* (WebRTC 信令) │
│ ├── POST /hid/* (HID 控制) │
│ ├── POST /audio/* (音频控制) │
│ └── WebSocket endpoints (实时通信) │
├─────────────────────────────────────────────────────────────────────────────┤
│ Admin (Admin Role) │
│ ├── GET/PATCH /config/* (配置管理) │
│ ├── POST /msd/* (MSD 操作) │
│ ├── POST /atx/* (电源控制) │
│ ├── POST /extensions/* (扩展管理) │
│ ├── POST /rustdesk/* (RustDesk 配置) │
│ └── POST /users/* (用户管理) │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 8. 部署架构
### 8.1 单机部署
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Single Binary Deployment │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ ARM64 Device (e.g., Rockchip RK3328) │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ one-kvm (single binary, ~15MB) │ │
│ │ ┌─────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Embedded Assets (rust-embed, gzip compressed) │ │ │
│ │ │ - index.html, app.js, app.css, assets/* │ │ │
│ │ └─────────────────────────────────────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Runtime Data (data_dir) │ │ │
│ │ │ - one-kvm.db (SQLite) │ │ │
│ │ │ - images/ (MSD images) │ │ │
│ │ │ - certs/ (SSL certificates) │ │ │
│ │ └─────────────────────────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │
│ Hardware Connections: │
│ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │
│ │ HDMI Input │ │ USB OTG Port │ │ GPIO Header │ │
│ │ (/dev/video0) │ │ (USB Gadget) │ │ (ATX Control) │ │
│ └───────────────────┘ └───────────────────┘ └───────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│ USB Cable
┌─────────────────────────────────────────────────────────────────────────────┐
│ Target PC │
│ - Receives USB HID events (keyboard/mouse) │
│ - Provides HDMI video output │
│ - Can boot from virtual USB drive │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 8.2 网络拓扑
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Network Topology │
└─────────────────────────────────────────────────────────────────────────────┘
Internet
┌───────────┴───────────┐
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ RustDesk │ │ Client │
│ Server │ │ Browser │
│ (hbbs/hbbr) │ │ │
└───────────────┘ └───────────────┘
│ │
│ │
└───────────┬───────────┘
┌────┴────┐
│ Router │
│ NAT │
└────┬────┘
Local Network
┌───────────┴───────────┐
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ One-KVM │───────│ Target PC │
│ Device │ USB │ │
│ :8080/:8443 │ HID │ │
└───────────────┘ └───────────────┘
Access Methods:
1. Local: http://one-kvm.local:8080
2. HTTPS: https://one-kvm.local:8443
3. RustDesk: Via RustDesk client with device ID
```
---
## 9. 扩展点
### 9.1 添加新编码器
```rust
// 1. 实现 Encoder trait
impl Encoder for MyEncoder {
fn encode(&mut self, frame: &VideoFrame) -> Result<Vec<u8>>;
fn codec(&self) -> Codec;
fn bitrate(&self) -> u32;
// ...
}
// 2. 在 registry 中注册
encoder_registry.register("my-encoder", || Box::new(MyEncoder::new()));
```
### 9.2 添加新 HID 后端
```rust
// 1. 在 backend.rs 中定义新后端类型
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum HidBackendType {
Otg,
Ch9329 { port: String, baud_rate: u32 },
MyBackend { /* 配置参数 */ }, // 新增
None,
}
// 2. 实现 HidBackend trait
#[async_trait]
impl HidBackend for MyBackend {
fn name(&self) -> &'static str { "MyBackend" }
async fn init(&self) -> Result<()> { /* ... */ }
async fn send_keyboard(&self, event: KeyboardEvent) -> Result<()> { /* ... */ }
async fn send_mouse(&self, event: MouseEvent) -> Result<()> { /* ... */ }
async fn send_consumer(&self, event: ConsumerEvent) -> Result<()> { /* ... */ }
async fn reset(&self) -> Result<()> { /* ... */ }
async fn shutdown(&self) -> Result<()> { /* ... */ }
fn supports_absolute_mouse(&self) -> bool { true }
fn screen_resolution(&self) -> Option<(u32, u32)> { None }
fn set_screen_resolution(&mut self, width: u32, height: u32) { /* ... */ }
}
// 3. 在 HidController::init() 中添加分支
match backend_type {
HidBackendType::MyBackend { /* params */ } => {
Box::new(MyBackend::new(/* params */)?)
}
// ...
}
```
### 9.3 添加新扩展
```rust
// 通过 ExtensionManager 管理外部进程
extension_manager.register("my-extension", ExtensionConfig {
command: "my-binary",
args: vec!["--port", "9000"],
health_check: HealthCheckConfig::Http { url: "http://localhost:9000/health" },
});
```
---
## 10. 参考资料
- [Axum Web Framework](https://github.com/tokio-rs/axum)
- [webrtc-rs](https://github.com/webrtc-rs/webrtc)
- [V4L2 Documentation](https://www.kernel.org/doc/html/latest/userspace-api/media/v4l/v4l2.html)
- [Linux USB Gadget](https://www.kernel.org/doc/html/latest/usb/gadget_configfs.html)
- [RustDesk Protocol](https://github.com/rustdesk/rustdesk)

File diff suppressed because it is too large Load Diff

View File

@@ -4,19 +4,21 @@ version = "0.8.0"
edition = "2021"
description = "Hardware video codec for IP-KVM (Windows/Linux)"
[package.metadata.cargo-machete]
ignored = ["serde"]
[features]
default = []
bytes = ["dep:bytes"]
rkmpp = []
[dependencies]
log = "0.4"
bytes = { version = "1", optional = true }
serde_derive = "1.0"
serde = "1.0"
serde_json = "1.0"
[build-dependencies]
cc = "1.0"
bindgen = "0.59"
[dev-dependencies]
env_logger = "0.10"
bindgen = "0.70.1"

View File

@@ -21,11 +21,16 @@ fn build_common(builder: &mut Build) {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let common_dir = manifest_dir.join("cpp").join("common");
bindgen::builder()
let mut bindings = bindgen::builder()
.header(common_dir.join("common.h").to_string_lossy().to_string())
.header(common_dir.join("callback.h").to_string_lossy().to_string())
.rustified_enum("*")
.parse_callbacks(Box::new(CommonCallbacks))
.rustified_enum(".*")
.parse_callbacks(Box::new(CommonCallbacks));
if target_os == "android" {
print_android_bindgen_env();
bindings = bindings.clang_args(android_clang_args());
}
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("common_ffi.rs"))
@@ -34,7 +39,9 @@ fn build_common(builder: &mut Build) {
// system
#[cfg(windows)]
{
["d3d11", "dxgi"].map(|lib| println!("cargo:rustc-link-lib={}", lib));
for lib in ["d3d11", "dxgi"] {
println!("cargo:rustc-link-lib={}", lib);
}
}
builder.include(&common_dir);
@@ -55,9 +62,9 @@ fn build_common(builder: &mut Build) {
}
// Unsupported platforms
if target_os != "windows" && target_os != "linux" {
if target_os != "windows" && target_os != "linux" && target_os != "android" {
panic!(
"Unsupported OS: {}. Only Windows and Linux are supported.",
"Unsupported OS: {}. Only Windows, Linux, and Android are supported.",
target_os
);
}
@@ -69,9 +76,9 @@ fn build_common(builder: &mut Build) {
#[derive(Debug)]
struct CommonCallbacks;
impl bindgen::callbacks::ParseCallbacks for CommonCallbacks {
fn add_derives(&self, name: &str) -> Vec<String> {
fn add_derives(&self, info: &bindgen::callbacks::DeriveInfo<'_>) -> Vec<String> {
let names = vec!["DataFormat", "SurfaceFormat", "API"];
if names.contains(&name) {
if names.contains(&info.name) {
vec!["Serialize", "Deserialize"]
.drain(..)
.map(|s| s.to_string())
@@ -82,15 +89,126 @@ impl bindgen::callbacks::ParseCallbacks for CommonCallbacks {
}
}
fn print_android_bindgen_env() {
println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
println!("cargo:rerun-if-env-changed=ANDROID_NDK_ROOT");
println!("cargo:rerun-if-env-changed=NDK_HOME");
println!("cargo:rerun-if-env-changed=ANDROID_HOME");
println!("cargo:rerun-if-env-changed=ANDROID_SDK_ROOT");
println!("cargo:rerun-if-env-changed=CARGO_NDK_PLATFORM");
}
fn android_clang_args() -> Vec<String> {
let ndk = android_ndk_home();
let target = env::var("TARGET").unwrap_or_default();
let toolchain = ndk.join("toolchains/llvm/prebuilt").join(host_tag());
let sysroot = toolchain.join("sysroot");
let clang_include = toolchain
.join("lib/clang")
.join(clang_version(&toolchain))
.join("include");
let api = env::var("CARGO_NDK_PLATFORM")
.ok()
.and_then(|value| value.parse::<u32>().ok())
.unwrap_or(21);
let clang_target = android_clang_target(&target);
vec![
format!("--target={clang_target}"),
format!("--sysroot={}", sysroot.display()),
format!("-D__ANDROID_API__={api}"),
format!("-isystem{}", clang_include.display()),
format!("-isystem{}", sysroot.join("usr/include").display()),
format!(
"-isystem{}",
sysroot.join("usr/include").join(clang_target).display()
),
]
}
fn android_clang_target(target: &str) -> &'static str {
match target {
"aarch64-linux-android" => "aarch64-linux-android",
"armv7-linux-androideabi" => "armv7a-linux-androideabi",
"i686-linux-android" => "i686-linux-android",
"x86_64-linux-android" => "x86_64-linux-android",
other => panic!("unsupported Android target for hwcodec bindgen: {other}"),
}
}
fn android_ndk_home() -> PathBuf {
for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"] {
if let Ok(value) = env::var(key) {
return PathBuf::from(value);
}
}
for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
if let Ok(value) = env::var(key) {
let ndk_dir = PathBuf::from(value).join("ndk");
if let Some(newest) = newest_child_dir(&ndk_dir) {
return newest;
}
}
}
panic!(
"hwcodec Android bindgen requires ANDROID_NDK_HOME, ANDROID_NDK_ROOT, NDK_HOME, \
or ANDROID_HOME/ANDROID_SDK_ROOT with an ndk directory"
);
}
fn newest_child_dir(path: &Path) -> Option<PathBuf> {
let mut entries = std::fs::read_dir(path)
.ok()?
.filter_map(|entry| entry.ok())
.map(|entry| entry.path())
.filter(|path| path.is_dir())
.collect::<Vec<_>>();
entries.sort();
entries.pop()
}
fn host_tag() -> &'static str {
if cfg!(target_os = "linux") {
"linux-x86_64"
} else if cfg!(target_os = "macos") {
"darwin-x86_64"
} else if cfg!(target_os = "windows") {
"windows-x86_64"
} else {
panic!("unsupported host OS for Android NDK");
}
}
fn clang_version(toolchain: &Path) -> String {
let clang_dir = toolchain.join("lib/clang");
let mut entries = std::fs::read_dir(&clang_dir)
.unwrap_or_else(|_| panic!("missing NDK clang directory: {}", clang_dir.display()))
.filter_map(|entry| entry.ok())
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect::<Vec<_>>();
entries.sort();
entries
.pop()
.unwrap_or_else(|| panic!("no clang versions found under: {}", clang_dir.display()))
}
mod ffmpeg {
use super::*;
pub fn build_ffmpeg(builder: &mut Build) {
ffmpeg_ffi();
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
link_android_ffmpeg(builder);
build_ffmpeg_ram(builder);
return;
}
// Try VCPKG first, fallback to system FFmpeg via pkg-config
if let Ok(vcpkg_root) = std::env::var("VCPKG_ROOT") {
link_vcpkg(builder, vcpkg_root.into());
if let Some(vcpkg_installed) = vcpkg_installed_root() {
link_vcpkg(builder, vcpkg_installed);
} else {
// Use system FFmpeg via pkg-config
link_system_ffmpeg(builder);
@@ -98,6 +216,85 @@ mod ffmpeg {
link_os();
build_ffmpeg_ram(builder);
build_ffmpeg_hw(builder);
build_ffmpeg_capture(builder);
}
fn link_android_ffmpeg(builder: &mut Build) {
let root = std::env::var("ONE_KVM_ANDROID_FFMPEG_ROOT").unwrap_or_else(|_| {
panic!(
"ONE_KVM_ANDROID_FFMPEG_ROOT is required when building hwcodec for Android. \
It must point to an FFmpeg Android build with MediaCodec enabled."
)
});
let root = PathBuf::from(root);
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let abi = match target_arch.as_str() {
"aarch64" => "arm64-v8a",
"arm" => "armeabi-v7a",
"x86" => "x86",
"x86_64" => "x86_64",
_ => target_arch.as_str(),
};
let abi_root = root.join(abi);
let lib_dir = if abi_root.join("lib").exists() {
abi_root.join("lib")
} else {
root.join("lib")
};
let include_dir = if abi_root.join("include").exists() {
abi_root.join("include")
} else {
root.join("include")
};
if !include_dir.exists() || !lib_dir.exists() {
panic!(
"Invalid ONE_KVM_ANDROID_FFMPEG_ROOT: include/lib not found for ABI {} under {}",
abi,
root.display()
);
}
println!("cargo:rustc-link-search=native={}", lib_dir.display());
builder.include(&include_dir);
let use_static = std::env::var("ONE_KVM_ANDROID_FFMPEG_STATIC")
.map(|value| value != "0")
.unwrap_or(true);
for lib in ["avcodec", "avutil"] {
if use_static {
println!("cargo:rustc-link-lib=static={}", lib);
} else {
println!("cargo:rustc-link-lib={}", lib);
}
}
println!("cargo:rustc-link-lib=log");
println!("cargo:rustc-link-lib=mediandk");
println!("cargo:rustc-link-lib=android");
println!("cargo:rustc-link-lib=dl");
println!("cargo:rustc-link-lib=m");
println!("cargo:rustc-link-lib=z");
println!("cargo:rustc-link-lib=c++_shared");
println!("cargo:info=Using Android FFmpeg from {}", root.display());
}
fn vcpkg_installed_root() -> Option<PathBuf> {
println!("cargo:rerun-if-env-changed=VCPKG_INSTALLED_DIR");
println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
if let Ok(path) = std::env::var("VCPKG_INSTALLED_DIR") {
if !path.trim().is_empty() {
return Some(PathBuf::from(path));
}
}
std::env::var("VCPKG_ROOT")
.ok()
.filter(|path| !path.trim().is_empty())
.map(|path| PathBuf::from(path).join("installed"))
}
/// Link system FFmpeg using pkg-config or custom path
@@ -270,7 +467,6 @@ mod ffmpeg {
target = target.replace("x64", "x86");
}
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
println!(
@@ -281,15 +477,26 @@ mod ffmpeg {
)
);
{
// Only need avcodec and avutil for encoding
// avdevice/avformat are needed by the Windows DirectShow capture bridge.
let mut static_libs = vec!["avcodec", "avutil"];
if target_os == "windows" {
static_libs.push("libmfx");
static_libs.extend([
"avformat",
"avdevice",
"avfilter",
"swresample",
"swscale",
"vpx",
"libx264",
"x265-static",
]);
}
for lib in static_libs {
println!("cargo:rustc-link-lib=static={}", lib);
}
if target_os == "windows" {
link_windows_qsv_lib(&path.join("lib"));
}
static_libs
.iter()
.map(|lib| println!("cargo:rustc-link-lib=static={}", lib))
.count();
}
let include = path.join("include");
@@ -298,12 +505,28 @@ mod ffmpeg {
include
}
fn link_windows_qsv_lib(lib_dir: &Path) {
if lib_dir.join("libmfx.lib").exists() {
println!("cargo:rustc-link-lib=static=libmfx");
println!("cargo:info=Using Windows QSV support library libmfx.lib");
return;
}
println!(
"cargo:warning=Windows QSV support library not found in {}",
lib_dir.display()
);
}
fn link_os() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let dyn_libs: Vec<&str> = if target_os == "windows" {
["User32", "bcrypt", "ole32", "advapi32"].to_vec()
[
"User32", "bcrypt", "ole32", "advapi32", "mfuuid", "strmiids",
]
.to_vec()
} else if target_os == "linux" {
// Base libraries for all Linux platforms
let mut v = vec!["drm", "stdc++"];
@@ -315,9 +538,11 @@ mod ffmpeg {
}
// ARM (aarch64, arm): no X11 needed, uses RKMPP/V4L2
v
} else if target_os == "android" {
Vec::new()
} else {
panic!(
"Unsupported OS: {}. Only Windows and Linux are supported.",
"Unsupported OS: {}. Only Windows, Linux, and Android are supported.",
target_os
);
};
@@ -333,9 +558,14 @@ mod ffmpeg {
let ffi_header_path = ffmpeg_ram_dir.join("ffmpeg_ffi.h");
println!("cargo:rerun-if-changed={}", ffi_header_path.display());
let ffi_header = ffi_header_path.to_string_lossy().to_string();
bindgen::builder()
let mut bindings = bindgen::builder()
.header(ffi_header)
.rustified_enum("*")
.rustified_enum(".*");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
print_android_bindgen_env();
bindings = bindings.clang_args(android_clang_args());
}
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_ffi.rs"))
@@ -349,9 +579,14 @@ mod ffmpeg {
.join("ffmpeg_ram_ffi.h")
.to_string_lossy()
.to_string();
bindgen::builder()
let mut bindings = bindgen::builder()
.header(ffi_header)
.rustified_enum("*")
.rustified_enum(".*");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
print_android_bindgen_env();
bindings = bindings.clang_args(android_clang_args());
}
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_ram_ffi.rs"))
@@ -362,7 +597,9 @@ mod ffmpeg {
// RKMPP decode only exists on ARM builds where FFmpeg is compiled with RKMPP support.
// Avoid compiling this file on x86/x64 where `AV_HWDEVICE_TYPE_RKMPP` doesn't exist.
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let enable_rkmpp = matches!(target_arch.as_str(), "aarch64" | "arm")
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let enable_rkmpp = target_os != "android"
&& matches!(target_arch.as_str(), "aarch64" | "arm")
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
if enable_rkmpp {
builder.file(ffmpeg_ram_dir.join("ffmpeg_ram_decode.cpp"));
@@ -373,4 +610,87 @@ mod ffmpeg {
);
}
}
fn build_ffmpeg_capture(builder: &mut Build) {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_os != "windows" {
return;
}
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let capture_header = manifest_dir
.join("cpp")
.join("ffmpeg_capture_ffi.h")
.to_string_lossy()
.to_string();
bindgen::builder()
.header(capture_header)
.rustified_enum(".*")
.generate()
.unwrap()
.write_to_file(
Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_capture_ffi.rs"),
)
.unwrap();
builder.file(manifest_dir.join("cpp").join("ffmpeg_capture.cpp"));
println!("cargo:rustc-link-lib=strmiids");
println!("cargo:rustc-link-lib=oleaut32");
println!("cargo:rustc-link-lib=quartz");
}
fn build_ffmpeg_hw(builder: &mut Build) {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let ffmpeg_hw_dir = manifest_dir.join("cpp").join("ffmpeg_hw");
let ffi_header = ffmpeg_hw_dir
.join("ffmpeg_hw_ffi.h")
.to_string_lossy()
.to_string();
bindgen::builder()
.header(ffi_header)
.rustified_enum(".*")
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_hw_ffi.rs"))
.unwrap();
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let enable_rkmpp = target_os != "android"
&& matches!(target_arch.as_str(), "aarch64" | "arm")
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
if enable_rkmpp {
// Include RGA headers for NV16->NV12 conversion (RGA im2d API)
let rga_sys_dirs = [
Path::new("/usr/aarch64-linux-gnu/include/rga"),
Path::new("/usr/include/rga"),
];
let mut added = false;
for dir in rga_sys_dirs.iter() {
if dir.exists() {
builder.include(dir);
added = true;
}
}
if !added {
// Fallback to repo-local rkrga headers if present
let repo_root = manifest_dir
.parent()
.and_then(|p| p.parent())
.map(|p| p.to_path_buf())
.unwrap_or_else(|| manifest_dir.clone());
let rkrga_dir = repo_root.join("ffmpeg").join("rkrga");
if rkrga_dir.exists() {
builder.include(rkrga_dir.join("include"));
builder.include(rkrga_dir.join("im2d_api"));
}
}
builder.file(ffmpeg_hw_dir.join("ffmpeg_hw_mjpeg_h26x.cpp"));
} else {
println!(
"cargo:info=Skipping ffmpeg_hw_mjpeg_h26x.cpp (RKMPP) for arch {}",
target_arch
);
}
}
}

View File

@@ -25,6 +25,7 @@ enum AVPixelFormat {
AV_PIX_FMT_NV24 = 188,
};
int av_get_pix_fmt(const char *name);
int av_log_get_level(void);
void av_log_set_level(int level);
void hwcodec_set_av_log_callback();

View File

@@ -1,12 +1,16 @@
#include "linux.h"
#include "../../log.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <dlfcn.h>
#include <errno.h>
#include <fstream>
#include <signal.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
// Check for NVIDIA driver support by loading CUDA libraries
int linux_support_nv()
@@ -106,11 +110,131 @@ int linux_support_rkmpp() {
// Check for V4L2 Memory-to-Memory (M2M) codec support
// Returns 0 if a M2M capable device is found, -1 otherwise
int linux_support_v4l2m2m() {
auto to_lower = [](std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
};
auto read_text_file = [](const char *path, std::string *out) -> bool {
std::ifstream file(path);
if (!file.is_open()) {
return false;
}
std::getline(file, *out, '\0');
return !out->empty();
};
auto v4l2m2m_allowed = []() -> bool {
const char *env = std::getenv("ONE_KVM_V4L2M2M_ALLOW");
if (env == nullptr) {
return false;
}
if (env[0] == '\0') {
return false;
}
return std::strcmp(env, "0") != 0;
};
auto contains_any = [](const std::string &value, const char *const *needles, size_t len) -> bool {
for (size_t i = 0; i < len; i++) {
if (value.find(needles[i]) != std::string::npos) {
return true;
}
}
return false;
};
auto is_amlogic_platform = [&]() -> bool {
const char *platform_hints[] = {
"amlogic",
"meson",
"gxl",
"gxbb",
"gxm",
"g12a",
"g12b",
"sm1",
};
const char *platform_files[] = {
"/proc/device-tree/compatible",
"/proc/device-tree/model",
"/sys/firmware/devicetree/base/compatible",
"/sys/firmware/devicetree/base/model",
};
for (size_t i = 0; i < sizeof(platform_files) / sizeof(platform_files[0]); i++) {
std::string value;
if (read_text_file(platform_files[i], &value) &&
contains_any(to_lower(value), platform_hints,
sizeof(platform_hints) / sizeof(platform_hints[0]))) {
return true;
}
}
const char *video_nodes[] = {
"video0",
"video1",
"video2",
"video10",
"video11",
"video32",
};
const char *vdec_hints[] = {
"meson",
"amlogic",
"vdec",
"decoder",
"video-decoder",
"gxl-vdec",
"gx-vdec",
};
for (size_t i = 0; i < sizeof(video_nodes) / sizeof(video_nodes[0]); i++) {
std::string name;
std::string modalias;
const std::string base = std::string("/sys/class/video4linux/") + video_nodes[i];
if (read_text_file((base + "/name").c_str(), &name) &&
contains_any(to_lower(name), vdec_hints, sizeof(vdec_hints) / sizeof(vdec_hints[0]))) {
return true;
}
if (read_text_file((base + "/device/modalias").c_str(), &modalias) &&
contains_any(to_lower(modalias), vdec_hints,
sizeof(vdec_hints) / sizeof(vdec_hints[0]))) {
return true;
}
}
return false;
};
const bool amlogic_platform = is_amlogic_platform();
if (amlogic_platform && !v4l2m2m_allowed()) {
LOG_WARN(std::string(
"V4L2 M2M: skipped probe on Amlogic platform; set ONE_KVM_V4L2M2M_ALLOW=1 to enable"));
return -1;
}
if (amlogic_platform) {
LOG_WARN(std::string("V4L2 M2M: ONE_KVM_V4L2M2M_ALLOW is set; probing Amlogic video nodes"));
}
// Check common V4L2 M2M device paths used by various ARM SoCs
// /dev/video10 - Standard on many SoCs
// /dev/video11 - Standard on many SoCs (often decoder)
// /dev/video0 - Some platforms (like RPi) might use this
// /dev/video1 - Alternate RPi path
// /dev/video2 - Alternate path
// /dev/video32 - Some Allwinner/Rockchip legacy
const char *m2m_devices[] = {
"/dev/video10", // Common M2M encoder device
"/dev/video11", // Common M2M decoder device
"/dev/video0", // Some SoCs use video0 for M2M
"/dev/video10",
"/dev/video11",
"/dev/video0",
"/dev/video1",
"/dev/video2",
"/dev/video32",
};
for (size_t i = 0; i < sizeof(m2m_devices) / sizeof(m2m_devices[0]); i++) {

View File

@@ -1,4 +1,5 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
}
@@ -99,13 +100,17 @@ void set_av_codec_ctx(AVCodecContext *c, const std::string &name, int kbs,
c->color_primaries = AVCOL_PRI_SMPTE170M;
c->color_trc = AVCOL_TRC_SMPTE170M;
// Profile selection: use BASELINE for software H264 (faster, simpler)
if (is_software_h264(name)) {
c->profile = FF_PROFILE_H264_BASELINE; // Simpler profile for real-time
} else if (name.find("h264") != std::string::npos) {
c->profile = FF_PROFILE_H264_HIGH;
// WebRTC SDP advertises constrained baseline. Keep most hardware and software
// encoders on the same browser-friendly H264 profile. Android MediaCodec is
// deliberately excluded because older vendor OMX encoders can reject explicit
// profile/level combinations during configure().
if (name.find("mediacodec") != std::string::npos) {
return;
}
if (name.find("h264") != std::string::npos) {
c->profile = AV_PROFILE_H264_CONSTRAINED_BASELINE;
} else if (name.find("hevc") != std::string::npos) {
c->profile = FF_PROFILE_HEVC_MAIN;
c->profile = AV_PROFILE_HEVC_MAIN;
}
}
@@ -120,8 +125,7 @@ bool set_lantency_free(void *priv_data, const std::string &name) {
}
if (name.find("amf") != std::string::npos) {
if ((ret = av_opt_set(priv_data, "query_timeout", "1000", 0)) < 0) {
LOG_ERROR(std::string("amf set_lantency_free failed, ret = ") + av_err2str(ret));
return false;
LOG_WARN(std::string("amf query_timeout option is unavailable, ret = ") + av_err2str(ret));
}
}
if (name.find("qsv") != std::string::npos) {
@@ -147,11 +151,11 @@ bool set_lantency_free(void *priv_data, const std::string &name) {
// V4L2 M2M hardware encoder - minimize buffer latency
if (name.find("v4l2m2m") != std::string::npos) {
// Minimize number of output buffers for lower latency
if ((ret = av_opt_set_int(priv_data, "num_output_buffers", 2, 0)) < 0) {
if ((ret = av_opt_set_int(priv_data, "num_output_buffers", 4, 0)) < 0) {
LOG_WARN(std::string("v4l2m2m set num_output_buffers failed, ret = ") + av_err2str(ret));
// Not fatal
}
if ((ret = av_opt_set_int(priv_data, "num_capture_buffers", 2, 0)) < 0) {
if ((ret = av_opt_set_int(priv_data, "num_capture_buffers", 4, 0)) < 0) {
LOG_WARN(std::string("v4l2m2m set num_capture_buffers failed, ret = ") + av_err2str(ret));
// Not fatal
}
@@ -306,23 +310,9 @@ bool set_quality(void *priv_data, const std::string &name, int quality) {
break;
}
}
if (name.find("mediacodec") != std::string::npos) {
if (name.find("h264") != std::string::npos) {
if ((ret = av_opt_set(priv_data, "level", "5.1", 0)) < 0) {
LOG_ERROR(std::string("mediacodec set opt level 5.1 failed, ret = ") +
av_err2str(ret));
return false;
}
}
if (name.find("hevc") != std::string::npos) {
// https:en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
if ((ret = av_opt_set(priv_data, "level", "h5.1", 0)) < 0) {
LOG_ERROR(std::string("mediacodec set opt level h5.1 failed, ret = ") +
av_err2str(ret));
return false;
}
}
}
// Do not force MediaCodec level here. Some Android TV vendor encoders,
// including older Amlogic OMX implementations, reject explicit level values
// even when they support the requested resolution and bitrate.
// libx264 software encoder presets
if (is_software_h264(name)) {
const char* preset = nullptr;
@@ -458,6 +448,13 @@ bool set_others(void *priv_data, const std::string &name) {
return false;
}
}
if (name.find("mediacodec") != std::string::npos) {
if ((ret = av_opt_set_int(priv_data, "ndk_codec", 1, 0)) < 0) {
LOG_ERROR(std::string("mediacodec set ndk_codec failed, ret = ") +
av_err2str(ret));
return false;
}
}
// NOTE: Removed idr_interval = INT_MAX for VAAPI.
// This was disabling automatic keyframe generation.
// The encoder should respect c->gop_size for keyframe interval.

View File

@@ -0,0 +1,879 @@
#define NOMINMAX
#include "ffmpeg_capture_ffi.h"
#include <Windows.h>
#include <dshow.h>
#include <dvdmedia.h>
extern "C" {
#include <libavcodec/codec_id.h>
#include <libavdevice/avdevice.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/error.h>
#include <libavutil/pixfmt.h>
}
#include <atomic>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#pragma comment(lib, "strmiids")
thread_local std::string g_last_error;
struct HwcodecDshowCaptureContext {
AVFormatContext* format_ctx = nullptr;
int stream_index = -1;
int width = 0;
int height = 0;
int pixel_format = HWCODEC_CAPTURE_FMT_UNKNOWN;
int stride = 0;
int timeout_ms = 2000;
std::atomic<long long> deadline_ms{0};
std::atomic<int> timed_out{0};
uint64_t sequence = 0;
};
namespace {
struct DshowCapabilityEntry {
std::string format;
int width = 0;
int height = 0;
std::vector<int> fps;
};
const char* requested_pixel_format_name(int requested_format);
void set_last_error(const std::string& message) {
g_last_error = message;
}
std::string ffmpeg_error(int errnum) {
char buffer[AV_ERROR_MAX_STRING_SIZE] = {0};
av_make_error_string(buffer, sizeof(buffer), errnum);
return std::string(buffer);
}
long long now_ms() {
return static_cast<long long>(GetTickCount64());
}
std::string wide_to_utf8(const wchar_t* value) {
if (!value) {
return std::string();
}
int size = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);
if (size <= 1) {
return std::string();
}
std::string result(static_cast<size_t>(size - 1), '\0');
WideCharToMultiByte(
CP_UTF8,
0,
value,
-1,
result.empty() ? nullptr : &result[0],
size,
nullptr,
nullptr);
return result;
}
void add_fps_candidate(std::vector<int>* fps, LONGLONG interval_100ns) {
if (!fps || interval_100ns <= 0) {
return;
}
double fps_value = 10000000.0 / static_cast<double>(interval_100ns);
int rounded = static_cast<int>(fps_value + 0.5);
if (rounded <= 0) {
return;
}
if (std::find(fps->begin(), fps->end(), rounded) == fps->end()) {
fps->push_back(rounded);
}
}
void normalize_fps(std::vector<int>* fps) {
if (!fps) {
return;
}
std::sort(fps->begin(), fps->end(), std::greater<int>());
fps->erase(std::unique(fps->begin(), fps->end()), fps->end());
}
const char* media_subtype_to_format(const GUID& subtype) {
if (subtype == MEDIASUBTYPE_MJPG) {
return "MJPEG";
}
if (subtype == MEDIASUBTYPE_YUY2) {
return "YUYV";
}
if (subtype == MEDIASUBTYPE_UYVY) {
return "UYVY";
}
if (subtype == MEDIASUBTYPE_YVYU) {
return "YVYU";
}
if (subtype == MEDIASUBTYPE_NV12) {
return "NV12";
}
if (subtype == MEDIASUBTYPE_RGB24) {
return "RGB24";
}
if (subtype == MEDIASUBTYPE_RGB32) {
return "BGR24";
}
if (subtype == MEDIASUBTYPE_IYUV) {
return "YUV420";
}
if (subtype == MEDIASUBTYPE_YV12) {
return "YVU420";
}
return nullptr;
}
void free_media_type(AM_MEDIA_TYPE* media_type) {
if (!media_type) {
return;
}
if (media_type->cbFormat != 0) {
CoTaskMemFree(media_type->pbFormat);
media_type->cbFormat = 0;
media_type->pbFormat = nullptr;
}
if (media_type->pUnk != nullptr) {
media_type->pUnk->Release();
media_type->pUnk = nullptr;
}
CoTaskMemFree(media_type);
}
bool fill_capability_entry(
const AM_MEDIA_TYPE* media_type,
const VIDEO_STREAM_CONFIG_CAPS* caps,
DshowCapabilityEntry* out_entry) {
if (!media_type || !out_entry) {
return false;
}
const char* format = media_subtype_to_format(media_type->subtype);
if (!format) {
return false;
}
LONG width = 0;
LONG height = 0;
REFERENCE_TIME avg_time_per_frame = 0;
if (media_type->formattype == FORMAT_VideoInfo && media_type->pbFormat &&
media_type->cbFormat >= sizeof(VIDEOINFOHEADER)) {
const auto* info = reinterpret_cast<const VIDEOINFOHEADER*>(media_type->pbFormat);
width = info->bmiHeader.biWidth;
height = std::abs(info->bmiHeader.biHeight);
avg_time_per_frame = info->AvgTimePerFrame;
} else if (media_type->formattype == FORMAT_VideoInfo2 && media_type->pbFormat &&
media_type->cbFormat >= sizeof(VIDEOINFOHEADER2)) {
const auto* info = reinterpret_cast<const VIDEOINFOHEADER2*>(media_type->pbFormat);
width = info->bmiHeader.biWidth;
height = std::abs(info->bmiHeader.biHeight);
avg_time_per_frame = info->AvgTimePerFrame;
}
if ((width <= 0 || height <= 0) && caps) {
width = std::max<LONG>(caps->InputSize.cx, caps->MinOutputSize.cx);
height = std::max<LONG>(caps->InputSize.cy, caps->MinOutputSize.cy);
if (width <= 0 || height <= 0) {
width = caps->MaxOutputSize.cx;
height = caps->MaxOutputSize.cy;
}
}
if (width <= 0 || height <= 0) {
return false;
}
out_entry->format = format;
out_entry->width = static_cast<int>(width);
out_entry->height = static_cast<int>(height);
out_entry->fps.clear();
add_fps_candidate(&out_entry->fps, avg_time_per_frame);
if (caps) {
add_fps_candidate(&out_entry->fps, caps->MinFrameInterval);
add_fps_candidate(&out_entry->fps, caps->MaxFrameInterval);
}
normalize_fps(&out_entry->fps);
return true;
}
void append_stream_capabilities(IAMStreamConfig* stream_config, std::vector<DshowCapabilityEntry>* entries) {
if (!stream_config || !entries) {
return;
}
int cap_count = 0;
int cap_size = 0;
HRESULT hr = stream_config->GetNumberOfCapabilities(&cap_count, &cap_size);
if (FAILED(hr) || cap_count <= 0 || cap_size < static_cast<int>(sizeof(VIDEO_STREAM_CONFIG_CAPS))) {
return;
}
std::vector<BYTE> caps_buffer(static_cast<size_t>(cap_size));
for (int index = 0; index < cap_count; ++index) {
AM_MEDIA_TYPE* media_type = nullptr;
hr = stream_config->GetStreamCaps(index, &media_type, caps_buffer.data());
if (FAILED(hr) || !media_type) {
continue;
}
DshowCapabilityEntry entry;
const auto* caps = reinterpret_cast<const VIDEO_STREAM_CONFIG_CAPS*>(caps_buffer.data());
if (fill_capability_entry(media_type, caps, &entry)) {
entries->push_back(std::move(entry));
}
free_media_type(media_type);
}
}
bool find_device_filter(const std::string& device_name, IBaseFilter** out_filter) {
if (!out_filter) {
return false;
}
*out_filter = nullptr;
ICreateDevEnum* dev_enum = nullptr;
IEnumMoniker* enum_moniker = nullptr;
HRESULT hr = CoCreateInstance(
CLSID_SystemDeviceEnum,
nullptr,
CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum,
reinterpret_cast<void**>(&dev_enum));
if (FAILED(hr) || !dev_enum) {
return false;
}
hr = dev_enum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &enum_moniker, 0);
dev_enum->Release();
if (hr != S_OK || !enum_moniker) {
return false;
}
bool found = false;
IMoniker* moniker = nullptr;
ULONG fetched = 0;
while (!found && enum_moniker->Next(1, &moniker, &fetched) == S_OK) {
IPropertyBag* bag = nullptr;
hr = moniker->BindToStorage(nullptr, nullptr, IID_IPropertyBag, reinterpret_cast<void**>(&bag));
if (SUCCEEDED(hr) && bag) {
VARIANT name;
VariantInit(&name);
if (SUCCEEDED(bag->Read(L"FriendlyName", &name, nullptr)) && name.vt == VT_BSTR) {
auto utf8_name = wide_to_utf8(name.bstrVal);
if (utf8_name == device_name) {
hr = moniker->BindToObject(nullptr, nullptr, IID_IBaseFilter, reinterpret_cast<void**>(out_filter));
found = SUCCEEDED(hr) && *out_filter != nullptr;
}
}
VariantClear(&name);
bag->Release();
}
moniker->Release();
}
enum_moniker->Release();
return found;
}
std::string build_capabilities_payload(const std::vector<DshowCapabilityEntry>& entries) {
std::string payload;
for (size_t i = 0; i < entries.size(); ++i) {
const auto& entry = entries[i];
payload += entry.format;
payload.push_back('|');
payload += std::to_string(entry.width);
payload.push_back('|');
payload += std::to_string(entry.height);
payload.push_back('|');
for (size_t fps_index = 0; fps_index < entry.fps.size(); ++fps_index) {
payload += std::to_string(entry.fps[fps_index]);
if (fps_index + 1 < entry.fps.size()) {
payload.push_back(',');
}
}
if (i + 1 < entries.size()) {
payload.push_back('\n');
}
}
return payload;
}
char* copy_payload(const std::string& payload) {
char* out = reinterpret_cast<char*>(std::malloc(payload.size() + 1));
if (!out) {
set_last_error("Failed to allocate capture payload buffer");
return nullptr;
}
std::memcpy(out, payload.c_str(), payload.size() + 1);
return out;
}
int open_dshow_input_with_options(
AVFormatContext** format_ctx,
const AVInputFormat* input,
const std::string& device_name,
int width,
int height,
int fps,
int requested_format,
bool use_video_size,
bool use_framerate,
bool use_pixel_format,
std::string* attempt_desc) {
if (!format_ctx || !input) {
return AVERROR(EINVAL);
}
AVDictionary* options = nullptr;
std::vector<std::string> parts;
if (use_video_size && width > 0 && height > 0) {
std::string video_size = std::to_string(width) + "x" + std::to_string(height);
av_dict_set(&options, "video_size", video_size.c_str(), 0);
parts.push_back("video_size=" + video_size);
}
if (use_framerate && fps > 0) {
std::string framerate = std::to_string(fps);
av_dict_set(&options, "framerate", framerate.c_str(), 0);
parts.push_back("framerate=" + framerate);
}
av_dict_set(&options, "rtbufsize", "64M", 0);
parts.push_back("rtbufsize=64M");
const char* pixel_format_name = requested_pixel_format_name(requested_format);
if (use_pixel_format && pixel_format_name) {
av_dict_set(&options, "pixel_format", pixel_format_name, 0);
parts.push_back(std::string("pixel_format=") + pixel_format_name);
}
if (attempt_desc) {
*attempt_desc = parts.empty() ? "default options" : "options{";
if (!parts.empty()) {
for (size_t i = 0; i < parts.size(); ++i) {
if (i > 0) {
attempt_desc->append(", ");
}
attempt_desc->append(parts[i]);
}
attempt_desc->append("}");
}
}
std::string input_name = "video=" + device_name;
int ret = avformat_open_input(format_ctx, input_name.c_str(), input, &options);
av_dict_free(&options);
return ret;
}
class ScopedComInit {
public:
ScopedComInit() {
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
initialized_ = hr == S_OK || hr == S_FALSE;
}
~ScopedComInit() {
if (initialized_) {
CoUninitialize();
}
}
private:
bool initialized_ = false;
};
int capture_stride(int pixel_format, int width) {
switch (pixel_format) {
case HWCODEC_CAPTURE_FMT_YUYV:
case HWCODEC_CAPTURE_FMT_YVYU:
case HWCODEC_CAPTURE_FMT_UYVY:
return width * 2;
case HWCODEC_CAPTURE_FMT_RGB24:
case HWCODEC_CAPTURE_FMT_BGR24:
return width * 3;
case HWCODEC_CAPTURE_FMT_NV24:
return width * 2;
case HWCODEC_CAPTURE_FMT_NV12:
case HWCODEC_CAPTURE_FMT_NV21:
case HWCODEC_CAPTURE_FMT_NV16:
case HWCODEC_CAPTURE_FMT_YUV420:
case HWCODEC_CAPTURE_FMT_YVU420:
case HWCODEC_CAPTURE_FMT_GREY:
case HWCODEC_CAPTURE_FMT_MJPEG:
case HWCODEC_CAPTURE_FMT_JPEG:
default:
return width;
}
}
int map_raw_pixfmt(int format) {
switch (format) {
case AV_PIX_FMT_YUYV422:
return HWCODEC_CAPTURE_FMT_YUYV;
case AV_PIX_FMT_UYVY422:
return HWCODEC_CAPTURE_FMT_UYVY;
#ifdef AV_PIX_FMT_YVYU422
case AV_PIX_FMT_YVYU422:
return HWCODEC_CAPTURE_FMT_YVYU;
#endif
case AV_PIX_FMT_NV12:
return HWCODEC_CAPTURE_FMT_NV12;
case AV_PIX_FMT_NV21:
return HWCODEC_CAPTURE_FMT_NV21;
#ifdef AV_PIX_FMT_NV16
case AV_PIX_FMT_NV16:
return HWCODEC_CAPTURE_FMT_NV16;
#endif
#ifdef AV_PIX_FMT_NV24
case AV_PIX_FMT_NV24:
return HWCODEC_CAPTURE_FMT_NV24;
#endif
case AV_PIX_FMT_YUV420P:
return HWCODEC_CAPTURE_FMT_YUV420;
#ifdef AV_PIX_FMT_YVU420P
case AV_PIX_FMT_YVU420P:
return HWCODEC_CAPTURE_FMT_YVU420;
#endif
case AV_PIX_FMT_RGB24:
return HWCODEC_CAPTURE_FMT_RGB24;
case AV_PIX_FMT_BGR24:
return HWCODEC_CAPTURE_FMT_BGR24;
case AV_PIX_FMT_GRAY8:
return HWCODEC_CAPTURE_FMT_GREY;
default:
return HWCODEC_CAPTURE_FMT_UNKNOWN;
}
}
int map_codec_to_capture_format(const AVCodecParameters* codecpar) {
if (!codecpar) {
return HWCODEC_CAPTURE_FMT_UNKNOWN;
}
switch (codecpar->codec_id) {
case AV_CODEC_ID_MJPEG:
return HWCODEC_CAPTURE_FMT_MJPEG;
case AV_CODEC_ID_JPEG2000:
return HWCODEC_CAPTURE_FMT_JPEG;
case AV_CODEC_ID_RAWVIDEO:
return map_raw_pixfmt(codecpar->format);
default:
return HWCODEC_CAPTURE_FMT_UNKNOWN;
}
}
int interrupt_callback(void* opaque) {
auto* ctx = reinterpret_cast<HwcodecDshowCaptureContext*>(opaque);
if (!ctx) {
return 0;
}
auto deadline = ctx->deadline_ms.load();
if (deadline <= 0) {
return 0;
}
if (now_ms() > deadline) {
ctx->timed_out.store(1);
return 1;
}
return 0;
}
const char* requested_pixel_format_name(int requested_format) {
switch (requested_format) {
case HWCODEC_CAPTURE_FMT_YUYV:
return "yuyv422";
case HWCODEC_CAPTURE_FMT_UYVY:
return "uyvy422";
case HWCODEC_CAPTURE_FMT_NV12:
return "nv12";
case HWCODEC_CAPTURE_FMT_NV21:
return "nv21";
case HWCODEC_CAPTURE_FMT_RGB24:
return "rgb24";
case HWCODEC_CAPTURE_FMT_BGR24:
return "bgr24";
case HWCODEC_CAPTURE_FMT_GREY:
return "gray";
default:
return nullptr;
}
}
} // namespace
extern "C" const char* hwcodec_capture_last_error(void) {
return g_last_error.c_str();
}
extern "C" char* hwcodec_dshow_list_video_devices(void) {
ScopedComInit com;
ICreateDevEnum* dev_enum = nullptr;
IEnumMoniker* enum_moniker = nullptr;
HRESULT hr = CoCreateInstance(
CLSID_SystemDeviceEnum,
nullptr,
CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum,
reinterpret_cast<void**>(&dev_enum));
if (FAILED(hr)) {
set_last_error("Failed to create DirectShow device enumerator");
return nullptr;
}
hr = dev_enum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &enum_moniker, 0);
dev_enum->Release();
if (hr != S_OK || !enum_moniker) {
char* out = reinterpret_cast<char*>(std::malloc(1));
if (out) {
out[0] = '\0';
}
return out;
}
std::vector<std::string> devices;
IMoniker* moniker = nullptr;
ULONG fetched = 0;
while (enum_moniker->Next(1, &moniker, &fetched) == S_OK) {
IPropertyBag* bag = nullptr;
hr = moniker->BindToStorage(nullptr, nullptr, IID_IPropertyBag, reinterpret_cast<void**>(&bag));
if (SUCCEEDED(hr) && bag) {
VARIANT name;
VariantInit(&name);
if (SUCCEEDED(bag->Read(L"FriendlyName", &name, nullptr)) && name.vt == VT_BSTR) {
auto utf8_name = wide_to_utf8(name.bstrVal);
if (!utf8_name.empty()) {
devices.push_back(utf8_name);
}
}
VariantClear(&name);
bag->Release();
}
moniker->Release();
}
enum_moniker->Release();
std::string payload;
for (size_t i = 0; i < devices.size(); ++i) {
payload += devices[i];
if (i + 1 < devices.size()) {
payload.push_back('\n');
}
}
return copy_payload(payload);
}
extern "C" char* hwcodec_dshow_list_device_capabilities(const char* device_name) {
if (!device_name || device_name[0] == '\0') {
set_last_error("DirectShow device name is empty");
return nullptr;
}
ScopedComInit com;
IBaseFilter* filter = nullptr;
if (!find_device_filter(device_name, &filter) || !filter) {
set_last_error("Failed to find DirectShow device filter");
return nullptr;
}
std::vector<DshowCapabilityEntry> entries;
IEnumPins* enum_pins = nullptr;
HRESULT hr = filter->EnumPins(&enum_pins);
if (SUCCEEDED(hr) && enum_pins) {
IPin* pin = nullptr;
ULONG fetched = 0;
while (enum_pins->Next(1, &pin, &fetched) == S_OK) {
PIN_DIRECTION direction = PINDIR_INPUT;
if (SUCCEEDED(pin->QueryDirection(&direction)) && direction == PINDIR_OUTPUT) {
IAMStreamConfig* stream_config = nullptr;
if (SUCCEEDED(pin->QueryInterface(IID_IAMStreamConfig, reinterpret_cast<void**>(&stream_config))) &&
stream_config) {
append_stream_capabilities(stream_config, &entries);
stream_config->Release();
}
}
pin->Release();
}
enum_pins->Release();
}
filter->Release();
std::sort(entries.begin(), entries.end(), [](const DshowCapabilityEntry& left, const DshowCapabilityEntry& right) {
if (left.format != right.format) {
return left.format < right.format;
}
if (left.width != right.width) {
return left.width < right.width;
}
if (left.height != right.height) {
return left.height < right.height;
}
return left.fps > right.fps;
});
entries.erase(
std::unique(entries.begin(), entries.end(), [](const DshowCapabilityEntry& left, const DshowCapabilityEntry& right) {
return left.format == right.format && left.width == right.width && left.height == right.height && left.fps == right.fps;
}),
entries.end());
return copy_payload(build_capabilities_payload(entries));
}
extern "C" void hwcodec_capture_string_free(char* ptr) {
if (ptr) {
std::free(ptr);
}
}
extern "C" HwcodecDshowCaptureContext* hwcodec_dshow_capture_open(
const char* device_name,
int width,
int height,
int fps,
int requested_format,
int timeout_ms) {
if (!device_name || device_name[0] == '\0') {
set_last_error("Device name is empty");
return nullptr;
}
avdevice_register_all();
const AVInputFormat* input = av_find_input_format("dshow");
if (!input) {
set_last_error("FFmpeg dshow input format is unavailable");
return nullptr;
}
auto* ctx = new HwcodecDshowCaptureContext();
ctx->timeout_ms = timeout_ms > 0 ? timeout_ms : 2000;
ctx->format_ctx = avformat_alloc_context();
if (!ctx->format_ctx) {
delete ctx;
set_last_error("Failed to allocate FFmpeg format context");
return nullptr;
}
ctx->format_ctx->interrupt_callback.callback = interrupt_callback;
ctx->format_ctx->interrupt_callback.opaque = ctx;
std::string open_attempt;
int ret = open_dshow_input_with_options(
&ctx->format_ctx,
input,
device_name,
width,
height,
fps,
requested_format,
true,
true,
true,
&open_attempt);
if (ret < 0) {
avformat_free_context(ctx->format_ctx);
ctx->format_ctx = avformat_alloc_context();
if (!ctx->format_ctx) {
delete ctx;
set_last_error("Failed to allocate FFmpeg format context for fallback open");
return nullptr;
}
ctx->format_ctx->interrupt_callback.callback = interrupt_callback;
ctx->format_ctx->interrupt_callback.opaque = ctx;
std::string fallback_attempt;
ret = open_dshow_input_with_options(
&ctx->format_ctx,
input,
device_name,
width,
height,
fps,
requested_format,
true,
false,
true,
&fallback_attempt);
if (ret >= 0) {
open_attempt = fallback_attempt;
}
}
if (ret < 0) {
avformat_free_context(ctx->format_ctx);
ctx->format_ctx = avformat_alloc_context();
if (!ctx->format_ctx) {
delete ctx;
set_last_error("Failed to allocate FFmpeg format context for final fallback open");
return nullptr;
}
ctx->format_ctx->interrupt_callback.callback = interrupt_callback;
ctx->format_ctx->interrupt_callback.opaque = ctx;
std::string fallback_attempt;
ret = open_dshow_input_with_options(
&ctx->format_ctx,
input,
device_name,
width,
height,
fps,
requested_format,
false,
false,
false,
&fallback_attempt);
if (ret >= 0) {
open_attempt = fallback_attempt;
}
}
if (ret < 0) {
set_last_error("Failed to open dshow input (" + open_attempt + "): " + ffmpeg_error(ret));
avformat_free_context(ctx->format_ctx);
delete ctx;
return nullptr;
}
ret = avformat_find_stream_info(ctx->format_ctx, nullptr);
if (ret < 0) {
set_last_error("Failed to read stream info: " + ffmpeg_error(ret));
avformat_close_input(&ctx->format_ctx);
delete ctx;
return nullptr;
}
for (unsigned int i = 0; i < ctx->format_ctx->nb_streams; ++i) {
AVStream* stream = ctx->format_ctx->streams[i];
if (stream && stream->codecpar && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
ctx->stream_index = static_cast<int>(i);
ctx->width = stream->codecpar->width > 0 ? stream->codecpar->width : width;
ctx->height = stream->codecpar->height > 0 ? stream->codecpar->height : height;
ctx->pixel_format = map_codec_to_capture_format(stream->codecpar);
ctx->stride = capture_stride(ctx->pixel_format, ctx->width);
break;
}
}
if (ctx->stream_index < 0) {
set_last_error("No video stream found on DirectShow device");
avformat_close_input(&ctx->format_ctx);
delete ctx;
return nullptr;
}
if (ctx->pixel_format == HWCODEC_CAPTURE_FMT_UNKNOWN) {
set_last_error("DirectShow stream format is unsupported in current Windows backend");
avformat_close_input(&ctx->format_ctx);
delete ctx;
return nullptr;
}
return ctx;
}
extern "C" int hwcodec_dshow_capture_info(
HwcodecDshowCaptureContext* ctx,
HwcodecCaptureStreamInfo* out_info) {
if (!ctx || !out_info) {
set_last_error("Invalid capture context");
return -1;
}
out_info->width = ctx->width;
out_info->height = ctx->height;
out_info->pixel_format = ctx->pixel_format;
out_info->stride = ctx->stride;
return 0;
}
extern "C" int hwcodec_dshow_capture_read(
HwcodecDshowCaptureContext* ctx,
uint8_t** out_data,
int* out_len,
uint64_t* out_sequence) {
if (!ctx || !out_data || !out_len || !out_sequence) {
set_last_error("Invalid capture read arguments");
return -1;
}
*out_data = nullptr;
*out_len = 0;
*out_sequence = 0;
AVPacket packet;
av_init_packet(&packet);
packet.data = nullptr;
packet.size = 0;
while (true) {
ctx->timed_out.store(0);
ctx->deadline_ms.store(now_ms() + ctx->timeout_ms);
int ret = av_read_frame(ctx->format_ctx, &packet);
ctx->deadline_ms.store(0);
if (ret < 0) {
if (ctx->timed_out.load() != 0) {
set_last_error("Timed out waiting for frame");
return -110;
}
set_last_error("Failed to read frame: " + ffmpeg_error(ret));
return ret;
}
if (packet.stream_index != ctx->stream_index) {
av_packet_unref(&packet);
continue;
}
if (packet.size <= 0 || !packet.data) {
av_packet_unref(&packet);
continue;
}
auto* buffer = reinterpret_cast<uint8_t*>(std::malloc(static_cast<size_t>(packet.size)));
if (!buffer) {
av_packet_unref(&packet);
set_last_error("Failed to allocate packet buffer");
return -12;
}
std::memcpy(buffer, packet.data, static_cast<size_t>(packet.size));
*out_data = buffer;
*out_len = packet.size;
*out_sequence = ctx->sequence++;
av_packet_unref(&packet);
return 0;
}
}
extern "C" void hwcodec_dshow_capture_packet_free(uint8_t* data) {
if (data) {
std::free(data);
}
}
extern "C" void hwcodec_dshow_capture_close(HwcodecDshowCaptureContext* ctx) {
if (!ctx) {
return;
}
if (ctx->format_ctx) {
avformat_close_input(&ctx->format_ctx);
}
delete ctx;
}

View File

@@ -0,0 +1,64 @@
#ifndef HWCODEC_FFMPEG_CAPTURE_FFI_H
#define HWCODEC_FFMPEG_CAPTURE_FFI_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct HwcodecDshowCaptureContext HwcodecDshowCaptureContext;
enum HwcodecCapturePixelFormat {
HWCODEC_CAPTURE_FMT_UNKNOWN = 0,
HWCODEC_CAPTURE_FMT_MJPEG = 1,
HWCODEC_CAPTURE_FMT_JPEG = 2,
HWCODEC_CAPTURE_FMT_YUYV = 3,
HWCODEC_CAPTURE_FMT_YVYU = 4,
HWCODEC_CAPTURE_FMT_UYVY = 5,
HWCODEC_CAPTURE_FMT_NV12 = 6,
HWCODEC_CAPTURE_FMT_NV21 = 7,
HWCODEC_CAPTURE_FMT_NV16 = 8,
HWCODEC_CAPTURE_FMT_NV24 = 9,
HWCODEC_CAPTURE_FMT_YUV420 = 10,
HWCODEC_CAPTURE_FMT_YVU420 = 11,
HWCODEC_CAPTURE_FMT_RGB24 = 12,
HWCODEC_CAPTURE_FMT_BGR24 = 13,
HWCODEC_CAPTURE_FMT_GREY = 14,
};
typedef struct HwcodecCaptureStreamInfo {
int width;
int height;
int pixel_format;
int stride;
} HwcodecCaptureStreamInfo;
const char* hwcodec_capture_last_error(void);
char* hwcodec_dshow_list_video_devices(void);
char* hwcodec_dshow_list_device_capabilities(const char* device_name);
void hwcodec_capture_string_free(char* ptr);
HwcodecDshowCaptureContext* hwcodec_dshow_capture_open(
const char* device_name,
int width,
int height,
int fps,
int requested_format,
int timeout_ms);
int hwcodec_dshow_capture_info(
HwcodecDshowCaptureContext* ctx,
HwcodecCaptureStreamInfo* out_info);
int hwcodec_dshow_capture_read(
HwcodecDshowCaptureContext* ctx,
uint8_t** out_data,
int* out_len,
uint64_t* out_sequence);
void hwcodec_dshow_capture_packet_free(uint8_t* data);
void hwcodec_dshow_capture_close(HwcodecDshowCaptureContext* ctx);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,50 @@
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// MJPEG -> H26x (H.264 / H.265) hardware pipeline
typedef struct FfmpegHwMjpegH26x FfmpegHwMjpegH26x;
// Create a new MJPEG -> H26x pipeline.
FfmpegHwMjpegH26x* ffmpeg_hw_mjpeg_h26x_new(const char* dec_name,
const char* enc_name,
int width,
int height,
int fps,
int bitrate_kbps,
int gop,
int thread_count);
// Encode one MJPEG frame. Returns 1 if output produced, 0 if no output, <0 on error.
int ffmpeg_hw_mjpeg_h26x_encode(FfmpegHwMjpegH26x* ctx,
const uint8_t* data,
int len,
int64_t pts_ms,
uint8_t** out_data,
int* out_len,
int* out_keyframe);
// Reconfigure bitrate/gop (best-effort, may recreate encoder internally).
int ffmpeg_hw_mjpeg_h26x_reconfigure(FfmpegHwMjpegH26x* ctx,
int bitrate_kbps,
int gop);
// Request next frame to be a keyframe.
int ffmpeg_hw_mjpeg_h26x_request_keyframe(FfmpegHwMjpegH26x* ctx);
// Free pipeline resources.
void ffmpeg_hw_mjpeg_h26x_free(FfmpegHwMjpegH26x* ctx);
// Free packet buffer allocated by ffmpeg_hw_mjpeg_h26x_encode.
void ffmpeg_hw_packet_free(uint8_t* data);
// Get last error message (thread-local).
const char* ffmpeg_hw_last_error(void);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,476 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/avutil.h>
#include <libavutil/error.h>
#include <libavutil/hwcontext.h>
#include <libavutil/hwcontext_drm.h>
#include <libavutil/pixdesc.h>
#include <libavutil/opt.h>
}
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define LOG_MODULE "FFMPEG_HW"
#include "../common/log.h"
#include "ffmpeg_hw_ffi.h"
namespace {
thread_local std::string g_last_error;
static void set_last_error(const std::string &msg) {
g_last_error = msg;
LOG_ERROR(msg);
}
static std::string make_err(const std::string &ctx, int err) {
return ctx + " (ret=" + std::to_string(err) + "): " + av_err2str(err);
}
static const char* pix_fmt_name(AVPixelFormat fmt) {
const char *name = av_get_pix_fmt_name(fmt);
return name ? name : "unknown";
}
struct FfmpegHwMjpegH26xCtx {
AVCodecContext *dec_ctx = nullptr;
AVCodecContext *enc_ctx = nullptr;
AVPacket *dec_pkt = nullptr;
AVFrame *dec_frame = nullptr;
AVPacket *enc_pkt = nullptr;
AVBufferRef *hw_device_ctx = nullptr;
AVBufferRef *hw_frames_ctx = nullptr;
AVPixelFormat hw_pixfmt = AV_PIX_FMT_NONE;
std::string dec_name;
std::string enc_name;
int width = 0;
int height = 0;
int aligned_width = 0;
int aligned_height = 0;
int fps = 30;
int bitrate_kbps = 2000;
int gop = 60;
int thread_count = 1;
bool force_keyframe = false;
};
static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
const enum AVPixelFormat *pix_fmts) {
auto *self = reinterpret_cast<FfmpegHwMjpegH26xCtx *>(ctx->opaque);
if (self && self->hw_pixfmt != AV_PIX_FMT_NONE) {
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
if (*p == self->hw_pixfmt) {
return *p;
}
}
}
return pix_fmts[0];
}
static int init_decoder(FfmpegHwMjpegH26xCtx *ctx) {
const AVCodec *dec = avcodec_find_decoder_by_name(ctx->dec_name.c_str());
if (!dec) {
set_last_error("Decoder not found: " + ctx->dec_name);
return -1;
}
ctx->dec_ctx = avcodec_alloc_context3(dec);
if (!ctx->dec_ctx) {
set_last_error("Failed to allocate decoder context");
return -1;
}
ctx->dec_ctx->width = ctx->width;
ctx->dec_ctx->height = ctx->height;
ctx->dec_ctx->thread_count = ctx->thread_count > 0 ? ctx->thread_count : 1;
ctx->dec_ctx->opaque = ctx;
// Pick HW pixfmt for RKMPP
const AVCodecHWConfig *cfg = nullptr;
for (int i = 0; (cfg = avcodec_get_hw_config(dec, i)); i++) {
if (cfg->device_type == AV_HWDEVICE_TYPE_RKMPP) {
ctx->hw_pixfmt = cfg->pix_fmt;
break;
}
}
if (ctx->hw_pixfmt == AV_PIX_FMT_NONE) {
set_last_error("No RKMPP hw pixfmt for decoder");
return -1;
}
int ret = av_hwdevice_ctx_create(&ctx->hw_device_ctx,
AV_HWDEVICE_TYPE_RKMPP, NULL, NULL, 0);
if (ret < 0) {
set_last_error(make_err("av_hwdevice_ctx_create failed", ret));
return -1;
}
ctx->dec_ctx->hw_device_ctx = av_buffer_ref(ctx->hw_device_ctx);
ctx->dec_ctx->get_format = get_hw_format;
ret = avcodec_open2(ctx->dec_ctx, dec, NULL);
if (ret < 0) {
set_last_error(make_err("avcodec_open2 decoder failed", ret));
return -1;
}
ctx->dec_pkt = av_packet_alloc();
ctx->dec_frame = av_frame_alloc();
ctx->enc_pkt = av_packet_alloc();
if (!ctx->dec_pkt || !ctx->dec_frame || !ctx->enc_pkt) {
set_last_error("Failed to allocate packet/frame");
return -1;
}
return 0;
}
static int init_encoder(FfmpegHwMjpegH26xCtx *ctx, AVBufferRef *frames_ctx) {
const AVCodec *enc = avcodec_find_encoder_by_name(ctx->enc_name.c_str());
if (!enc) {
set_last_error("Encoder not found: " + ctx->enc_name);
return -1;
}
ctx->enc_ctx = avcodec_alloc_context3(enc);
if (!ctx->enc_ctx) {
set_last_error("Failed to allocate encoder context");
return -1;
}
ctx->enc_ctx->width = ctx->width;
ctx->enc_ctx->height = ctx->height;
ctx->enc_ctx->coded_width = ctx->width;
ctx->enc_ctx->coded_height = ctx->height;
ctx->aligned_width = ctx->width;
ctx->aligned_height = ctx->height;
ctx->enc_ctx->time_base = AVRational{1, 1000};
ctx->enc_ctx->framerate = AVRational{ctx->fps, 1};
ctx->enc_ctx->bit_rate = (int64_t)ctx->bitrate_kbps * 1000;
ctx->enc_ctx->gop_size = ctx->gop > 0 ? ctx->gop : ctx->fps;
ctx->enc_ctx->max_b_frames = 0;
ctx->enc_ctx->pix_fmt = AV_PIX_FMT_DRM_PRIME;
ctx->enc_ctx->sw_pix_fmt = AV_PIX_FMT_NV12;
if (frames_ctx) {
AVHWFramesContext *hwfc = reinterpret_cast<AVHWFramesContext *>(frames_ctx->data);
if (hwfc) {
ctx->enc_ctx->pix_fmt = static_cast<AVPixelFormat>(hwfc->format);
ctx->enc_ctx->sw_pix_fmt = static_cast<AVPixelFormat>(hwfc->sw_format);
if (hwfc->width > 0) {
ctx->aligned_width = hwfc->width;
ctx->enc_ctx->coded_width = hwfc->width;
}
if (hwfc->height > 0) {
ctx->aligned_height = hwfc->height;
ctx->enc_ctx->coded_height = hwfc->height;
}
}
ctx->hw_frames_ctx = av_buffer_ref(frames_ctx);
ctx->enc_ctx->hw_frames_ctx = av_buffer_ref(frames_ctx);
}
if (ctx->hw_device_ctx) {
ctx->enc_ctx->hw_device_ctx = av_buffer_ref(ctx->hw_device_ctx);
}
AVDictionary *opts = nullptr;
av_dict_set(&opts, "rc_mode", "CBR", 0);
if (enc->id == AV_CODEC_ID_H264) {
av_dict_set(&opts, "profile", "high", 0);
} else if (enc->id == AV_CODEC_ID_HEVC) {
av_dict_set(&opts, "profile", "main", 0);
}
av_dict_set_int(&opts, "qp_init", 23, 0);
av_dict_set_int(&opts, "qp_max", 48, 0);
av_dict_set_int(&opts, "qp_min", 0, 0);
av_dict_set_int(&opts, "qp_max_i", 48, 0);
av_dict_set_int(&opts, "qp_min_i", 0, 0);
int ret = avcodec_open2(ctx->enc_ctx, enc, &opts);
av_dict_free(&opts);
if (ret < 0) {
std::string detail = "avcodec_open2 encoder failed: ";
detail += ctx->enc_name;
detail += " fmt=" + std::string(pix_fmt_name(ctx->enc_ctx->pix_fmt));
detail += " sw=" + std::string(pix_fmt_name(ctx->enc_ctx->sw_pix_fmt));
detail += " size=" + std::to_string(ctx->enc_ctx->width) + "x" + std::to_string(ctx->enc_ctx->height);
detail += " fps=" + std::to_string(ctx->fps);
set_last_error(make_err(detail, ret));
avcodec_free_context(&ctx->enc_ctx);
ctx->enc_ctx = nullptr;
if (ctx->hw_frames_ctx) {
av_buffer_unref(&ctx->hw_frames_ctx);
ctx->hw_frames_ctx = nullptr;
}
return -1;
}
return 0;
}
static void free_encoder(FfmpegHwMjpegH26xCtx *ctx) {
if (ctx->enc_ctx) {
avcodec_free_context(&ctx->enc_ctx);
ctx->enc_ctx = nullptr;
}
if (ctx->hw_frames_ctx) {
av_buffer_unref(&ctx->hw_frames_ctx);
ctx->hw_frames_ctx = nullptr;
}
}
} // namespace
extern "C" FfmpegHwMjpegH26x* ffmpeg_hw_mjpeg_h26x_new(const char* dec_name,
const char* enc_name,
int width,
int height,
int fps,
int bitrate_kbps,
int gop,
int thread_count) {
if (!dec_name || !enc_name || width <= 0 || height <= 0) {
set_last_error("Invalid parameters for ffmpeg_hw_mjpeg_h26x_new");
return nullptr;
}
auto *ctx = new FfmpegHwMjpegH26xCtx();
ctx->dec_name = dec_name;
ctx->enc_name = enc_name;
ctx->width = width;
ctx->height = height;
ctx->fps = fps > 0 ? fps : 30;
ctx->bitrate_kbps = bitrate_kbps > 0 ? bitrate_kbps : 2000;
ctx->gop = gop > 0 ? gop : ctx->fps;
ctx->thread_count = thread_count > 0 ? thread_count : 1;
if (init_decoder(ctx) != 0) {
ffmpeg_hw_mjpeg_h26x_free(reinterpret_cast<FfmpegHwMjpegH26x*>(ctx));
return nullptr;
}
return reinterpret_cast<FfmpegHwMjpegH26x*>(ctx);
}
extern "C" int ffmpeg_hw_mjpeg_h26x_encode(FfmpegHwMjpegH26x* handle,
const uint8_t* data,
int len,
int64_t pts_ms,
uint8_t** out_data,
int* out_len,
int* out_keyframe) {
if (!handle || !data || len <= 0 || !out_data || !out_len || !out_keyframe) {
set_last_error("Invalid parameters for encode");
return -1;
}
auto *ctx = reinterpret_cast<FfmpegHwMjpegH26xCtx*>(handle);
*out_data = nullptr;
*out_len = 0;
*out_keyframe = 0;
bool encoded = false;
av_packet_unref(ctx->dec_pkt);
int ret = av_new_packet(ctx->dec_pkt, len);
if (ret < 0) {
set_last_error(make_err("av_new_packet failed", ret));
return -1;
}
memcpy(ctx->dec_pkt->data, data, len);
ctx->dec_pkt->size = len;
ret = avcodec_send_packet(ctx->dec_ctx, ctx->dec_pkt);
if (ret < 0) {
set_last_error(make_err("avcodec_send_packet failed", ret));
return -1;
}
while (true) {
ret = avcodec_receive_frame(ctx->dec_ctx, ctx->dec_frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
return encoded ? 1 : 0;
}
if (ret < 0) {
set_last_error(make_err("avcodec_receive_frame failed", ret));
return -1;
}
if (ctx->dec_frame->format != AV_PIX_FMT_DRM_PRIME) {
set_last_error("Decoder output is not DRM_PRIME");
av_frame_unref(ctx->dec_frame);
return -1;
}
if (!ctx->enc_ctx) {
if (!ctx->dec_frame->hw_frames_ctx) {
set_last_error("Decoder returned frame without hw_frames_ctx");
av_frame_unref(ctx->dec_frame);
return -1;
}
if (init_encoder(ctx, ctx->dec_frame->hw_frames_ctx) != 0) {
av_frame_unref(ctx->dec_frame);
return -1;
}
}
AVFrame *send_frame = ctx->dec_frame;
AVFrame *tmp = nullptr;
if (ctx->force_keyframe) {
tmp = av_frame_clone(send_frame);
if (tmp) {
tmp->pict_type = AV_PICTURE_TYPE_I;
send_frame = tmp;
}
ctx->force_keyframe = false;
}
// Apply visible size crop if aligned buffer is larger than display size
if (ctx->aligned_width > 0 && ctx->width > 0 && ctx->aligned_width > ctx->width) {
send_frame->crop_right = ctx->aligned_width - ctx->width;
}
if (ctx->aligned_height > 0 && ctx->height > 0 && ctx->aligned_height > ctx->height) {
send_frame->crop_bottom = ctx->aligned_height - ctx->height;
}
send_frame->pts = pts_ms; // time_base is ms
ret = avcodec_send_frame(ctx->enc_ctx, send_frame);
if (tmp) {
av_frame_free(&tmp);
}
if (ret < 0) {
std::string detail = "avcodec_send_frame failed";
if (send_frame) {
detail += " frame_fmt=";
detail += pix_fmt_name(static_cast<AVPixelFormat>(send_frame->format));
detail += " w=" + std::to_string(send_frame->width);
detail += " h=" + std::to_string(send_frame->height);
if (send_frame->format == AV_PIX_FMT_DRM_PRIME && send_frame->data[0]) {
const AVDRMFrameDescriptor *drm =
reinterpret_cast<const AVDRMFrameDescriptor *>(send_frame->data[0]);
if (drm && drm->layers[0].format) {
detail += " drm_fmt=0x";
char buf[9];
snprintf(buf, sizeof(buf), "%08x", drm->layers[0].format);
detail += buf;
}
if (drm && drm->objects[0].format_modifier) {
detail += " drm_mod=0x";
char buf[17];
snprintf(buf, sizeof(buf), "%016llx",
(unsigned long long)drm->objects[0].format_modifier);
detail += buf;
}
}
}
set_last_error(make_err(detail, ret));
av_frame_unref(ctx->dec_frame);
return -1;
}
while (true) {
av_packet_unref(ctx->enc_pkt);
ret = avcodec_receive_packet(ctx->enc_ctx, ctx->enc_pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
}
if (ret < 0) {
set_last_error(make_err("avcodec_receive_packet failed", ret));
av_packet_unref(ctx->enc_pkt);
av_frame_unref(ctx->dec_frame);
return -1;
}
if (ctx->enc_pkt->size <= 0) {
set_last_error("avcodec_receive_packet failed, pkt size is 0");
av_packet_unref(ctx->enc_pkt);
av_frame_unref(ctx->dec_frame);
return -1;
}
if (!encoded) {
uint8_t *buf = (uint8_t*)malloc(ctx->enc_pkt->size);
if (!buf) {
set_last_error("malloc for output packet failed");
av_packet_unref(ctx->enc_pkt);
av_frame_unref(ctx->dec_frame);
return -1;
}
memcpy(buf, ctx->enc_pkt->data, ctx->enc_pkt->size);
*out_data = buf;
*out_len = ctx->enc_pkt->size;
*out_keyframe = (ctx->enc_pkt->flags & AV_PKT_FLAG_KEY) ? 1 : 0;
encoded = true;
}
}
av_frame_unref(ctx->dec_frame);
}
}
extern "C" int ffmpeg_hw_mjpeg_h26x_reconfigure(FfmpegHwMjpegH26x* handle,
int bitrate_kbps,
int gop) {
if (!handle) {
set_last_error("Invalid handle for reconfigure");
return -1;
}
auto *ctx = reinterpret_cast<FfmpegHwMjpegH26xCtx*>(handle);
if (!ctx->enc_ctx || !ctx->hw_frames_ctx) {
set_last_error("Encoder not initialized for reconfigure");
return -1;
}
ctx->bitrate_kbps = bitrate_kbps > 0 ? bitrate_kbps : ctx->bitrate_kbps;
ctx->gop = gop > 0 ? gop : ctx->gop;
AVBufferRef *frames_ref = ctx->hw_frames_ctx ? av_buffer_ref(ctx->hw_frames_ctx) : nullptr;
free_encoder(ctx);
if (init_encoder(ctx, frames_ref) != 0) {
if (frames_ref) av_buffer_unref(&frames_ref);
return -1;
}
if (frames_ref) av_buffer_unref(&frames_ref);
return 0;
}
extern "C" int ffmpeg_hw_mjpeg_h26x_request_keyframe(FfmpegHwMjpegH26x* handle) {
if (!handle) {
set_last_error("Invalid handle for request_keyframe");
return -1;
}
auto *ctx = reinterpret_cast<FfmpegHwMjpegH26xCtx*>(handle);
ctx->force_keyframe = true;
return 0;
}
extern "C" void ffmpeg_hw_mjpeg_h26x_free(FfmpegHwMjpegH26x* handle) {
auto *ctx = reinterpret_cast<FfmpegHwMjpegH26xCtx*>(handle);
if (!ctx) return;
if (ctx->dec_pkt) av_packet_free(&ctx->dec_pkt);
if (ctx->dec_frame) av_frame_free(&ctx->dec_frame);
if (ctx->enc_pkt) av_packet_free(&ctx->enc_pkt);
if (ctx->dec_ctx) avcodec_free_context(&ctx->dec_ctx);
free_encoder(ctx);
if (ctx->hw_device_ctx) av_buffer_unref(&ctx->hw_device_ctx);
delete ctx;
}
extern "C" void ffmpeg_hw_packet_free(uint8_t* data) {
if (data) {
free(data);
}
}
extern "C" const char* ffmpeg_hw_last_error(void) {
return g_last_error.c_str();
}

View File

@@ -137,6 +137,13 @@ public:
av_buffer_unref(&frames_ref);
}
if (name_.find("mediacodec") != std::string::npos && c_->priv_data) {
if ((ret = av_opt_set_int(c_->priv_data, "ndk_codec", 1, 0)) < 0) {
LOG_WARN(std::string("mediacodec decoder ndk_codec option failed, ret = ") +
av_err2str(ret));
}
}
if ((ret = avcodec_open2(c_, codec, NULL)) < 0) {
set_last_error(std::string("avcodec_open2 failed, ret = ") + av_err2str(ret));
return false;

View File

@@ -30,9 +30,15 @@ static int calculate_offset_length(int pix_fmt, int height, const int *linesize,
*length = offset[1] + linesize[2] * height / 2;
break;
case AV_PIX_FMT_NV12:
case AV_PIX_FMT_NV21:
offset[0] = linesize[0] * height;
*length = offset[0] + linesize[1] * height / 2;
break;
case AV_PIX_FMT_NV16:
case AV_PIX_FMT_NV24:
offset[0] = linesize[0] * height;
*length = offset[0] + linesize[1] * height;
break;
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
@@ -41,6 +47,11 @@ static int calculate_offset_length(int pix_fmt, int height, const int *linesize,
offset[0] = 0; // Only one plane
*length = linesize[0] * height;
break;
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_BGR24:
offset[0] = 0; // Only one plane
*length = linesize[0] * height;
break;
default:
LOG_ERROR(std::string("unsupported pixfmt") + std::to_string(pix_fmt));
return -1;
@@ -101,6 +112,9 @@ _exit:
namespace {
typedef void (*RamEncodeCallback)(const uint8_t *data, int len, int64_t pts,
int key, const void *obj);
typedef void (*RamEncodePacketCallback)(void *packet, const uint8_t *data,
int len, int64_t pts, int key,
const void *obj);
class FFmpegRamEncoder {
public:
@@ -123,6 +137,7 @@ public:
int thread_count_ = 1;
int gpu_ = 0;
RamEncodeCallback callback_ = NULL;
RamEncodePacketCallback packet_callback_ = NULL;
int offset_[AV_NUM_DATA_POINTERS] = {0};
bool force_keyframe_ = false; // Force next frame to be a keyframe
@@ -130,6 +145,7 @@ public:
AVPixelFormat hw_pixfmt_ = AV_PIX_FMT_NONE;
AVBufferRef *hw_device_ctx_ = NULL;
AVFrame *hw_frame_ = NULL;
AVFrame *borrowed_frame_ = NULL;
FFmpegRamEncoder(const char *name, const char *mc_name, int width, int height,
int pixfmt, int align, int fps, int gop, int rc, int quality,
@@ -236,6 +252,11 @@ public:
LOG_ERROR(std::string("Could not allocate video packet"));
return false;
}
borrowed_frame_ = av_frame_alloc();
if (!borrowed_frame_) {
LOG_ERROR(std::string("Could not allocate borrowed video frame"));
return false;
}
/* resolution must be a multiple of two */
c_->width = width_;
@@ -286,11 +307,19 @@ public:
int encode(const uint8_t *data, int length, const void *obj, uint64_t ms) {
int ret;
if (can_borrow_input(length)) {
AVFrame *borrowed = wrap_borrowed_frame(data, length);
if (!borrowed) {
return -1;
}
return do_encode(borrowed, obj, ms);
}
if ((ret = av_frame_make_writable(frame_)) != 0) {
LOG_ERROR(std::string("av_frame_make_writable failed, ret = ") + av_err2str(ret));
return ret;
}
if ((ret = fill_frame(frame_, (uint8_t *)data, length, offset_)) != 0)
if ((ret = fill_frame(frame_, data, length, offset_)) != 0)
return ret;
AVFrame *tmp_frame;
if (hw_device_type_ != AV_HWDEVICE_TYPE_NONE) {
@@ -306,6 +335,14 @@ public:
return do_encode(tmp_frame, obj, ms);
}
int encode_packet(const uint8_t *data, int length, const void *obj,
uint64_t ms, RamEncodePacketCallback callback) {
packet_callback_ = callback;
int ret = encode(data, length, obj, ms);
packet_callback_ = NULL;
return ret;
}
void free_encoder() {
if (pkt_)
av_packet_free(&pkt_);
@@ -313,6 +350,8 @@ public:
av_frame_free(&frame_);
if (hw_frame_)
av_frame_free(&hw_frame_);
if (borrowed_frame_)
av_frame_free(&borrowed_frame_);
if (hw_device_ctx_)
av_buffer_unref(&hw_device_ctx_);
if (c_)
@@ -365,76 +404,203 @@ private:
frame->pict_type = AV_PICTURE_TYPE_NONE;
}
if ((ret = avcodec_send_frame(c_, frame)) < 0) {
ret = avcodec_send_frame(c_, frame);
if (ret == AVERROR(EAGAIN)) {
int drain_ret = receive_available_packets(obj, encoded);
if (drain_ret < 0) {
return drain_ret;
}
ret = avcodec_send_frame(c_, frame);
}
if (ret == AVERROR(EAGAIN)) {
return encoded ? 0 : AVERROR(EAGAIN);
}
if (ret < 0) {
LOG_ERROR(std::string("avcodec_send_frame failed, ret = ") + av_err2str(ret));
return ret;
}
auto start = util::now();
while (ret >= 0 && util::elapsed_ms(start) < DECODE_TIMEOUT_MS) {
if ((ret = avcodec_receive_packet(c_, pkt_)) < 0) {
if (ret != AVERROR(EAGAIN)) {
LOG_ERROR(std::string("avcodec_receive_packet failed, ret = ") + av_err2str(ret));
}
goto _exit;
}
if (!pkt_->data || !pkt_->size) {
LOG_ERROR(std::string("avcodec_receive_packet failed, pkt size is 0"));
goto _exit;
}
encoded = true;
callback_(pkt_->data, pkt_->size, pkt_->pts,
pkt_->flags & AV_PKT_FLAG_KEY, obj);
ret = receive_available_packets(obj, encoded);
if (ret < 0) {
return ret;
}
_exit:
av_packet_unref(pkt_);
// If no packet is produced for this input frame, treat it as EAGAIN.
// This is not a fatal error: encoders may buffer internally (e.g., startup delay).
return encoded ? 0 : AVERROR(EAGAIN);
}
int fill_frame(AVFrame *frame, uint8_t *data, int data_length,
const int *const offset) {
int receive_available_packets(const void *obj, bool &encoded) {
int ret = 0;
auto start = util::now();
while (util::elapsed_ms(start) < DECODE_TIMEOUT_MS) {
ret = avcodec_receive_packet(c_, pkt_);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
return 0;
}
if (ret < 0) {
LOG_ERROR(std::string("avcodec_receive_packet failed, ret = ") + av_err2str(ret));
av_packet_unref(pkt_);
return ret;
}
if (!pkt_->data || !pkt_->size) {
LOG_WARN(std::string("avcodec_receive_packet returned empty packet"));
av_packet_unref(pkt_);
continue;
}
encoded = true;
if (packet_callback_) {
AVPacket *owned_pkt = av_packet_clone(pkt_);
if (!owned_pkt) {
LOG_ERROR("av_packet_clone failed");
av_packet_unref(pkt_);
return AVERROR(ENOMEM);
}
packet_callback_(owned_pkt, owned_pkt->data, owned_pkt->size,
owned_pkt->pts, owned_pkt->flags & AV_PKT_FLAG_KEY,
obj);
} else {
callback_(pkt_->data, pkt_->size, pkt_->pts,
pkt_->flags & AV_PKT_FLAG_KEY, obj);
}
av_packet_unref(pkt_);
}
return 0;
}
int copy_plane(uint8_t *dst, int dst_stride, const uint8_t *src,
int src_stride, int row_bytes, int rows) {
if (!dst || !src || dst_stride < row_bytes || src_stride < row_bytes) {
return -1;
}
if (rows <= 0 || row_bytes <= 0) {
return 0;
}
if (dst_stride == row_bytes && src_stride == row_bytes) {
memcpy(dst, src, static_cast<size_t>(row_bytes) * rows);
return 0;
}
for (int y = 0; y < rows; y++) {
memcpy(dst + y * dst_stride, src + y * src_stride, row_bytes);
}
return 0;
}
int fill_frame(AVFrame *frame, const uint8_t *data, int data_length,
const int *const) {
const int src_y_stride = width_;
const int src_packed_stride = width_ * bytes_per_pixel(frame->format);
const int src_uv_stride = width_;
const int src_y_size = width_ * frame->height;
const int src_420_chroma_size = (width_ / 2) * (frame->height / 2);
switch (frame->format) {
case AV_PIX_FMT_NV12:
case AV_PIX_FMT_NV21:
if (data_length <
frame->height * (frame->linesize[0] + frame->linesize[1] / 2)) {
LOG_ERROR(std::string("fill_frame: NV12 data length error. data_length:") +
frame->height * src_y_stride + frame->height / 2 * src_uv_stride) {
LOG_ERROR(std::string("fill_frame: NV12/NV21 data length error. data_length:") +
std::to_string(data_length) +
", linesize[0]:" + std::to_string(frame->linesize[0]) +
", linesize[1]:" + std::to_string(frame->linesize[1]));
", width:" + std::to_string(width_) +
", height:" + std::to_string(frame->height));
return -1;
}
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
width_, frame->height) != 0 ||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
src_uv_stride, width_, frame->height / 2) != 0) {
LOG_ERROR("fill_frame: NV12/NV21 copy failed");
return -1;
}
frame->data[0] = data;
frame->data[1] = data + offset[0];
break;
case AV_PIX_FMT_NV16:
if (data_length <
frame->height * src_y_stride + frame->height * src_uv_stride) {
LOG_ERROR(std::string("fill_frame: NV16 data length error. data_length:") +
std::to_string(data_length) +
", width:" + std::to_string(width_) +
", height:" + std::to_string(frame->height));
return -1;
}
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
width_, frame->height) != 0 ||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
src_uv_stride, width_, frame->height) != 0) {
LOG_ERROR("fill_frame: NV16 copy failed");
return -1;
}
break;
case AV_PIX_FMT_NV24: {
const int src_nv24_uv_stride = width_ * 2;
if (data_length <
frame->height * src_y_stride + frame->height * src_nv24_uv_stride) {
LOG_ERROR(std::string("fill_frame: NV24 data length error. data_length:") +
std::to_string(data_length) +
", width:" + std::to_string(width_) +
", height:" + std::to_string(frame->height));
return -1;
}
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
width_, frame->height) != 0 ||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
src_nv24_uv_stride, width_ * 2, frame->height) != 0) {
LOG_ERROR("fill_frame: NV24 copy failed");
return -1;
}
break;
}
case AV_PIX_FMT_YUV420P:
if (data_length <
frame->height * (frame->linesize[0] + frame->linesize[1] / 2 +
frame->linesize[2] / 2)) {
width_ * frame->height + (width_ / 2) * (frame->height / 2) * 2) {
LOG_ERROR(std::string("fill_frame: 420P data length error. data_length:") +
std::to_string(data_length) +
", linesize[0]:" + std::to_string(frame->linesize[0]) +
", linesize[1]:" + std::to_string(frame->linesize[1]) +
", linesize[2]:" + std::to_string(frame->linesize[2]));
", width:" + std::to_string(width_) +
", height:" + std::to_string(frame->height));
return -1;
}
if (copy_plane(frame->data[0], frame->linesize[0], data, width_,
width_, frame->height) != 0 ||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
width_ / 2, width_ / 2, frame->height / 2) != 0 ||
copy_plane(frame->data[2], frame->linesize[2],
data + src_y_size + src_420_chroma_size,
width_ / 2, width_ / 2, frame->height / 2) != 0) {
LOG_ERROR("fill_frame: 420P copy failed");
return -1;
}
frame->data[0] = data;
frame->data[1] = data + offset[0];
frame->data[2] = data + offset[1];
break;
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
// Packed YUV 4:2:2 formats: single plane, linesize[0] = width * 2
if (data_length < frame->height * frame->linesize[0]) {
if (data_length < frame->height * src_packed_stride) {
LOG_ERROR(std::string("fill_frame: YUYV422 data length error. data_length:") +
std::to_string(data_length) +
", linesize[0]:" + std::to_string(frame->linesize[0]) +
", stride:" + std::to_string(src_packed_stride) +
", height:" + std::to_string(frame->height));
return -1;
}
frame->data[0] = data;
if (copy_plane(frame->data[0], frame->linesize[0], data,
src_packed_stride, src_packed_stride, frame->height) != 0) {
LOG_ERROR("fill_frame: YUYV422 copy failed");
return -1;
}
break;
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_BGR24:
if (data_length < frame->height * src_packed_stride) {
LOG_ERROR(std::string("fill_frame: RGB24/BGR24 data length error. data_length:") +
std::to_string(data_length) +
", stride:" + std::to_string(src_packed_stride) +
", height:" + std::to_string(frame->height));
return -1;
}
if (copy_plane(frame->data[0], frame->linesize[0], data,
src_packed_stride, src_packed_stride, frame->height) != 0) {
LOG_ERROR("fill_frame: RGB24/BGR24 copy failed");
return -1;
}
break;
default:
LOG_ERROR(std::string("fill_frame: unsupported format, ") +
@@ -443,6 +609,79 @@ private:
}
return 0;
}
bool can_borrow_input(int data_length) const {
if (hw_device_type_ != AV_HWDEVICE_TYPE_NONE) {
return false;
}
if (name_.find("mediacodec") == std::string::npos) {
return false;
}
switch (pixfmt_) {
case AV_PIX_FMT_NV12:
case AV_PIX_FMT_NV21:
return data_length >= width_ * height_ * 3 / 2;
case AV_PIX_FMT_YUV420P:
return data_length >= width_ * height_ * 3 / 2;
default:
return false;
}
}
AVFrame *wrap_borrowed_frame(const uint8_t *data, int data_length) {
if (!borrowed_frame_) {
return NULL;
}
av_frame_unref(borrowed_frame_);
borrowed_frame_->format = pixfmt_;
borrowed_frame_->width = width_;
borrowed_frame_->height = height_;
const int y_size = width_ * height_;
const int uv_size = y_size / 4;
switch (pixfmt_) {
case AV_PIX_FMT_NV12:
case AV_PIX_FMT_NV21:
if (data_length < y_size + y_size / 2) {
LOG_ERROR("wrap_borrowed_frame: NV12/NV21 data length error");
return NULL;
}
borrowed_frame_->data[0] = const_cast<uint8_t *>(data);
borrowed_frame_->data[1] = const_cast<uint8_t *>(data + y_size);
borrowed_frame_->linesize[0] = width_;
borrowed_frame_->linesize[1] = width_;
break;
case AV_PIX_FMT_YUV420P:
if (data_length < y_size + uv_size * 2) {
LOG_ERROR("wrap_borrowed_frame: YUV420P data length error");
return NULL;
}
borrowed_frame_->data[0] = const_cast<uint8_t *>(data);
borrowed_frame_->data[1] = const_cast<uint8_t *>(data + y_size);
borrowed_frame_->data[2] = const_cast<uint8_t *>(data + y_size + uv_size);
borrowed_frame_->linesize[0] = width_;
borrowed_frame_->linesize[1] = width_ / 2;
borrowed_frame_->linesize[2] = width_ / 2;
break;
default:
return NULL;
}
return borrowed_frame_;
}
int bytes_per_pixel(int pix_fmt) {
switch (pix_fmt) {
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
return 2;
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_BGR24:
return 3;
default:
return 1;
}
}
};
} // namespace
@@ -496,6 +735,25 @@ extern "C" void ffmpeg_ram_free_encoder(FFmpegRamEncoder *encoder) {
}
}
extern "C" int ffmpeg_ram_encode_packet(FFmpegRamEncoder *encoder,
const uint8_t *data, int length,
const void *obj, uint64_t ms,
RamEncodePacketCallback callback) {
try {
return encoder->encode_packet(data, length, obj, ms, callback);
} catch (const std::exception &e) {
LOG_ERROR(std::string("encode_packet failed, ") + std::string(e.what()));
return -1;
}
}
extern "C" void ffmpeg_ram_free_packet(void *packet) {
AVPacket *pkt = reinterpret_cast<AVPacket *>(packet);
if (pkt) {
av_packet_free(&pkt);
}
}
extern "C" int ffmpeg_ram_set_bitrate(FFmpegRamEncoder *encoder, int kbs) {
try {
return encoder->set_bitrate(kbs);

View File

@@ -7,6 +7,9 @@
typedef void (*RamEncodeCallback)(const uint8_t *data, int len, int64_t pts,
int key, const void *obj);
typedef void (*RamEncodePacketCallback)(void *packet, const uint8_t *data,
int len, int64_t pts, int key,
const void *obj);
typedef void (*RamDecodeCallback)(const uint8_t *data, int len, int width,
int height, int pixfmt, const void *obj);
@@ -18,7 +21,11 @@ void *ffmpeg_ram_new_encoder(const char *name, const char *mc_name, int width,
RamEncodeCallback callback);
int ffmpeg_ram_encode(void *encoder, const uint8_t *data, int length,
const void *obj, int64_t ms);
int ffmpeg_ram_encode_packet(void *encoder, const uint8_t *data, int length,
const void *obj, int64_t ms,
RamEncodePacketCallback callback);
void ffmpeg_ram_free_encoder(void *encoder);
void ffmpeg_ram_free_packet(void *packet);
int ffmpeg_ram_get_linesize_offset_length(int pix_fmt, int width, int height,
int align, int *linesize, int *offset,
int *length);

297
libs/hwcodec/src/capture.rs Normal file
View File

@@ -0,0 +1,297 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use std::ffi::{CStr, CString};
use std::os::raw::c_int;
include!(concat!(env!("OUT_DIR"), "/ffmpeg_capture_ffi.rs"));
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CapturePixelFormat {
Unknown,
Mjpeg,
Jpeg,
Yuyv,
Yvyu,
Uyvy,
Nv12,
Nv21,
Nv16,
Nv24,
Yuv420,
Yvu420,
Rgb24,
Bgr24,
Grey,
}
impl CapturePixelFormat {
pub fn to_ffi(self) -> c_int {
match self {
Self::Unknown => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_UNKNOWN as c_int,
Self::Mjpeg => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_MJPEG as c_int,
Self::Jpeg => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_JPEG as c_int,
Self::Yuyv => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YUYV as c_int,
Self::Yvyu => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YVYU as c_int,
Self::Uyvy => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_UYVY as c_int,
Self::Nv12 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV12 as c_int,
Self::Nv21 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV21 as c_int,
Self::Nv16 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV16 as c_int,
Self::Nv24 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV24 as c_int,
Self::Yuv420 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YUV420 as c_int,
Self::Yvu420 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YVU420 as c_int,
Self::Rgb24 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_RGB24 as c_int,
Self::Bgr24 => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_BGR24 as c_int,
Self::Grey => HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_GREY as c_int,
}
}
pub fn from_ffi(value: c_int) -> Self {
match value {
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_MJPEG as c_int => Self::Mjpeg,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_JPEG as c_int => Self::Jpeg,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YUYV as c_int => Self::Yuyv,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YVYU as c_int => Self::Yvyu,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_UYVY as c_int => Self::Uyvy,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV12 as c_int => Self::Nv12,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV21 as c_int => Self::Nv21,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV16 as c_int => Self::Nv16,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_NV24 as c_int => Self::Nv24,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YUV420 as c_int => {
Self::Yuv420
}
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_YVU420 as c_int => {
Self::Yvu420
}
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_RGB24 as c_int => Self::Rgb24,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_BGR24 as c_int => Self::Bgr24,
x if x == HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_GREY as c_int => Self::Grey,
_ => Self::Unknown,
}
}
pub fn from_name(name: &str) -> Option<Self> {
match name.trim().to_ascii_uppercase().as_str() {
"MJPEG" | "MJPG" => Some(Self::Mjpeg),
"JPEG" => Some(Self::Jpeg),
"YUYV" => Some(Self::Yuyv),
"YVYU" => Some(Self::Yvyu),
"UYVY" => Some(Self::Uyvy),
"NV12" => Some(Self::Nv12),
"NV21" => Some(Self::Nv21),
"NV16" => Some(Self::Nv16),
"NV24" => Some(Self::Nv24),
"YUV420" | "I420" | "IYUV" => Some(Self::Yuv420),
"YVU420" | "YV12" => Some(Self::Yvu420),
"RGB24" => Some(Self::Rgb24),
"BGR24" => Some(Self::Bgr24),
"GREY" | "GRAY" | "Y800" => Some(Self::Grey),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct DshowCapability {
pub format: CapturePixelFormat,
pub width: u32,
pub height: u32,
pub fps: Vec<u32>,
}
#[derive(Debug, Clone, Copy)]
pub struct CaptureStreamInfo {
pub width: i32,
pub height: i32,
pub pixel_format: CapturePixelFormat,
pub stride: i32,
}
#[derive(Debug)]
pub struct CaptureError {
pub code: i32,
pub message: String,
}
impl std::fmt::Display for CaptureError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for CaptureError {}
fn last_error_message() -> String {
unsafe {
let ptr = hwcodec_capture_last_error();
if ptr.is_null() {
return String::new();
}
CStr::from_ptr(ptr).to_string_lossy().to_string()
}
}
pub fn list_dshow_video_devices() -> Result<Vec<String>, CaptureError> {
unsafe {
let ptr = hwcodec_dshow_list_video_devices();
if ptr.is_null() {
return Err(CaptureError {
code: -1,
message: last_error_message(),
});
}
let payload = CStr::from_ptr(ptr).to_string_lossy().to_string();
hwcodec_capture_string_free(ptr as *mut _);
Ok(payload
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(ToOwned::to_owned)
.collect())
}
}
pub fn list_dshow_device_capabilities(device_name: &str) -> Result<Vec<DshowCapability>, CaptureError> {
let device_name = CString::new(device_name).map_err(|_| CaptureError {
code: -1,
message: "device name contains NUL byte".to_string(),
})?;
unsafe {
let ptr = hwcodec_dshow_list_device_capabilities(device_name.as_ptr());
if ptr.is_null() {
return Err(CaptureError {
code: -1,
message: last_error_message(),
});
}
let payload = CStr::from_ptr(ptr).to_string_lossy().to_string();
hwcodec_capture_string_free(ptr as *mut _);
let capabilities = payload
.lines()
.filter_map(parse_dshow_capability_line)
.collect();
Ok(capabilities)
}
}
fn parse_dshow_capability_line(line: &str) -> Option<DshowCapability> {
let mut parts = line.split('|');
let format = CapturePixelFormat::from_name(parts.next()?.trim())?;
let width = parts.next()?.trim().parse::<u32>().ok()?;
let height = parts.next()?.trim().parse::<u32>().ok()?;
let fps = parts
.next()
.unwrap_or_default()
.split(',')
.filter_map(|value| value.trim().parse::<u32>().ok())
.filter(|value| *value > 0)
.collect::<Vec<_>>();
Some(DshowCapability {
format,
width,
height,
fps,
})
}
pub struct DshowCapture {
ctx: *mut HwcodecDshowCaptureContext,
}
unsafe impl Send for DshowCapture {}
impl DshowCapture {
pub fn open(
device_name: &str,
width: i32,
height: i32,
fps: i32,
requested_format: CapturePixelFormat,
timeout_ms: i32,
) -> Result<Self, CaptureError> {
let device_name = CString::new(device_name).map_err(|_| CaptureError {
code: -1,
message: "device name contains NUL byte".to_string(),
})?;
unsafe {
let ctx = hwcodec_dshow_capture_open(
device_name.as_ptr(),
width,
height,
fps,
requested_format.to_ffi(),
timeout_ms,
);
if ctx.is_null() {
return Err(CaptureError {
code: -1,
message: last_error_message(),
});
}
Ok(Self { ctx })
}
}
pub fn info(&self) -> Result<CaptureStreamInfo, CaptureError> {
unsafe {
let mut info = HwcodecCaptureStreamInfo {
width: 0,
height: 0,
pixel_format: HwcodecCapturePixelFormat::HWCODEC_CAPTURE_FMT_UNKNOWN as c_int,
stride: 0,
};
let ret = hwcodec_dshow_capture_info(self.ctx, &mut info);
if ret != 0 {
return Err(CaptureError {
code: ret,
message: last_error_message(),
});
}
Ok(CaptureStreamInfo {
width: info.width,
height: info.height,
pixel_format: CapturePixelFormat::from_ffi(info.pixel_format),
stride: info.stride,
})
}
}
pub fn read_packet(&mut self) -> Result<(Vec<u8>, u64), CaptureError> {
unsafe {
let mut data = std::ptr::null_mut();
let mut len = 0;
let mut sequence = 0u64;
let ret = hwcodec_dshow_capture_read(self.ctx, &mut data, &mut len, &mut sequence);
if ret != 0 {
return Err(CaptureError {
code: ret,
message: last_error_message(),
});
}
if data.is_null() || len <= 0 {
return Err(CaptureError {
code: -1,
message: "empty packet returned by capture backend".to_string(),
});
}
let slice = std::slice::from_raw_parts(data, len as usize);
let vec = slice.to_vec();
hwcodec_dshow_capture_packet_free(data);
Ok((vec, sequence))
}
}
}
impl Drop for DshowCapture {
fn drop(&mut self) {
unsafe {
hwcodec_dshow_capture_close(self.ctx);
}
self.ctx = std::ptr::null_mut();
}
}

View File

@@ -13,7 +13,7 @@ pub enum Driver {
FFMPEG,
}
#[cfg(any(windows, target_os = "linux"))]
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
pub(crate) fn supported_gpu(_encode: bool) -> (bool, bool, bool) {
#[cfg(target_os = "linux")]
use std::ffi::c_int;
@@ -39,6 +39,8 @@ pub(crate) fn supported_gpu(_encode: bool) -> (bool, bool, bool) {
linux_support_amd() == 0,
linux_support_intel() == 0,
);
#[cfg(target_os = "android")]
return (false, false, false);
#[allow(unreachable_code)]
(false, false, false)
}

View File

@@ -6,6 +6,7 @@
include!(concat!(env!("OUT_DIR"), "/ffmpeg_ffi.rs"));
use serde_derive::{Deserialize, Serialize};
use std::{env, ffi::CString};
#[derive(Debug, Eq, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub enum AVHWDeviceType {
@@ -53,7 +54,52 @@ pub extern "C" fn hwcodec_av_log_callback(level: i32, message: *const std::os::r
pub(crate) fn init_av_log() {
static INIT: std::sync::Once = std::sync::Once::new();
INIT.call_once(|| unsafe {
av_log_set_level(AV_LOG_ERROR as i32);
av_log_set_level(parse_ffmpeg_log_level());
hwcodec_set_av_log_callback();
});
}
pub fn resolve_pixel_format(name: &str, fallback: AVPixelFormat) -> i32 {
let c_name = match CString::new(name) {
Ok(name) => name,
Err(_) => return fallback as i32,
};
unsafe {
let resolved = av_get_pix_fmt(c_name.as_ptr());
if resolved >= 0 {
resolved
} else {
fallback as i32
}
}
}
fn parse_ffmpeg_log_level() -> i32 {
let raw = match env::var("ONE_KVM_FFMPEG_LOG") {
Ok(value) => value,
Err(_) => return AV_LOG_ERROR as i32,
};
let value = raw.trim().to_ascii_lowercase();
if value.is_empty() {
return AV_LOG_ERROR as i32;
}
if let Ok(level) = value.parse::<i32>() {
return level;
}
match value.as_str() {
"quiet" => AV_LOG_QUIET as i32,
"panic" => AV_LOG_PANIC as i32,
"fatal" => AV_LOG_FATAL as i32,
"error" => AV_LOG_ERROR as i32,
"warn" | "warning" => AV_LOG_WARNING as i32,
"info" => AV_LOG_INFO as i32,
"verbose" => AV_LOG_VERBOSE as i32,
"debug" => AV_LOG_DEBUG as i32,
"trace" => AV_LOG_TRACE as i32,
_ => AV_LOG_ERROR as i32,
}
}

View File

@@ -0,0 +1,120 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use std::{
ffi::{CStr, CString},
os::raw::c_int,
};
include!(concat!(env!("OUT_DIR"), "/ffmpeg_hw_ffi.rs"));
#[derive(Debug, Clone)]
pub struct HwMjpegH26xConfig {
pub decoder: String,
pub encoder: String,
pub width: i32,
pub height: i32,
pub fps: i32,
pub bitrate_kbps: i32,
pub gop: i32,
pub thread_count: i32,
}
pub struct HwMjpegH26xPipeline {
ctx: *mut FfmpegHwMjpegH26x,
config: HwMjpegH26xConfig,
}
unsafe impl Send for HwMjpegH26xPipeline {}
impl HwMjpegH26xPipeline {
pub fn new(config: HwMjpegH26xConfig) -> Result<Self, String> {
unsafe {
let dec = CString::new(config.decoder.as_str())
.map_err(|_| "decoder name invalid".to_string())?;
let enc = CString::new(config.encoder.as_str())
.map_err(|_| "encoder name invalid".to_string())?;
let ctx = ffmpeg_hw_mjpeg_h26x_new(
dec.as_ptr(),
enc.as_ptr(),
config.width,
config.height,
config.fps,
config.bitrate_kbps,
config.gop,
config.thread_count,
);
if ctx.is_null() {
return Err(last_error_message());
}
Ok(Self { ctx, config })
}
}
pub fn encode(&mut self, data: &[u8], pts_ms: i64) -> Result<Option<(Vec<u8>, bool)>, String> {
unsafe {
let mut out_data: *mut u8 = std::ptr::null_mut();
let mut out_len: c_int = 0;
let mut out_key: c_int = 0;
let ret = ffmpeg_hw_mjpeg_h26x_encode(
self.ctx,
data.as_ptr(),
data.len() as c_int,
pts_ms,
&mut out_data,
&mut out_len,
&mut out_key,
);
if ret < 0 {
return Err(last_error_message());
}
if out_data.is_null() || out_len == 0 {
return Ok(None);
}
let slice = std::slice::from_raw_parts(out_data, out_len as usize);
let mut vec = Vec::with_capacity(slice.len());
vec.extend_from_slice(slice);
ffmpeg_hw_packet_free(out_data);
Ok(Some((vec, out_key != 0)))
}
}
pub fn reconfigure(&mut self, bitrate_kbps: i32, gop: i32) -> Result<(), String> {
unsafe {
let ret = ffmpeg_hw_mjpeg_h26x_reconfigure(self.ctx, bitrate_kbps, gop);
if ret != 0 {
return Err(last_error_message());
}
self.config.bitrate_kbps = bitrate_kbps;
self.config.gop = gop;
Ok(())
}
}
pub fn request_keyframe(&mut self) {
unsafe {
let _ = ffmpeg_hw_mjpeg_h26x_request_keyframe(self.ctx);
}
}
}
impl Drop for HwMjpegH26xPipeline {
fn drop(&mut self) {
unsafe {
ffmpeg_hw_mjpeg_h26x_free(self.ctx);
}
self.ctx = std::ptr::null_mut();
}
}
pub fn last_error_message() -> String {
unsafe {
let ptr = ffmpeg_hw_last_error();
if ptr.is_null() {
return String::new();
}
let cstr = CStr::from_ptr(ptr);
cstr.to_string_lossy().to_string()
}
}

View File

@@ -1,8 +1,7 @@
use crate::{
ffmpeg::{init_av_log, AVPixelFormat},
ffmpeg_ram::{
ffmpeg_ram_decode, ffmpeg_ram_free_decoder, ffmpeg_ram_last_error,
ffmpeg_ram_new_decoder,
ffmpeg_ram_decode, ffmpeg_ram_free_decoder, ffmpeg_ram_last_error, ffmpeg_ram_new_decoder,
},
};
use std::{

View File

@@ -2,11 +2,13 @@ use crate::{
common::DataFormat::{self, *},
ffmpeg::{init_av_log, AVPixelFormat},
ffmpeg_ram::{
ffmpeg_linesize_offset_length, ffmpeg_ram_encode, ffmpeg_ram_free_encoder,
ffmpeg_ram_new_encoder, ffmpeg_ram_request_keyframe, ffmpeg_ram_set_bitrate, CodecInfo,
AV_NUM_DATA_POINTERS,
ffmpeg_linesize_offset_length, ffmpeg_ram_encode, ffmpeg_ram_encode_packet,
ffmpeg_ram_free_encoder, ffmpeg_ram_free_packet, ffmpeg_ram_new_encoder,
ffmpeg_ram_request_keyframe, ffmpeg_ram_set_bitrate, CodecInfo, AV_NUM_DATA_POINTERS,
},
};
#[cfg(feature = "bytes")]
use bytes::Bytes;
use log::trace;
use std::{
ffi::{c_void, CString},
@@ -15,12 +17,450 @@ use std::{
slice,
};
use super::Priority;
#[cfg(any(windows, target_os = "linux"))]
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
use crate::common::Driver;
/// Timeout for encoder test in milliseconds
const TEST_TIMEOUT_MS: u64 = 3000;
const PRIORITY_NVENC: i32 = 0;
const PRIORITY_QSV: i32 = 1;
const PRIORITY_AMF: i32 = 2;
const PRIORITY_RKMPP: i32 = 3;
const PRIORITY_VAAPI: i32 = 4;
const PRIORITY_V4L2M2M: i32 = 5;
const PRIORITY_MEDIACODEC: i32 = 2;
#[derive(Clone, Copy)]
struct CandidateCodecSpec {
name: &'static str,
format: DataFormat,
priority: i32,
}
fn push_candidate(codecs: &mut Vec<CodecInfo>, candidate: CandidateCodecSpec) {
codecs.push(CodecInfo {
name: candidate.name.to_owned(),
format: candidate.format,
priority: candidate.priority,
..Default::default()
});
}
#[cfg(target_os = "linux")]
fn linux_support_vaapi() -> bool {
let entries = match std::fs::read_dir("/dev/dri") {
Ok(entries) => entries,
Err(_) => return false,
};
entries.flatten().any(|entry| {
entry
.file_name()
.to_str()
.map(|name| name.starts_with("renderD"))
.unwrap_or(false)
})
}
#[cfg(not(target_os = "linux"))]
fn linux_support_vaapi() -> bool {
false
}
#[cfg(target_os = "linux")]
fn linux_support_rkmpp() -> bool {
extern "C" {
fn linux_support_rkmpp() -> c_int;
}
unsafe { linux_support_rkmpp() == 0 }
}
#[cfg(not(target_os = "linux"))]
fn linux_support_rkmpp() -> bool {
false
}
#[cfg(target_os = "linux")]
fn linux_support_v4l2m2m() -> bool {
extern "C" {
fn linux_support_v4l2m2m() -> c_int;
}
unsafe { linux_support_v4l2m2m() == 0 }
}
#[cfg(not(target_os = "linux"))]
fn linux_support_v4l2m2m() -> bool {
false
}
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
fn enumerate_candidate_codecs(ctx: &EncodeContext) -> Vec<CodecInfo> {
use log::debug;
let mut codecs = Vec::new();
if cfg!(target_os = "android") {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_mediacodec",
format: H264,
priority: PRIORITY_MEDIACODEC,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_mediacodec",
format: H265,
priority: PRIORITY_MEDIACODEC,
},
);
return codecs;
}
let contains = |_vendor: Driver, _format: DataFormat| {
// Without VRAM feature, we can't check SDK availability.
// Keep the prefilter coarse and let FFmpeg validation do the real check.
true
};
let (nv, amf, intel) = crate::common::supported_gpu(true);
debug!(
"GPU support detected - NV: {}, AMF: {}, Intel: {}",
nv, amf, intel
);
if nv && contains(Driver::NV, H264) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_nvenc",
format: H264,
priority: PRIORITY_NVENC,
},
);
}
if nv && contains(Driver::NV, H265) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_nvenc",
format: H265,
priority: PRIORITY_NVENC,
},
);
}
if intel && contains(Driver::MFX, H264) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_qsv",
format: H264,
priority: PRIORITY_QSV,
},
);
}
if intel && contains(Driver::MFX, H265) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_qsv",
format: H265,
priority: PRIORITY_QSV,
},
);
}
if amf && contains(Driver::AMF, H264) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_amf",
format: H264,
priority: PRIORITY_AMF,
},
);
}
if amf && contains(Driver::AMF, H265) {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_amf",
format: H265,
priority: PRIORITY_AMF,
},
);
}
if linux_support_rkmpp() {
debug!("RKMPP hardware detected, adding Rockchip encoders");
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_rkmpp",
format: H264,
priority: PRIORITY_RKMPP,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_rkmpp",
format: H265,
priority: PRIORITY_RKMPP,
},
);
}
if cfg!(target_os = "linux") && linux_support_vaapi() {
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_vaapi",
format: H264,
priority: PRIORITY_VAAPI,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_vaapi",
format: H265,
priority: PRIORITY_VAAPI,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "vp8_vaapi",
format: VP8,
priority: PRIORITY_VAAPI,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "vp9_vaapi",
format: VP9,
priority: PRIORITY_VAAPI,
},
);
}
if linux_support_v4l2m2m() {
debug!("V4L2 M2M hardware detected, adding V4L2 encoders");
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "h264_v4l2m2m",
format: H264,
priority: PRIORITY_V4L2M2M,
},
);
push_candidate(
&mut codecs,
CandidateCodecSpec {
name: "hevc_v4l2m2m",
format: H265,
priority: PRIORITY_V4L2M2M,
},
);
}
codecs.retain(|codec| {
!(ctx.pixfmt == AVPixelFormat::AV_PIX_FMT_YUV420P as i32 && codec.name.contains("qsv"))
});
codecs
}
#[derive(Clone, Copy)]
struct ProbePolicy {
max_attempts: usize,
request_keyframe: bool,
accept_any_output: bool,
}
impl ProbePolicy {
fn for_codec(codec_name: &str) -> Self {
if codec_name.contains("mediacodec") {
Self {
max_attempts: 30,
request_keyframe: true,
accept_any_output: true,
}
} else if codec_name.contains("amf") {
Self {
max_attempts: 5,
request_keyframe: true,
accept_any_output: true,
}
} else if codec_name.contains("v4l2m2m") {
Self {
max_attempts: 5,
request_keyframe: true,
accept_any_output: true,
}
} else {
Self {
max_attempts: 1,
request_keyframe: false,
accept_any_output: false,
}
}
}
fn prepare_attempt(&self, encoder: &mut Encoder) {
if self.request_keyframe {
encoder.request_keyframe();
}
}
fn passed(&self, frames: &[EncodeFrame], elapsed_ms: u128) -> bool {
if elapsed_ms >= TEST_TIMEOUT_MS as u128 {
return false;
}
if self.accept_any_output {
!frames.is_empty()
} else {
frames.len() == 1 && frames[0].key == 1
}
}
}
fn log_failed_probe_attempt(
codec_name: &str,
policy: ProbePolicy,
attempt: usize,
frames: &[EncodeFrame],
elapsed_ms: u128,
) {
use log::{debug, trace};
if policy.accept_any_output {
if frames.is_empty() {
trace!(
"Encoder {} test produced no output on attempt {}",
codec_name, attempt
);
} else {
debug!(
"Encoder {} test failed on attempt {} - frames: {}, timeout: {}ms",
codec_name,
attempt,
frames.len(),
elapsed_ms
);
}
} else if frames.len() == 1 {
debug!(
"Encoder {} test failed on attempt {} - key: {}, timeout: {}ms",
codec_name, attempt, frames[0].key, elapsed_ms
);
} else {
debug!(
"Encoder {} test failed on attempt {} - wrong frame count: {}",
codec_name,
attempt,
frames.len()
);
}
}
fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> bool {
use log::{debug, warn};
debug!("Testing encoder: {}", codec.name);
let test_ctx = EncodeContext {
name: codec.name.clone(),
mc_name: codec.mc_name.clone(),
..ctx.clone()
};
match Encoder::new(test_ctx) {
Ok(mut encoder) => {
debug!("Encoder {} created successfully", codec.name);
let policy = ProbePolicy::for_codec(&codec.name);
let mut last_err: Option<i32> = None;
for attempt in 0..policy.max_attempts {
let attempt_no = attempt + 1;
policy.prepare_attempt(&mut encoder);
let pts = (attempt as i64) * 33;
let start = std::time::Instant::now();
match encoder.encode(yuv, pts) {
Ok(frames) => {
let elapsed = start.elapsed().as_millis();
if policy.passed(frames, elapsed) {
if policy.accept_any_output {
debug!(
"Encoder {} test passed on attempt {} (frames: {})",
codec.name,
attempt_no,
frames.len()
);
} else {
debug!(
"Encoder {} test passed on attempt {}",
codec.name, attempt_no
);
}
return true;
} else {
log_failed_probe_attempt(
&codec.name,
policy,
attempt_no,
frames,
elapsed,
);
}
}
Err(err) => {
last_err = Some(err);
warn!(
"Encoder {} test attempt {} returned error: {}",
codec.name, attempt_no, err
);
}
}
}
debug!(
"Encoder {} test failed after retries{}",
codec.name,
last_err
.map(|e| format!(" (last err: {})", e))
.unwrap_or_default()
);
false
}
Err(_) => {
warn!("Failed to create encoder {}", codec.name);
false
}
}
}
fn add_software_fallback(codecs: &mut Vec<CodecInfo>) {
use log::debug;
if cfg!(target_os = "android") {
return;
}
for fallback in CodecInfo::soft().into_vec() {
if !codecs.iter().any(|codec| codec.format == fallback.format) {
debug!(
"Adding software {:?} encoder: {}",
fallback.format, fallback.name
);
codecs.push(fallback);
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct EncodeContext {
@@ -28,7 +468,7 @@ pub struct EncodeContext {
pub mc_name: Option<String>,
pub width: i32,
pub height: i32,
pub pixfmt: AVPixelFormat,
pub pixfmt: i32,
pub align: i32,
pub fps: i32,
pub gop: i32,
@@ -45,6 +485,39 @@ pub struct EncodeFrame {
pub key: i32,
}
#[cfg(feature = "bytes")]
pub struct EncodeBytesFrame {
pub data: Bytes,
pub pts: i64,
pub key: i32,
}
#[cfg(feature = "bytes")]
struct FfmpegPacketOwner {
packet: *mut c_void,
data: *const u8,
len: usize,
}
#[cfg(feature = "bytes")]
unsafe impl Send for FfmpegPacketOwner {}
#[cfg(feature = "bytes")]
impl AsRef<[u8]> for FfmpegPacketOwner {
fn as_ref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.data, self.len) }
}
}
#[cfg(feature = "bytes")]
impl Drop for FfmpegPacketOwner {
fn drop(&mut self) {
unsafe {
ffmpeg_ram_free_packet(self.packet);
}
}
}
impl Display for EncodeFrame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "encode len:{}, pts:{}", self.data.len(), self.pts)
@@ -83,7 +556,7 @@ impl Encoder {
CString::new(mc_name.as_str()).map_err(|_| ())?.as_ptr(),
ctx.width,
ctx.height,
ctx.pixfmt as c_int,
ctx.pixfmt,
ctx.align,
ctx.fps,
ctx.gop,
@@ -137,6 +610,25 @@ impl Encoder {
}
}
#[cfg(feature = "bytes")]
pub fn encode_bytes(&mut self, data: &[u8], ms: i64) -> Result<Vec<EncodeBytesFrame>, i32> {
unsafe {
let mut frames = Vec::<EncodeBytesFrame>::new();
let result = ffmpeg_ram_encode_packet(
self.codec,
data.as_ptr(),
data.len() as _,
&mut frames as *mut _ as *const c_void,
ms,
Some(Encoder::packet_callback),
);
if result == -11 || result == 0 {
return Ok(frames);
}
Err(result)
}
}
extern "C" fn callback(data: *const u8, size: c_int, pts: i64, key: i32, obj: *const c_void) {
unsafe {
let frames = &mut *(obj as *mut Vec<EncodeFrame>);
@@ -148,6 +640,30 @@ impl Encoder {
}
}
#[cfg(feature = "bytes")]
extern "C" fn packet_callback(
packet: *mut c_void,
data: *const u8,
size: c_int,
pts: i64,
key: i32,
obj: *const c_void,
) {
unsafe {
let frames = &mut *(obj as *mut Vec<EncodeBytesFrame>);
let owner = FfmpegPacketOwner {
packet,
data,
len: size as usize,
};
frames.push(EncodeBytesFrame {
data: Bytes::from_owner(owner),
pts,
key,
});
}
}
pub fn set_bitrate(&mut self, kbs: i32) -> Result<(), ()> {
let ret = unsafe { ffmpeg_ram_set_bitrate(self.codec, kbs) };
if ret == 0 {
@@ -182,278 +698,24 @@ impl Encoder {
pub fn available_encoders(ctx: EncodeContext, _sdk: Option<String>) -> Vec<CodecInfo> {
use log::debug;
if !(cfg!(windows) || cfg!(target_os = "linux")) {
if !(cfg!(windows) || cfg!(target_os = "linux") || cfg!(target_os = "android")) {
return vec![];
}
let mut codecs: Vec<CodecInfo> = vec![];
#[cfg(any(windows, target_os = "linux"))]
{
let contains = |_vendor: Driver, _format: DataFormat| {
// Without VRAM feature, we can't check SDK availability
// Just return true and let FFmpeg handle the actual detection
true
};
let (_nv, amf, _intel) = crate::common::supported_gpu(true);
debug!(
"GPU support detected - NV: {}, AMF: {}, Intel: {}",
_nv, amf, _intel
);
#[cfg(windows)]
if _intel && contains(Driver::MFX, H264) {
codecs.push(CodecInfo {
name: "h264_qsv".to_owned(),
format: H264,
priority: Priority::Best as _,
..Default::default()
});
}
#[cfg(windows)]
if _intel && contains(Driver::MFX, H265) {
codecs.push(CodecInfo {
name: "hevc_qsv".to_owned(),
format: H265,
priority: Priority::Best as _,
..Default::default()
});
}
if _nv && contains(Driver::NV, H264) {
codecs.push(CodecInfo {
name: "h264_nvenc".to_owned(),
format: H264,
priority: Priority::Best as _,
..Default::default()
});
}
if _nv && contains(Driver::NV, H265) {
codecs.push(CodecInfo {
name: "hevc_nvenc".to_owned(),
format: H265,
priority: Priority::Best as _,
..Default::default()
});
}
if amf && contains(Driver::AMF, H264) {
codecs.push(CodecInfo {
name: "h264_amf".to_owned(),
format: H264,
priority: Priority::Best as _,
..Default::default()
});
}
if amf {
codecs.push(CodecInfo {
name: "hevc_amf".to_owned(),
format: H265,
priority: Priority::Best as _,
..Default::default()
});
}
#[cfg(target_os = "linux")]
{
codecs.push(CodecInfo {
name: "h264_vaapi".to_owned(),
format: H264,
priority: Priority::Good as _,
..Default::default()
});
codecs.push(CodecInfo {
name: "hevc_vaapi".to_owned(),
format: H265,
priority: Priority::Good as _,
..Default::default()
});
codecs.push(CodecInfo {
name: "vp8_vaapi".to_owned(),
format: VP8,
priority: Priority::Good as _,
..Default::default()
});
codecs.push(CodecInfo {
name: "vp9_vaapi".to_owned(),
format: VP9,
priority: Priority::Good as _,
..Default::default()
});
// Rockchip MPP hardware encoder support
use std::ffi::c_int;
extern "C" {
fn linux_support_rkmpp() -> c_int;
fn linux_support_v4l2m2m() -> c_int;
}
if unsafe { linux_support_rkmpp() } == 0 {
debug!("RKMPP hardware detected, adding Rockchip encoders");
codecs.push(CodecInfo {
name: "h264_rkmpp".to_owned(),
format: H264,
priority: Priority::Best as _,
..Default::default()
});
codecs.push(CodecInfo {
name: "hevc_rkmpp".to_owned(),
format: H265,
priority: Priority::Best as _,
..Default::default()
});
}
// V4L2 Memory-to-Memory hardware encoder support (generic ARM)
if unsafe { linux_support_v4l2m2m() } == 0 {
debug!("V4L2 M2M hardware detected, adding V4L2 encoders");
codecs.push(CodecInfo {
name: "h264_v4l2m2m".to_owned(),
format: H264,
priority: Priority::Good as _,
..Default::default()
});
codecs.push(CodecInfo {
name: "hevc_v4l2m2m".to_owned(),
format: H265,
priority: Priority::Good as _,
..Default::default()
});
}
}
}
// qsv doesn't support yuv420p
codecs.retain(|c| {
let ctx = ctx.clone();
if ctx.pixfmt == AVPixelFormat::AV_PIX_FMT_YUV420P && c.name.contains("qsv") {
return false;
}
return true;
});
let mut res = vec![];
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
let codecs = enumerate_candidate_codecs(&ctx);
if let Ok(yuv) = Encoder::dummy_yuv(ctx.clone()) {
for codec in codecs {
// Skip if this format already exists in results
if res
.iter()
.any(|existing: &CodecInfo| existing.format == codec.format)
{
continue;
}
debug!("Testing encoder: {}", codec.name);
let c = EncodeContext {
name: codec.name.clone(),
mc_name: codec.mc_name.clone(),
..ctx
};
match Encoder::new(c) {
Ok(mut encoder) => {
debug!("Encoder {} created successfully", codec.name);
let mut passed = false;
let mut last_err: Option<i32> = None;
let max_attempts = 1;
for attempt in 0..max_attempts {
let pts = (attempt as i64) * 33; // 33ms is an approximation for 30 FPS (1000 / 30)
let start = std::time::Instant::now();
match encoder.encode(&yuv, pts) {
Ok(frames) => {
let elapsed = start.elapsed().as_millis();
if frames.len() == 1 {
if frames[0].key == 1 && elapsed < TEST_TIMEOUT_MS as _ {
debug!(
"Encoder {} test passed on attempt {}",
codec.name,
attempt + 1
);
res.push(codec.clone());
passed = true;
break;
} else {
debug!(
"Encoder {} test failed on attempt {} - key: {}, timeout: {}ms",
codec.name,
attempt + 1,
frames[0].key,
elapsed
);
}
} else {
debug!(
"Encoder {} test failed on attempt {} - wrong frame count: {}",
codec.name,
attempt + 1,
frames.len()
);
}
}
Err(err) => {
last_err = Some(err);
debug!(
"Encoder {} test attempt {} returned error: {}",
codec.name,
attempt + 1,
err
);
}
}
}
if !passed {
debug!(
"Encoder {} test failed after retries{}",
codec.name,
last_err
.map(|e| format!(" (last err: {})", e))
.unwrap_or_default()
);
}
}
Err(_) => {
debug!("Failed to create encoder {}", codec.name);
}
if validate_candidate(&codec, &ctx, &yuv) {
res.push(codec);
}
}
} else {
debug!("Failed to generate dummy YUV data");
}
// Add software encoders as fallback
let soft_codecs = CodecInfo::soft();
// Add H264 software encoder if not already present
if !res.iter().any(|c| c.format == H264) {
if let Some(h264_soft) = soft_codecs.h264 {
debug!("Adding software H264 encoder: {}", h264_soft.name);
res.push(h264_soft);
}
}
// Add H265 software encoder if not already present
if !res.iter().any(|c| c.format == H265) {
if let Some(h265_soft) = soft_codecs.h265 {
debug!("Adding software H265 encoder: {}", h265_soft.name);
res.push(h265_soft);
}
}
// Add VP8 software encoder if not already present
if !res.iter().any(|c| c.format == VP8) {
if let Some(vp8_soft) = soft_codecs.vp8 {
debug!("Adding software VP8 encoder: {}", vp8_soft.name);
res.push(vp8_soft);
}
}
// Add VP9 software encoder if not already present
if !res.iter().any(|c| c.format == VP9) {
if let Some(vp9_soft) = soft_codecs.vp9 {
debug!("Adding software VP9 encoder: {}", vp9_soft.name);
res.push(vp9_soft);
}
}
add_software_fallback(&mut res);
res
}

View File

@@ -3,21 +3,24 @@
#![allow(non_snake_case)]
use crate::common::DataFormat::{self, *};
use crate::ffmpeg::{
AVHWDeviceType::{self, *},
AVPixelFormat,
};
use crate::ffmpeg::AVHWDeviceType::{self, *};
use serde_derive::{Deserialize, Serialize};
use std::ffi::c_int;
include!(concat!(env!("OUT_DIR"), "/ffmpeg_ram_ffi.rs"));
#[cfg(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"))]
#[cfg(all(
any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"),
not(target_os = "android")
))]
pub mod decode;
// Provide a small stub on non-ARM builds so dependents can still compile, but decoder
// construction will fail (since the C++ RKMPP decoder isn't built/linked).
#[cfg(not(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp")))]
#[cfg(any(
not(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp")),
target_os = "android"
))]
pub mod decode {
use crate::ffmpeg::AVPixelFormat;
@@ -86,6 +89,40 @@ impl Default for CodecInfo {
}
impl CodecInfo {
pub fn software(format: DataFormat) -> Option<Self> {
match format {
H264 => Some(CodecInfo {
name: "libx264".to_owned(),
mc_name: Default::default(),
format: H264,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
H265 => Some(CodecInfo {
name: "libx265".to_owned(),
mc_name: Default::default(),
format: H265,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
VP8 => Some(CodecInfo {
name: "libvpx".to_owned(),
mc_name: Default::default(),
format: VP8,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
VP9 => Some(CodecInfo {
name: "libvpx-vp9".to_owned(),
mc_name: Default::default(),
format: VP9,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
AV1 => None,
}
}
pub fn prioritized(coders: Vec<CodecInfo>) -> CodecInfos {
let mut h264: Option<CodecInfo> = None;
let mut h265: Option<CodecInfo> = None;
@@ -148,34 +185,10 @@ impl CodecInfo {
pub fn soft() -> CodecInfos {
CodecInfos {
h264: Some(CodecInfo {
name: "libx264".to_owned(),
mc_name: Default::default(),
format: H264,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
h265: Some(CodecInfo {
name: "libx265".to_owned(),
mc_name: Default::default(),
format: H265,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
vp8: Some(CodecInfo {
name: "libvpx".to_owned(),
mc_name: Default::default(),
format: VP8,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
vp9: Some(CodecInfo {
name: "libvpx-vp9".to_owned(),
mc_name: Default::default(),
format: VP9,
hwdevice: AV_HWDEVICE_TYPE_NONE,
priority: Priority::Soft as _,
}),
h264: CodecInfo::software(H264),
h265: CodecInfo::software(H265),
vp8: CodecInfo::software(VP8),
vp9: CodecInfo::software(VP9),
av1: None,
}
}
@@ -191,6 +204,23 @@ pub struct CodecInfos {
}
impl CodecInfos {
pub fn into_vec(self) -> Vec<CodecInfo> {
let mut codecs = Vec::new();
if let Some(codec) = self.h264 {
codecs.push(codec);
}
if let Some(codec) = self.h265 {
codecs.push(codec);
}
if let Some(codec) = self.vp8 {
codecs.push(codec);
}
if let Some(codec) = self.vp9 {
codecs.push(codec);
}
codecs
}
pub fn serialize(&self) -> Result<String, ()> {
match serde_json::to_string_pretty(self) {
Ok(s) => Ok(s),
@@ -207,7 +237,7 @@ impl CodecInfos {
}
pub fn ffmpeg_linesize_offset_length(
pixfmt: AVPixelFormat,
pixfmt: i32,
width: usize,
height: usize,
align: usize,
@@ -220,7 +250,7 @@ pub fn ffmpeg_linesize_offset_length(
length.resize(1, 0);
unsafe {
if ffmpeg_ram_get_linesize_offset_length(
pixfmt as _,
pixfmt,
width as _,
height as _,
align as _,

View File

@@ -1,5 +1,12 @@
#[cfg(windows)]
pub mod capture;
pub mod common;
pub mod ffmpeg;
#[cfg(all(
any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"),
not(target_os = "android")
))]
pub mod ffmpeg_hw;
pub mod ffmpeg_ram;
#[no_mangle]

1
libs/v4l2r/.cargo-ok Normal file
View File

@@ -0,0 +1 @@
{"v":1}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "7b441383125ae583017a1c18b3fc9ec6c88ddbe8"
},
"path_in_vcs": "lib"
}

52
libs/v4l2r/Android.bp Normal file
View File

@@ -0,0 +1,52 @@
// This file is generated by cargo_embargo.
// Do not modify this file because the changes will be overridden on upgrade.
package {
default_applicable_licenses: ["external_rust_crates_v4l2r_license"],
}
rust_library {
name: "libv4l2r",
crate_name: "v4l2r",
cargo_env_compat: true,
cargo_pkg_version: "0.0.7",
crate_root: "src/lib.rs",
edition: "2021",
rustlibs: [
"libbitflags",
"liblog_rust",
"libnix",
"libthiserror",
],
proc_macros: ["libenumn"],
apex_available: [
"//apex_available:platform",
"//apex_available:anyapex",
],
product_available: true,
vendor_available: true,
// Bindgen-generated bindings of our local videodev2.h.
srcs: [":libv4l2r_bindgen"],
}
rust_test {
name: "v4l2r_test_src_lib",
crate_name: "v4l2r",
cargo_env_compat: true,
cargo_pkg_version: "0.0.7",
crate_root: "src/lib.rs",
test_suites: ["general-tests"],
auto_gen_config: true,
edition: "2021",
rustlibs: [
"libbitflags",
"liblog_rust",
"libnix",
"libthiserror",
],
proc_macros: ["libenumn"],
// Bindgen-generated bindings of our local videodev2.h.
srcs: [":libv4l2r_bindgen"],
}

65
libs/v4l2r/Cargo.toml Normal file
View File

@@ -0,0 +1,65 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
name = "v4l2r"
version = "0.0.7"
authors = ["Alexandre Courbot <gnurou@gmail.com>"]
build = "build.rs"
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Safe and flexible abstraction over V4L2"
readme = "README.md"
keywords = [
"v4l2",
"video",
"linux",
]
categories = ["os"]
license-file = "LICENSE"
repository = "https://github.com/Gnurou/v4l2r"
[features]
arch32 = []
arch64 = []
[lib]
name = "v4l2r"
path = "src/lib.rs"
[dependencies.bitflags]
version = "2.4"
[dependencies.enumn]
version = "0.1.6"
[dependencies.log]
version = "0.4.14"
[dependencies.nix]
version = "0.28"
features = [
"ioctl",
"mman",
"poll",
"fs",
"event",
]
[dependencies.thiserror]
version = "1.0"
[build-dependencies.bindgen]
version = "0.70.1"

28
libs/v4l2r/Cargo.toml.orig generated Normal file
View File

@@ -0,0 +1,28 @@
[package]
name = "v4l2r"
version = "0.0.7"
authors = ["Alexandre Courbot <gnurou@gmail.com>"]
edition = "2021"
description = "Safe and flexible abstraction over V4L2"
repository = "https://github.com/Gnurou/v4l2r"
categories = ["os"]
keywords = ["v4l2", "video", "linux"]
license-file.workspace = true
readme.workspace = true
[features]
# Generate the bindings for 64-bit even if the host is 32-bit.
arch64 = []
# Generate the bindings for 32-bit even if the host is 64-bit.
arch32 = []
[dependencies]
nix = { version = "0.28", features = ["ioctl", "mman", "poll", "fs", "event"] }
bitflags = "2.4"
thiserror = "1.0"
log = "0.4.14"
enumn = "0.1.6"
[build-dependencies]
bindgen = "0.70.1"

23
libs/v4l2r/LICENSE Normal file
View File

@@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

Some files were not shown because too many files have changed in this diff Show More