Compare commits

..

172 Commits

Author SHA1 Message Date
SilentWind
9ef5011760 Merge pull request #312 from mofeng-git/dev
Dev
2026-09-21 21:50:53 +08:00
mofeng-git
d71112380c chore: bump version to v0.2.7 2026-09-21 21:49:52 +08:00
mofeng-git
491bfbecb5 fix: improve UAC playback and OTG rebinding 2026-09-21 21:47:49 +08:00
mofeng-git
8a6cc98806 fix(build): 禁用阿里云镜像推送的证明元数据 2026-09-17 18:15:08 +08:00
mofeng-git
728373b067 build: 撤销 Debian 11 快照修复并迁移至 Debian 12 2026-09-16 23:18:51 +08:00
mofeng-git
c62ff2da87 fix(extensions): explicitly disable gostc TLS for HTTP connections 2026-09-12 23:10:50 +08:00
SilentWind
572bf859ba Merge pull request #309 from mofeng-git/fix/uac-native-alsa
fix: 修正 UAC 链接顺序及原生 ALSA 启动恢复
2026-09-11 08:24:02 +08:00
SilentWind
aef136241a Merge pull request #304 from drgnchan/fix/ch9329-macos-drag
fix(hid): add macOS drag compatibility for OTG and CH9329
2026-09-10 23:02:29 +08:00
mofeng-git
78af9f67de fix(hid): share macOS drag compatibility across OTG and CH9329 2026-09-10 23:00:34 +08:00
mofeng-git
9f34b4109b fix: 修正 UAC 链接顺序及原生 ALSA 启动恢复 2026-09-10 22:43:36 +08:00
mofeng-git
1967d22dff Merge remote-tracking branch 'origin/dev' into review/pr304-macos 2026-09-10 22:42:18 +08:00
mofeng-git
0cba8ab127 fix: 固定 Debian 11 软件源快照以修复交叉编译 2026-09-10 14:08:17 +08:00
raymond
d002226acb merge: resolve dev conflicts for CH9329 macOS drag compatibility 2026-09-07 23:26:57 +08:00
mofeng-git
1db572e020 feat(web): 完善控制台视频与电源控件 2026-09-06 11:20:11 +08:00
mofeng-git
5de5ee42c2 feat(web): 新增 HID 配置引导 2026-09-06 11:19:55 +08:00
mofeng-git
2c19208094 feat(bluetooth-hid): 支持经典蓝牙 HID 后端 2026-09-06 11:17:58 +08:00
mofeng-git
3014edffbb fix(db): 使用 FULL 同步确保事务提交时落盘 2026-09-05 22:40:01 +08:00
mofeng-git
ece4f303ce feat(web): 新增控制台布局切换并完善状态与磁盘交互
新增经典、悬浮和侧栏布局,保存用户偏好,并调整工具栏、状态摘要及窄屏交互。
统一控制台弹层外观、焦点行为和中英文文案。
根据虚拟磁盘文件访问能力显示浏览入口、容量信息和不可用状态。

验证:npm run build 通过(vue-tsc 类型检查和 Vite 生产构建)。
2026-09-05 20:59:15 +08:00
mofeng-git
db9d79554a perf(video): 新增 RKMPP DMA 采集编码通路并完善恢复逻辑
支持原生 HDMI 和 UVC 缓冲区导出,增加同步 RKMPP 编码及可选 MJPEG 硬件转码。
校验帧布局和缓冲区租约,在 DMA 不可用或编码失败时回退到复制通路。
保留自定义码率和 GOP 策略,重开采集时同步 HDMI 源帧率,并区分 UVC 超时状态。

验证:88 个视频测试通过(含 4 个新增回归测试);ARM64 cargo check --tests 通过。
2026-09-05 20:55:30 +08:00
mofeng-git
620fe0be54 perf(video): 并行解码 MJPEG 并丢弃积压帧
按可用 CPU 数量启动独立 MJPEG 解码线程,通过无缓冲通道分发任务;线程全忙时丢弃新帧,按序列号拒绝过时解码结果。

复用帧缓冲池,在线程启动失败时回退到采集线程解码,并更新并行解码说明及工作线程数量测试。
2026-09-05 14:10:53 +08:00
mofeng-git
79a4dcf2b0 fix(video): 统一关键帧参数集处理并缓存启动帧
在共享管线中将长度前缀 H264 转为 Annex-B,要求编码器标记与 IDR/IRAP 内容一致,并补齐参数集后才标记可独立解码的关键帧。

向新订阅者提供缓存启动帧,启动管线时清理缓存,并移除 RustDesk 会话内重复的 SPS/PPS 处理。补充格式归一化、关键帧判定和订阅测试。
2026-09-05 14:10:53 +08:00
mofeng-git
a8ee9552a0 perf(video): 使用有界 VBR 优化 H264 码率
H264 编码器探测与初始化使用 VBR,将峰值码率和缓冲区限制为目标码率的两倍。动态调整码率时同步更新限制,并保留 QSV 的专用处理。
2026-09-05 14:10:53 +08:00
mofeng-git
3749bafae0 fix(rustdesk): 按键盘模式和码空间转换 HID 输入
将对外兼容平台与 Windows Set-1 扫描码映射绑定,分离物理键、字符和控制键语义,拒绝未知码值跨码空间回退。

保留按下、释放、重复输入与临时 Shift 的状态语义,补充键位矩阵和事件转换回归测试,并记录输入模式及原始码值。
2026-09-05 14:10:53 +08:00
mofeng-git
b573f478fc fix(msd): 区分虚拟磁盘挂载能力与文件访问状态
使用原始文件元数据挂载虚拟磁盘,允许主机使用网页文件管理不支持的文件系统。连接期间只读取元数据;初始化和删除持有外层写锁,并同步控制器缓存。

API 的 used/free 改为可空值,新增 file_access 表示 available、unsupported、blocked_while_connected 或 unknown,需要前端配套处理。补充状态序列化、元数据校验和文件系统兼容测试。
2026-09-05 14:10:53 +08:00
mofeng-git
d67a3ab7f8 fix(build): 在运行时解析编解码依赖源码路径
hwcodec 与 libyuv 构建脚本在运行时读取 CARGO_MANIFEST_DIR,避免复用或迁移构建产物后继续引用旧源码目录。
2026-09-05 14:10:53 +08:00
mofeng-git
dbe5672df4 refactor: 优化数据库初始化与 WOL 存储 2026-08-30 21:27:00 +08:00
mofeng-git
48fd64319e merge: 合并 RustDesk 直连与会话优化 2026-08-30 20:50:03 +08:00
mofeng-git
ccf821ab22 refactor(rustdesk): 移除密钥对状态展示 2026-08-30 20:48:55 +08:00
mofeng-git
b074aa5779 fix(rustdesk): 降低视频直连延迟 2026-08-30 08:50:38 +08:00
mofeng-git
95a1fdf42d feat(rustdesk): 强化会话管理并优化流媒体传输 2026-08-30 08:21:37 +08:00
mofeng-git
e678ec394d feat(rustdesk): 新增独占式 IP 直连模式 2026-08-30 08:21:27 +08:00
raymond
628909a192 fix(hid): add CH9329 macOS drag compatibility 2026-08-29 01:30:18 +08:00
mofeng-git
5cab585115 Merge remote-tracking branch 'origin/main' into dev 2026-08-26 16:39:31 +08:00
Carbon
dcfa3eadaf fix: 为 RKCIF/RK628 选择受支持的视频格式 (#292)
RK628 通过 RKCIF 接入时,如果 One-KVM 启动时 HDMI 信号尚未锁定,
SourceFollowing 路径可能回退到默认 MJPEG。由于 RKCIF 不支持 MJPEG,
后续 S_FMT 无法建立有效的采集链路。

解决方案:
在解析 SourceFollowing 配置后,根据设备的 VIDIOC_ENUM_FMT 枚举结果
校验最终格式。如果该格式不受支持且格式列表非空,则选择按优先级排序
的首个可用格式,对于 RKCIF/RK628 通常为 NV12。

该方法只替换 FourCC,保留 HDMI DV timings 提供的分辨率和帧率。
同时覆盖无信号启动和当前格式已失效两种场景。
2026-08-26 16:37:57 +08:00
Carbon
1647e70243 fix: RK3588 原生 HDMIRX 被错误地关联到了 RK628 subdev (#293)
* fix: RK3588 原生 HDMIRX 被错误地关联到了 RK628 subdev

当 RK628 和 RK3588 原生 HDMI IN 同时存在时,页面配置为 rk_hdmirx,
会无法使用,提示无信号。

是因为原来的 subdev 发现逻辑会全局扫描 v4l-subdev,并返回首个匹配节点。
原生 HDMI IN 可能错误使用 RK628 subdev 的信号状态,最终被判断为无信号。

解决方案:
根据 video 节点的设备号找到对应 media device,读取 Media Controller
中的 entity 和已启用链路,只返回与当前 video 节点实际连通的 HDMI
bridge subdev。

* fix: 精确匹配视频设备的 Media 拓扑

---------

Co-authored-by: mofeng-git <mofeng654321@hotmail.com>
2026-08-26 16:32:03 +08:00
BigfootACA
9c6d8a614c fix(webrtc): preserve H.26x headers for new sessions
Detect random-access frames from Annex-B data and cache codec headers.
Prepend missing headers to later H.264 IDR and H.265 IRAP frames.
Forward standalone headers while WebRTC waits for a decodable frame.

Signed-off-by: BigfootACA <bigfoot@radxa.com>
2026-08-26 15:51:55 +08:00
BigfootACA
db7a845d3b fix(hwcodec): release V4L2M2M packets before delivery
Copy compressed V4L2M2M output before asynchronous delivery.
This releases driver capture buffers and prevents encoder stalls.

Signed-off-by: BigfootACA <bigfoot@radxa.com>
2026-08-26 15:51:55 +08:00
a15355447898
1d48d45592 feat: 支持高通 iris v4l2m2m 硬件编码器
- 新增高通平台检测,避免 Amlogic v4l2m2m 检测误判
- 对高通 Iris 编码器调整 GOP 和 capture buffers
- 强制关键帧仅在高通 Iris 之外启用
2026-08-26 15:51:55 +08:00
TXIuTnVsbA
d613739b06 fix(hid): 兼容 CH9329/CH9329F 串口响应 (#300)
支持 CH9329/CH9329F 扩展参数响应、粘包与乱序处理,保留严格校验和及有界接收缓冲。
2026-08-26 15:19:41 +08:00
mofeng-git
6e1194fe4c refactor: 移除 AMLENC 私有编码后端 2026-08-26 12:06:10 +08:00
mofeng-git
f101ddb918 refactor: 降低 hwcodec 探测日志噪音 2026-08-26 12:04:52 +08:00
mofeng-git
0054100414 refactor: 精简运行时重复初始化
统一服务与 CLI 的数据库初始化入口,由视频流管理器负责 WebRTC 采集源同步,并将 MSD 目录创建收敛到控制器内部。
2026-08-26 11:37:39 +08:00
mofeng-git
486f3887c2 refactor: 简化日志级别配置并移除 verbose 参数 2026-08-26 11:04:40 +08:00
mofeng-git
37af369b43 refactor: 简化运行时与服务协调
提取运行时生命周期管理,集中远程访问与 USB 协调,并缩小 Web 路由状态依赖。
2026-08-26 10:53:08 +08:00
mofeng-git
827d24fde4 feat: 增加 Amlogic 硬件编码的并行解码支持 2026-08-25 14:58:09 +08:00
mofeng-git
b8ea38b5f3 feat: 增加 s905 晶晨 H.264 硬件编码支持 2026-08-15 21:26:34 +08:00
mofeng-git
4530d8663d fix: 将电源管理选项自动隐藏修改为手动控制,避免 WOL 功能无法显示 #289 2026-08-07 15:49:58 +08:00
SilentWind
a4073d64cb Merge pull request #287 from mofeng-git/dev
Dev
2026-08-02 16:38:35 +08:00
mofeng-git
16400df182 chore: bump version to v0.2.6 2026-08-02 16:37:47 +08:00
mofeng-git
47af17bebc feat: 新增 Amlogic AMLENC 硬件编码支持
- 新增动态加载及 ABI 校验的 AMLENC H.264/H.265 编码器
- 注册 Amlogic 后端并扩展编码器自检
- 并行执行 MJPEG 解码与 AMLENC 编码
- 复用 NV12 缓冲区并移除冗余帧初始化
- 优化低延迟帧分发及 RTCP 关键帧恢复
- 动态调整 AMLENC 码率尚未完成,效果不佳
2026-08-02 16:24:10 +08:00
mofeng-git
814f23a27c ci: 优化 Cargo 构建缓存
- 共享 deb 与 Docker 的 Linux cross 编译缓存
- 为 Windows MSVC 构建添加独立缓存
- 固定 cross 版本以保证缓存一致性
2026-07-31 09:55:14 +08:00
mofeng-git
6bbe137f09 fix: 修复 Windows 音频设备函数可见性 2026-07-31 09:46:32 +08:00
mofeng-git
6fdcf5c7c9 fix: 修复无信号状态同步与采集管线阻塞
- 使用非阻塞 V4L2 句柄并类型化采集错误
- 完善视频管线生命周期,避免复用停止中的管线
- 区分音视频事件并支持 REST/WebSocket 状态快照
- 修复信号丢失后保留最后一帧及刷新后黑屏问题
- 优化无信号提示、状态展示优先级及相关界面细节
- 降低重复 OTG 错误日志级别
2026-07-30 22:43:59 +08:00
mofeng-git
ce1712ff2e feat: 为 EasyTier 添加完整 TOML 配置支持
- 新增快速配置与完整配置模式,兼容旧版配置
 - 统一扩展配置校验及受保护临时文件生命周期
- 支持通过 easytier-core -c 加载 TOML 配置
- 复用前端配置模式编辑组件并更新中英文文案与类型
- 补充配置校验、启动参数、文件权限及清理测试
2026-07-30 21:26:00 +08:00
mofeng-git
8b09824e04 fix: 修正 RustDesk UDP 注册状态判定
- 移除无法证明服务器可达的 connected 状态
- 引入注册跟踪器统一管理响应、超时与退避
- 连续注册超时后正确降级为未连接
 - 分离本地服务状态与 HBBS 注册状态
- 补充注册状态机单元测试
2026-07-30 19:43:28 +08:00
mofeng-git
9fb23476ac fix: 完善 RK3588 HDMI RX 信号检测与自动恢复
- 统一使用 QUERY_DV_TIMINGS 判断 HDMI RX 输入状态
  - 增加 source-following 设备状态 API 与前端只读展示
  - 支持长时间无信号后的 MJPEG/WebRTC 自动恢复
  - 修复模式切换时采集设备尚未释放导致的 EBUSY
  - 取消陈旧 WebRTC 重连并统一采集恢复策略
  - 移除视频输入状态区域的冗余标题
2026-07-30 19:41:44 +08:00
mofeng-git
971c263bf8 feat: 虚拟媒体显示镜像上传进度百分比 2026-07-29 23:25:12 +08:00
mofeng-git
cb3fd3e646 feat: 添加视频窗口等比例缩放按钮 2026-07-29 19:32:46 +08:00
mofeng-git
d414557d74 fix: 修复设置页页眉回弹和状态色辨识度 #281
- 在侧栏布局滚动容器统一阻止纵向 overscroll
  - 拆分状态指示色与成功文本色,提升在线状态辨识度
  - 统一连接、运行及键盘 LED 等状态点样式
2026-07-29 18:50:20 +08:00
mofeng-git
fbcd95b617 fix: 升级目录改为使用 /tmp 目录,避免遗留升级文件 #280 2026-07-29 17:59:28 +08:00
mofeng-git
887f29096f feat: 增加 OTG HID 远程唤醒和 OTG MSD 设备名称配置
- 在补丁内核上启用 HID 写入唤醒及 USB 远程唤醒描述符
  - 支持全局配置 Flash 和 CD-ROM INQUIRY 字符串
  - 兼容普通内核的通用 INQUIRY 属性
  - 调整 OTG 功能布局并更新大容量 DVD 镜像提示
2026-07-29 13:56:52 +08:00
mofeng-git
e0bddc2faa fix: 修复设备识别问题 #286 2026-07-27 15:12:54 +08:00
mofeng-git
4f770a1eea fix: 完善 MSD 错误提示;解决 MSD 文件名称过长问题;优化粘贴文本样式;优化所有下拉框样式;删除“画面静止时会自动降帧”提示 2026-07-26 23:13:47 +08:00
mofeng-git
376dc97134 fix: 修复 MSD ISO/FLASH 挂载识别错误;完善错误提示 2026-07-26 22:59:27 +08:00
mofeng-git
27c8da9a75 fix: 完善 RK3588 HDMI RX 兼容性 2026-07-26 22:27:47 +08:00
mofeng-git
5963dfa01a feat: 完善 OTG UAC 音频支持 2026-07-26 11:59:58 +08:00
mofeng-git
f86cba6ce5 Merge branch 'main' into dev
# Conflicts:
#	src/web/handlers/setup.rs
#	web/src/i18n/en-US.ts
#	web/src/i18n/zh-CN.ts
2026-07-24 11:09:36 +08:00
mofeng-git
e1b82519b9 test: 更新报告格式 2026-07-24 11:03:22 +08:00
mofeng-git
32d8a62fec fix: 初始化时完整应用 USB 运行时配置,避免遗漏 MSD 功能 2026-07-24 11:02:14 +08:00
mofeng-git
4cd622ff07 fix: OTG 网卡桥接改由 NetworkManager 生成桥接配置 UUID;docker 补全 NetworkManager 依赖 2026-07-24 11:01:54 +08:00
SilentWind
6ec4361f43 Merge pull request #282 from arounyf/fix/hid-reload-on-gadget-rebuild
fix: 修复OTG gadget重建后HID后端未重载导致键鼠失效
2026-07-23 15:25:37 +08:00
arounyf
e9bed3688f feat: UAC USB microphone passthrough
- Add UAC1 gadget function (ConfigFS) with optimized endpoint config
- Browser mic capture with Opus encoding via WebCodecs AudioEncoder
- WebSocket audio transport (Opus 64kbps, 100x bandwidth reduction vs raw PCM)
- aplay subprocess for reliable PCM playback to USB gadget
- Settings toggle + ActionBar mic button (hidden when UAC disabled)
- Dynamic PCM device resolution (/proc/asound)
- c_chmask=0 + req_number=4 fixes DWC3 composite isochronous endpoint issue
2026-07-23 06:56:53 +00:00
mofeng-git
8d5366444b fix: 完善测试套件 2026-07-22 22:53:21 +08:00
arounyf
4e32b05124 fix: 修复OTG gadget重建后HID后端未重载导致键鼠失效
当MSD或OTG网络配置变更导致gadget被重建时,新的/dev/hidg*设备
被创建但HID后端因'配置未变'跳过了reload,导致仍持有已删除设备
的旧文件描述符,键鼠操作无效。

修复: 在apply_usb_config中检测gadget是否因MSD/网络变更被重建,
若是且HID后端为OTG,强制reload HID以打开新的/dev/hidg*设备。

同时为MsdConfig添加PartialEq derive以支持变更检测。
2026-07-22 04:54:18 +00:00
mofeng-git
e0055bf491 fix: 删除 nmcli 命令缺失弹窗提示 2026-07-20 21:24:27 +08:00
SilentWind
d60ddb21dc Merge pull request #279 from mofeng-git/dev
Dev
2026-07-20 08:04:01 +08:00
mofeng-git
219d1ccd08 fix: 前端 UI 下拉框修改为全宽 2026-07-20 08:01:23 +08:00
mofeng-git
6f697e56c8 fix: 修复 windows 构建 2026-07-19 23:44:34 +08:00
SilentWind
05535b9bb2 Merge pull request #278 from mofeng-git/dev
Dev
2026-07-19 21:50:59 +08:00
SilentWind
5ce2cb658c Merge pull request #277 from uranami/fix/otg-led-disconnect-cpu
fix: prevent OTG LED listener busy loop after USB disconnect
2026-07-19 21:49:44 +08:00
mofeng-git
a86df52d9a chore: bump version to v0.2.5 2026-07-19 21:47:02 +08:00
mofeng-git
275c2ca343 feat: 统一和完善 UI 2026-07-19 21:43:27 +08:00
mofeng-git
5d871e8b21 fix: 修复 MSD 启用时 Ventoy 资源初始化问题 #275
- 将 Ventoy 资源初始化纳入 MSD 控制器启用流程
- 支持运行时启用 MSD,无需重启服务
- 调整验收测试并移除启用后的重启逻辑
2026-07-19 20:08:03 +08:00
uranami
694afdd07f fix: stop OTG LED listener spin after USB disconnect 2026-07-19 09:41:54 +08:00
mofeng-git
d31e70515a fix: 修复 npm 依赖版本错误 2026-07-18 11:50:43 +08:00
mofeng-git
701b141347 fix: 完善虚拟U盘创建错误提示 #275 2026-07-18 11:50:26 +08:00
mofeng-git
eaa114f40c fix: 修复 v4l2loopback 的 DQBUF 兼容问题 2026-07-17 23:25:24 +08:00
mofeng-git
563c808836 fix: 完善 libyuv 静态库构建 2026-07-17 23:25:04 +08:00
mofeng-git
79b6683817 feat: 优化 UI 样式 2026-07-17 22:07:25 +08:00
mofeng-git
8bd16df6f8 feat: 添加 TOTP 2FA 功能 2026-07-17 16:34:06 +08:00
mofeng-git
fdea52d59d feat: 优化 CUA 功能体验 2026-07-17 16:32:17 +08:00
mofeng-git
4031abd8d6 fix: 修复移动端浏览器的触屏鼠标映射 2026-07-17 13:16:20 +08:00
mofeng-git
cf2bfaf6a7 fix: 尝试修复虚拟U盘文件系统大文件解析错误 2026-07-17 10:47:04 +08:00
mofeng-git
d35021ee5d fix: 修复扩展服务开启和自启动状态错误 2026-07-17 10:46:34 +08:00
mofeng-git
57d1597264 update: 更新前端依赖;修改前端样式 2026-07-17 01:33:44 +08:00
mofeng-git
aca847e76c update: 升级 rust 依赖 2026-07-16 22:59:22 +08:00
mofeng-git
8036c164b4 fix: 修复 MJPEG/HTTP 视频窗口可被选中拖拽的问题 2026-07-16 21:03:27 +08:00
mofeng-git
0482987bf1 feat: 完善按配置隐藏控制台菜单选项 2026-07-16 21:02:23 +08:00
mofeng-git
50dd419e5a feat: 支持 WatchDog 2026-07-16 20:07:33 +08:00
mofeng-git
213359b6c8 feat: 初步支持 USB 网卡桥接;删除 OTG 端点预算管理 2026-07-16 19:19:24 +08:00
mofeng-git
63c2bb4ca2 Merge branch 'main' into dev
# Conflicts:
#	libs/hwcodec/cpp/common/util.cpp
#	libs/hwcodec/cpp/ffmpeg_ram/ffmpeg_ram_encode.cpp
2026-07-14 23:43:27 +08:00
mofeng-git
6693020e6d feat: 增强 VNC 功能的兼容性 2026-07-14 22:59:33 +08:00
SilentWind
05c5f45995 Merge pull request #273 from cheng-zongkai/fix/vaapi-cqp-rate-control
fix: 为 VAAPI 添加 CQP 码率控制回退
2026-07-14 21:39:04 +08:00
mofeng-git
1ded7a8a66 del: 移除安卓支持 2026-07-14 21:01:47 +08:00
chengzongkai
809d0ca65c fix: 为 VAAPI 添加 CQP 码率控制回退 2026-07-13 16:01:43 +08:00
mofeng-git
139064de35 feta: 更新测试套件中的虚拟媒体部分测试 2026-07-12 17:04:37 +08:00
mofeng-git
54e0cbc84e featt: 增加 redfish 身份验证,完善 redfish 虚拟媒体资源管理能力 2026-07-12 16:13:41 +08:00
mofeng-git
7c9166a8cf feat: 虚拟媒体支持同时挂载多个镜像 2026-07-12 11:40:01 +08:00
mofeng-git
a9a16f2218 docs: 更新说明 2026-07-08 08:22:27 +08:00
mofeng-git
c9ae9dd893 docs: 更新说明 2026-07-08 08:19:09 +08:00
SilentWind
010d50b727 Merge branch 'dev' 2026-07-08 07:07:03 +08:00
mofeng-git
c88fb03243 chore: bump version to v0.2.4 2026-07-08 00:06:33 +08:00
mofeng-git
7bae9b633c del: 删除构建日期设定 2026-07-08 00:04:59 +08:00
mofeng-git
fc3f1d6aac feat: 优化网页终端样式 2026-07-08 00:04:19 +08:00
mofeng-git
b719be3e38 ci: 移除 GitHub Actions 里的 APK 构建 2026-07-07 23:55:55 +08:00
mofeng-git
db2410cc7f feat: 优化 MSD 功能体验和控件样式 2026-07-07 23:52:38 +08:00
mofeng-git
d9c2854911 feat: 优化网页 ATX 控件中的状态显示样式 2026-07-07 22:08:59 +08:00
mofeng-git
99c051a874 del: MJPEG /HTTTP 视频模式删除网页连接统计功能 2026-07-07 22:08:20 +08:00
mofeng-git
a0ad151fbc fix: 修复 typeshare 生成问题 2026-07-07 00:41:25 +08:00
mofeng-git
4806a5e0a9 fix: 修复 LCUS HID 继电器协议错误 #263 2026-07-07 00:29:33 +08:00
mofeng-git
e60152d38b feat: 完善 ATX 功能逻辑与控件样式 2026-07-07 00:21:54 +08:00
mofeng-git
f6e97a06f5 del: 删除 MJPEG 输入格式自动切换功能 2026-07-06 20:51:58 +08:00
mofeng-git
618599266e fix:恢复错误消失的 redfish 入口 2026-07-05 22:01:33 +08:00
mofeng-git
696c1b4bb2 test: 增加测试套件 2026-07-05 21:30:11 +08:00
mofeng-git
b346af35d3 feat: VNC、RTSP 服务支持监听 ipv6 地址 2026-07-05 21:20:23 +08:00
mofeng-git
16a65289f2 feat: v4l2 buffer 由2改为4 2026-07-05 21:15:44 +08:00
mofeng-git
bb2691fe8f fix: 从 gitee 切换到 github,避免 gitee 平台不稳定影响构建 2026-07-05 16:35:44 +08:00
mofeng-git
7753c83e27 Merge branch 'dev' 2026-06-26 23:23:37 +08:00
mofeng-git
1d6fb2e3c5 chore: bump version to v0.2.3 2026-06-26 23:18:08 +08:00
mofeng-git
6c1bff5d0c fix: 修复 mpp 库静态构建错误 2026-06-20 21:28:01 +08:00
mofeng-git
f1e362a820 refactor: 前端界面微调 2026-06-15 23:36:17 +08:00
mofeng-git
e2c19d550c Merge commit '4b7be20fe0cce3e7979cc3bdfdd7b02ec6630c00' into dev 2026-06-15 22:26:22 +08:00
mofeng-git
c101ef1c80 feat: 新增 MJPEG/H.264 VNC 初步支持 2026-06-15 22:25:18 +08:00
mofeng-git
4b7be20fe0 feat: 新增 Computer Use Agent 初步支持 2026-06-15 22:24:40 +08:00
mofeng-git
5c98aea7e3 feat: 新增 Linux 绝对鼠标兼容模式 #266;新增 CH9329 描述符设置 2026-06-14 20:59:23 +08:00
mofeng-git
da61644dbc fix: 修复 CH9329 健康检测错误和切换错误 #251 #255 #265 2026-06-13 16:47:21 +08:00
mofeng-git
5de7ecd4c5 feat: 新增 frp 远程访问扩展 2026-06-13 16:05:34 +08:00
SilentWind
3fc6b055a0 Merge pull request #267 from mofeng-git/dev
ci: 完善构建流程和中国网络环境加速
2026-06-10 09:50:04 +08:00
mofeng-git
4b65eebd5d ci: 完善构建流程和中国网络环境加速 2026-06-10 09:48:42 +08:00
mofeng-git
921c00c472 fix: 修复 libyuv 构建错误 2026-06-04 18:29:17 +08:00
mofeng-git
b6bd76534f fix: 修正 iConfiguration 描述字符串 2026-05-31 13:46:56 +08:00
mofeng-git
780cfb4cca fix:修复 deb 依赖关系,兼容 Dieban 13 系统安装 2026-05-26 14:16:44 +08:00
mofeng-git
8f9272d985 ci: 添加 docker 镜像构建 2026-05-25 15:33:57 +00:00
mofeng-git
f679647ec9 fix: 安卓构建脚本添加可执行权限 2026-05-25 11:04:51 +08:00
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
549 changed files with 77550 additions and 24161 deletions

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

@@ -0,0 +1,189 @@
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
- name: Build frontend
working-directory: web
run: |
npm install
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: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
# The Docker workflow builds the same targets with the same Cross images.
shared-key: linux-cross-release
key: ${{ hashFiles('Cross.toml', 'build/cross/Dockerfile.*') }}
cache-all-crates: true
- name: Install cross
run: cargo install cross --version 0.2.5 --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: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
shared-key: windows-msvc-release
key: ${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json') }}
- 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
release:
runs-on: ubuntu-22.04
needs: [deb, windows]
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: 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

91
.github/workflows/docker.yml vendored Normal file
View File

@@ -0,0 +1,91 @@
name: Docker
on:
workflow_dispatch:
inputs:
tag:
description: Docker image tag
required: false
default: latest
platforms:
description: Docker platforms
required: false
default: linux/amd64,linux/arm64,linux/arm/v7
push:
tags:
- "v*"
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
DOCKER_PLATFORMS: ${{ github.event_name == 'workflow_dispatch' && inputs.platforms || 'linux/amd64,linux/arm64,linux/arm/v7' }}
DOCKER_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
jobs:
docker:
runs-on: ubuntu-22.04
timeout-minutes: 360
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- uses: dtolnay/rust-toolchain@stable
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
# Reuse dependency artifacts produced by the deb job and vice versa.
shared-key: linux-cross-release
key: ${{ hashFiles('Cross.toml', 'build/cross/Dockerfile.*') }}
cache-all-crates: true
- name: Install build dependencies
run: |
sudo apt-get update
sudo apt-get install -y unzip xz-utils
cargo install cross --version 0.2.5 --locked
- name: Build frontend
working-directory: web
run: |
npm install
npm run build
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build linux binaries
run: bash build/build-images.sh
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
registry: docker.io
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Log in to Aliyun Container Registry
uses: docker/login-action@v3
with:
registry: registry.cn-hangzhou.aliyuncs.com
username: ${{ secrets.ALIYUN_USERNAME }}
password: ${{ secrets.ALIYUN_PASSWORD }}
- name: Publish Docker images
run: |
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry docker.io/silentwind0 --tag "$DOCKER_TAG" --push
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry registry.cn-hangzhou.aliyuncs.com/silentwind --tag "$DOCKER_TAG" --push
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry docker.io/silentwind0 --variant full --tag "$DOCKER_TAG" --push
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry registry.cn-hangzhou.aliyuncs.com/silentwind --variant full --tag "$DOCKER_TAG" --push

3
.gitignore vendored
View File

@@ -1,5 +1,5 @@
# Rust
/target/
target/
Cargo.lock
# IDE
@@ -31,6 +31,7 @@ Thumbs.db
# Build artifacts
/dist/
/build-staging
/.tmp/
# Frontend (built files)
/web/node_modules/

View File

@@ -1,6 +1,6 @@
[package]
name = "one-kvm"
version = "0.2.0"
version = "0.2.7"
edition = "2021"
authors = ["SilentWind"]
description = "A open and lightweight IP-KVM solution written in Rust"
@@ -9,121 +9,201 @@ 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:toml_edit",
"dep:tracing",
"dep:tracing-subscriber",
"dep:thiserror",
"dep:anyhow",
"dep:argon2",
"dep:rand",
"dep:totp-rs",
"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:tempfile",
"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:libloading",
"dep:ventoy-img",
"dep:protobuf",
"dep:sodiumoxide",
"dep:des",
"dep:sha2",
"dep:typeshare",
"dep:hwcodec",
"dep:libyuv",
"dep:turbojpeg",
"dep:audiopus",
"dep:v4l2r",
"dep:alsa",
"dep:gpio-cdev",
"dep:one-kvm-bluetooth-hid",
"dep:cpal",
"dep:windows-sys",
]
[dependencies]
# Async runtime
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.7", features = ["rt"] }
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"], 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 = ["cookie"] }
tower-http = { version = "0.6", features = ["cors", "trace"] }
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.9", default-features = false, features = ["runtime-tokio", "sqlite-bundled"], optional = true }
# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde = { version = "1", features = ["derive"], optional = true }
serde_json = { version = "1", optional = true }
toml_edit = { version = "0.25", optional = true }
# Logging
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "tracing-log"] }
tracing = { version = "0.1", 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.10", optional = true }
totp-rs = { version = "5.7", features = ["gen_secret", "otpauth", "zeroize"], optional = true }
# Utilities
uuid = { version = "1", features = ["v4", "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 }
tempfile = { version = "3", 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", "json"], default-features = false }
urlencoding = "2"
reqwest = { version = "0.13", features = ["stream", "rustls-no-provider", "json"], default-features = false, optional = true }
urlencoding = { version = "2", optional = true }
# Static file embedding
rust-embed = { version = "8", features = ["compression", "debug-embed"] }
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", default-features = false, features = ["ring", "std", "tls12"], optional = true }
rcgen = { version = "0.14", optional = true }
axum-server = { version = "0.8", features = ["tls-rustls-no-provider"], optional = true }
# CLI argument parsing
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive"], optional = true }
# Time (cookie max_age + RFC3339 timestamps)
time = { version = "0.3", features = ["serde", "formatting", "parsing"] }
# Video capture (V4L2)
v4l2r = "0.0.7"
# JPEG encoding (libjpeg-turbo, SIMD accelerated)
turbojpeg = "1.3"
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.29", 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"
rtsp-types = "0.1"
sdp-types = "0.1"
# Audio (ALSA capture + Opus encoding)
# Note: audiopus links to libopus.so (unavoidable for audio support)
alsa = "0.11"
audiopus = "0.2"
webrtc = { version = "0.17", optional = true }
rtp = { version = "0.17", 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 }
libloading = { version = "0.8", 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 }
des = { version = "0.9", optional = true }
sha2 = { version = "0.11", optional = true }
# TypeScript type generation
typeshare = "1.0"
typeshare = { version = "1.0", optional = true }
[dev-dependencies]
tempfile = "3"
[target.'cfg(any(target_os = "linux", 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(target_os = "linux")'.dependencies]
one-kvm-bluetooth-hid = { path = "libs/bluetooth-hid", optional = true }
# Utilities
nix = { version = "0.31", default-features = false, features = ["fs", "socket", "net", "hostname", "poll"], optional = true }
# 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.18", 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 }
[build-dependencies]
protobuf-codegen = "3.7"

View File

@@ -1,5 +1,5 @@
# Cross-compilation configuration for One-KVM
# Uses pre-built custom Debian 11 based images for consistent build/runtime environment
# Uses pre-built custom Debian 12 based images for consistent build/runtime environment
# See: https://github.com/cross-rs/cross
[build]

View File

@@ -22,6 +22,8 @@ Goals: an open, lightweight, easy-to-use IP-KVM stack.
- **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.
For more information, see the [One-KVM Rust documentation](https://docs.one-kvm.cn/).
> **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">
@@ -32,7 +34,7 @@ Goals: an open, lightweight, easy-to-use IP-KVM stack.
## Features
### Core
**Core**
| Area | Capabilities |
|------|----------------|
@@ -40,11 +42,9 @@ Goals: an open, lightweight, easy-to-use IP-KVM stack.
| 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 |
| ATX power | GPIO or USB relay; power 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).
@@ -216,15 +216,22 @@ One-KVM builds on many great open-source projects; a lot of time goes into testi
- 爱发电用户_d3d9c
- 爱发电用户_97b41
- 偶然
- 爱发电用户_dba45
- 爱发电用户_d4f8b
- 故人。
- ......
</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
@@ -236,3 +243,9 @@ One-KVM builds on many great open-source projects; a lot of time goes into testi
![林枫云](https://docs.one-kvm.cn/img/36076FEFF0898A80EBD5756D28F4076C.png)
林枫云 offers premium network routes, high-frequency game servers, and high-bandwidth servers in China and abroad.
- **[Beta Network](https://my.beita.cc/?ref=github_onekvm)** — project server sponsorship
![BTBT](https://github.com/user-attachments/assets/c442d5f5-d72f-4a07-b9f4-400a6a0c3f1e)
Remote computers, consumer GPU servers, and dedicated physical machines with fully automated online delivery.

View File

@@ -12,7 +12,7 @@
---
## 📖 项目概述
## 项目概述
**One-KVM Rust** 是一个用 Rust 编写的轻量级 IP-KVM 解决方案,可通过网络远程管理服务器和工作站,实现 BIOS 级远程控制。
@@ -22,6 +22,8 @@
- **轻量**:以二进制文件形式分发,无繁杂的依赖项,部署过程简单。
- **易用**:无需手动编辑配置文件,参数设置均可通过网页界面完成。
更多内容可访问 [One-KVM Rust 文档站点](https://docs.one-kvm.cn/)。
> **One-KVM Python** 已停止开发,如有需要可访问 <https://github.com/mofeng-git/One-KVM/tree/python>。
<div align="center">
@@ -30,9 +32,9 @@
</div>
## 📊 功能介绍
## 功能介绍
### 核心功能
**核心功能**
| 功能 | 能力说明 |
|------|------|
@@ -40,12 +42,10 @@
| 视频编码 | VAAPI/QSV/RKMPP/V4L2M2M 硬件编码支持,以及软件编码兜底 |
| 键鼠控制 | USB OTG HID 或 CH340 + CH9329 HID支持绝对/相对鼠标模式 |
| 虚拟媒体 | USB Mass Storage支持 ISO/IMG 镜像挂载和 Ventoy 虚拟U盘模式 |
| ATX 电源控制 | GPIO /USB 继电器,支持控制电源、重启按钮 |
| ATX 电源控制 | GPIO/USB 继电器,支持电源控制 |
| 音频传输 | ALSA 采集 + Opus 编码HTTP/WebRTC |
此外提供基于 Web UI 的可视化配置与中英文界面;并集成 Web 终端ttyd、内网穿透gostc、P2P 组网EasyTier、RustDesk 协议(扩展跨平台远程访问)以及 RTSP 推流等能力。
## ⚡ 安装使用
## 安装使用
构建产物见 [GitHub Releases](https://github.com/mofeng-git/One-KVM/releases)。以下为常见安装方式的简要步骤;**系统要求、硬件准备、Docker 环境变量与 USB OTG 等完整说明**请查阅 [One-KVM Rust 文档站点](https://docs.one-kvm.cn/)。
@@ -210,6 +210,16 @@ One-KVM 已上架飞牛 **应用市场**,在 NAS 上直接搜索安装即可
- 爱发电用户_d3d9c
- 爱发电用户_97b41
- 偶然
- 爱发电用户_dba45
- 爱发电用户_d4f8b
- 故人。
- ......
</details>
@@ -218,9 +228,6 @@ One-KVM 已上架飞牛 **应用市场**,在 NAS 上直接搜索安装即可
本项目得到以下赞助商的支持:
**镜像下载服务:**
- **[重庆大学开源软件镜像站](https://mirrors.cqu.edu.cn/)** - 提供镜像站下载服务
**文件存储服务:**
- **[Huang1111公益计划](https://pan.huang1111.cn/s/mxkx3T1)** - 提供免登录下载服务
@@ -228,6 +235,12 @@ One-KVM 已上架飞牛 **应用市场**,在 NAS 上直接搜索安装即可
- **[林枫云](https://www.dkdun.cn)** - 赞助了本项目服务器
![林枫云](https://docs.one-kvm.cn/img/36076FEFF0898A80EBD5756D28F4076C.png)
<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服务器、独服物理机全自动在线交付。

View File

@@ -2,21 +2,6 @@ use std::fs;
use std::path::Path;
fn main() {
// Set BUILD_DATE environment variable for compile-time access
// Use system time to avoid adding chrono as a build dependency
let now = std::time::SystemTime::now();
let duration = now.duration_since(std::time::UNIX_EPOCH).unwrap();
let secs = duration.as_secs();
// Convert Unix timestamp to date (simplified calculation)
// Days since epoch
let days = secs / 86400;
// Calculate year, month, day from days since 1970-01-01
let (year, month, day) = days_to_ymd(days as i64);
let build_date = format!("{:04}-{:02}-{:02}", year, month, day);
println!("cargo:rustc-env=BUILD_DATE={}", build_date);
// Compile protobuf files for RustDesk protocol
compile_protos();
@@ -86,19 +71,3 @@ pub mod rustdesk {
fs::write(&dest_path, code).expect("Failed to write secrets_generated.rs");
}
/// Convert days since Unix epoch to year-month-day
fn days_to_ymd(days: i64) -> (i32, u32, u32) {
// Algorithm from http://howardhinnant.github.io/date_algorithms.html
let z = days + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = (z - era * 146097) as u32;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if m <= 2 { y + 1 } else { y };
(year as i32, m, d)
}

View File

@@ -1,24 +1,30 @@
# One-KVM Runtime Image
# 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)
# Using Debian 12 to match the build images (GLIBC 2.36)
ARG TARGETPLATFORM=linux/amd64
FROM debian:11-slim
FROM debian:12-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 && \
RUN sed -i 's/^Components: main$/Components: main contrib non-free non-free-firmware/' /etc/apt/sources.list.d/debian.sources && \
apt-get update && \
apt-get install -y --no-install-recommends \
# Core runtime (all platforms) - no codec libs needed
ca-certificates \
# Bluetooth HID uses the host BlueZ system bus; btmgmt manages a dedicated adapter.
bluez \
libudev1 \
libasound2 \
# OTG Ethernet bridge control (nmcli talks to the host NetworkManager over D-Bus)
network-manager \
iproute2 \
iputils-ping \
# v4l2 is handled by kernel, minimal userspace needed
libv4l-0 \
&& \

View File

@@ -1,24 +1,30 @@
# 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)
# Using Debian 12 to match the build images (GLIBC 2.36)
ARG TARGETPLATFORM=linux/amd64
FROM debian:11-slim
FROM debian:12-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 && \
RUN sed -i 's/^Components: main$/Components: main contrib non-free non-free-firmware/' /etc/apt/sources.list.d/debian.sources && \
apt-get update && \
apt-get install -y --no-install-recommends \
# Core runtime (all platforms) - no codec libs needed
ca-certificates \
# Bluetooth HID uses the host BlueZ system bus; btmgmt manages a dedicated adapter.
bluez \
libudev1 \
libasound2 \
# OTG Ethernet bridge control (nmcli talks to the host NetworkManager over D-Bus)
network-manager \
iproute2 \
iputils-ping \
# v4l2 is handled by kernel, minimal userspace needed
libv4l-0 \
&& \

View File

@@ -19,6 +19,28 @@ 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 }--progress=plain --build-arg CHINAMIRRO=1 --build-arg GH_PROXY=${GH_PROXY:-https://gh-proxy.com/} --build-arg DEBIAN_IMAGE=${DEBIAN_IMAGE:-docker.1ms.run/library/debian:12}"
cross_build_opts="$cross_build_opts --build-arg HTTP_PROXY= --build-arg HTTPS_PROXY= --build-arg ALL_PROXY= --build-arg NO_PROXY="
cross_build_opts="$cross_build_opts --build-arg http_proxy= --build-arg https_proxy= --build-arg all_proxy= --build-arg no_proxy="
echo "=== China mirror acceleration: enabled ==="
echo "=== Building: $rust_target (via cross with custom Dockerfile) ==="
env \
CROSS_BUILD_OPTS="$cross_build_opts" \
CARGO_SOURCE_CRATES_IO_REPLACE_WITH=rsproxy-sparse \
CARGO_SOURCE_RSPROXY_REGISTRY=https://rsproxy.cn/crates.io-index \
CARGO_SOURCE_RSPROXY_SPARSE_REGISTRY=sparse+https://rsproxy.cn/index/ \
CARGO_REGISTRIES_RSPROXY_INDEX=https://rsproxy.cn/crates.io-index \
CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse \
CARGO_NET_GIT_FETCH_WITH_CLI=true \
RUSTUP_DIST_SERVER=https://rsproxy.cn \
RUSTUP_UPDATE_ROOT=https://rsproxy.cn/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 +71,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 China mirrors"
exit 0
;;
*)
@@ -65,16 +88,4 @@ for target in "${ARCH_MAP[@]}"; do
fi
done
echo ""
echo "Static libraries:"
for target in "${ARCH_MAP[@]}"; do
case "$target" in
x86_64-unknown-linux-gnu) gnu_target="x86_64-linux-gnu" ;;
aarch64-unknown-linux-gnu) gnu_target="aarch64-linux-gnu" ;;
armv7-unknown-linux-gnueabihf) gnu_target="armv7-linux-gnueabihf" ;;
esac
if [ -d "$PROJECT_DIR/target/one-kvm-libs/$gnu_target/lib" ]; then
echo " $gnu_target: OK"
fi
done
echo ""
echo "Next step: ./build/package-docker.sh or ./build/package-deb.sh"

View File

@@ -1,21 +1,55 @@
# Cross-compilation image for ARM64 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
# Cross-compilation image for ARM64 based on Debian 12
# Build on Debian 12 (GLIBC 2.36) to match the runtime images
FROM debian:11
ARG DEBIAN_IMAGE=debian:12
FROM ${DEBIAN_IMAGE}
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
ARG GH_PROXY=https://gh-proxy.com/
ARG RUSTUP_DIST_SERVER_CN=https://rsproxy.cn
ARG RUSTUP_UPDATE_ROOT_CN=https://rsproxy.cn/rustup
ARG CARGO_INDEX_CN=https://rsproxy.cn/crates.io-index
ARG CARGO_REGISTRY_CN=sparse+https://rsproxy.cn/index/
ARG LIBJPEG_TURBO_VERSION=3.1.4.1
ARG LIBYUV_REV=957f295ea946cbbd13fcfc46e7066f2efa801233
ARG LIBVPX_VERSION=1.16.0
ARG X265_VERSION=3.4
ARG OPUS_VERSION=1.5.2
ARG RKMPP_BRANCH=jellyfin-mpp
ARG RKRGA_BRANCH=jellyfin-rga
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
# Set Rustup mirrors (Aliyun)
#ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
# RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i -E \
-e 's@http://deb.debian.org/debian([[:space:]]|$)@http://mirrors.tuna.tsinghua.edu.cn/debian\1@g' \
/etc/apt/sources.list.d/debian.sources; \
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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
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 = 'rsproxy-sparse'" \
'[source.rsproxy]' \
"registry = '${CARGO_INDEX_CN}'" \
'[source.rsproxy-sparse]' \
"registry = '${CARGO_REGISTRY_CN}'" \
'[registries.rsproxy]' \
"index = '${CARGO_INDEX_CN}'" \
'[net]' \
'git-fetch-with-cli = true' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -49,6 +83,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Install ARM64 development libraries (without VAAPI/X11 for ARM)
RUN apt-get update && apt-get install -y --no-install-recommends \
libssl3 \
libssl3:arm64 \
libasound2-dev:arm64 \
libv4l-dev:arm64 \
libudev-dev:arm64 \
@@ -58,23 +94,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
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 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& git remote add origin "${github_prefix}https://github.com/libjpeg-turbo/libjpeg-turbo.git" \
&& git fetch --depth 1 origin "refs/tags/${LIBJPEG_TURBO_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& 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 \
@@ -84,8 +115,13 @@ RUN git clone --depth 1 https://github.com/libjpeg-turbo/libjpeg-turbo /tmp/libj
&& rm -rf /tmp/libjpeg-turbo
# Build static libyuv from source (cross-compile for ARM64)
RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
RUN git init /tmp/libyuv \
&& cd /tmp/libyuv \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git remote add origin "${github_prefix}https://github.com/lemenkov/libyuv" \
&& git fetch --depth 1 origin ${LIBYUV_REV} \
&& git checkout --detach FETCH_HEAD \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_INSTALL_PREFIX=/usr/aarch64-linux-gnu \
@@ -93,14 +129,24 @@ 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
# Build static libvpx from source (cross-compile for ARM64)
# CC/CXX/LD/AR must be environment variables, not configure arguments
RUN git clone --depth 1 https://github.com/webmproject/libvpx /tmp/libvpx \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libvpx \
&& cd /tmp/libvpx \
&& git remote add origin "${github_prefix}https://github.com/webmproject/libvpx.git" \
&& git fetch --depth 1 origin "refs/tags/v${LIBVPX_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& echo "=== libvpx: Configuring for ARM64 ===" \
&& export CC=aarch64-linux-gnu-gcc \
&& export CXX=aarch64-linux-gnu-g++ \
@@ -123,7 +169,9 @@ RUN git clone --depth 1 https://github.com/webmproject/libvpx /tmp/libvpx \
&& rm -rf /tmp/libvpx
# Build static libx264 from source (cross-compile for ARM64)
RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git clone --depth 1 "${github_prefix}https://github.com/mirror/x264.git" /tmp/x264 \
&& cd /tmp/x264 \
&& export CC=aarch64-linux-gnu-gcc \
&& export AR=aarch64-linux-gnu-ar \
@@ -139,12 +187,18 @@ RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
&& rm -rf /tmp/x264
# Build static libx265 from source (cross-compile for ARM64)
RUN git clone --depth 1 https://bitbucket.org/multicoreware/x265_git /tmp/x265 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/x265 \
&& cd /tmp/x265 \
&& git remote add origin "${github_prefix}https://github.com/videolan/x265.git" \
&& git fetch --depth 1 origin "refs/tags/${X265_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& cd source \
&& mkdir -p build \
&& cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_ASM_NASM_FLAGS="-w-macro-params-legacy" \
-DCMAKE_INSTALL_PREFIX=/usr/aarch64-linux-gnu \
-DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_SYSTEM_PROCESSOR=aarch64 \
@@ -178,12 +232,15 @@ Cflags: -I\${includedir}
EOF
# Build static libopus from source (cross-compile for ARM64)
RUN git clone --depth 1 https://github.com/xiph/opus /tmp/opus \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& wget -O /tmp/opus.tar.gz "${github_prefix}https://github.com/xiph/opus/releases/download/v${OPUS_VERSION}/opus-${OPUS_VERSION}.tar.gz" \
&& tar -xzf /tmp/opus.tar.gz -C /tmp \
&& mv "/tmp/opus-${OPUS_VERSION}" /tmp/opus \
&& cd /tmp/opus \
&& export CC=aarch64-linux-gnu-gcc \
&& export AR=aarch64-linux-gnu-ar \
&& export RANLIB=aarch64-linux-gnu-ranlib \
&& ./autogen.sh \
&& ./configure \
--prefix=/usr/aarch64-linux-gnu \
--host=aarch64-linux-gnu \
@@ -191,13 +248,20 @@ RUN git clone --depth 1 https://github.com/xiph/opus /tmp/opus \
--disable-doc \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/opus
&& rm -rf /tmp/opus /tmp/opus.tar.gz
# Download and build FFmpeg with RKMPP support
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& wget -q https://files.mofeng.run/src/image/other/ffmpeg.tar.gz \
&& tar -xzf ffmpeg.tar.gz \
&& cd ffmpeg \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git clone --depth 1 --branch ${RKMPP_BRANCH} "${github_prefix}https://github.com/nyanmisaka/mpp.git" rkmpp \
&& git clone --depth 1 --branch ${RKRGA_BRANCH} "${github_prefix}https://github.com/nyanmisaka/rk-mirrors.git" rkrga \
&& git init ffmpeg-rockchip \
&& cd ffmpeg-rockchip \
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
&& git fetch --depth 1 origin ${FFMPEG_ROCKCHIP_REV} \
&& git checkout --detach FETCH_HEAD \
&& cd .. \
# Build RKMPP
&& mkdir -p rkmpp/build && cd rkmpp/build \
&& cmake .. \
@@ -212,6 +276,7 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& make -j$(nproc) \
&& make install \
&& sed -i 's/^Libs:.*$/& -lstdc++ -lm -lpthread/' /usr/aarch64-linux-gnu/lib/pkgconfig/rockchip_mpp.pc \
&& rm -f /usr/aarch64-linux-gnu/lib/librockchip_mpp.so* \
&& cd ../.. \
# Build RKRGA - create cross file for meson
&& echo '[binaries]' > /tmp/aarch64-cross.txt \
@@ -239,6 +304,7 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& ar rcs /usr/aarch64-linux-gnu/lib/librga.a $(find build -name '*.o') \
&& ranlib /usr/aarch64-linux-gnu/lib/librga.a \
&& sed -i 's/^Libs:.*$/& -lstdc++ -lm -lpthread/' /usr/aarch64-linux-gnu/lib/pkgconfig/librga.pc \
&& rm -f /usr/aarch64-linux-gnu/lib/librga.so* \
&& cd .. \
# Create pkg-config wrapper for cross-compilation
&& echo '#!/bin/sh' > /tmp/aarch64-pkg-config \
@@ -327,7 +393,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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
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 \
@@ -341,4 +411,4 @@ ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \
LIBYUV_STATIC=1 \
OPUS_STATIC=1 \
PKG_CONFIG_ALL_STATIC=1 \
RUSTFLAGS="-C linker=aarch64-linux-gnu-gcc"
RUSTFLAGS="-C linker=aarch64-linux-gnu-gcc -C link-arg=-Wl,--allow-multiple-definition"

View File

@@ -1,21 +1,55 @@
# Cross-compilation image for ARMv7 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
# Cross-compilation image for ARMv7 based on Debian 12
# Build on Debian 12 (GLIBC 2.36) to match the runtime images
FROM debian:11
ARG DEBIAN_IMAGE=debian:12
FROM ${DEBIAN_IMAGE}
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
ARG GH_PROXY=https://gh-proxy.com/
ARG RUSTUP_DIST_SERVER_CN=https://rsproxy.cn
ARG RUSTUP_UPDATE_ROOT_CN=https://rsproxy.cn/rustup
ARG CARGO_INDEX_CN=https://rsproxy.cn/crates.io-index
ARG CARGO_REGISTRY_CN=sparse+https://rsproxy.cn/index/
ARG LIBJPEG_TURBO_VERSION=3.1.4.1
ARG LIBYUV_REV=957f295ea946cbbd13fcfc46e7066f2efa801233
ARG LIBVPX_VERSION=1.16.0
ARG X265_VERSION=3.4
ARG OPUS_VERSION=1.5.2
ARG RKMPP_BRANCH=jellyfin-mpp
ARG RKRGA_BRANCH=jellyfin-rga
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
# Set Rustup mirrors (Aliyun)
#ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
# RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i -E \
-e 's@http://deb.debian.org/debian([[:space:]]|$)@http://mirrors.tuna.tsinghua.edu.cn/debian\1@g' \
/etc/apt/sources.list.d/debian.sources; \
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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
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 = 'rsproxy-sparse'" \
'[source.rsproxy]' \
"registry = '${CARGO_INDEX_CN}'" \
'[source.rsproxy-sparse]' \
"registry = '${CARGO_REGISTRY_CN}'" \
'[registries.rsproxy]' \
"index = '${CARGO_INDEX_CN}'" \
'[net]' \
'git-fetch-with-cli = true' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -49,6 +83,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Install ARMv7 development libraries (without VAAPI/X11 for ARM)
RUN apt-get update && apt-get install -y --no-install-recommends \
libssl3 \
libssl3:armhf \
libasound2-dev:armhf \
libv4l-dev:armhf \
libudev-dev:armhf \
@@ -57,23 +93,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
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 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& git remote add origin "${github_prefix}https://github.com/libjpeg-turbo/libjpeg-turbo.git" \
&& git fetch --depth 1 origin "refs/tags/${LIBJPEG_TURBO_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& 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 \
@@ -83,8 +114,13 @@ RUN git clone --depth 1 https://github.com/libjpeg-turbo/libjpeg-turbo /tmp/libj
&& rm -rf /tmp/libjpeg-turbo
# Build static libyuv from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
RUN git init /tmp/libyuv \
&& cd /tmp/libyuv \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git remote add origin "${github_prefix}https://github.com/lemenkov/libyuv" \
&& git fetch --depth 1 origin ${LIBYUV_REV} \
&& git checkout --detach FETCH_HEAD \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_INSTALL_PREFIX=/usr/arm-linux-gnueabihf \
@@ -92,13 +128,23 @@ 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
# Build static libvpx from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://github.com/webmproject/libvpx /tmp/libvpx \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libvpx \
&& cd /tmp/libvpx \
&& git remote add origin "${github_prefix}https://github.com/webmproject/libvpx.git" \
&& git fetch --depth 1 origin "refs/tags/v${LIBVPX_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& export CC=arm-linux-gnueabihf-gcc \
&& export CXX=arm-linux-gnueabihf-g++ \
&& export LD=arm-linux-gnueabihf-ld \
@@ -115,7 +161,9 @@ RUN git clone --depth 1 https://github.com/webmproject/libvpx /tmp/libvpx \
&& rm -rf /tmp/libvpx
# Build static libx264 from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git clone --depth 1 "${github_prefix}https://github.com/mirror/x264.git" /tmp/x264 \
&& cd /tmp/x264 \
&& export CC=arm-linux-gnueabihf-gcc \
&& export AR=arm-linux-gnueabihf-ar \
@@ -132,12 +180,18 @@ RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
&& rm -rf /tmp/x264
# Build static libx265 from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://bitbucket.org/multicoreware/x265_git /tmp/x265 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/x265 \
&& cd /tmp/x265 \
&& git remote add origin "${github_prefix}https://github.com/videolan/x265.git" \
&& git fetch --depth 1 origin "refs/tags/${X265_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& cd source \
&& mkdir -p build \
&& cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_ASM_NASM_FLAGS="-w-macro-params-legacy" \
-DCMAKE_INSTALL_PREFIX=/usr/arm-linux-gnueabihf \
-DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_SYSTEM_PROCESSOR=arm \
@@ -167,12 +221,15 @@ Cflags: -I\${includedir}
EOF
# Build static libopus from source (cross-compile for ARMv7)
RUN git clone --depth 1 https://github.com/xiph/opus /tmp/opus \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& wget -O /tmp/opus.tar.gz "${github_prefix}https://github.com/xiph/opus/releases/download/v${OPUS_VERSION}/opus-${OPUS_VERSION}.tar.gz" \
&& tar -xzf /tmp/opus.tar.gz -C /tmp \
&& mv "/tmp/opus-${OPUS_VERSION}" /tmp/opus \
&& cd /tmp/opus \
&& export CC=arm-linux-gnueabihf-gcc \
&& export AR=arm-linux-gnueabihf-ar \
&& export RANLIB=arm-linux-gnueabihf-ranlib \
&& ./autogen.sh \
&& ./configure \
--prefix=/usr/arm-linux-gnueabihf \
--host=arm-linux-gnueabihf \
@@ -180,13 +237,20 @@ RUN git clone --depth 1 https://github.com/xiph/opus /tmp/opus \
--disable-doc \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/opus
&& rm -rf /tmp/opus /tmp/opus.tar.gz
# Download and build FFmpeg with RKMPP support
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& wget -q https://files.mofeng.run/src/image/other/ffmpeg.tar.gz \
&& tar -xzf ffmpeg.tar.gz \
&& cd ffmpeg \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git clone --depth 1 --branch ${RKMPP_BRANCH} "${github_prefix}https://github.com/nyanmisaka/mpp.git" rkmpp \
&& git clone --depth 1 --branch ${RKRGA_BRANCH} "${github_prefix}https://github.com/nyanmisaka/rk-mirrors.git" rkrga \
&& git init ffmpeg-rockchip \
&& cd ffmpeg-rockchip \
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
&& git fetch --depth 1 origin ${FFMPEG_ROCKCHIP_REV} \
&& git checkout --detach FETCH_HEAD \
&& cd .. \
# Build RKMPP
&& mkdir -p rkmpp/build && cd rkmpp/build \
&& cmake .. \
@@ -201,6 +265,7 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& make -j$(nproc) \
&& make install \
&& sed -i 's/^Libs:.*$/& -lstdc++ -lm -lpthread/' /usr/arm-linux-gnueabihf/lib/pkgconfig/rockchip_mpp.pc \
&& rm -f /usr/arm-linux-gnueabihf/lib/librockchip_mpp.so* \
&& cd ../.. \
# Build RKRGA - create cross file for meson
&& echo '[binaries]' > /tmp/armhf-cross.txt \
@@ -228,6 +293,7 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& ar rcs /usr/arm-linux-gnueabihf/lib/librga.a $(find build -name '*.o') \
&& ranlib /usr/arm-linux-gnueabihf/lib/librga.a \
&& sed -i 's/^Libs:.*$/& -lstdc++ -lm -lpthread/' /usr/arm-linux-gnueabihf/lib/pkgconfig/librga.pc \
&& rm -f /usr/arm-linux-gnueabihf/lib/librga.so* \
&& cd .. \
# Create pkg-config wrapper for cross-compilation
&& echo '#!/bin/sh' > /tmp/armhf-pkg-config \
@@ -316,7 +382,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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
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 \
@@ -330,7 +400,7 @@ ENV CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \
LIBYUV_STATIC=1 \
OPUS_STATIC=1 \
PKG_CONFIG_ALL_STATIC=1 \
RUSTFLAGS="-C linker=arm-linux-gnueabihf-gcc"
RUSTFLAGS="-C linker=arm-linux-gnueabihf-gcc -C link-arg=-Wl,--allow-multiple-definition"
# Default command
CMD ["bash"]

View File

@@ -1,21 +1,53 @@
# Cross-compilation image for x86_64 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
# Cross-compilation image for x86_64 based on Debian 12
# Build on Debian 12 (GLIBC 2.36) to match the runtime images
FROM debian:11
ARG DEBIAN_IMAGE=debian:12
FROM ${DEBIAN_IMAGE}
# Linux headers used by v4l2r bindgen
ARG LINUX_HEADERS_VERSION=6.6
ARG LINUX_HEADERS_SHA256=
ARG CHINAMIRRO=0
ARG GH_PROXY=https://gh-proxy.com/
ARG RUSTUP_DIST_SERVER_CN=https://rsproxy.cn
ARG RUSTUP_UPDATE_ROOT_CN=https://rsproxy.cn/rustup
ARG CARGO_INDEX_CN=https://rsproxy.cn/crates.io-index
ARG CARGO_REGISTRY_CN=sparse+https://rsproxy.cn/index/
ARG LIBJPEG_TURBO_VERSION=3.1.4.1
ARG LIBYUV_REV=957f295ea946cbbd13fcfc46e7066f2efa801233
ARG LIBVPX_VERSION=1.16.0
ARG X265_VERSION=3.4
ARG OPUS_VERSION=1.5.2
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
# Set Rustup mirrors (Aliyun)
#ENV RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup \
# RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i -E \
-e 's@http://deb.debian.org/debian([[:space:]]|$)@http://mirrors.tuna.tsinghua.edu.cn/debian\1@g' \
/etc/apt/sources.list.d/debian.sources; \
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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
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 = 'rsproxy-sparse'" \
'[source.rsproxy]' \
"registry = '${CARGO_INDEX_CN}'" \
'[source.rsproxy-sparse]' \
"registry = '${CARGO_REGISTRY_CN}'" \
'[registries.rsproxy]' \
"index = '${CARGO_INDEX_CN}'" \
'[net]' \
'git-fetch-with-cli = true' \
> /root/.cargo/config.toml; \
fi \
&& rm -rf /var/lib/apt/lists/*
ENV PATH="/root/.cargo/bin:${PATH}"
@@ -56,48 +88,62 @@ 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 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libjpeg-turbo \
&& cd /tmp/libjpeg-turbo \
&& git remote add origin "${github_prefix}https://github.com/libjpeg-turbo/libjpeg-turbo.git" \
&& git fetch --depth 1 origin "refs/tags/${LIBJPEG_TURBO_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& 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 \
&& rm -rf /tmp/libjpeg-turbo
# Build static libyuv from source (uses libjpeg-turbo headers)
RUN git clone --depth 1 https://github.com/lemenkov/libyuv /tmp/libyuv \
RUN git init /tmp/libyuv \
&& cd /tmp/libyuv \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git remote add origin "${github_prefix}https://github.com/lemenkov/libyuv" \
&& git fetch --depth 1 origin ${LIBYUV_REV} \
&& git checkout --detach FETCH_HEAD \
&& 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
# Build static libvpx from source
RUN git clone --depth 1 https://github.com/webmproject/libvpx /tmp/libvpx \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/libvpx \
&& cd /tmp/libvpx \
&& git remote add origin "${github_prefix}https://github.com/webmproject/libvpx.git" \
&& git fetch --depth 1 origin "refs/tags/v${LIBVPX_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& ./configure \
--enable-static --disable-shared --enable-pic \
--disable-examples --disable-tools --disable-docs \
--disable-unit-tests \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/libvpx
# Build static libx264 from source
RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git clone --depth 1 "${github_prefix}https://github.com/mirror/x264.git" /tmp/x264 \
&& cd /tmp/x264 \
&& ./configure --enable-static --disable-cli \
&& make -j$(nproc) \
@@ -105,12 +151,18 @@ RUN git clone --depth 1 https://code.videolan.org/videolan/x264.git /tmp/x264 \
&& rm -rf /tmp/x264
# Build static libx265 from source
RUN git clone --depth 1 https://bitbucket.org/multicoreware/x265_git /tmp/x265 \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init /tmp/x265 \
&& cd /tmp/x265 \
&& git remote add origin "${github_prefix}https://github.com/videolan/x265.git" \
&& git fetch --depth 1 origin "refs/tags/${X265_VERSION}" \
&& git checkout --detach FETCH_HEAD \
&& cd source \
&& mkdir -p build \
&& cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_ASM_NASM_FLAGS="-w-macro-params-legacy" \
-DENABLE_SHARED=OFF \
-DENABLE_CLI=OFF \
-DBUILD_SHARED_LIBS=OFF \
@@ -135,21 +187,28 @@ Cflags: -I\${includedir}
EOF
# Build static libopus from source
RUN git clone --depth 1 https://github.com/xiph/opus /tmp/opus \
RUN github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& wget -O /tmp/opus.tar.gz "${github_prefix}https://github.com/xiph/opus/releases/download/v${OPUS_VERSION}/opus-${OPUS_VERSION}.tar.gz" \
&& tar -xzf /tmp/opus.tar.gz -C /tmp \
&& mv "/tmp/opus-${OPUS_VERSION}" /tmp/opus \
&& cd /tmp/opus \
&& ./autogen.sh \
&& ./configure \
--enable-static --disable-shared \
--disable-doc \
&& make -j$(nproc) \
&& make install \
&& rm -rf /tmp/opus
&& rm -rf /tmp/opus /tmp/opus.tar.gz
# Download and build FFmpeg with minimal configuration for encoding only
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
&& wget -q https://files.mofeng.run/src/image/other/ffmpeg.tar.gz \
&& tar -xzf ffmpeg.tar.gz \
&& cd ffmpeg/ffmpeg-rockchip \
&& github_prefix="" \
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
&& git init ffmpeg-rockchip \
&& cd ffmpeg-rockchip \
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
&& git fetch --depth 1 origin ${FFMPEG_ROCKCHIP_REV} \
&& git checkout --detach FETCH_HEAD \
&& ./configure \
--enable-gpl \
--enable-version3 \
@@ -221,7 +280,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=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
fi \
&& rustup target add x86_64-unknown-linux-gnu
# Configure environment for static linking
ENV PKG_CONFIG_ALLOW_CROSS=1\

View File

@@ -6,6 +6,7 @@ Maintainer: SilentWind <admin@mofeng.run>
Package: one-kvm
Architecture: {arch}
Depends: ${{auto}}, ca-certificates{distsuffix}
Recommends: bluez
Description: A open and lightweight IP-KVM solution written in Rust
Enables BIOS-level remote management of servers and workstations.
.
@@ -17,6 +18,7 @@ Description: A open and lightweight IP-KVM solution written in Rust
* Hardware-accelerated video encoding (VAAPI, QSV, RKMPP)
* WebRTC and MJPEG streaming with low latency
* USB HID emulation via OTG gadget
* Classic Bluetooth keyboard and mouse via BlueZ
* Mass storage device for ISO/IMG mounting
* ATX power control via GPIO or USB relay
Homepage: https://github.com/mofeng-git/One-KVM

View File

@@ -1,7 +1,7 @@
[Unit]
Description=One-KVM IP-KVM Service
Documentation=https://github.com/mofeng-git/One-KVM
After=network.target
After=network-online.target bluetooth.service
Wants=network-online.target
[Service]

View File

@@ -1,6 +1,6 @@
#!/bin/bash
# Build deb packages from pre-compiled binaries
# Binaries are compiled once on Debian 11 (GLIBC 2.31) via build-images.sh
# Binaries are compiled once on Debian 12 (GLIBC 2.36) via build-images.sh
# This script packages them directly on the host using dpkg-deb
# Usage: ./build/build-deb.sh [arch]
# Example: ./build/build-deb.sh aarch64
@@ -125,8 +125,8 @@ EOF
chmod 755 "$PKG_DIR/DEBIAN/prerm"
# 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), i965-va-driver-shaders (>= 2.4), intel-media-va-driver-non-free (>= 21.1)"
BASE_DEPS="libc6 (>= 2.36), libgcc-s1, libstdc++6, libasound2t64 (>= 1.1) | libasound2 (>= 1.1), libdrm2 (>= 2.4)"
AMD64_DEPS="libva2 (>= 2.0), libva-drm2 (>= 2.10), libva-x11-2 (>= 2.10), libmfx-gen1.2 (>= 22.0) | 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"
@@ -139,10 +139,11 @@ Section: admin
Priority: optional
Architecture: $DEB_ARCH
Depends: $DEPS
Recommends: bluez
Maintainer: SilentWind <admin@mofeng.run>
Description: A open and lightweight IP-KVM solution
Enables BIOS-level remote management of servers and workstations.
Built on Debian 11, compatible with Debian 11+, Ubuntu 20.04+.
Built on Debian 12, compatible with Debian 12+, Ubuntu 24.04+.
EOF
# Build deb directly on host

View File

@@ -314,6 +314,10 @@ build_for_platform() {
if [ "$PUSH" = true ]; then
build_cmd="$build_cmd --push"
# Aliyun ACR rejects the OCI artifact manifests used by BuildKit attestations.
if [[ "$REGISTRY" == registry.cn-*.aliyuncs.com/* ]]; then
build_cmd="$build_cmd --provenance=false --sbom=false"
fi
elif [ "$LOAD" = true ]; then
build_cmd="$build_cmd --load"
fi

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

@@ -0,0 +1,24 @@
# macOS 拖拽兼容模式(实验性)
适用于 OTG 和 CH9329 后端的绝对鼠标输入。遇到目标 Mac 上拖拽只能移动一小段便停止时,可在设置页的 HID 配置中开启「macOS 拖拽兼容模式」。默认关闭。
配置字段为 `hid.mouse_macos_drag`,旧 PR 的 `ch9329_macos_drag` 字段仍可作为读取别名。OTG 必须同时启用相对鼠标和绝对鼠标接口否则配置保存会被拒绝。CH9329 同时启用 Linux 兼容开关时,此模式优先。
## 报告行为
- 未按键时仍使用绝对坐标定位。
- 从绝对输入开始的拖拽:按下使用绝对报告,移动和滚轮使用相对报告,释放时先更新相对按钮状态,再发送绝对按钮释放。
- 按键报告的通道保持到所有按钮释放,不随拖拽期间的输入模式切换而改变。
- 从相对输入开始的点击、拖拽继续使用相对按钮报告;此选项不修复原生相对模式的点击兼容问题。
- 位移从原始 15 位输入坐标换算,累计小数余量,大位移按单包范围分包并保留总量及方向。
- 运行时使用当前视频采集尺寸,并在 HID 重载后恢复尺寸;视频尚未提供尺寸时使用配置尺寸。
## 验证范围与限制
本次 OTG 扩展及位移换算修改没有 macOS 实机验证。原 PR 作者对旧 CH9329 实现的实机反馈不能视为本版本已经验证。
本地自动化覆盖位移累计/分包、1080p/4K 换算、往返移动、滚轮、输入模式切换、复位、CH9329 命令队列、OTG 临时文件模拟端点及配置校验。临时文件测试仅验证写出的字节,不验证 USB 枚举或目标系统的事件解释。
相对位移受 macOS 鼠标速度、加速、显示缩放及多屏布局影响,无法保证与绝对定位逐像素一致。松手报告携带最后的客户端绝对坐标,仍可能出现落点偏移或光标跳位;大位移分包也可能增加低波特率串口延迟。
后续实机验证应分别覆盖两个后端:窗口/文件/文本拖拽快速及慢速移动滚轮和多按钮组合1080p/4K 与缩放显示,输入模式切换、断开重连、精确落点。异常时关闭此选项恢复默认行为。

View File

@@ -0,0 +1,16 @@
[package]
name = "one-kvm-bluetooth-hid"
version = "0.1.0"
edition = "2021"
license = "GPL-2.0"
[dependencies]
bluer = { version = "0.17", features = ["bluetoothd", "l2cap"] }
dbus = { version = "0.9", features = ["vendored"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "process"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dbus-crossroads = "0.5"
dbus-tokio = "0.7"
libc = "0.2"
tracing = "0.1"

View File

@@ -0,0 +1,49 @@
//! Explicit hardware regression: opens a 10-second pairing window without
//! removing existing bonds or sending input. Stop the production HID first.
use one_kvm_bluetooth_hid::{Action, Config, Peripheral};
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), String> {
let peripheral = Peripheral::start(Config {
adapter: "hci0".into(),
name: "One-KVM HID".into(),
peer: None,
})?;
let result = async {
for _ in 0..50 {
if peripheral.status().initialized {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
let before = peripheral.status();
if !before.initialized {
return Err(format!("Initialization failed: {:?}", before.error));
}
if !before
.devices
.iter()
.any(|d| Some(&d.address) == before.peer.as_ref() && d.paired)
{
return Err("This regression needs an existing bonded computer".into());
}
peripheral.action(Action::Pair(10)).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
let open = peripheral.status();
println!("open: {}", serde_json::to_string(&open).unwrap());
if open.pairing_seconds == 0 {
return Err("Existing bond prematurely closed pairing".into());
}
tokio::time::sleep(Duration::from_secs(10)).await;
let expired = peripheral.status();
println!("expired: {}", serde_json::to_string(&expired).unwrap());
if expired.pairing_seconds != 0 || expired.peer != before.peer {
return Err("Window did not expire while preserving the bonded peer".into());
}
Ok(())
}
.await;
let cleanup = peripheral.shutdown().await;
result.and(cleanup)
}

View File

@@ -0,0 +1,24 @@
//! Native hardware smoke check. Registers for 12 seconds, sends no input,
//! opens no pairing window, then restores the adapter configuration.
use one_kvm_bluetooth_hid::{Config, Peripheral};
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), String> {
let peripheral = Peripheral::start(Config {
adapter: "hci0".into(),
name: "One-KVM HID".into(),
peer: None,
})?;
let mut initialized = false;
for _ in 0..12 {
tokio::time::sleep(Duration::from_secs(1)).await;
let status = peripheral.status();
initialized |= status.initialized;
println!("{}", serde_json::to_string(&status).unwrap());
}
peripheral.shutdown().await?;
if !initialized {
return Err("Native BlueZ peripheral never initialized".into());
}
Ok(())
}

View File

@@ -0,0 +1,236 @@
use crate::Shared;
use dbus::{channel::MatchingReceiver, message::MatchRule, nonblock::Proxy, Path};
use dbus_crossroads::Crossroads;
use std::{
sync::Arc,
time::{Duration, Instant},
};
const PATH: &str = "/org/onekvm/bluetooth/agent";
pub struct Agent {
connection: Arc<dbus::nonblock::SyncConnection>,
task: tokio::task::JoinHandle<()>,
}
impl Agent {
pub async fn register(shared: Arc<Shared>, adapter: String) -> Result<Self, String> {
let (resource, connection) =
dbus_tokio::connection::new_system_sync().map_err(|e| e.to_string())?;
let task = tokio::spawn(async move {
let _ = resource.await;
});
let mut cr = Crossroads::new();
let iface = cr.register("org.bluez.Agent1", |b| {
b.method("Release", (), (), |_, _: &mut (), ()| Ok(()));
b.method("Cancel", (), (), |_, _: &mut (), ()| Ok(()));
let state = shared.clone();
let name = adapter.clone();
b.method(
"RequestAuthorization",
("device",),
(),
move |_, _: &mut (), (path,): (Path<'static>,)| {
authorize(&state, &name, &path, true)
},
);
let state = shared.clone();
let name = adapter.clone();
b.method(
"RequestConfirmation",
("device", "passkey"),
(),
move |_, _: &mut (), (path, _): (Path<'static>, u32)| {
authorize(&state, &name, &path, true)
},
);
b.method(
"AuthorizeService",
("device", "uuid"),
(),
move |_, _: &mut (), (path, uuid): (Path<'static>, String)| {
if !matches!(uuid.as_str(), "00001124-0000-1000-8000-00805f9b34fb") {
return Err(dbus::MethodErr::from((
"org.bluez.Error.Rejected",
"Not an HID service",
)));
}
authorize(&shared, &adapter, &path, false)
},
);
});
cr.insert(PATH, &[iface], ());
let profile = cr.register("org.bluez.Profile1", |b| {
b.method("Release", (), (), |_, _: &mut (), ()| Ok(()));
b.method(
"RequestDisconnection",
("device",),
(),
|_, _: &mut (), (_device,): (Path<'static>,)| Ok(()),
);
b.method(
"NewConnection",
("device", "fd", "properties"),
(),
|_,
_: &mut (),
(_device, _fd, _props): (
Path<'static>,
dbus::arg::OwnedFd,
dbus::arg::PropMap,
)| {
// This profile only publishes SDP. Our L2CAP sockets own both HID channels.
Err::<(), _>(dbus::MethodErr::from((
"org.bluez.Error.Rejected",
"Unexpected profile connection",
)))
},
);
});
cr.insert("/org/onekvm/bluetooth/profile", &[profile], ());
connection.start_receive(
MatchRule::new_method_call(),
Box::new(move |msg, conn| {
let _ = cr.handle_message(msg, conn);
true
}),
);
let agent = Self { connection, task };
let proxy = Proxy::new(
"org.bluez",
"/org/bluez",
Duration::from_secs(5),
agent.connection.clone(),
);
let result: Result<(), dbus::Error> = proxy
.method_call(
"org.bluez.AgentManager1",
"RegisterAgent",
(Path::from(PATH), "NoInputNoOutput"),
)
.await;
if let Err(error) = result {
return Err(error.to_string());
}
let result: Result<(), dbus::Error> = proxy
.method_call(
"org.bluez.AgentManager1",
"RequestDefaultAgent",
(Path::from(PATH),),
)
.await;
result.map_err(|e| e.to_string())?;
let mut options: dbus::arg::PropMap = std::collections::HashMap::new();
options.insert(
"ServiceRecord".into(),
dbus::arg::Variant(Box::new(crate::protocol::sdp())),
);
options.insert(
"Role".into(),
dbus::arg::Variant(Box::new("server".to_string())),
);
options.insert(
"RequireAuthentication".into(),
dbus::arg::Variant(Box::new(true)),
);
options.insert(
"RequireAuthorization".into(),
dbus::arg::Variant(Box::new(false)),
);
let result: Result<(), dbus::Error> = proxy
.method_call(
"org.bluez.ProfileManager1",
"RegisterProfile",
(
Path::from("/org/onekvm/bluetooth/profile"),
crate::protocol::HID_UUID,
options,
),
)
.await;
result.map_err(|e| format!("Register HID SDP: {e}"))?;
Ok(agent)
}
}
impl Drop for Agent {
fn drop(&mut self) {
self.task.abort();
}
}
fn authorize(
shared: &Shared,
adapter: &str,
path: &str,
pairing: bool,
) -> Result<(), dbus::MethodErr> {
let rejected = || {
dbus::MethodErr::from((
"org.bluez.Error.Rejected",
"Open pairing in One-KVM or select the paired computer",
))
};
let prefix = format!("/org/bluez/{adapter}/dev_");
let address = path
.strip_prefix(&prefix)
.ok_or_else(rejected)?
.replace('_', ":");
let mut state = shared.state.lock().unwrap();
if pairing
&& !state
.pairing_until
.is_some_and(|until| until > Instant::now())
{
return Err(rejected());
}
if state.peer.as_ref().is_some_and(|peer| peer != &address) {
return Err(rejected());
}
if state.peer.is_none() {
if !pairing || state.bonded_before_pairing.contains(&address) {
return Err(rejected());
}
state.peer = Some(address);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn existing_unrelated_bond_cannot_be_adopted_by_agent_callback() {
let shared = Shared::new(None);
{
let mut state = shared.state.lock().unwrap();
state.pairing_until = Some(Instant::now() + Duration::from_secs(120));
state
.bonded_before_pairing
.insert("10:6F:D9:66:97:88".into());
}
assert!(authorize(
&shared,
"hci0",
"/org/bluez/hci0/dev_10_6F_D9_66_97_88",
true
)
.is_err());
assert!(shared.state.lock().unwrap().peer.is_none());
}
#[test]
fn only_pair_during_window_and_pin_first_peer() {
let state = Shared::new(None);
let first = "/org/bluez/hci0/dev_10_6F_D9_66_97_88";
assert!(authorize(&state, "hci0", first, true).is_err());
state.state.lock().unwrap().pairing_until = Some(Instant::now() + Duration::from_secs(60));
assert!(authorize(&state, "hci0", first, true).is_ok());
assert!(authorize(
&state,
"hci0",
"/org/bluez/hci0/dev_10_6F_D9_66_97_89",
true
)
.is_err());
assert!(authorize(&state, "hci1", first, true).is_err());
state.state.lock().unwrap().pairing_until = None;
assert!(authorize(&state, "hci0", first, false).is_ok());
assert!(authorize(&state, "hci0", first, true).is_err());
}
}

View File

@@ -0,0 +1,145 @@
//! Only bonds explicitly owned by this HID peripheral may be removed.
use bluer::{Adapter, Session};
use std::{future::Future, pin::Pin};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bond {
pub adapter: String,
pub peer: String,
pub pending: bool,
}
pub type Operation<'a, T> = Pin<Box<dyn Future<Output = Result<T, String>> + Send + 'a>>;
pub trait BondStore: Send + Sync {
fn list(&self) -> Operation<'_, Vec<Bond>>;
fn save(&self, bond: Bond) -> Operation<'_, ()>;
fn remove(&self, bond: Bond) -> Operation<'_, ()>;
}
pub async fn clean_adapter(store: &dyn BondStore, adapter: &Adapter) -> Result<(), String> {
let address = adapter
.address()
.await
.map_err(|e| e.to_string())?
.to_string();
clean_owned(store, &address, |peer| async move {
let peer = peer.parse().map_err(|_| "Invalid stored HID peer")?;
if adapter
.device_addresses()
.await
.map_err(|e| e.to_string())?
.contains(&peer)
{
adapter
.remove_device(peer)
.await
.map_err(|e| e.to_string())?;
}
Ok(())
})
.await
}
async fn clean_owned<F, Fut>(
store: &dyn BondStore,
address: &str,
mut remove: F,
) -> Result<(), String>
where
F: FnMut(String) -> Fut,
Fut: Future<Output = Result<(), String>>,
{
for bond in store
.list()
.await?
.into_iter()
.filter(|b| b.pending && b.adapter == address)
{
remove(bond.peer.clone()).await?;
// Keep the tombstone until BlueZ confirms removal; retry safely after interruption.
store.remove(bond).await?;
}
Ok(())
}
pub async fn reset(store: &dyn BondStore, explicit: Vec<Bond>) -> Result<(), String> {
let session = Session::new().await.map_err(|e| e.to_string())?;
let mut owned = store.list().await?;
owned.extend(explicit);
for mut bond in owned {
bond.pending = true;
store.save(bond).await?;
}
for name in session.adapter_names().await.map_err(|e| e.to_string())? {
clean_adapter(store, &session.adapter(&name).map_err(|e| e.to_string())?).await?;
}
// Records for absent adapters remain pending and are cleaned before their next use.
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Default)]
struct Memory(Mutex<Vec<Bond>>);
impl BondStore for Memory {
fn list(&self) -> Operation<'_, Vec<Bond>> {
Box::pin(async { Ok(self.0.lock().unwrap().clone()) })
}
fn save(&self, bond: Bond) -> Operation<'_, ()> {
Box::pin(async move {
let mut rows = self.0.lock().unwrap();
rows.retain(|b| b.adapter != bond.adapter || b.peer != bond.peer);
rows.push(bond);
Ok(())
})
}
fn remove(&self, bond: Bond) -> Operation<'_, ()> {
Box::pin(async move {
self.0.lock().unwrap().retain(|b| b != &bond);
Ok(())
})
}
}
fn bond(adapter: &str, peer: &str, pending: bool) -> Bond {
Bond {
adapter: adapter.into(),
peer: peer.into(),
pending,
}
}
#[tokio::test]
async fn cleanup_only_removes_owned_pending_bonds_on_the_selected_hardware() {
let current = bond("adapter-A", "host-1", true);
let absent = bond("adapter-B", "host-2", true);
let retained = bond("adapter-A", "host-3", false);
let store = Memory(Mutex::new(vec![current, absent.clone(), retained.clone()]));
let removed = Mutex::new(Vec::new());
clean_owned(&store, "adapter-A", |peer| {
removed.lock().unwrap().push(peer);
async { Ok(()) }
})
.await
.unwrap();
assert_eq!(*removed.lock().unwrap(), vec!["host-1"]);
assert_eq!(store.list().await.unwrap(), vec![absent, retained]);
}
#[tokio::test]
async fn cleanup_failure_keeps_tombstone_and_is_reported() {
let record = bond("adapter-A", "host-1", true);
let store = Memory(Mutex::new(vec![record.clone()]));
assert_eq!(
clean_owned(&store, "adapter-A", |_| async {
Err("BlueZ denied removal".into())
})
.await
.unwrap_err(),
"BlueZ denied removal"
);
assert_eq!(store.list().await.unwrap(), vec![record]);
clean_owned(&store, "adapter-A", |_| async { Ok(()) })
.await
.unwrap();
assert!(store.list().await.unwrap().is_empty());
}
}

View File

@@ -0,0 +1,135 @@
//! Exclusive controller ownership. No BLE switching or power cycling.
use std::{
fs::{File, OpenOptions},
os::{fd::AsRawFd, unix::fs::OpenOptionsExt},
process::Stdio,
time::Duration,
};
use tokio::process::Command;
pub struct Controller {
_lock: File,
adapter: String,
old_class: (u8, u8),
old_connectable: bool,
}
async fn run_once(adapter: &str, args: &[&str]) -> Result<String, String> {
let mut cmd = Command::new("btmgmt");
cmd.arg("--index")
.arg(adapter.trim_start_matches("hci"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = cmd
.spawn()
.map_err(|e| format!("Install bluez/btmgmt: {e}"))?;
// BlueZ 5.55's btmgmt exits on stdin EOF, even with a command argument.
// Keep a pipe open until it finishes; systemd normally supplies /dev/null.
let stdin = child.stdin.take();
let result = tokio::time::timeout(Duration::from_secs(5), child.wait_with_output())
.await
.map_err(|_| "btmgmt timeout")?
.map_err(|e| format!("Install bluez/btmgmt: {e}"))?;
drop(stdin);
let text = String::from_utf8_lossy(&result.stdout).into_owned();
if !result.status.success()
|| !result.stderr.is_empty()
|| text.to_lowercase().contains("failed")
{
return Err(format!(
"btmgmt {}: {text} {}",
args.join(" "),
String::from_utf8_lossy(&result.stderr)
));
}
Ok(text)
}
async fn run(adapter: &str, args: &[&str]) -> Result<String, String> {
// BlueZ updates the EIR/class asynchronously after registering SDP.
// Kernel management rejects a simultaneous class change with Busy.
for attempt in 0..5 {
match run_once(adapter, args).await {
Err(error) if error.contains("(Busy)") && attempt < 4 => {
tokio::time::sleep(Duration::from_millis(200)).await;
}
result => return result,
}
}
unreachable!()
}
impl Controller {
pub async fn acquire(adapter: &str) -> Result<Self, String> {
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(format!("/run/one-kvm-bluetooth-{adapter}.lock"))
.map_err(|e| e.to_string())?;
if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
return Err("Bluetooth adapter already owned by One-KVM".into());
}
let info = run(adapter, &["info"]).await?;
let settings = info
.lines()
.find_map(|l| l.trim().strip_prefix("current settings:"))
.ok_or("Cannot read Bluetooth settings")?;
if !settings.split_whitespace().any(|s| s == "br/edr") {
return Err(
"Classic Bluetooth disabled; enable BR/EDR with btmgmt before using HID".into(),
);
}
let class = info
.split_whitespace()
.skip_while(|s| *s != "class")
.nth(1)
.ok_or("Missing Bluetooth class")?;
let class =
u32::from_str_radix(class.trim_start_matches("0x"), 16).map_err(|e| e.to_string())?;
Ok(Self {
_lock: lock,
adapter: adapter.into(),
old_class: (((class >> 8) & 0x1f) as u8, (class & 0xfc) as u8),
old_connectable: settings.split_whitespace().any(|s| s == "connectable"),
})
}
pub async fn configure(&self) -> Result<(), String> {
run(&self.adapter, &["class", "5", "192"]).await?;
run(&self.adapter, &["connectable", "on"]).await?;
Ok(())
}
pub async fn restore(&self) -> Result<(), String> {
let mut errors = vec![];
if let Err(e) = run(
&self.adapter,
&[
"class",
&self.old_class.0.to_string(),
&self.old_class.1.to_string(),
],
)
.await
{
errors.push(e);
}
if let Err(e) = run(
&self.adapter,
&[
"connectable",
if self.old_connectable { "on" } else { "off" },
],
)
.await
{
errors.push(e);
}
if errors.is_empty() {
Ok(())
} else {
Err(errors.join("; "))
}
}
}

View File

@@ -0,0 +1,964 @@
//! Classic Bluetooth HID peripheral: SDP + L2CAP. Linux/BlueZ only.
mod agent;
pub mod bonds;
mod controller;
mod protocol;
use bluer::{
l2cap::{Security, SecurityLevel, SeqPacket, SeqPacketListener, Socket, SocketAddr},
Adapter, Address, AddressType, Session,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::sync::{mpsc, oneshot, watch, Mutex as AsyncMutex};
#[derive(Debug, Clone)]
pub struct Config {
pub adapter: String,
pub name: String,
pub peer: Option<String>,
}
impl Config {
pub fn validate(&self) -> Result<(), String> {
if !self
.adapter
.strip_prefix("hci")
.is_some_and(|n| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()))
{
return Err("Bluetooth adapter must be hci followed by an index".into());
}
if self.name.is_empty() || self.name.len() > 64 || self.name.chars().any(char::is_control) {
return Err(
"Bluetooth name must contain 164 UTF-8 bytes without control characters".into(),
);
}
if let Some(peer) = &self.peer {
peer.parse::<Address>()
.map_err(|_| "Invalid Bluetooth peer address")?;
}
Ok(())
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Status {
pub initialized: bool,
pub connected: bool,
pub ready: bool,
pub adapter: String,
pub adapter_address: String,
pub peer: Option<String>,
pub pairing_seconds: u32,
pub control_connected: bool,
pub interrupt_connected: bool,
pub leds: u8,
pub generation: u64,
pub error: Option<String>,
pub devices: Vec<Device>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Device {
pub address: String,
pub name: String,
pub paired: bool,
pub connected: bool,
}
#[derive(Debug, Clone, Copy)]
pub enum Report {
Keyboard,
Mouse,
Consumer,
}
impl Report {
fn len(self) -> usize {
match self {
Self::Keyboard => 8,
Self::Mouse => 4,
Self::Consumer => 2,
}
}
fn id(self) -> u8 {
match self {
Self::Keyboard => 1,
Self::Mouse => 2,
Self::Consumer => 3,
}
}
}
struct State {
peer: Option<String>,
pairing_until: Option<Instant>,
bonded_before_pairing: HashSet<String>,
}
impl State {
fn observe_bond(&mut self, address: &str, paired: bool) {
// Just Works may complete without an Agent1 authorization callback.
// Adopt only a new bond from our explicit window, respecting a pinned peer.
if paired
&& self.peer.is_none()
&& self
.pairing_until
.is_some_and(|until| until > Instant::now())
&& !self.bonded_before_pairing.contains(address)
{
self.peer = Some(address.to_owned());
tracing::info!(
peer = address,
"Bluetooth HID selected newly bonded computer"
);
}
}
fn close_pairing(&mut self, paired: bool, fallback: Option<String>) {
self.pairing_until = None;
if !paired {
self.peer = fallback;
}
}
fn pairing_completed(&self, selected_paired: bool) -> bool {
selected_paired
&& self
.peer
.as_ref()
.is_some_and(|peer| !self.bonded_before_pairing.contains(peer))
}
}
struct Shared {
state: Mutex<State>,
}
impl Shared {
fn new(peer: Option<String>) -> Self {
Self {
state: Mutex::new(State {
peer,
pairing_until: None,
bonded_before_pairing: HashSet::new(),
}),
}
}
fn allowed(&self, address: Address) -> bool {
self.state.lock().unwrap().peer.as_deref() == Some(address.to_string().as_str())
}
}
pub enum Action {
Pair(u32),
ClosePairing,
Forget,
Disconnect,
Reset,
}
enum Command {
Report(Report, Vec<u8>),
Action(Action),
Stop,
}
struct Request {
command: Command,
result: oneshot::Sender<Result<(), String>>,
expires: Instant,
}
pub struct Peripheral {
tx: mpsc::Sender<Request>,
status: watch::Receiver<Status>,
task: AsyncMutex<Option<tokio::task::JoinHandle<()>>>,
}
impl Peripheral {
pub fn start(config: Config) -> Result<Self, String> {
Self::start_with_store(config, None)
}
pub fn start_with_store(
config: Config,
bonds: Option<Arc<dyn bonds::BondStore>>,
) -> Result<Self, String> {
config.validate()?;
let (tx, rx) = mpsc::channel(64);
let (state_tx, status) = watch::channel(Status {
adapter: config.adapter.clone(),
..Default::default()
});
let task = tokio::spawn(supervise(config, bonds, rx, state_tx));
Ok(Self {
tx,
status,
task: AsyncMutex::new(Some(task)),
})
}
pub fn status(&self) -> Status {
self.status.borrow().clone()
}
pub fn subscribe(&self) -> watch::Receiver<Status> {
self.status.clone()
}
async fn request(&self, command: Command, duration: Duration) -> Result<(), String> {
let (result, rx) = oneshot::channel();
let request = Request {
command,
result,
expires: Instant::now() + duration,
};
self.tx
.try_send(request)
.map_err(|_| "Bluetooth input queue unavailable or full".to_string())?;
tokio::time::timeout(duration, rx)
.await
.map_err(|_| "Bluetooth operation timed out".to_string())?
.map_err(|_| "Bluetooth worker stopped".to_string())?
}
pub async fn send(&self, report: Report, value: Vec<u8>) -> Result<(), String> {
if value.len() != report.len() {
return Err("Invalid HID report size".into());
}
self.request(Command::Report(report, value), Duration::from_millis(500))
.await
}
pub async fn action(&self, action: Action) -> Result<(), String> {
self.request(Command::Action(action), Duration::from_secs(15))
.await
}
pub async fn shutdown(&self) -> Result<(), String> {
if let Some(task) = self.task.lock().await.take() {
let result = self.request(Command::Stop, Duration::from_secs(45)).await;
// Do not abort: the worker must restore the radio before a backend switch.
task.await.map_err(|e| e.to_string())?;
result
} else {
Ok(())
}
}
}
fn listen(address: Address, psm: u16) -> Result<SeqPacketListener, String> {
let socket = Socket::<SeqPacket>::new_seq_packet().map_err(|e| e.to_string())?;
socket
.set_security(Security {
level: SecurityLevel::Medium,
key_size: 0,
})
.map_err(|e| e.to_string())?;
socket.bind(SocketAddr::new(address,AddressType::BrEdr,psm))
.map_err(|e|format!("Cannot bind classic HID PSM 0x{psm:02x}: {e}. Disable BlueZ input plugin; see Bluetooth HID setup."))?;
socket.listen(2).map_err(|e| e.to_string())
}
struct Runtime {
adapter: Adapter,
_session: Session,
shared: Arc<Shared>,
agent: Option<agent::Agent>,
controller: controller::Controller,
listeners: [SeqPacketListener; 2],
channels: [Option<Arc<SeqPacket>>; 2],
channel_peer: Option<Address>,
partial_since: Option<Instant>,
hid: protocol::HidProtocol,
generation: u64,
old_pairable: bool,
old_powered: bool,
old_alias: String,
old_discoverable: bool,
old_discoverable_timeout: u32,
old_pairable_timeout: u32,
config: Config,
bonds: Option<Arc<dyn bonds::BondStore>>,
recorded_peer: Option<String>,
}
impl Runtime {
async fn open(
config: &Config,
bonds: Option<Arc<dyn bonds::BondStore>>,
) -> Result<Self, String> {
let controller = controller::Controller::acquire(&config.adapter).await?;
let session = Session::new().await.map_err(|e| e.to_string())?;
let adapter = session
.adapter(&config.adapter)
.map_err(|e| e.to_string())?;
let address = adapter.address().await.map_err(|e| e.to_string())?;
let mut config = config.clone();
if let Some(store) = &bonds {
bonds::clean_adapter(store.as_ref(), &adapter).await?;
if config.peer.is_none() {
config.peer = store
.list()
.await?
.into_iter()
.find(|bond| bond.adapter == address.to_string() && !bond.pending)
.map(|bond| bond.peer);
}
}
// Acquire BOTH channels before changing adapter state. Conflict is a startup error.
let listeners = [listen(address, 0x11)?, listen(address, 0x13)?];
let old_powered = adapter.is_powered().await.map_err(|e| e.to_string())?;
let old_pairable = adapter.is_pairable().await.map_err(|e| e.to_string())?;
let old_alias = adapter.alias().await.map_err(|e| e.to_string())?;
let old_discoverable = adapter.is_discoverable().await.map_err(|e| e.to_string())?;
let old_discoverable_timeout = adapter
.discoverable_timeout()
.await
.map_err(|e| e.to_string())?;
let old_pairable_timeout = adapter
.pairable_timeout()
.await
.map_err(|e| e.to_string())?;
let shared = Arc::new(Shared::new(
config.peer.as_ref().map(|p| p.to_ascii_uppercase()),
));
let mut runtime = Self {
adapter,
_session: session,
shared,
agent: None,
controller,
listeners,
channels: [None, None],
channel_peer: None,
partial_since: None,
hid: Default::default(),
generation: 0,
old_pairable,
old_powered,
old_alias,
old_discoverable,
old_discoverable_timeout,
old_pairable_timeout,
config: config.clone(),
bonds,
recorded_peer: None,
};
if let Err(e) = runtime.setup().await {
let restore = runtime.close().await;
return Err(format!("{e}; cleanup: {restore:?}"));
}
Ok(runtime)
}
async fn setup(&mut self) -> Result<(), String> {
self.adapter
.set_powered(true)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_discoverable(false)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_pairable(false)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_alias(self.config.name.clone())
.await
.map_err(|e| e.to_string())?;
self.agent =
Some(agent::Agent::register(self.shared.clone(), self.config.adapter.clone()).await?);
self.controller.configure().await?;
self.public(None).await?;
Ok(())
}
async fn public(&self, seconds: Option<u32>) -> Result<(), String> {
if let Some(seconds) = seconds {
self.adapter
.set_pairable_timeout(seconds)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_discoverable_timeout(seconds)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_pairable(true)
.await
.map_err(|e| e.to_string())?;
if let Err(e) = self.adapter.set_discoverable(true).await {
let _ = self.adapter.set_pairable(false).await;
return Err(e.to_string());
}
} else {
self.adapter
.set_discoverable(false)
.await
.map_err(|e| e.to_string())?;
self.adapter
.set_pairable(false)
.await
.map_err(|e| e.to_string())?;
}
Ok(())
}
fn drop_channels(&mut self) {
for socket in self.channels.iter_mut().filter_map(Option::take) {
let _ = socket.shutdown(std::net::Shutdown::Both);
}
self.channel_peer = None;
self.partial_since = None;
self.hid = Default::default();
self.generation = self.generation.wrapping_add(1);
}
async fn packet(&self, index: usize, data: &[u8]) -> Result<(), String> {
let socket = self.channels[index]
.as_ref()
.ok_or("Classic HID channel not connected")?;
let sent = tokio::time::timeout(Duration::from_millis(250), socket.send(data))
.await
.map_err(|_| "HID send timeout")?
.map_err(|e| e.to_string())?;
if sent != data.len() {
return Err("Short HID packet write".into());
}
Ok(())
}
async fn release(&mut self) {
for packet in self.hid.release() {
if self.channels[1].is_some() && self.packet(1, &packet).await.is_err() {
self.drop_channels();
break;
}
}
self.generation = self.generation.wrapping_add(1);
}
async fn accept(
&mut self,
index: usize,
socket: SeqPacket,
peer: SocketAddr,
) -> Result<(), String> {
if peer.addr_type != AddressType::BrEdr {
return Ok(());
}
// A host can open HID channels before the next status poll.
let paired = self
.adapter
.device(peer.addr)
.map_err(|e| e.to_string())?
.is_paired()
.await
.map_err(|e| e.to_string())?;
self.shared
.state
.lock()
.unwrap()
.observe_bond(&peer.addr.to_string(), paired);
if !self.shared.allowed(peer.addr) {
return Ok(());
}
if self.channel_peer.is_some_and(|p| p != peer.addr) || self.channels[index].is_some() {
return Ok(());
}
// Kernel BT_SECURITY_MEDIUM negotiates encryption before accept completes.
if socket
.as_ref()
.security()
.map_err(|e| e.to_string())?
.key_size
< 7
{
return Ok(());
}
self.channel_peer = Some(peer.addr);
self.channels[index] = Some(Arc::new(socket));
if self.channels.iter().all(Option::is_some) {
self.partial_since = None;
self.release().await;
} else {
self.partial_since = Some(Instant::now());
}
Ok(())
}
async fn status(&mut self) -> Result<Status, String> {
if !self.adapter.is_powered().await.map_err(|e| e.to_string())? {
return Err("Bluetooth adapter powered off".into());
}
// A daemon restart loses the SDP registration even if the adapter comes back powered.
if !self
.adapter
.uuids()
.await
.map_err(|e| e.to_string())?
.unwrap_or_default()
.iter()
.any(|id| id.to_string() == protocol::HID_UUID)
{
return Err("Classic HID SDP registration lost; restarting Bluetooth backend".into());
}
let mut status = Status {
initialized: true,
adapter: self.config.adapter.clone(),
adapter_address: self
.adapter
.address()
.await
.map_err(|e| e.to_string())?
.to_string(),
..Default::default()
};
for address in self
.adapter
.device_addresses()
.await
.map_err(|e| e.to_string())?
{
let device = self.adapter.device(address).map_err(|e| e.to_string())?;
let connected = device.is_connected().await.unwrap_or(false);
let paired = device.is_paired().await.unwrap_or(false);
self.shared
.state
.lock()
.unwrap()
.observe_bond(&address.to_string(), paired);
if paired || connected {
status.devices.push(Device {
address: address.to_string(),
name: device.alias().await.unwrap_or_default(),
paired,
connected,
});
}
}
status.devices.sort_by(|a, b| a.address.cmp(&b.address));
let (peer, until) = {
let state = self.shared.state.lock().unwrap();
(state.peer.clone(), state.pairing_until)
};
status.peer = peer.clone();
let selected = status
.devices
.iter()
.find(|device| Some(&device.address) == peer.as_ref());
let selected_paired = selected.is_some_and(|device| device.paired);
if selected_paired && self.recorded_peer != peer {
if let (Some(store), Some(peer)) = (&self.bonds, &peer) {
store
.save(bonds::Bond {
adapter: status.adapter_address.clone(),
peer: peer.clone(),
pending: false,
})
.await?;
self.recorded_peer = Some(peer.clone());
}
}
status.connected = selected.is_some_and(|device| device.paired && device.connected);
if self.channels.iter().any(Option::is_some)
&& (!status.connected
|| self
.partial_since
.is_some_and(|time| time.elapsed() > Duration::from_secs(10)))
{
self.drop_channels();
}
if let Some(until) = until {
let completed = self
.shared
.state
.lock()
.unwrap()
.pairing_completed(selected_paired);
if until <= Instant::now() || completed {
{
let mut state = self.shared.state.lock().unwrap();
state.close_pairing(
selected_paired,
self.config.peer.as_ref().map(|p| p.to_ascii_uppercase()),
);
status.peer = state.peer.clone();
}
self.public(None).await?;
tracing::info!(reason = if completed { "bonded" } else { "expired" }, peer = ?status.peer, "Bluetooth HID pairing window closed");
} else {
status.pairing_seconds =
until.saturating_duration_since(Instant::now()).as_secs() as u32 + 1;
}
}
status.control_connected = self.channels[0].is_some();
status.interrupt_connected = self.channels[1].is_some();
status.ready = status.connected
&& status.control_connected
&& status.interrupt_connected
&& !self.hid.suspended;
status.leds = self.hid.leds;
status.generation = self.generation;
Ok(status)
}
async fn forget(&mut self) -> Result<(), String> {
self.release().await;
self.drop_channels();
let peer = self.shared.state.lock().unwrap().peer.clone();
if let Some(peer) = &peer {
let address = peer.parse().map_err(|_| "Invalid peer")?;
if self
.adapter
.device_addresses()
.await
.map_err(|e| e.to_string())?
.contains(&address)
{
self.adapter
.remove_device(address)
.await
.map_err(|e| e.to_string())?;
}
self.shared
.state
.lock()
.unwrap()
.bonded_before_pairing
.remove(peer);
tracing::info!(%peer, "Bluetooth HID forgot computer");
}
if let Some(store) = &self.bonds {
let address = self
.adapter
.address()
.await
.map_err(|e| e.to_string())?
.to_string();
for bond in store
.list()
.await?
.into_iter()
.filter(|b| b.adapter == address && Some(&b.peer) == peer.as_ref())
{
store.remove(bond).await?;
}
}
self.recorded_peer = None;
self.config.peer = None;
self.shared.state.lock().unwrap().peer = None;
Ok(())
}
async fn incoming(&mut self, index: usize, data: &[u8]) -> Result<(), String> {
if index == 1 {
self.hid.output(data);
return Ok(());
}
let result = self.hid.control(data);
if let Some(reply) = result.reply {
self.packet(0, &reply).await?;
}
if result.reset {
self.release().await;
}
if result.unplug {
self.forget().await?;
}
Ok(())
}
async fn execute(&mut self, command: Command) -> Result<(), String> {
match command {
Command::Report(kind, value) => {
let peer = self.channel_peer.ok_or("Classic HID is not connected")?;
if !self.shared.allowed(peer) || self.channels.iter().any(Option::is_none) {
return Err("Classic HID channels are not ready".into());
}
let device = self.adapter.device(peer).map_err(|e| e.to_string())?;
if !device.is_paired().await.unwrap_or(false)
|| !device.is_connected().await.unwrap_or(false)
{
self.drop_channels();
return Err("Selected Bluetooth computer disconnected".into());
}
let packet = self.hid.input(kind, &value)?;
if let Err(e) = self.packet(1, &packet).await {
self.drop_channels();
return Err(e);
}
}
Command::Action(Action::Pair(seconds)) => {
if !(10..=300).contains(&seconds) {
return Err("Pairing window must be 10300 seconds".into());
}
let mut bonded = HashSet::new();
for address in self
.adapter
.device_addresses()
.await
.map_err(|e| e.to_string())?
{
if self
.adapter
.device(address)
.map_err(|e| e.to_string())?
.is_paired()
.await
.map_err(|e| e.to_string())?
{
bonded.insert(address.to_string());
}
}
{
let mut state = self.shared.state.lock().unwrap();
// Preserve the original baseline when extending an open window.
if !state
.pairing_until
.is_some_and(|until| until > Instant::now())
{
state.bonded_before_pairing = bonded;
}
state.pairing_until =
Some(Instant::now() + Duration::from_secs(seconds.into()));
}
if let Err(e) = self.public(Some(seconds)).await {
self.shared.state.lock().unwrap().pairing_until = None;
return Err(e);
}
tracing::info!(seconds, "Bluetooth HID pairing window opened");
}
Command::Action(Action::ClosePairing) => {
self.public(None).await?;
let peer = self.shared.state.lock().unwrap().peer.clone();
let paired = if let Some(peer) = peer {
self.adapter
.device(peer.parse().map_err(|_| "Invalid HID peer")?)
.map_err(|e| e.to_string())?
.is_paired()
.await
.map_err(|e| e.to_string())?
} else {
false
};
self.shared
.state
.lock()
.unwrap()
.close_pairing(paired, self.config.peer.clone());
tracing::info!(reason = "manual", "Bluetooth HID pairing window closed");
}
Command::Action(Action::Forget) => self.forget().await?,
Command::Action(Action::Disconnect) => {
self.release().await;
self.drop_channels();
let peer = self.shared.state.lock().unwrap().peer.clone();
if let Some(peer) = peer {
self.adapter
.device(peer.parse().map_err(|_| "Invalid peer")?)
.map_err(|e| e.to_string())?
.disconnect()
.await
.map_err(|e| e.to_string())?;
}
}
Command::Action(Action::Reset) => self.release().await,
Command::Stop => {}
}
Ok(())
}
async fn close(&mut self) -> Result<(), String> {
self.release().await;
self.drop_channels();
self.agent.take();
tokio::time::sleep(Duration::from_millis(100)).await;
let mut errors = vec![];
if let Err(e) = self.adapter.set_discoverable(false).await {
errors.push(e.to_string());
}
if let Err(e) = self.controller.restore().await {
errors.push(e);
}
if let Err(e) = self.adapter.set_alias(self.old_alias.clone()).await {
errors.push(e.to_string());
}
if let Err(e) = self
.adapter
.set_discoverable_timeout(self.old_discoverable_timeout)
.await
{
errors.push(e.to_string());
}
if let Err(e) = self
.adapter
.set_pairable_timeout(self.old_pairable_timeout)
.await
{
errors.push(e.to_string());
}
if let Err(e) = self.adapter.set_pairable(self.old_pairable).await {
errors.push(e.to_string());
}
if let Err(e) = self.adapter.set_discoverable(self.old_discoverable).await {
errors.push(e.to_string());
}
if let Err(e) = self.adapter.set_powered(self.old_powered).await {
errors.push(e.to_string());
}
if errors.is_empty() {
Ok(())
} else {
Err(errors.join("; "))
}
}
}
async fn receive(socket: Option<Arc<SeqPacket>>, buffer: &mut [u8]) -> std::io::Result<usize> {
match socket {
Some(socket) => socket.recv(buffer).await,
None => std::future::pending().await,
}
}
async fn supervise(
config: Config,
bonds: Option<Arc<dyn bonds::BondStore>>,
mut rx: mpsc::Receiver<Request>,
tx: watch::Sender<Status>,
) {
let mut generation = 0;
loop {
let mut runtime = match Runtime::open(&config, bonds.clone()).await {
Ok(runtime) => runtime,
Err(error) => {
tx.send_replace(Status {
adapter: config.adapter.clone(),
error: Some(error.clone()),
generation,
..Default::default()
});
let delay = tokio::time::sleep(Duration::from_secs(5));
tokio::pin!(delay);
loop {
tokio::select! {_=&mut delay=>break,request=rx.recv()=>{
let Some(request)=request else{return;};
if matches!(request.command,Command::Stop){let _=request.result.send(Ok(()));return;}
let _=request.result.send(Err(error.clone()));
}}
}
continue;
}
};
runtime.generation = generation;
let mut timer = tokio::time::interval(Duration::from_millis(500));
let failure = loop {
let ctl = runtime.channels[0].clone();
let intr = runtime.channels[1].clone();
let mut ctl_buffer = [0; 1024];
let mut intr_buffer = [0; 1024];
tokio::select! {
accepted=runtime.listeners[0].accept()=>{match accepted{Ok((socket,peer))=>{if let Err(e)=runtime.accept(0,socket,peer).await{break e;}},Err(e)=>break e.to_string()}}
accepted=runtime.listeners[1].accept()=>{match accepted{Ok((socket,peer))=>{if let Err(e)=runtime.accept(1,socket,peer).await{break e;}},Err(e)=>break e.to_string()}}
read=receive(ctl,&mut ctl_buffer)=>{match read{Ok(n)if n>0=>{if runtime.incoming(0,&ctl_buffer[..n]).await.is_err(){runtime.drop_channels();}},_=>runtime.drop_channels()}}
read=receive(intr,&mut intr_buffer)=>{match read{Ok(n)if n>0=>{if runtime.incoming(1,&intr_buffer[..n]).await.is_err(){runtime.drop_channels();}},_=>runtime.drop_channels()}}
_=timer.tick()=>{match runtime.status().await{Ok(status)=>{tx.send_if_modified(|old|{if *old!=status{*old=status;true}else{false}});},Err(e)=>break e}}
request=rx.recv()=>{
let Some(request)=request else{let _=runtime.close().await;return;};
if matches!(request.command,Command::Stop){let result=runtime.close().await;tx.send_replace(Status{adapter:config.adapter.clone(),..Default::default()});let _=request.result.send(result);return;}
if request.expires<=Instant::now()||request.result.is_closed(){runtime.release().await;continue;}
let action = matches!(&request.command, Command::Action(_));
let result=runtime.execute(request.command).await;
if result.is_err(){runtime.release().await;}
if action {
if let Ok(status) = runtime.status().await { tx.send_replace(status); }
}
let _=request.result.send(result);
}
}
};
let restore = runtime.close().await;
generation = runtime.generation.wrapping_add(1);
tx.send_replace(Status {
adapter: config.adapter.clone(),
error: Some(format!("{failure}; cleanup: {restore:?}")),
generation,
..Default::default()
});
drop(runtime);
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn closing_pairing_preserves_completed_bonds_but_releases_unpaired_targets() {
let shared = Shared::new(Some("10:6F:D9:66:97:88".into()));
let mut state = shared.state.lock().unwrap();
state.pairing_until = Some(Instant::now() + Duration::from_secs(120));
state.close_pairing(true, None);
assert_eq!(state.peer.as_deref(), Some("10:6F:D9:66:97:88"));
assert!(state.pairing_until.is_none());
state.close_pairing(false, None);
assert!(state.peer.is_none());
}
#[test]
fn configuration_validation() {
let mut c = Config {
adapter: "hci0".into(),
name: "One-KVM".into(),
peer: None,
};
assert!(c.validate().is_ok());
c.adapter = "hci0;reboot".into();
assert!(c.validate().is_err());
c.adapter = "hci1".into();
c.peer = Some("bogus".into());
assert!(c.validate().is_err());
}
#[test]
fn peer_isolation() {
let state = Shared::new(Some("10:6F:D9:66:97:88".into()));
assert!(state.allowed("10:6F:D9:66:97:88".parse().unwrap()));
assert!(!state.allowed("10:6F:D9:66:97:89".parse().unwrap()));
}
#[test]
fn new_bond_without_agent_callback_completes_pairing() {
let shared = Shared::new(None);
let mut state = shared.state.lock().unwrap();
state.pairing_until = Some(Instant::now() + Duration::from_secs(120));
let peer = "10:6F:D9:66:97:88";
state.observe_bond(peer, false);
assert_eq!(state.peer, None);
state.observe_bond(peer, true);
assert_eq!(state.peer.as_deref(), Some(peer));
assert!(state.pairing_completed(true));
// A second computer cannot replace the one selected in this window.
state.observe_bond("10:6F:D9:66:97:89", true);
assert_eq!(state.peer.as_deref(), Some(peer));
}
#[test]
fn old_bond_does_not_finish_a_new_window() {
let peer = "10:6F:D9:66:97:88";
let shared = Shared::new(Some(peer.into()));
let mut state = shared.state.lock().unwrap();
state.pairing_until = Some(Instant::now() + Duration::from_secs(120));
state.bonded_before_pairing.insert(peer.into());
state.observe_bond(peer, true);
assert!(!state.pairing_completed(true));
state.peer = None;
state.observe_bond(peer, true);
assert_eq!(state.peer, None);
}
#[test]
fn bond_observation_respects_closed_window_and_pinned_peer() {
let peer = "10:6F:D9:66:97:88";
let shared = Shared::new(None);
let mut state = shared.state.lock().unwrap();
state.observe_bond(peer, true);
assert_eq!(state.peer, None);
state.pairing_until = Some(Instant::now() - Duration::from_secs(1));
state.observe_bond(peer, true);
assert_eq!(state.peer, None);
state.pairing_until = Some(Instant::now() + Duration::from_secs(120));
state.peer = Some("10:6F:D9:66:97:89".into());
state.observe_bond(peer, true);
assert_eq!(state.peer.as_deref(), Some("10:6F:D9:66:97:89"));
}
}
#[derive(Serialize)]
pub struct AdapterInfo {
pub name: String,
pub address: String,
pub powered: bool,
}
pub async fn adapters() -> Result<Vec<AdapterInfo>, String> {
let session = Session::new().await.map_err(|e| e.to_string())?;
let mut output = vec![];
for name in session.adapter_names().await.map_err(|e| e.to_string())? {
let adapter = session.adapter(&name).map_err(|e| e.to_string())?;
output.push(AdapterInfo {
name,
address: adapter
.address()
.await
.map_err(|e| e.to_string())?
.to_string(),
powered: adapter.is_powered().await.map_err(|e| e.to_string())?,
});
}
Ok(output)
}

View File

@@ -0,0 +1,267 @@
//! Classic HIDP framing and report descriptor.
use crate::Report;
pub const MAP: &[u8] = &[
0x05, 0x01, 0x09, 0x06, 0xa1, 0x01, 0x85, 0x01, 0x05, 0x07, 0x19, 0xe0, 0x29, 0xe7, 0x15, 0x00,
0x25, 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x95, 0x01, 0x75, 0x08, 0x81, 0x01, 0x95, 0x05,
0x75, 0x01, 0x05, 0x08, 0x19, 0x01, 0x29, 0x05, 0x91, 0x02, 0x95, 0x01, 0x75, 0x03, 0x91, 0x01,
0x95, 0x06, 0x75, 0x08, 0x15, 0x00, 0x25, 0x65, 0x05, 0x07, 0x19, 0x00, 0x29, 0x65, 0x81, 0x00,
0xc0, 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x85, 0x02, 0x09, 0x01, 0xa1, 0x00, 0x05, 0x09, 0x19,
0x01, 0x29, 0x05, 0x15, 0x00, 0x25, 0x01, 0x95, 0x05, 0x75, 0x01, 0x81, 0x02, 0x95, 0x01, 0x75,
0x03, 0x81, 0x01, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x75,
0x08, 0x95, 0x03, 0x81, 0x06, 0xc0, 0xc0, 0x05, 0x0c, 0x09, 0x01, 0xa1, 0x01, 0x85, 0x03, 0x15,
0x00, 0x26, 0xff, 0x03, 0x19, 0x00, 0x2a, 0xff, 0x03, 0x75, 0x10, 0x95, 0x01, 0x81, 0x00, 0xc0,
];
pub const HID_UUID: &str = "00001124-0000-1000-8000-00805f9b34fb";
pub fn sdp() -> String {
let hex: String = MAP.iter().map(|byte| format!("{byte:02x}")).collect();
format!(
r#"<?xml version="1.0"?>
<record>
<attribute id="0x0001"><sequence><uuid value="0x1124"/></sequence></attribute>
<attribute id="0x0004"><sequence><sequence><uuid value="0x0100"/><uint16 value="0x0011"/></sequence><sequence><uuid value="0x0011"/></sequence></sequence></attribute>
<attribute id="0x0005"><sequence><uuid value="0x1002"/></sequence></attribute>
<attribute id="0x0006"><sequence><uint16 value="0x656e"/><uint16 value="0x006a"/><uint16 value="0x0100"/></sequence></attribute>
<attribute id="0x0009"><sequence><sequence><uuid value="0x1124"/><uint16 value="0x0100"/></sequence></sequence></attribute>
<attribute id="0x000d"><sequence><sequence><sequence><uuid value="0x0100"/><uint16 value="0x0013"/></sequence><sequence><uuid value="0x0011"/></sequence></sequence></sequence></attribute>
<attribute id="0x0100"><text value="One-KVM Keyboard and Mouse"/></attribute>
<attribute id="0x0101"><text value="Classic Bluetooth HID"/></attribute>
<attribute id="0x0102"><text value="One-KVM"/></attribute>
<attribute id="0x0200"><uint16 value="0x0100"/></attribute>
<attribute id="0x0201"><uint16 value="0x0111"/></attribute>
<attribute id="0x0202"><uint8 value="0xc0"/></attribute>
<attribute id="0x0203"><uint8 value="0x00"/></attribute>
<attribute id="0x0204"><boolean value="false"/></attribute>
<attribute id="0x0205"><boolean value="false"/></attribute>
<attribute id="0x0206"><sequence><sequence><uint8 value="0x22"/><text encoding="hex" value="{hex}"/></sequence></sequence></attribute>
<attribute id="0x0207"><sequence><sequence><uint16 value="0x0409"/><uint16 value="0x0100"/></sequence></sequence></attribute>
<attribute id="0x0209"><boolean value="false"/></attribute>
<attribute id="0x020a"><boolean value="false"/></attribute>
<attribute id="0x020b"><uint16 value="0x0100"/></attribute>
<attribute id="0x020c"><uint16 value="0x0c80"/></attribute>
<attribute id="0x020d"><boolean value="true"/></attribute>
<attribute id="0x020e"><boolean value="true"/></attribute>
</record>"#
)
}
#[derive(Debug, Default)]
pub struct HidProtocol {
pub boot: bool,
pub suspended: bool,
pub leds: u8,
pub keyboard: [u8; 8],
pub buttons: u8,
pub consumer: [u8; 2],
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ControlResult {
pub reply: Option<Vec<u8>>,
pub unplug: bool,
pub reset: bool,
}
impl HidProtocol {
pub fn input(&mut self, kind: Report, value: &[u8]) -> Result<Vec<u8>, String> {
if value.len() != kind.len() {
return Err("Invalid HID report length".into());
}
if self.suspended {
return Err("Bluetooth HID is suspended".into());
}
let mut packet = vec![0xa1, kind.id()];
match kind {
Report::Keyboard => {
self.keyboard.copy_from_slice(value);
packet.extend_from_slice(value);
}
Report::Mouse => {
self.buttons = value[0];
packet.extend_from_slice(&value[..if self.boot { 3 } else { 4 }]);
if self.boot {
packet[2] &= 7;
}
}
Report::Consumer if !self.boot => {
self.consumer.copy_from_slice(value);
packet.extend_from_slice(value);
}
Report::Consumer => return Err("Consumer keys unavailable in boot protocol".into()),
}
Ok(packet)
}
pub fn release(&mut self) -> Vec<Vec<u8>> {
self.keyboard = [0; 8];
self.buttons = 0;
self.consumer = [0; 2];
let mut packets = vec![
vec![0xa1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
if self.boot {
vec![0xa1, 2, 0, 0, 0]
} else {
vec![0xa1, 2, 0, 0, 0, 0]
},
];
if !self.boot {
packets.push(vec![0xa1, 3, 0, 0]);
}
packets
}
pub fn output(&mut self, data: &[u8]) -> bool {
if data.len() == 3 && data[0] == 0xa2 && data[1] == 1 {
self.leds = data[2] & 0x1f;
true
} else {
false
}
}
pub fn control(&mut self, data: &[u8]) -> ControlResult {
let mut result = ControlResult::default();
let handshake = |code| ControlResult {
reply: Some(vec![code]),
..Default::default()
};
let Some(&header) = data.first() else {
return handshake(4);
};
match header {
0x13 if data.len() == 1 => {
self.suspended = true;
result.reset = true;
}
0x14 if data.len() == 1 => {
self.suspended = false;
result.reset = true;
}
0x15 if data.len() == 1 => {
result.unplug = true;
}
0x11 | 0x12 if data.len() == 1 => {
self.suspended = false;
result.reset = true;
}
0x60 if data.len() == 1 => {
result.reply = Some(vec![0xa0, if self.boot { 0 } else { 1 }]);
}
0x70 | 0x71 if data.len() == 1 => {
self.boot = header == 0x70;
result.reply = Some(vec![0]);
result.reset = true;
}
0x52 if data.len() == 3 && data[1] == 1 => {
self.leds = data[2] & 0x1f;
return handshake(0);
}
0x41 | 0x49 | 0x42 | 0x4a => {
let sized = header & 8 != 0;
if data.len() != if sized { 4 } else { 2 } {
return handshake(4);
}
let mut report = vec![0xa0 | (header & 3), data[1]];
match (header & 3, data[1]) {
(1, 1) => report.extend(self.keyboard),
(1, 2) => report.extend(if self.boot {
vec![self.buttons & 7, 0, 0]
} else {
vec![self.buttons, 0, 0, 0]
}),
(1, 3) if !self.boot => report.extend(self.consumer),
(2, 1) => report.push(self.leds),
_ => return handshake(2),
}
if sized {
report.truncate(1 + u16::from_le_bytes([data[2], data[3]]) as usize);
}
result.reply = Some(report);
}
_ => return handshake(3), // ERR_UNSUPPORTED_REQUEST
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classic_frames_and_boot_protocol() {
let mut hid = HidProtocol::default();
assert_eq!(
hid.input(Report::Keyboard, &[2, 0, 4, 0, 0, 0, 0, 0])
.unwrap(),
[0xa1, 1, 2, 0, 4, 0, 0, 0, 0, 0]
);
assert_eq!(hid.control(&[0x60]).reply.unwrap(), [0xa0, 1]);
assert_eq!(hid.control(&[0x70]).reply.unwrap(), [0]);
assert_eq!(
hid.input(Report::Mouse, &[0x1f, 127, 128, 1]).unwrap(),
[0xa1, 2, 7, 127, 128]
);
assert!(hid.input(Report::Consumer, &[0, 0]).is_err());
assert!(hid.input(Report::Keyboard, &[0]).is_err());
}
#[test]
fn led_read_write_and_errors() {
let mut hid = HidProtocol::default();
assert!(hid.output(&[0xa2, 1, 3]));
assert_eq!(hid.leds, 3);
assert_eq!(hid.control(&[0x42, 1]).reply.unwrap(), [0xa2, 1, 3]);
assert_eq!(hid.control(&[0x52, 1, 2]).reply.unwrap(), [0]);
assert_eq!(hid.leds, 2);
assert_eq!(hid.control(&[0x41, 99]).reply.unwrap(), [2]);
assert_eq!(hid.control(&[0x41]).reply.unwrap(), [4]);
assert_eq!(hid.control(&[0x90, 0]).reply.unwrap(), [3]);
assert_eq!(
hid.control(&[0x49, 1, 3, 0]).reply.unwrap(),
[0xa1, 1, 0, 0]
);
}
#[test]
fn suspend_reset_and_virtual_unplug() {
let mut hid = HidProtocol::default();
assert!(hid.control(&[0x13]).reset);
assert!(hid.input(Report::Mouse, &[0; 4]).is_err());
assert!(hid.control(&[0x14]).reset);
assert!(hid.input(Report::Mouse, &[0; 4]).is_ok());
assert!(hid.control(&[0x15]).unplug);
hid.keyboard[2] = 4;
hid.buttons = 1;
assert_eq!(hid.release().len(), 3);
assert_eq!(hid.keyboard, [0; 8]);
assert_eq!(hid.buttons, 0);
}
#[test]
fn sdp_describes_both_classic_channels() {
let record = sdp();
assert!(record.contains("uuid value=\"0x1124\""));
assert!(record.contains("uint16 value=\"0x0011\""));
assert!(record.contains("uint16 value=\"0x0013\""));
assert!(!record.contains("0x1812"));
}
#[test]
fn descriptor_report_sizes() {
let (mut pos, mut size, mut count, mut id, mut depth) = (0, 0, 0, 0, 0);
let mut input = [0; 4];
let mut output = [0; 4];
while pos < MAP.len() {
let prefix = MAP[pos];
pos += 1;
let length = [0, 1, 2, 4][(prefix & 3) as usize];
let mut value = 0;
for i in 0..length {
value |= (MAP[pos + i] as usize) << (8 * i);
}
pos += length;
match ((prefix >> 2) & 3, prefix >> 4) {
(1, 7) => size = value,
(1, 8) => id = value,
(1, 9) => count = value,
(0, 8) => input[id] += size * count,
(0, 9) => output[id] += size * count,
(0, 10) => depth += 1,
(0, 12) => depth -= 1,
_ => {}
}
}
assert_eq!(depth, 0);
assert_eq!(input, [0, 64, 32, 16]);
assert_eq!(output, [0, 8, 0, 0]);
}
}

View File

@@ -8,8 +8,6 @@
/ffmpeg/linux/debug
!/ffmpeg/mac
/ffmpeg/mac/debug
!/ffmpeg/android
/ffmpeg/android/debug
!/ffmpeg/ios
/ffmpeg/ios/debug
/input

View File

@@ -9,14 +9,16 @@ 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"
bindgen = "0.72"

View File

@@ -41,18 +41,6 @@ Based on the information above, there are several optimizations and changes made
* remove hevc_vaapi because of possible poor quality
* amf: not tested, https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/378
### MacOS
| FFmpeg ram encode | FFmpeg ram decode |
| ------------------ | ------------------ |
| h265 only | Y |
### Android
| FFmpeg ram encode |
| ------------------ |
| Y |
## System requirements
* intel
@@ -76,4 +64,3 @@ Based on the information above, there are several optimizations and changes made
https://docs.nvidia.com/video-technologies/video-codec-sdk/11.1/read-me/index.html
https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new?ncid=em-prod-816193

View File

@@ -5,7 +5,8 @@ use std::{
};
fn main() {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
// Read the current source path when running, since build artifacts may move.
let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let cpp_dir = manifest_dir.join("cpp");
println!("cargo:rerun-if-changed=src");
println!("cargo:rerun-if-changed={}", cpp_dir.display());
@@ -17,15 +18,16 @@ fn main() {
}
fn build_common(builder: &mut Build) {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let common_dir = manifest_dir.join("cpp").join("common");
bindgen::builder()
let 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));
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("common_ffi.rs"))
@@ -34,7 +36,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);
@@ -69,9 +73,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())
@@ -89,8 +93,8 @@ mod ffmpeg {
ffmpeg_ffi();
// 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);
@@ -99,6 +103,23 @@ mod ffmpeg {
link_os();
build_ffmpeg_ram(builder);
build_ffmpeg_hw(builder);
build_ffmpeg_capture(builder);
}
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
@@ -142,7 +163,7 @@ mod ffmpeg {
println!("cargo:rustc-link-lib=static=avcodec");
println!("cargo:rustc-link-lib=static=avutil");
// Link hardware acceleration dependencies (dynamic)
// Link hardware acceleration dependencies
// These vary by architecture
if target_arch == "x86_64" {
// VAAPI for x86_64
@@ -151,13 +172,11 @@ mod ffmpeg {
println!("cargo:rustc-link-lib=va-x11"); // Required for vaGetDisplay
println!("cargo:rustc-link-lib=mfx");
} else {
// RKMPP for ARM
println!("cargo:rustc-link-lib=rockchip_mpp");
let rga_static = lib_dir.join("librga.a");
if rga_static.exists() {
println!("cargo:rustc-link-lib=static=rga");
} else {
println!("cargo:rustc-link-lib=rga");
for lib in ["rockchip_mpp", "rga"] {
if !lib_dir.join(format!("lib{lib}.a")).exists() {
panic!("missing static library: lib{lib}.a");
}
println!("cargo:rustc-link-lib=static={}", lib);
}
}
@@ -216,12 +235,6 @@ mod ffmpeg {
// For static linking, link FFmpeg libs statically, others dynamically
if lib_name.starts_with("av") || lib_name == "swresample" {
println!("cargo:rustc-link-lib=static={}", lib_name);
} else if lib_name == "rga"
&& link_paths
.iter()
.any(|path| Path::new(path).join("librga.a").exists())
{
println!("cargo:rustc-link-lib=static=rga");
} else {
// Runtime libraries (va, drm, etc.) must be dynamic
println!("cargo:rustc-link-lib={}", lib_name);
@@ -271,7 +284,6 @@ mod ffmpeg {
target = target.replace("x64", "x86");
}
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
println!(
@@ -282,15 +294,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");
@@ -299,12 +322,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++"];
@@ -329,14 +368,13 @@ mod ffmpeg {
}
fn ffmpeg_ffi() {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let ffmpeg_ram_dir = manifest_dir.join("cpp").join("common");
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()
.header(ffi_header)
.rustified_enum("*")
let bindings = bindgen::builder().header(ffi_header).rustified_enum(".*");
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_ffi.rs"))
@@ -344,15 +382,14 @@ mod ffmpeg {
}
fn build_ffmpeg_ram(builder: &mut Build) {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let ffmpeg_ram_dir = manifest_dir.join("cpp").join("ffmpeg_ram");
let ffi_header = ffmpeg_ram_dir
.join("ffmpeg_ram_ffi.h")
.to_string_lossy()
.to_string();
bindgen::builder()
.header(ffi_header)
.rustified_enum("*")
let bindings = bindgen::builder().header(ffi_header).rustified_enum(".*");
bindings
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_ram_ffi.rs"))
@@ -367,6 +404,9 @@ mod ffmpeg {
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
if enable_rkmpp {
builder.file(ffmpeg_ram_dir.join("ffmpeg_ram_decode.cpp"));
if enable_rkmpp {
builder.define("ONE_KVM_FFMPEG_RKMPP", None);
}
} else {
println!(
"cargo:info=Skipping ffmpeg_ram_decode.cpp (RKMPP) for arch {}",
@@ -375,8 +415,36 @@ 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::var_os("CARGO_MANIFEST_DIR").unwrap());
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 manifest_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
let ffmpeg_hw_dir = manifest_dir.join("cpp").join("ffmpeg_hw");
let ffi_header = ffmpeg_hw_dir
.join("ffmpeg_hw_ffi.h")
@@ -384,7 +452,7 @@ mod ffmpeg {
.to_string();
bindgen::builder()
.header(ffi_header)
.rustified_enum("*")
.rustified_enum(".*")
.generate()
.unwrap()
.write_to_file(Path::new(&env::var_os("OUT_DIR").unwrap()).join("ffmpeg_hw_ffi.rs"))
@@ -420,6 +488,7 @@ mod ffmpeg {
}
}
builder.file(ffmpeg_hw_dir.join("ffmpeg_hw_mjpeg_h26x.cpp"));
builder.file(ffmpeg_hw_dir.join("rkmpp_dmabuf.cpp"));
} else {
println!(
"cargo:info=Skipping ffmpeg_hw_mjpeg_h26x.cpp (RKMPP) for arch {}",

View File

@@ -122,12 +122,12 @@ int linux_support_v4l2m2m() {
if (!file.is_open()) {
return false;
}
std::getline(file, *out);
std::getline(file, *out, '\0');
return !out->empty();
};
auto allow_video0_probe = []() -> bool {
const char *env = std::getenv("ONE_KVM_V4L2M2M_ALLOW_VIDEO0");
auto v4l2m2m_allowed = []() -> bool {
const char *env = std::getenv("ONE_KVM_V4L2M2M_ALLOW");
if (env == nullptr) {
return false;
}
@@ -137,30 +137,152 @@ int linux_support_v4l2m2m() {
return std::strcmp(env, "0") != 0;
};
auto is_amlogic_vdec = [&]() -> bool {
std::string name;
std::string modalias;
if (read_text_file("/sys/class/video4linux/video0/name", &name)) {
const std::string lowered = to_lower(name);
if (lowered.find("meson") != std::string::npos ||
lowered.find("vdec") != std::string::npos ||
lowered.find("decoder") != std::string::npos ||
lowered.find("video-decoder") != std::string::npos) {
return true;
}
}
if (read_text_file("/sys/class/video4linux/video0/device/modalias", &modalias)) {
const std::string lowered = to_lower(modalias);
if (lowered.find("amlogic") != std::string::npos ||
lowered.find("meson") != std::string::npos ||
lowered.find("gxl-vdec") != std::string::npos ||
lowered.find("gx-vdec") != std::string::npos) {
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_qcom_platform = [&]() -> bool {
const char *platform_hints[] = {
"qcom",
"qualcomm",
"venus",
"iris",
"sc7280",
"qcm6490",
"qcs6490",
};
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",
"video3",
"video10",
"video11",
"video32",
};
const char *video_hints[] = {
"qcom-iris",
"qcom,",
"venus",
"iris",
};
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), video_hints, sizeof(video_hints) / sizeof(video_hints[0]))) {
return true;
}
if (read_text_file((base + "/device/modalias").c_str(), &modalias) &&
contains_any(to_lower(modalias), video_hints,
sizeof(video_hints) / sizeof(video_hints[0]))) {
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 qcom_platform = is_qcom_platform();
const bool amlogic_platform = !qcom_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)
@@ -179,13 +301,6 @@ int linux_support_v4l2m2m() {
for (size_t i = 0; i < sizeof(m2m_devices) / sizeof(m2m_devices[0]); i++) {
if (access(m2m_devices[i], F_OK) == 0) {
if (std::strcmp(m2m_devices[i], "/dev/video0") == 0) {
if (!allow_video0_probe() && is_amlogic_vdec()) {
LOG_TRACE(std::string("V4L2 M2M: Skipping /dev/video0 (Amlogic vdec)"));
continue;
}
}
// Device exists, check if it's an M2M device by trying to open it
int fd = open(m2m_devices[i], O_RDWR | O_NONBLOCK);
if (fd >= 0) {

View File

@@ -1,8 +1,12 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
}
#include "util.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <limits>
#include <map>
#include <string.h>
@@ -23,7 +27,7 @@ bool is_software_h264(const std::string &name) {
// Exclude all hardware encoders
static const char* hw_suffixes[] = {
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
"v4l2m2m", "videotoolbox", "mediacodec", "_mf"
"v4l2m2m", "videotoolbox", "_mf"
};
for (const auto& suffix : hw_suffixes) {
if (name.find(suffix) != std::string::npos) return false;
@@ -36,7 +40,7 @@ bool is_software_hevc(const std::string &name) {
if (name != "hevc" && name != "libx265") return false;
static const char* hw_suffixes[] = {
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
"v4l2m2m", "videotoolbox", "mediacodec", "_mf"
"v4l2m2m", "videotoolbox", "_mf"
};
for (const auto& suffix : hw_suffixes) {
if (name.find(suffix) != std::string::npos) return false;
@@ -44,17 +48,46 @@ bool is_software_hevc(const std::string &name) {
return true;
}
bool is_qcom_iris_driver() {
const char *driver_path = "/sys/class/video4linux/video1/name";
std::ifstream file(driver_path);
if (!file.is_open()) return false;
std::string value;
std::getline(file, value, '\0');
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value.find("qcom-iris") != std::string::npos ||
value.find("iris-encoder") != std::string::npos ||
value.find("iris") != std::string::npos;
}
} // anonymous namespace
namespace util_encode {
bool is_qcom_iris_platform() {
return is_qcom_iris_driver();
}
bool supports_forced_keyframe(const std::string &name) {
if (name.find("v4l2m2m") != std::string::npos && is_qcom_iris_platform()) {
return false;
}
return true;
}
void set_av_codec_ctx(AVCodecContext *c, const std::string &name, int kbs,
int gop, int fps, int thread_count) {
c->has_b_frames = 0;
c->max_b_frames = 0;
if (gop > 0 && gop < std::numeric_limits<int16_t>::max()) {
c->gop_size = gop;
c->keyint_min = gop; // Match keyint_min to gop for consistent keyframe interval
const bool qcom_iris_v4l2 =
name.find("v4l2m2m") != std::string::npos && is_qcom_iris_platform();
const int effective_gop = qcom_iris_v4l2 ? std::max(5, fps / 3) : gop;
if (effective_gop > 0 && effective_gop < std::numeric_limits<int16_t>::max()) {
c->gop_size = effective_gop;
c->keyint_min = effective_gop; // Match keyint_min to gop for consistent keyframe interval
} else if (name.find("vaapi") != std::string::npos) {
c->gop_size = fps > 0 ? fps : 30; // Default to 1 second keyframe interval
c->keyint_min = c->gop_size;
@@ -99,13 +132,12 @@ 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 hardware and software
// encoders on the same browser-friendly H264 profile.
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 +152,8 @@ 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_DEBUG(std::string("amf query_timeout option is unavailable, ret = ") +
av_err2str(ret));
}
}
if (name.find("qsv") != std::string::npos) {
@@ -140,7 +172,8 @@ bool set_lantency_free(void *priv_data, const std::string &name) {
if (name.find("rkmpp") != std::string::npos) {
// Set async_depth to 1 for minimal buffering (0 = synchronous, higher = more buffering)
if ((ret = av_opt_set(priv_data, "async_depth", "1", 0)) < 0) {
LOG_WARN(std::string("rkmpp set async_depth failed, ret = ") + av_err2str(ret));
LOG_DEBUG(std::string("rkmpp async_depth option is unavailable, ret = ") +
av_err2str(ret));
// Not fatal - older FFmpeg versions may not support this option
}
}
@@ -148,11 +181,14 @@ bool set_lantency_free(void *priv_data, const std::string &name) {
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", 4, 0)) < 0) {
LOG_WARN(std::string("v4l2m2m set num_output_buffers failed, ret = ") + av_err2str(ret));
LOG_DEBUG(std::string("v4l2m2m num_output_buffers option is unavailable, ret = ") +
av_err2str(ret));
// Not fatal
}
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));
const int capture_buffers = is_qcom_iris_driver() ? 12 : 8;
if ((ret = av_opt_set_int(priv_data, "num_capture_buffers", capture_buffers, 0)) < 0) {
LOG_DEBUG(std::string("v4l2m2m num_capture_buffers option is unavailable, ret = ") +
av_err2str(ret));
// Not fatal
}
}
@@ -306,23 +342,6 @@ 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;
}
}
}
// libx264 software encoder presets
if (is_software_h264(name)) {
const char* preset = nullptr;
@@ -378,6 +397,33 @@ struct CodecOptions {
bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
int q) {
// Remote-desktop content is usually sparse. VBR avoids padding static
// frames up to the target bitrate while allowing short bursts for screen
// changes. Keep those bursts bounded at twice the target bitrate.
if (rc == RC_VBR && c->bit_rate > 0) {
c->rc_max_rate = c->bit_rate * 2;
c->rc_buffer_size = c->rc_max_rate;
}
if (name.find("vaapi") != std::string::npos && rc == RC_CQ) {
// Used only after the normal bitrate-based VAAPI initialization fails.
// Some drivers, including Intel iHD on Jasper Lake, expose CQP as their
// only compatible rate-control mode.
c->bit_rate = 0;
c->rc_min_rate = 0;
c->rc_max_rate = 0;
c->rc_buffer_size = 0;
c->rc_initial_buffer_occupancy = 0;
const int qp = q > 0 ? q : 23;
const int ret = av_opt_set_int(c->priv_data, "qp", qp, 0);
if (ret < 0) {
LOG_ERROR(std::string("vaapi set qp failed, ret = ") +
av_err2str(ret));
return false;
}
return true;
}
if (name.find("qsv") != std::string::npos) {
// https://github.com/LizardByte/Sunshine/blob/3e47cd3cc8fd37a7a88be82444ff4f3c0022856b/src/video.cpp#L1635
c->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
@@ -385,9 +431,6 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
std::vector<CodecOptions> codecs = {
{"nvenc", "rc", {{RC_CBR, "cbr"}, {RC_VBR, "vbr"}}},
{"amf", "rc", {{RC_CBR, "cbr"}, {RC_VBR, "vbr_latency"}}},
{"mediacodec",
"bitrate_mode",
{{RC_CBR, "cbr"}, {RC_VBR, "vbr"}, {RC_CQ, "cq"}}},
// {"videotoolbox", "constant_bit_rate", {{RC_CBR, "1"}}},
};
@@ -402,13 +445,6 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
it->second + " failed, ret = " + av_err2str(ret));
return false;
}
if (name.find("mediacodec") != std::string::npos) {
if (rc == RC_CQ) {
if (q >= 0 && q <= 51) {
c->global_quality = q;
}
}
}
}
break;
}
@@ -467,6 +503,10 @@ bool set_others(void *priv_data, const std::string &name) {
bool change_bit_rate(AVCodecContext *c, const std::string &name, int kbs) {
if (kbs > 0) {
c->bit_rate = kbs * 1000;
if (c->rc_max_rate > 0 && name.find("qsv") == std::string::npos) {
c->rc_max_rate = c->bit_rate * 2;
c->rc_buffer_size = c->rc_max_rate;
}
if (name.find("qsv") != std::string::npos) {
c->rc_max_rate = c->bit_rate;
}

View File

@@ -9,6 +9,9 @@ extern "C" {
namespace util_encode {
bool is_qcom_iris_platform();
bool supports_forced_keyframe(const std::string &name);
void set_av_codec_ctx(AVCodecContext *c, const std::string &name, int kbs,
int gop, int fps, int thread_count);
bool set_lantency_free(void *priv_data, const std::string &name);

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,38 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
// Validate bounded JPEG headers before giving hardware a fixed-size output
// buffer. Only baseline 8-bit JPEG is accepted; other streams use copy fallback.
// No scan-data traversal or full-packet copy is needed.
inline bool rkmpp_dma_jpeg_header(const uint8_t *data, size_t size, int width, int height) {
if (!data || size < 4 || data[0] != 0xff || data[1] != 0xd8) return false;
size_t pos = 2;
bool sof = false;
while (pos < size) {
if (data[pos++] != 0xff) return false;
while (pos < size && data[pos] == 0xff) ++pos;
if (pos == size) return false;
const unsigned marker = data[pos++];
if (!marker || marker == 0xd8 || marker == 0xd9 || marker == 1 ||
(marker >= 0xd0 && marker <= 0xd7)) return false;
if (size - pos < 2) return false;
const size_t length = (size_t(data[pos]) << 8) | data[pos + 1];
if (length < 2 || length > size - pos) return false;
if (marker == 0xc0) {
if (sof || length < 8 || data[pos + 2] != 8) return false;
const unsigned h = (unsigned(data[pos + 3]) << 8) | data[pos + 4];
const unsigned w = (unsigned(data[pos + 5]) << 8) | data[pos + 6];
const unsigned components = data[pos + 7];
if (w != unsigned(width) || h != unsigned(height) ||
(components != 1 && components != 3) || length != 8 + 3 * components) return false;
sof = true;
} else if (marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 && marker != 0xcc) {
return false; // Progressive, lossless, extended or differential SOF.
} else if (marker == 0xda) {
return sof && length >= 6 && size - pos > length;
}
pos += length;
}
return false;
}

View File

@@ -0,0 +1,329 @@
#include "rkmpp_dmabuf_ffi.h"
#include <array>
#include <cstdio>
#include <limits>
#include <new>
#include "rkmpp_dma_jpeg.h"
// Native MPP is already linked by the ARM FFmpeg/RKMPP build. Keep this
// optional for toolchains which only supply the FFmpeg headers.
#if defined(__linux__) && __has_include(<rockchip/rk_mpi.h>)
#define HAVE_MPP_DMA 1
#include <cerrno>
#include <linux/dma-buf.h>
#include <sys/ioctl.h>
extern "C" {
#include <rockchip/rk_mpi.h>
#include <rockchip/mpp_buffer.h>
#include <rockchip/mpp_frame.h>
#include <rockchip/mpp_packet.h>
#include <rockchip/mpp_task.h>
#include <rockchip/rk_venc_cfg.h>
#include <rockchip/rk_venc_rc.h>
}
#endif
static thread_local char dma_error[192] = {};
static int fail(const char *operation, int code) {
std::snprintf(dma_error, sizeof(dma_error), "%s (ret=%d)", operation, code);
return -1;
}
#ifdef HAVE_MPP_DMA
struct RkmppDmaEncoder {
MppCtx ctx = nullptr;
MppApi *api = nullptr;
MppEncCfg cfg = nullptr;
MppPacket packet = nullptr;
std::array<MppBuffer, 16> buffers{};
std::array<size_t, 16> capacities{};
size_t count = 0;
size_t minimum = 0;
int width = 0, height = 0, stride = 0;
MppFrameFormat format = MPP_FMT_YUV420SP;
bool jpeg = false;
MppCtx decoder = nullptr;
MppApi *dec_api = nullptr;
MppBufferGroup decoded_group = nullptr;
MppBuffer decoded_buffer = nullptr;
MppFrame decoded_frame = nullptr;
MppPacket input_packet = nullptr;
bool decoded_layout_set = false;
int decoded_stride = 0, decoded_vstride = 0;
void close() {
if (packet) mpp_packet_deinit(&packet);
if (ctx) {
// A timeout must not expose still-in-use input to V4L2 QBUF.
api->reset(ctx);
mpp_destroy(ctx);
ctx = nullptr;
}
// On any decoder failure, end hardware access before releasing the
// input packet, exported buffers, or allowing the caller's QBUF.
if (decoder) {
dec_api->reset(decoder);
mpp_destroy(decoder);
decoder = nullptr;
}
if (input_packet) mpp_packet_deinit(&input_packet);
if (decoded_frame) mpp_frame_deinit(&decoded_frame);
if (decoded_buffer) { mpp_buffer_put(decoded_buffer); decoded_buffer = nullptr; }
if (decoded_group) { mpp_buffer_group_put(decoded_group); decoded_group = nullptr; }
for (auto &buffer : buffers) {
if (buffer) { mpp_buffer_put(buffer); buffer = nullptr; }
}
if (cfg) { mpp_enc_cfg_deinit(cfg); cfg = nullptr; }
}
~RkmppDmaEncoder() { close(); }
};
static bool set_cfg(RkmppDmaEncoder *e, const char *key, int value) {
int ret = mpp_enc_cfg_set_s32(e->cfg, key, value);
if (ret) fail(key, ret);
return ret == 0;
}
extern "C" int rkmpp_dma_reconfigure(RkmppDmaEncoder *e, int kbps, int gop) {
if (!e || !e->ctx || kbps <= 0 || kbps > 1000000 || gop <= 0)
return fail("invalid DMA encoder configuration", -1);
const int bps = kbps * 1000;
if (!set_cfg(e, "rc:bps_target", bps) ||
!set_cfg(e, "rc:bps_max", bps + bps / 16) ||
!set_cfg(e, "rc:bps_min", bps - bps / 16) ||
!set_cfg(e, "rc:gop", gop)) return -1;
int ret = e->api->control(e->ctx, MPP_ENC_SET_CFG, e->cfg);
return ret ? fail("MPP_ENC_SET_CFG", ret) : 0;
}
extern "C" RkmppDmaEncoder *rkmpp_dma_new(
int width, int height, int stride, int format, int codec, int fps,
int kbps, int gop, const int *fds, const size_t *sizes, size_t count) {
if (width <= 0 || height <= 0 || width > 8192 || height > 8192 ||
(width & 1) || (height & 1) || format < 0 || format > 4 ||
codec < 0 || codec > 1 || fps <= 0 || fps > 240 ||
(format != 4 && stride < width * (format == 1 || format == 3 ? 3 : format == 2 ? 2 : 1)) ||
(format == 2 && stride % 16 != 0) || !fds || !sizes || !count || count > 16) {
fail("invalid DMA frame layout", -1); return nullptr;
}
auto *e = new (std::nothrow) RkmppDmaEncoder;
if (!e) { fail("allocate DMA encoder", -1); return nullptr; }
e->width = width; e->height = height; e->stride = stride; e->count = count;
e->jpeg = format == 4;
if (e->jpeg) e->stride = stride = (width + 15) & ~15;
const int vstride = e->jpeg ? (height + 15) & ~15 : height;
e->format = format == 3 ? MPP_FMT_RGB888 : format == 2 ? MPP_FMT_YUV422_YUYV : format == 1 ? MPP_FMT_BGR888 : MPP_FMT_YUV420SP;
auto abort_init = [e](const char *op, int ret) -> RkmppDmaEncoder * {
fail(op, ret); delete e; return nullptr;
};
int ret = mpp_create(&e->ctx, &e->api);
if (ret) return abort_init("mpp_create", ret);
RK_S64 timeout = 2000;
ret = e->api->control(e->ctx, MPP_SET_OUTPUT_TIMEOUT, &timeout);
if (ret) return abort_init("MPP_SET_OUTPUT_TIMEOUT", ret);
ret = e->api->control(e->ctx, MPP_SET_INPUT_TIMEOUT, &timeout);
if (ret) return abort_init("MPP_SET_INPUT_TIMEOUT", ret);
ret = mpp_init(e->ctx, MPP_CTX_ENC, codec ? MPP_VIDEO_CodingHEVC : MPP_VIDEO_CodingAVC);
if (ret) return abort_init("mpp_init", ret);
ret = mpp_enc_cfg_init(&e->cfg);
if (ret) return abort_init("mpp_enc_cfg_init", ret);
ret = e->api->control(e->ctx, MPP_ENC_GET_CFG, e->cfg);
if (ret) return abort_init("MPP_ENC_GET_CFG", ret);
if (!set_cfg(e, "prep:width", width) || !set_cfg(e, "prep:height", height) ||
!set_cfg(e, "prep:hor_stride", stride) || !set_cfg(e, "prep:ver_stride", vstride) ||
!set_cfg(e, "prep:format", e->format) || !set_cfg(e, "rc:mode", MPP_ENC_RC_MODE_CBR) ||
!set_cfg(e, "rc:fps_in_flex", 0) || !set_cfg(e, "rc:fps_in_num", fps) ||
!set_cfg(e, "rc:fps_in_denorm", 1) || !set_cfg(e, "rc:fps_out_flex", 0) ||
!set_cfg(e, "rc:fps_out_num", fps) || !set_cfg(e, "rc:fps_out_denorm", 1) ||
!set_cfg(e, "codec:type", codec ? MPP_VIDEO_CodingHEVC : MPP_VIDEO_CodingAVC)) {
delete e; return nullptr;
}
// Match the browser-friendly baseline profile used by the existing RKMPP
// byte encoder, rather than inheriting MPP's High-profile default.
const int level = int64_t(width) * height * fps <= int64_t(1920) * 1080 * 60 ? 42 : 52;
if (!codec && (!set_cfg(e, "h264:profile", 66) || !set_cfg(e, "h264:level", level) ||
!set_cfg(e, "h264:cabac_en", 0) || !set_cfg(e, "h264:trans8x8", 0))) {
delete e; return nullptr;
}
if (rkmpp_dma_reconfigure(e, kbps, gop)) { delete e; return nullptr; }
MppEncHeaderMode mode = MPP_ENC_HEADER_MODE_EACH_IDR;
ret = e->api->control(e->ctx, MPP_ENC_SET_HEADER_MODE, &mode);
if (ret) return abort_init("MPP_ENC_SET_HEADER_MODE", ret);
// Reject arithmetic overflow even on 32-bit ARM; stride is supplied by a driver.
if (size_t(stride) > std::numeric_limits<size_t>::max() / size_t(height))
return abort_init("DMA buffer size overflow", -1);
size_t minimum = size_t(stride) * height;
if (format == 0) {
if (minimum > std::numeric_limits<size_t>::max() / 3)
return abort_init("DMA buffer size overflow", -1);
minimum = minimum * 3 / 2;
}
if (e->jpeg) minimum = 68; // SOI/payload plus bounded hardware read headroom.
e->minimum = minimum;
for (size_t i = 0; i < count; ++i) {
if (fds[i] < 0 || sizes[i] < minimum) return abort_init("short DMA buffer", -1);
MppBufferInfo info{};
info.type = MPP_BUFFER_TYPE_EXT_DMA; info.fd = fds[i];
info.size = sizes[i]; info.index = static_cast<int>(i);
ret = mpp_buffer_import(&e->buffers[i], &info);
if (ret) return abort_init("mpp_buffer_import", ret);
e->capacities[i] = sizes[i];
}
if (e->jpeg) {
ret = mpp_create(&e->decoder, &e->dec_api);
if (ret) return abort_init("mpp_create JPEG decoder", ret);
ret = mpp_init(e->decoder, MPP_CTX_DEC, MPP_VIDEO_CodingMJPEG);
if (ret) return abort_init("mpp_init JPEG decoder", ret);
MppFrameFormat output = MPP_FMT_YUV420SP;
ret = e->dec_api->control(e->decoder, MPP_DEC_SET_OUTPUT_FORMAT, &output);
if (ret) return abort_init("JPEG NV12 output", ret);
ret = mpp_buffer_group_get_internal(&e->decoded_group, MPP_BUFFER_TYPE_DRM);
if (ret) return abort_init("JPEG output buffer group", ret);
// MPP JPEG requires aligned storage; reserve the conservative size used
// by its advanced-task decoder demo. One output reused after encode.
ret = mpp_buffer_get(e->decoded_group, &e->decoded_buffer, size_t(stride) * vstride * 4);
if (ret) return abort_init("JPEG output buffer", ret);
ret = mpp_frame_init(&e->decoded_frame);
if (ret) return abort_init("JPEG output frame", ret);
mpp_frame_set_buffer(e->decoded_frame, e->decoded_buffer);
}
return e;
}
static int dma_read_sync(MppBuffer buffer, bool start) {
dma_buf_sync sync{};
sync.flags = DMA_BUF_SYNC_READ | (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END);
int ret;
do { ret = ioctl(mpp_buffer_get_fd(buffer), DMA_BUF_IOCTL_SYNC, &sync); }
while (ret < 0 && errno == EINTR);
return ret;
}
static int decode_jpeg(RkmppDmaEncoder *e, size_t index, size_t bytes_used) {
MppBuffer input = e->buffers[index];
// The parser reads only header bytes with explicit DMA CPU-read ownership.
if (dma_read_sync(input, true)) return fail("JPEG DMA read sync start", errno);
const auto *data = static_cast<const uint8_t *>(mpp_buffer_get_ptr(input));
const bool valid = rkmpp_dma_jpeg_header(data, bytes_used, e->width, e->height);
if (dma_read_sync(input, false)) return fail("JPEG DMA read sync end", errno);
if (!valid) return fail("unsupported/mismatched JPEG header", -1);
int ret = mpp_packet_init_with_buffer(&e->input_packet, input);
if (ret) return fail("JPEG input packet", ret);
mpp_packet_set_length(e->input_packet, bytes_used);
MppTask task = nullptr;
ret = e->dec_api->poll(e->decoder, MPP_PORT_INPUT, static_cast<MppPollType>(2000));
if (ret) return fail("JPEG input poll", ret);
ret = e->dec_api->dequeue(e->decoder, MPP_PORT_INPUT, &task);
if (ret || !task) return fail("JPEG input task", ret);
ret = mpp_task_meta_set_packet(task, KEY_INPUT_PACKET, e->input_packet);
if (ret) return fail("JPEG input metadata", ret);
ret = mpp_task_meta_set_frame(task, KEY_OUTPUT_FRAME, e->decoded_frame);
if (ret) return fail("JPEG output metadata", ret);
ret = e->dec_api->enqueue(e->decoder, MPP_PORT_INPUT, task);
if (ret) return fail("JPEG submit", ret);
task = nullptr;
ret = e->dec_api->poll(e->decoder, MPP_PORT_OUTPUT, static_cast<MppPollType>(2000));
if (ret) return fail("JPEG output poll", ret);
ret = e->dec_api->dequeue(e->decoder, MPP_PORT_OUTPUT, &task);
if (ret || !task) return fail("JPEG output task", ret);
MppFrame result = nullptr;
ret = mpp_task_meta_get_frame(task, KEY_OUTPUT_FRAME, &result);
if (ret || result != e->decoded_frame) return fail("JPEG output frame mismatch", ret);
ret = e->dec_api->enqueue(e->decoder, MPP_PORT_OUTPUT, task);
if (ret) return fail("JPEG return output task", ret);
ret = e->dec_api->poll(e->decoder, MPP_PORT_INPUT, static_cast<MppPollType>(2000));
if (ret) return fail("JPEG input completion", ret);
mpp_packet_deinit(&e->input_packet);
if (mpp_frame_get_errinfo(result) || mpp_frame_get_discard(result) ||
mpp_frame_get_info_change(result) ||
mpp_frame_get_width(result) != unsigned(e->width) ||
mpp_frame_get_height(result) != unsigned(e->height) ||
mpp_frame_get_fmt(result) != MPP_FMT_YUV420SP ||
mpp_frame_get_buffer(result) != e->decoded_buffer) {
std::snprintf(dma_error, sizeof(dma_error),
"invalid JPEG decoded frame: err=%u discard=%u info_change=%u size=%ux%u fmt=%x buffer_match=%d",
mpp_frame_get_errinfo(result), mpp_frame_get_discard(result), mpp_frame_get_info_change(result),
mpp_frame_get_width(result), mpp_frame_get_height(result), unsigned(mpp_frame_get_fmt(result)),
int(mpp_frame_get_buffer(result) == e->decoded_buffer));
return -1;
}
const int hs = mpp_frame_get_hor_stride(result), vs = mpp_frame_get_ver_stride(result);
if (hs < e->width || vs < e->height || hs > 8192 || vs > 8192 || (hs & 15) || (vs & 15) ||
size_t(hs) * vs * 3 / 2 > mpp_buffer_get_size(e->decoded_buffer))
return fail("invalid JPEG decoded stride", -1);
if (!e->decoded_layout_set) {
if (!set_cfg(e, "prep:hor_stride", hs) || !set_cfg(e, "prep:ver_stride", vs)) return -1;
ret = e->api->control(e->ctx, MPP_ENC_SET_CFG, e->cfg);
if (ret) return fail("JPEG encoder layout", ret);
e->decoded_stride = hs; e->decoded_vstride = vs; e->decoded_layout_set = true;
} else if (hs != e->decoded_stride || vs != e->decoded_vstride) {
return fail("JPEG decoded layout changed", -1);
}
return 0;
}
extern "C" int rkmpp_dma_encode(RkmppDmaEncoder *e, size_t index, size_t bytes_used, int fresh_fd, int64_t pts_us,
int force_idr, const uint8_t **data, size_t *size) {
if (!e || !e->ctx || index >= e->count || !data || !size)
return fail("invalid DMA encode call", -1);
*data = nullptr; *size = 0;
if (e->packet) mpp_packet_deinit(&e->packet);
auto abort_encode = [e](const char *op, int ret) {
fail(op, ret); e->close(); return -1;
};
if (bytes_used > e->capacities[index] ||
(e->jpeg ? (bytes_used < 4 || e->capacities[index] - bytes_used < 64) : bytes_used != e->minimum))
return abort_encode("invalid DMA payload length", -1);
if (fresh_fd >= 0) {
MppBuffer replacement = nullptr;
MppBufferInfo info{};
info.type = MPP_BUFFER_TYPE_EXT_DMA; info.fd = fresh_fd;
info.size = e->capacities[index]; info.index = static_cast<int>(index);
const int ret = mpp_buffer_import(&replacement, &info);
if (ret) return abort_encode("refresh USB DMA import", ret);
if (e->buffers[index]) mpp_buffer_put(e->buffers[index]);
e->buffers[index] = replacement;
}
if (e->jpeg && decode_jpeg(e, index, bytes_used)) {
// Preserve the detailed decoder failure while ending BOTH engines.
e->close(); return -1;
}
if (force_idr) {
int ret = e->api->control(e->ctx, MPP_ENC_SET_IDR_FRAME, nullptr);
if (ret) return abort_encode("MPP_ENC_SET_IDR_FRAME", ret);
}
MppFrame frame = e->jpeg ? e->decoded_frame : nullptr;
int ret = 0;
if (!e->jpeg) {
ret = mpp_frame_init(&frame);
if (ret) return abort_encode("mpp_frame_init", ret);
mpp_frame_set_width(frame, e->width); mpp_frame_set_height(frame, e->height);
mpp_frame_set_hor_stride(frame, e->stride); mpp_frame_set_ver_stride(frame, e->height);
mpp_frame_set_fmt(frame, e->format);
mpp_frame_set_buffer(frame, e->buffers[index]);
}
mpp_frame_set_pts(frame, pts_us);
ret = e->api->encode_put_frame(e->ctx, frame);
if (!e->jpeg) mpp_frame_deinit(&frame);
if (ret) return abort_encode("encode_put_frame", ret);
ret = e->api->encode_get_packet(e->ctx, &e->packet);
if (ret || !e->packet) return abort_encode("encode_get_packet", ret);
if (mpp_packet_is_partition(e->packet) || !mpp_packet_get_length(e->packet))
return abort_encode("incomplete DMA encoder output", -1);
// One synchronous input, no temporal scalability/reordering/split output.
// A completed packet is the input-consumption barrier for this mode.
*data = static_cast<const uint8_t *>(mpp_packet_get_pos(e->packet));
*size = mpp_packet_get_length(e->packet);
return 0;
}
extern "C" void rkmpp_dma_free(RkmppDmaEncoder *e) { delete e; }
#else
extern "C" RkmppDmaEncoder *rkmpp_dma_new(int,int,int,int,int,int,int,int,const int*,const size_t*,size_t) {
fail("RKMPP DMA support not built", -1); return nullptr;
}
extern "C" int rkmpp_dma_encode(RkmppDmaEncoder*,size_t,size_t,int,int64_t,int,const uint8_t**,size_t*) { return -1; }
extern "C" int rkmpp_dma_reconfigure(RkmppDmaEncoder*,int,int) { return -1; }
extern "C" void rkmpp_dma_free(RkmppDmaEncoder*) {}
#endif
extern "C" const char *rkmpp_dma_error(void) { return dma_error; }

View File

@@ -0,0 +1,31 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct RkmppDmaEncoder RkmppDmaEncoder;
// format: 0=NV12, 1=BGR24, 2=YUYV, 3=RGB24 (byte stride), 4=MJPEG (stride ignored).
// codec: 0=H264, 1=HEVC. MJPEG is decoded to hardware NV12, then encoded.
RkmppDmaEncoder *rkmpp_dma_new(int width, int height, int stride, int format,
int codec, int fps, int kbps, int gop,
const int *fds, const size_t *sizes, size_t count);
// Synchronous input-completion boundary. On failure the encoder is destroyed
// internally BEFORE returning, so it cannot keep reading the capture buffer.
// Output is borrowed until the next call or destruction; copy before reusing it.
// bytes_used must be the actual captured payload. MJPEG needs 64 bytes of
// readable allocation headroom; never pass sizeimage as the compressed length.
// fresh_fd=-1 reuses the original import (native HDMI). UVC supplies a new
// export of this dequeued slot. Keep it open until replacement/free; the old
// export can be closed AFTER this call, including on failure.
int rkmpp_dma_encode(RkmppDmaEncoder *encoder, size_t index, size_t bytes_used, int fresh_fd, int64_t pts_us,
int force_idr, const uint8_t **data, size_t *size);
int rkmpp_dma_reconfigure(RkmppDmaEncoder *encoder, int kbps, int gop);
void rkmpp_dma_free(RkmppDmaEncoder *encoder);
const char *rkmpp_dma_error(void);
#ifdef __cplusplus
}
#endif

View File

@@ -1,4 +1,4 @@
// Minimal FFmpeg RAM MJPEG decoder (RKMPP only) -> NV12 in CPU memory.
// FFmpeg RAM decoder with optional RKMPP hardware-frame support.
extern "C" {
#include <libavcodec/avcodec.h>
@@ -54,9 +54,11 @@ public:
thread_count_ = thread_count > 0 ? thread_count : 1;
callback_ = callback;
#ifdef ONE_KVM_FFMPEG_RKMPP
if (name_.find("rkmpp") != std::string::npos) {
hw_device_type_ = AV_HWDEVICE_TYPE_RKMPP;
}
#endif
}
~FFmpegRamDecoder() {}

View File

@@ -11,6 +11,7 @@ extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "common.h"
@@ -21,6 +22,12 @@ extern "C" {
#include "win.h"
#endif
static thread_local std::string g_encoder_last_error;
static void set_encoder_last_error(const std::string &message) {
g_encoder_last_error = message;
}
static int calculate_offset_length(int pix_fmt, int height, const int *linesize,
int *offset, int *length) {
switch (pix_fmt) {
@@ -112,6 +119,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:
@@ -119,7 +129,6 @@ public:
AVFrame *frame_ = NULL;
AVPacket *pkt_ = NULL;
std::string name_;
std::string mc_name_; // for mediacodec
int width_ = 0;
int height_ = 0;
@@ -134,6 +143,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
@@ -142,12 +152,11 @@ public:
AVBufferRef *hw_device_ctx_ = NULL;
AVFrame *hw_frame_ = NULL;
FFmpegRamEncoder(const char *name, const char *mc_name, int width, int height,
FFmpegRamEncoder(const char *name, int width, int height,
int pixfmt, int align, int fps, int gop, int rc, int quality,
int kbs, int q, int thread_count, int gpu,
RamEncodeCallback callback) {
name_ = name;
mc_name_ = mc_name ? mc_name : "";
width_ = width;
height_ = height;
pixfmt_ = (AVPixelFormat)pixfmt;
@@ -179,12 +188,13 @@ public:
}
bool init(int *linesize, int *offset, int *length) {
g_encoder_last_error.clear();
const AVCodec *codec = NULL;
int ret;
if (!(codec = avcodec_find_encoder_by_name(name_.c_str()))) {
LOG_ERROR(std::string("Codec ") + name_ + " not found");
set_encoder_last_error(std::string("Codec ") + name_ + " not found");
return false;
}
@@ -247,7 +257,6 @@ public:
LOG_ERROR(std::string("Could not allocate video packet"));
return false;
}
/* resolution must be a multiple of two */
c_->width = width_;
c_->height = height_;
@@ -263,23 +272,16 @@ public:
LOG_ERROR(std::string("set_quality failed, name: ") + name_);
return false;
}
util_encode::set_rate_control(c_, name_, rc_, q_);
if (!util_encode::set_rate_control(c_, name_, rc_, q_)) {
LOG_ERROR(std::string("set_rate_control failed, name: ") + name_);
return false;
}
util_encode::set_gpu(c_->priv_data, name_, gpu_);
util_encode::force_hw(c_->priv_data, name_);
util_encode::set_others(c_->priv_data, name_);
if (name_.find("mediacodec") != std::string::npos) {
if (mc_name_.length() > 0) {
LOG_INFO(std::string("mediacodec codec_name: ") + mc_name_);
if ((ret = av_opt_set(c_->priv_data, "codec_name", mc_name_.c_str(),
0)) < 0) {
LOG_ERROR(std::string("mediacodec codec_name failed, ret = ") + av_err2str(ret));
}
}
}
if ((ret = avcodec_open2(c_, codec, NULL)) < 0) {
LOG_ERROR(std::string("avcodec_open2 failed, ret = ") + av_err2str(ret) +
", name: " + name_);
set_encoder_last_error(std::string("avcodec_open2 failed, ret = ") +
av_err2str(ret) + ", name: " + name_);
return false;
}
@@ -301,7 +303,7 @@ public:
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) {
@@ -317,6 +319,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_);
@@ -369,108 +379,210 @@ private:
frame->pts = ms;
// Force keyframe if requested
if (force_keyframe_) {
if (force_keyframe_ && util_encode::supports_forced_keyframe(name_)) {
frame->pict_type = AV_PICTURE_TYPE_I;
force_keyframe_ = false;
} else {
frame->pict_type = AV_PICTURE_TYPE_NONE;
}
force_keyframe_ = false;
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)) {
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:
case AV_PIX_FMT_NV24:
if (data_length <
frame->height * (frame->linesize[0] + frame->linesize[1])) {
LOG_ERROR(std::string("fill_frame: NV16/NV24 data length error. 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) +
", 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) != 0) {
LOG_ERROR("fill_frame: NV16 copy failed");
return -1;
}
frame->data[0] = data;
frame->data[1] = data + offset[0];
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 * frame->linesize[0]) {
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) +
", 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: RGB24/BGR24 copy failed");
return -1;
}
break;
default:
LOG_ERROR(std::string("fill_frame: unsupported format, ") +
@@ -479,23 +591,64 @@ private:
}
return 0;
}
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
extern "C" FFmpegRamEncoder *
ffmpeg_ram_new_encoder(const char *name, const char *mc_name, int width,
ffmpeg_ram_new_encoder(const char *name, int width,
int height, int pixfmt, int align, int fps, int gop,
int rc, int quality, int kbs, int q, int thread_count,
int gpu, int *linesize, int *offset, int *length,
RamEncodeCallback callback) {
FFmpegRamEncoder *encoder = NULL;
try {
encoder = new FFmpegRamEncoder(name, mc_name, width, height, pixfmt, align,
fps, gop, rc, quality, kbs, q, thread_count,
gpu, callback);
auto try_create = [&](int attempt_rc, int attempt_kbs) {
FFmpegRamEncoder *candidate = new FFmpegRamEncoder(
name, width, height, pixfmt, align, fps, gop, attempt_rc, quality,
attempt_kbs, q, thread_count, gpu, callback);
if (candidate && candidate->init(linesize, offset, length)) {
return candidate;
}
if (candidate) {
candidate->free_encoder();
delete candidate;
}
return static_cast<FFmpegRamEncoder *>(NULL);
};
// Preserve the existing VAAPI path first. With a target bitrate and no
// explicit QP, FFmpeg negotiates a supported bitrate-based mode such as
// AVBR, VBR or CBR with the driver.
encoder = try_create(rc, kbs);
if (encoder) {
if (encoder->init(linesize, offset, length)) {
return encoder;
}
// Retry only VAAPI with a fresh context in explicit-QP mode. This avoids
// changing rate control on hardware which already supports CBR/VBR while
// allowing CQP-only drivers to pass probing and normal encoder creation.
if (name && std::string(name).find("vaapi") != std::string::npos &&
rc != RC_CQ) {
LOG_DEBUG(std::string("VAAPI bitrate-based rate control failed for ") +
name + ", retrying with CQP");
encoder = try_create(RC_CQ, 0);
if (encoder) {
return encoder;
}
}
@@ -532,6 +685,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);
@@ -550,3 +722,7 @@ extern "C" void ffmpeg_ram_request_keyframe(FFmpegRamEncoder *encoder) {
LOG_ERROR(std::string("ffmpeg_ram_request_keyframe failed, ") + std::string(e.what()));
}
}
extern "C" const char *ffmpeg_ram_encoder_last_error(void) {
return g_encoder_last_error.c_str();
}

View File

@@ -7,10 +7,13 @@
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);
void *ffmpeg_ram_new_encoder(const char *name, const char *mc_name, int width,
void *ffmpeg_ram_new_encoder(const char *name, int width,
int height, int pixfmt, int align, int fps,
int gop, int rc, int quality, int kbs, int q,
int thread_count, int gpu, int *linesize,
@@ -18,12 +21,17 @@ 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);
int ffmpeg_ram_set_bitrate(void *encoder, int kbs);
void ffmpeg_ram_request_keyframe(void *encoder);
const char *ffmpeg_ram_encoder_last_error(void);
void *ffmpeg_ram_new_decoder(const char *name, int width, int height,
int sw_pixfmt, int thread_count,

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

@@ -32,14 +32,14 @@ pub extern "C" fn hwcodec_av_log_callback(level: i32, message: *const std::os::r
if let Ok(str_slice) = c_str.to_str() {
let string = String::from(str_slice);
if level == AV_LOG_ERROR as i32 {
log::error!("{}", string);
if string.contains(could_not_find_ref_with_poc) {
hwcodec_set_flag_could_not_find_ref_with_poc();
}
log::debug!("{}", string);
} else if level == AV_LOG_PANIC as i32 || level == AV_LOG_FATAL as i32 {
log::error!("{}", string);
} else if level == AV_LOG_WARNING as i32 {
log::warn!("{}", string);
log::debug!("{}", string);
} else if level == AV_LOG_INFO as i32 {
log::info!("{}", string);
} else if level == AV_LOG_VERBOSE as i32 || level == AV_LOG_DEBUG as i32 {

View File

@@ -114,7 +114,7 @@ impl Drop for Decoder {
}
}
fn last_error_message() -> String {
pub fn last_error_message() -> String {
unsafe {
let ptr = ffmpeg_ram_last_error();
if ptr.is_null() {

View File

@@ -1,12 +1,16 @@
#[cfg(feature = "bytes")]
use crate::ffmpeg_ram::{ffmpeg_ram_encode_packet, ffmpeg_ram_free_packet};
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_encoder_last_error,
ffmpeg_ram_free_encoder, 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},
@@ -97,6 +101,7 @@ fn enumerate_candidate_codecs(ctx: &EncodeContext) -> Vec<CodecInfo> {
use log::debug;
let mut codecs = Vec::new();
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.
@@ -257,7 +262,13 @@ struct ProbePolicy {
impl ProbePolicy {
fn for_codec(codec_name: &str) -> Self {
if codec_name.contains("v4l2m2m") {
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,
@@ -298,13 +309,14 @@ fn log_failed_probe_attempt(
frames: &[EncodeFrame],
elapsed_ms: u128,
) {
use log::debug;
use log::{debug, trace};
if policy.accept_any_output {
if frames.is_empty() {
debug!(
trace!(
"Encoder {} test produced no output on attempt {}",
codec_name, attempt
codec_name,
attempt
);
} else {
debug!(
@@ -337,7 +349,6 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
let test_ctx = EncodeContext {
name: codec.name.clone(),
mc_name: codec.mc_name.clone(),
..ctx.clone()
};
@@ -401,10 +412,7 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
);
false
}
Err(_) => {
debug!("Failed to create encoder {}", codec.name);
false
}
Err(_) => false,
}
}
@@ -425,7 +433,6 @@ fn add_software_fallback(codecs: &mut Vec<CodecInfo>) {
#[derive(Debug, Clone, PartialEq)]
pub struct EncodeContext {
pub name: String,
pub mc_name: Option<String>,
pub width: i32,
pub height: i32,
pub pixfmt: i32,
@@ -445,6 +452,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)
@@ -477,10 +517,8 @@ impl Encoder {
.unwrap_or("-1".to_owned())
.parse()
.unwrap_or(-1);
let mc_name = ctx.mc_name.clone().unwrap_or_default();
let codec = ffmpeg_ram_new_encoder(
CString::new(ctx.name.as_str()).map_err(|_| ())?.as_ptr(),
CString::new(mc_name.as_str()).map_err(|_| ())?.as_ptr(),
ctx.width,
ctx.height,
ctx.pixfmt,
@@ -500,6 +538,10 @@ impl Encoder {
);
if codec.is_null() {
let message = encoder_last_error_message();
if !message.is_empty() {
log::debug!("ffmpeg_ram_new_encoder failed: {}", message);
}
return Err(());
}
@@ -537,6 +579,35 @@ 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 {
if self.ctx.name.contains("v4l2m2m") {
return Ok(frames
.into_iter()
.map(|frame| EncodeBytesFrame {
data: Bytes::copy_from_slice(frame.data.as_ref()),
pts: frame.pts,
key: frame.key,
})
.collect());
}
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>);
@@ -548,6 +619,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 {
@@ -620,6 +715,16 @@ impl Encoder {
}
}
pub fn encoder_last_error_message() -> String {
unsafe {
let ptr = ffmpeg_ram_encoder_last_error();
if ptr.is_null() {
return String::new();
}
std::ffi::CStr::from_ptr(ptr).to_string_lossy().to_string()
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe {

View File

@@ -63,8 +63,6 @@ pub enum Priority {
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct CodecInfo {
pub name: String,
#[serde(skip)]
pub mc_name: Option<String>,
pub format: DataFormat,
pub priority: i32,
pub hwdevice: AVHWDeviceType,
@@ -74,7 +72,6 @@ impl Default for CodecInfo {
fn default() -> Self {
Self {
name: Default::default(),
mc_name: Default::default(),
format: DataFormat::H264,
priority: Default::default(),
hwdevice: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
@@ -87,28 +84,24 @@ impl CodecInfo {
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 _,

View File

@@ -1,8 +1,15 @@
#[cfg(windows)]
pub mod capture;
pub mod common;
pub mod ffmpeg;
#[cfg(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"))]
pub mod ffmpeg_hw;
pub mod ffmpeg_ram;
#[cfg(all(
target_os = "linux",
any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp")
))]
pub mod rkmpp_dmabuf;
#[no_mangle]
pub extern "C" fn hwcodec_log(level: i32, message: *const std::os::raw::c_char) {

View File

@@ -0,0 +1,193 @@
//! Synchronous RKMPP encoder for pre-exported V4L2 DMA buffers.
//! Unlike the byte-slice encoder this never reads raw pixels on the CPU.
use std::ffi::{c_char, c_int, c_void, CStr};
use std::os::fd::{AsRawFd, OwnedFd};
use std::ptr::NonNull;
unsafe extern "C" {
fn rkmpp_dma_new(
width: c_int,
height: c_int,
stride: c_int,
format: c_int,
codec: c_int,
fps: c_int,
kbps: c_int,
gop: c_int,
fds: *const c_int,
sizes: *const usize,
count: usize,
) -> *mut c_void;
fn rkmpp_dma_encode(
encoder: *mut c_void,
index: usize,
bytes_used: usize,
fresh_fd: c_int,
pts_us: i64,
force_idr: c_int,
data: *mut *const u8,
size: *mut usize,
) -> c_int;
fn rkmpp_dma_reconfigure(encoder: *mut c_void, kbps: c_int, gop: c_int) -> c_int;
fn rkmpp_dma_free(encoder: *mut c_void);
fn rkmpp_dma_error() -> *const c_char;
}
#[derive(Debug, Clone, Copy)]
#[repr(i32)]
pub enum DmaFormat {
Nv12 = 0,
Bgr24 = 1,
Yuyv = 2,
Rgb24 = 3,
Mjpeg = 4,
}
pub struct DmaEncoderConfig {
pub width: u32,
pub height: u32,
pub stride: u32,
pub format: DmaFormat,
pub hevc: bool,
pub fps: u32,
pub bitrate_kbps: u32,
pub gop: u32,
}
pub struct DmaEncoder {
ctx: NonNull<c_void>,
// Export FDs remain open until AFTER mpp_destroy and imported buffer release.
_buffers: Vec<(OwnedFd, usize)>,
// Keep refreshed exports alive until native replacement/release has ended
// all references to the previous import. At most one FD per capture slot.
fresh_buffers: Vec<Option<OwnedFd>>,
}
// Exclusive ownership: the context can move between threads but all calls are sequential.
unsafe impl Send for DmaEncoder {}
fn last_error() -> String {
unsafe {
CStr::from_ptr(rkmpp_dma_error())
.to_string_lossy()
.into_owned()
}
}
impl DmaEncoder {
pub fn new(config: DmaEncoderConfig, buffers: Vec<(OwnedFd, usize)>) -> Result<Self, String> {
let fds: Vec<_> = buffers.iter().map(|(fd, _)| fd.as_raw_fd()).collect();
let sizes: Vec<_> = buffers.iter().map(|(_, size)| *size).collect();
for value in [
config.width,
config.height,
config.stride,
config.fps,
config.bitrate_kbps,
config.gop,
] {
if value > c_int::MAX as u32 {
return Err("DMA encoder parameter overflow".into());
}
}
let ptr = unsafe {
rkmpp_dma_new(
config.width as _,
config.height as _,
config.stride as _,
config.format as c_int,
config.hevc as _,
config.fps as _,
config.bitrate_kbps as _,
config.gop as _,
fds.as_ptr(),
sizes.as_ptr(),
buffers.len(),
)
};
Ok(Self {
ctx: NonNull::new(ptr).ok_or_else(last_error)?,
fresh_buffers: (0..buffers.len()).map(|_| None).collect(),
_buffers: buffers,
})
}
/// # Safety
/// The indexed buffer must be dequeued and exclusively leased to this call.
/// Do not requeue/write it until this function returns. On failure native MPP
/// is synchronously destroyed before returning, ending all input access.
/// `bytes_used` is the actual DQBUF payload length, not the buffer capacity.
/// A refreshed FD, if supplied, must refer to the same leased capture slot
/// with the capacity registered at construction. Ownership is retained here.
pub unsafe fn encode(
&mut self,
index: usize,
bytes_used: usize,
fresh_fd: Option<OwnedFd>,
pts_ms: i64,
force_idr: bool,
) -> Result<Vec<u8>, String> {
let mut data = std::ptr::null();
let mut size = 0;
if index >= self.fresh_buffers.len() {
return Err("Invalid DMA capture index".into());
}
let ret = unsafe {
rkmpp_dma_encode(
self.ctx.as_ptr(),
index,
bytes_used,
fresh_fd.as_ref().map_or(-1, AsRawFd::as_raw_fd),
pts_ms.saturating_mul(1000),
force_idr as _,
&mut data,
&mut size,
)
};
if fresh_fd.is_some() {
// Native has now released the previous import, or destroyed both
// hardware contexts on error. Only now may its old FD be closed.
self.fresh_buffers[index] = fresh_fd;
}
if ret != 0 {
return Err(last_error());
}
if data.is_null() || size == 0 {
return Err("Empty RKMPP DMA packet".into());
}
// Copy only the compressed output, releasing the driver's packet promptly
// regardless of how long a network subscriber retains its Bytes.
Ok(unsafe { std::slice::from_raw_parts(data, size) }.to_vec())
}
pub fn reconfigure(&mut self, kbps: u32, gop: u32) -> Result<(), String> {
if kbps > c_int::MAX as u32 || gop > c_int::MAX as u32 {
return Err("DMA encoder parameter overflow".into());
}
if unsafe { rkmpp_dma_reconfigure(self.ctx.as_ptr(), kbps as _, gop as _) } != 0 {
return Err(last_error());
}
Ok(())
}
}
impl Drop for DmaEncoder {
fn drop(&mut self) {
unsafe { rkmpp_dma_free(self.ctx.as_ptr()) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_discriminants_match_native_abi() {
assert_eq!(DmaFormat::Nv12 as c_int, 0);
assert_eq!(DmaFormat::Bgr24 as c_int, 1);
assert_eq!(DmaFormat::Yuyv as c_int, 2);
assert_eq!(DmaFormat::Rgb24 as c_int, 3);
assert_eq!(DmaFormat::Mjpeg as c_int, 4);
}
}

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"
}

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.31"
features = [
"ioctl",
"mman",
"poll",
"fs",
"event",
]
[dependencies.thiserror]
version = "2"
[build-dependencies.bindgen]
version = "0.72"

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.31", features = ["ioctl", "mman", "poll", "fs", "event"] }
bitflags = "2.4"
thiserror = "2"
log = "0.4.14"
enumn = "0.1.6"
[build-dependencies]
bindgen = "0.72"

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.

19
libs/v4l2r/README.md Normal file
View File

@@ -0,0 +1,19 @@
# Rust bindings for V4L2
This is a vendored, One-KVM-specific subset of `v4l2r`.
It keeps only the pieces needed for video capture:
- generated Linux V4L2 bindings,
- safe low-level ioctl wrappers used by capture and device probing,
- memory handle helpers for `MMAP`, `USERPTR`, and `DMABUF`,
- core V4L2 types such as `Format`, `PixelFormat`, and `QueueType`.
The upstream crate also contains high-level device abstractions, stateful
decoder/encoder helpers, stateless codec controls, examples, and C FFI. Those
parts are intentionally removed here so this dependency stays scoped to capture.
## Build options
`cargo build` generates V4L2 bindings from the vendored Linux UAPI headers in
`include/`.

20
libs/v4l2r/bindgen.rs Normal file
View File

@@ -0,0 +1,20 @@
// This file defines the customizations to the bindgen builder used to generate the v4l2r
// bindings.
//
// It is meant to be included from `build.rs`.
#[derive(Debug)]
/// Workaround for https://github.com/rust-lang/rust-bindgen/issues/753.
pub struct Fix753;
impl bindgen::callbacks::ParseCallbacks for Fix753 {
fn item_name(&self, item_info: bindgen::callbacks::ItemInfo<'_>) -> Option<String> {
Some(item_info.name.trim_start_matches("Fix753_").to_owned())
}
}
fn v4l2r_bindgen_builder(builder: bindgen::Builder) -> bindgen::Builder {
builder
.parse_callbacks(Box::new(Fix753))
.derive_default(true)
}

43
libs/v4l2r/build.rs Normal file
View File

@@ -0,0 +1,43 @@
use std::env;
use std::path::PathBuf;
include!("bindgen.rs");
/// Vendored Linux UAPI include root.
const VENDORED_INCLUDE_DIR: &str = "include";
/// Wrapper file to use as input of bindgen.
const WRAPPER_H: &str = "v4l2r_wrapper.h";
// Fix for https://github.com/rust-lang/rust-bindgen/issues/753
const FIX753_H: &str = "fix753.h";
fn main() {
let include_root =
PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is not set"))
.join(VENDORED_INCLUDE_DIR);
let videodev2_h = include_root.join("linux/videodev2.h");
println!("cargo::rerun-if-changed={}", videodev2_h.display());
println!("cargo::rerun-if-changed={}", FIX753_H);
println!("cargo::rerun-if-changed={}", WRAPPER_H);
let clang_args = vec![
format!("-I{}", include_root.display()),
#[cfg(all(feature = "arch64", not(feature = "arch32")))]
"--target=x86_64-linux-gnu".into(),
#[cfg(all(feature = "arch32", not(feature = "arch64")))]
"--target=i686-linux-gnu".into(),
];
let bindings = v4l2r_bindgen_builder(bindgen::Builder::default())
.header(WRAPPER_H)
.clang_args(clang_args)
.generate()
.expect("unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").expect("`OUT_DIR` is not set"));
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

55
libs/v4l2r/fix753.h Normal file
View File

@@ -0,0 +1,55 @@
#undef V4L2_FWHT_FL_COMPONENTS_NUM_MSK
#undef V4L2_FWHT_FL_PIXENC_MSK
#ifdef V4L2_FWHT_FL_IS_INTERLACED
MARK_FIX_753(V4L2_FWHT_FL_IS_INTERLACED);
#endif
#ifdef V4L2_FWHT_FL_IS_BOTTOM_FIRST
MARK_FIX_753(V4L2_FWHT_FL_IS_BOTTOM_FIRST);
#endif
#ifdef V4L2_FWHT_FL_IS_ALTERNATE
MARK_FIX_753(V4L2_FWHT_FL_IS_ALTERNATE);
#endif
#ifdef V4L2_FWHT_FL_IS_BOTTOM_FIELD
MARK_FIX_753(V4L2_FWHT_FL_IS_BOTTOM_FIELD);
#endif
#ifdef V4L2_FWHT_FL_LUMA_IS_UNCOMPRESSED
MARK_FIX_753(V4L2_FWHT_FL_LUMA_IS_UNCOMPRESSED);
#endif
#ifdef V4L2_FWHT_FL_CB_IS_UNCOMPRESSED
MARK_FIX_753(V4L2_FWHT_FL_CB_IS_UNCOMPRESSED);
#endif
#ifdef V4L2_FWHT_FL_CR_IS_UNCOMPRESSED
MARK_FIX_753(V4L2_FWHT_FL_CR_IS_UNCOMPRESSED);
#endif
#ifdef V4L2_FWHT_FL_CHROMA_FULL_HEIGHT
MARK_FIX_753(V4L2_FWHT_FL_CHROMA_FULL_HEIGHT);
#endif
#ifdef V4L2_FWHT_FL_CHROMA_FULL_WIDTH
MARK_FIX_753(V4L2_FWHT_FL_CHROMA_FULL_WIDTH);
#endif
#ifdef V4L2_FWHT_FL_ALPHA_IS_UNCOMPRESSED
MARK_FIX_753(V4L2_FWHT_FL_ALPHA_IS_UNCOMPRESSED);
#endif
#ifdef V4L2_FWHT_FL_I_FRAME
MARK_FIX_753(V4L2_FWHT_FL_I_FRAME);
#endif
#ifdef V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET
#define V4L2_FWHT_FL_COMPONENTS_NUM_MSK \
(7 << V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET)
#endif
#ifdef V4L2_FWHT_FL_PIXENC_OFFSET
#define V4L2_FWHT_FL_PIXENC_MSK (3 << V4L2_FWHT_FL_PIXENC_OFFSET)
#endif

View File

@@ -0,0 +1,31 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef __ASM_GENERIC_BITS_PER_LONG
#define __ASM_GENERIC_BITS_PER_LONG
#ifndef __BITS_PER_LONG
/*
* In order to keep safe and avoid regression, only unify uapi
* bitsperlong.h for some archs which are using newer toolchains
* that have the definitions of __CHAR_BIT__ and __SIZEOF_LONG__.
* See the following link for more info:
* https://lore.kernel.org/linux-arch/b9624545-2c80-49a1-ac3c-39264a591f7b@app.fastmail.com/
*/
#if defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__)
#define __BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
#else
/*
* There seems to be no way of detecting this automatically from user
* space, so 64 bit architectures should override this in their
* bitsperlong.h. In particular, an architecture that supports
* both 32 and 64 bit user space must not rely on CONFIG_64BIT
* to decide it, but rather check a compiler provided macro.
*/
#define __BITS_PER_LONG 32
#endif
#endif
#ifndef __BITS_PER_LONG_LONG
#define __BITS_PER_LONG_LONG 64
#endif
#endif /* __ASM_GENERIC_BITS_PER_LONG */

View File

@@ -0,0 +1,40 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/*
* asm-generic/int-ll64.h
*
* Integer declarations for architectures which use "long long"
* for 64-bit types.
*/
#ifndef _ASM_GENERIC_INT_LL64_H
#define _ASM_GENERIC_INT_LL64_H
#include <asm/bitsperlong.h>
#ifndef __ASSEMBLY__
/*
* __xx is ok: it doesn't pollute the POSIX namespace. Use these in the
* header files exported to user space
*/
typedef __signed__ char __s8;
typedef unsigned char __u8;
typedef __signed__ short __s16;
typedef unsigned short __u16;
typedef __signed__ int __s32;
typedef unsigned int __u32;
#ifdef __GNUC__
__extension__ typedef __signed__ long long __s64;
__extension__ typedef unsigned long long __u64;
#else
typedef __signed__ long long __s64;
typedef unsigned long long __u64;
#endif
#endif /* __ASSEMBLY__ */
#endif /* _ASM_GENERIC_INT_LL64_H */

View File

@@ -0,0 +1,105 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _ASM_GENERIC_IOCTL_H
#define _ASM_GENERIC_IOCTL_H
/* ioctl command encoding: 32 bits total, command in lower 16 bits,
* size of the parameter structure in the lower 14 bits of the
* upper 16 bits.
* Encoding the size of the parameter structure in the ioctl request
* is useful for catching programs compiled with old versions
* and to avoid overwriting user space outside the user buffer area.
* The highest 2 bits are reserved for indicating the ``access mode''.
* NOTE: This limits the max parameter size to 16kB -1 !
*/
/*
* The following is for compatibility across the various Linux
* platforms. The generic ioctl numbering scheme doesn't really enforce
* a type field. De facto, however, the top 8 bits of the lower 16
* bits are indeed used as a type field, so we might just as well make
* this explicit here. Please be sure to use the decoding macros
* below from now on.
*/
#define _IOC_NRBITS 8
#define _IOC_TYPEBITS 8
/*
* Let any architecture override either of the following before
* including this file.
*/
#ifndef _IOC_SIZEBITS
# define _IOC_SIZEBITS 14
#endif
#ifndef _IOC_DIRBITS
# define _IOC_DIRBITS 2
#endif
#define _IOC_NRMASK ((1 << _IOC_NRBITS)-1)
#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS)-1)
#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS)-1)
#define _IOC_DIRMASK ((1 << _IOC_DIRBITS)-1)
#define _IOC_NRSHIFT 0
#define _IOC_TYPESHIFT (_IOC_NRSHIFT+_IOC_NRBITS)
#define _IOC_SIZESHIFT (_IOC_TYPESHIFT+_IOC_TYPEBITS)
#define _IOC_DIRSHIFT (_IOC_SIZESHIFT+_IOC_SIZEBITS)
/*
* Direction bits, which any architecture can choose to override
* before including this file.
*
* NOTE: _IOC_WRITE means userland is writing and kernel is
* reading. _IOC_READ means userland is reading and kernel is writing.
*/
#ifndef _IOC_NONE
# define _IOC_NONE 0U
#endif
#ifndef _IOC_WRITE
# define _IOC_WRITE 1U
#endif
#ifndef _IOC_READ
# define _IOC_READ 2U
#endif
#define _IOC(dir,type,nr,size) \
(((dir) << _IOC_DIRSHIFT) | \
((type) << _IOC_TYPESHIFT) | \
((nr) << _IOC_NRSHIFT) | \
((size) << _IOC_SIZESHIFT))
#define _IOC_TYPECHECK(t) (sizeof(t))
/*
* Used to create numbers.
*
* NOTE: _IOW means userland is writing and kernel is reading. _IOR
* means userland is reading and kernel is writing.
*/
#define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0)
#define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))
#define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
#define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
#define _IOR_BAD(type,nr,size) _IOC(_IOC_READ,(type),(nr),sizeof(size))
#define _IOW_BAD(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size))
#define _IOWR_BAD(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size))
/* used to decode ioctl numbers.. */
#define _IOC_DIR(nr) (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK)
#define _IOC_TYPE(nr) (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)
#define _IOC_NR(nr) (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK)
#define _IOC_SIZE(nr) (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)
/* ...and for the drivers/sound files... */
#define IOC_IN (_IOC_WRITE << _IOC_DIRSHIFT)
#define IOC_OUT (_IOC_READ << _IOC_DIRSHIFT)
#define IOC_INOUT ((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT)
#define IOCSIZE_MASK (_IOC_SIZEMASK << _IOC_SIZESHIFT)
#define IOCSIZE_SHIFT (_IOC_SIZESHIFT)
#endif /* _ASM_GENERIC_IOCTL_H */

View File

@@ -0,0 +1,99 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef __ASM_GENERIC_POSIX_TYPES_H
#define __ASM_GENERIC_POSIX_TYPES_H
#include <asm/bitsperlong.h>
/*
* This file is generally used by user-level software, so you need to
* be a little careful about namespace pollution etc.
*
* First the types that are often defined in different ways across
* architectures, so that you can override them.
*/
#ifndef __kernel_long_t
typedef long __kernel_long_t;
typedef unsigned long __kernel_ulong_t;
#endif
#ifndef __kernel_ino_t
typedef __kernel_ulong_t __kernel_ino_t;
#endif
#ifndef __kernel_mode_t
typedef unsigned int __kernel_mode_t;
#endif
#ifndef __kernel_pid_t
typedef int __kernel_pid_t;
#endif
#ifndef __kernel_ipc_pid_t
typedef int __kernel_ipc_pid_t;
#endif
#ifndef __kernel_uid_t
typedef unsigned int __kernel_uid_t;
typedef unsigned int __kernel_gid_t;
#endif
#ifndef __kernel_suseconds_t
typedef __kernel_long_t __kernel_suseconds_t;
#endif
#ifndef __kernel_daddr_t
typedef int __kernel_daddr_t;
#endif
#ifndef __kernel_uid32_t
typedef unsigned int __kernel_uid32_t;
typedef unsigned int __kernel_gid32_t;
#endif
#ifndef __kernel_old_uid_t
typedef __kernel_uid_t __kernel_old_uid_t;
typedef __kernel_gid_t __kernel_old_gid_t;
#endif
#ifndef __kernel_old_dev_t
typedef unsigned int __kernel_old_dev_t;
#endif
/*
* Most 32 bit architectures use "unsigned int" size_t,
* and all 64 bit architectures use "unsigned long" size_t.
*/
#ifndef __kernel_size_t
#if __BITS_PER_LONG != 64
typedef unsigned int __kernel_size_t;
typedef int __kernel_ssize_t;
typedef int __kernel_ptrdiff_t;
#else
typedef __kernel_ulong_t __kernel_size_t;
typedef __kernel_long_t __kernel_ssize_t;
typedef __kernel_long_t __kernel_ptrdiff_t;
#endif
#endif
#ifndef __kernel_fsid_t
typedef struct {
int val[2];
} __kernel_fsid_t;
#endif
/*
* anything below here should be completely generic
*/
typedef __kernel_long_t __kernel_off_t;
typedef long long __kernel_loff_t;
typedef __kernel_long_t __kernel_old_time_t;
typedef __kernel_long_t __kernel_time_t;
typedef long long __kernel_time64_t;
typedef __kernel_long_t __kernel_clock_t;
typedef int __kernel_timer_t;
typedef int __kernel_clockid_t;
typedef char * __kernel_caddr_t;
typedef unsigned short __kernel_uid16_t;
typedef unsigned short __kernel_gid16_t;
#endif /* __ASM_GENERIC_POSIX_TYPES_H */

View File

@@ -0,0 +1,9 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _ASM_GENERIC_TYPES_H
#define _ASM_GENERIC_TYPES_H
/*
* int-ll64 is used everywhere now.
*/
#include <asm-generic/int-ll64.h>
#endif /* _ASM_GENERIC_TYPES_H */

View File

@@ -0,0 +1,53 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/* const.h: Macros for dealing with constants. */
#ifndef _LINUX_CONST_H
#define _LINUX_CONST_H
/* Some constant macros are used in both assembler and
* C code. Therefore we cannot annotate them always with
* 'UL' and other type specifiers unilaterally. We
* use the following macros to deal with this.
*
* Similarly, _AT() will cast an expression with a type in C, but
* leave it unchanged in asm.
*/
#ifdef __ASSEMBLY__
#define _AC(X,Y) X
#define _AT(T,X) X
#else
#define __AC(X,Y) (X##Y)
#define _AC(X,Y) __AC(X,Y)
#define _AT(T,X) ((T)(X))
#endif
#define _UL(x) (_AC(x, UL))
#define _ULL(x) (_AC(x, ULL))
#define _BITUL(x) (_UL(1) << (x))
#define _BITULL(x) (_ULL(1) << (x))
#if !defined(__ASSEMBLY__)
/*
* Missing __asm__ support
*
* __BIT128() would not work in the __asm__ code, as it shifts an
* 'unsigned __init128' data type as direct representation of
* 128 bit constants is not supported in the gcc compiler, as
* they get silently truncated.
*
* TODO: Please revisit this implementation when gcc compiler
* starts representing 128 bit constants directly like long
* and unsigned long etc. Subsequently drop the comment for
* GENMASK_U128() which would then start supporting __asm__ code.
*/
#define _BIT128(x) ((unsigned __int128)(1) << (x))
#endif
#define __ALIGN_KERNEL(x, a) __ALIGN_KERNEL_MASK(x, (__typeof__(x))(a) - 1)
#define __ALIGN_KERNEL_MASK(x, mask) (((x) + (mask)) & ~(mask))
#define __KERNEL_DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
#endif /* _LINUX_CONST_H */

View File

@@ -0,0 +1,8 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _LINUX_IOCTL_H
#define _LINUX_IOCTL_H
#include <asm/ioctl.h>
#endif /* _LINUX_IOCTL_H */

View File

@@ -0,0 +1,38 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _LINUX_POSIX_TYPES_H
#define _LINUX_POSIX_TYPES_H
#include <linux/stddef.h>
/*
* This allows for 1024 file descriptors: if NR_OPEN is ever grown
* beyond that you'll have to change this too. But 1024 fd's seem to be
* enough even for such "real" unices like OSF/1, so hopefully this is
* one limit that doesn't have to be changed [again].
*
* Note that POSIX wants the FD_CLEAR(fd,fdsetp) defines to be in
* <sys/time.h> (and thus <linux/time.h>) - but this is a more logical
* place for them. Solved by having dummy defines in <sys/time.h>.
*/
/*
* This macro may have been defined in <gnu/types.h>. But we always
* use the one here.
*/
#undef __FD_SETSIZE
#define __FD_SETSIZE 1024
typedef struct {
unsigned long fds_bits[__FD_SETSIZE / (8 * sizeof(long))];
} __kernel_fd_set;
/* Type of a signal handler. */
typedef void (*__kernel_sighandler_t)(int);
/* Type of a SYSV IPC key. */
typedef int __kernel_key_t;
typedef int __kernel_mqd_t;
#include <asm/posix_types.h>
#endif /* _LINUX_POSIX_TYPES_H */

View File

@@ -0,0 +1,73 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _LINUX_STDDEF_H
#define _LINUX_STDDEF_H
#ifndef __always_inline
#define __always_inline __inline__
#endif
/* Not all C++ standards support type declarations inside an anonymous union */
#ifndef __cplusplus
#define __struct_group_tag(TAG) TAG
#else
#define __struct_group_tag(TAG)
#endif
/**
* __struct_group() - Create a mirrored named and anonyomous struct
*
* @TAG: The tag name for the named sub-struct (usually empty)
* @NAME: The identifier name of the mirrored sub-struct
* @ATTRS: Any struct attributes (usually empty)
* @MEMBERS: The member declarations for the mirrored structs
*
* Used to create an anonymous union of two structs with identical layout
* and size: one anonymous and one named. The former's members can be used
* normally without sub-struct naming, and the latter can be used to
* reason about the start, end, and size of the group of struct members.
* The named struct can also be explicitly tagged for layer reuse (C only),
* as well as both having struct attributes appended.
*/
#define __struct_group(TAG, NAME, ATTRS, MEMBERS...) \
union { \
struct { MEMBERS } ATTRS; \
struct __struct_group_tag(TAG) { MEMBERS } ATTRS NAME; \
} ATTRS
#ifdef __cplusplus
/* sizeof(struct{}) is 1 in C++, not 0, can't use C version of the macro. */
#define __DECLARE_FLEX_ARRAY(T, member) \
T member[0]
#else
/**
* __DECLARE_FLEX_ARRAY() - Declare a flexible array usable in a union
*
* @TYPE: The type of each flexible array element
* @NAME: The name of the flexible array member
*
* In order to have a flexible array member in a union or alone in a
* struct, it needs to be wrapped in an anonymous struct with at least 1
* named member, but that member can be empty.
*/
#define __DECLARE_FLEX_ARRAY(TYPE, NAME) \
struct { \
struct { } __empty_ ## NAME; \
TYPE NAME[]; \
}
#endif
#ifndef __counted_by
#define __counted_by(m)
#endif
#ifndef __counted_by_le
#define __counted_by_le(m)
#endif
#ifndef __counted_by_be
#define __counted_by_be(m)
#endif
#endif /* _LINUX_STDDEF_H */

View File

@@ -0,0 +1,58 @@
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _LINUX_TYPES_H
#define _LINUX_TYPES_H
#include <asm/types.h>
#ifndef __ASSEMBLY__
#include <linux/posix_types.h>
#ifdef __SIZEOF_INT128__
typedef __signed__ __int128 __s128 __attribute__((aligned(16)));
typedef unsigned __int128 __u128 __attribute__((aligned(16)));
#endif
/*
* Below are truly Linux-specific types that should never collide with
* any application/library that wants linux/types.h.
*/
/* sparse defines __CHECKER__; see Documentation/dev-tools/sparse.rst */
#ifdef __CHECKER__
#define __bitwise __attribute__((bitwise))
#else
#define __bitwise
#endif
/* The kernel doesn't use this legacy form, but user space does */
#define __bitwise__ __bitwise
typedef __u16 __bitwise __le16;
typedef __u16 __bitwise __be16;
typedef __u32 __bitwise __le32;
typedef __u32 __bitwise __be32;
typedef __u64 __bitwise __le64;
typedef __u64 __bitwise __be64;
typedef __u16 __bitwise __sum16;
typedef __u32 __bitwise __wsum;
/*
* aligned_u64 should be used in defining kernel<->userspace ABIs to avoid
* common 32/64-bit compat problems.
* 64-bit values align to 4-byte boundaries on x86_32 (and possibly other
* architectures) and to 8-byte boundaries on 64-bit architectures. The new
* aligned_64 type enforces 8-byte alignment so that structs containing
* aligned_64 values have the same alignment on 32-bit and 64-bit architectures.
* No conversions are necessary between 32-bit user-space and a 64-bit kernel.
*/
#define __aligned_u64 __u64 __attribute__((aligned(8)))
#define __aligned_s64 __s64 __attribute__((aligned(8)))
#define __aligned_be64 __be64 __attribute__((aligned(8)))
#define __aligned_le64 __le64 __attribute__((aligned(8)))
typedef unsigned __bitwise __poll_t;
#endif /* __ASSEMBLY__ */
#endif /* _LINUX_TYPES_H */

View File

@@ -0,0 +1,69 @@
/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */
/*
* include/linux/v4l2-common.h
*
* Common V4L2 and V4L2 subdev definitions.
*
* Users are advised to #include this file either through videodev2.h
* (V4L2) or through v4l2-subdev.h (V4L2 subdev) rather than to refer
* to this file directly.
*
* Copyright (C) 2012 Nokia Corporation
* Contact: Sakari Ailus <sakari.ailus@iki.fi>
*/
#ifndef __V4L2_COMMON__
#define __V4L2_COMMON__
#include <linux/types.h>
/*
*
* Selection interface definitions
*
*/
/* Current cropping area */
#define V4L2_SEL_TGT_CROP 0x0000
/* Default cropping area */
#define V4L2_SEL_TGT_CROP_DEFAULT 0x0001
/* Cropping bounds */
#define V4L2_SEL_TGT_CROP_BOUNDS 0x0002
/* Native frame size */
#define V4L2_SEL_TGT_NATIVE_SIZE 0x0003
/* Current composing area */
#define V4L2_SEL_TGT_COMPOSE 0x0100
/* Default composing area */
#define V4L2_SEL_TGT_COMPOSE_DEFAULT 0x0101
/* Composing bounds */
#define V4L2_SEL_TGT_COMPOSE_BOUNDS 0x0102
/* Current composing area plus all padding pixels */
#define V4L2_SEL_TGT_COMPOSE_PADDED 0x0103
/* Selection flags */
#define V4L2_SEL_FLAG_GE (1 << 0)
#define V4L2_SEL_FLAG_LE (1 << 1)
#define V4L2_SEL_FLAG_KEEP_CONFIG (1 << 2)
struct v4l2_edid {
__u32 pad;
__u32 start_block;
__u32 blocks;
__u32 reserved[5];
__u8 *edid;
};
/* Backward compatibility target definitions --- to be removed. */
#define V4L2_SEL_TGT_CROP_ACTIVE V4L2_SEL_TGT_CROP
#define V4L2_SEL_TGT_COMPOSE_ACTIVE V4L2_SEL_TGT_COMPOSE
#define V4L2_SUBDEV_SEL_TGT_CROP_ACTUAL V4L2_SEL_TGT_CROP
#define V4L2_SUBDEV_SEL_TGT_COMPOSE_ACTUAL V4L2_SEL_TGT_COMPOSE
#define V4L2_SUBDEV_SEL_TGT_CROP_BOUNDS V4L2_SEL_TGT_CROP_BOUNDS
#define V4L2_SUBDEV_SEL_TGT_COMPOSE_BOUNDS V4L2_SEL_TGT_COMPOSE_BOUNDS
/* Backward compatibility flag definitions --- to be removed. */
#define V4L2_SUBDEV_SEL_FLAG_SIZE_GE V4L2_SEL_FLAG_GE
#define V4L2_SUBDEV_SEL_FLAG_SIZE_LE V4L2_SEL_FLAG_LE
#define V4L2_SUBDEV_SEL_FLAG_KEEP_CONFIG V4L2_SEL_FLAG_KEEP_CONFIG
#endif /* __V4L2_COMMON__ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(deref_nullptr)]
#![allow(clippy::all)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

1177
libs/v4l2r/src/ioctl.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
use crate::ioctl::ioctl_and_convert;
use crate::ioctl::IoctlConvertError;
use crate::ioctl::IoctlConvertResult;
use crate::ioctl::UncheckedV4l2Buffer;
use crate::memory::MemoryType;
use crate::QueueType;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use thiserror::Error;
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_buffer;
nix::ioctl_readwrite!(vidioc_dqbuf, b'V', 17, v4l2_buffer);
}
#[derive(Debug, Error)]
pub enum DqBufIoctlError {
#[error("end-of-stream reached")]
Eos,
#[error("no buffer ready for dequeue")]
NotReady,
#[error("unexpected ioctl error: {0}")]
Other(Errno),
}
impl From<Errno> for DqBufIoctlError {
fn from(error: Errno) -> Self {
match error {
Errno::EAGAIN => Self::NotReady,
Errno::EPIPE => Self::Eos,
error => Self::Other(error),
}
}
}
impl From<DqBufIoctlError> for Errno {
fn from(err: DqBufIoctlError) -> Self {
match err {
DqBufIoctlError::Eos => Errno::EPIPE,
DqBufIoctlError::NotReady => Errno::EAGAIN,
DqBufIoctlError::Other(e) => e,
}
}
}
pub type DqBufError<CE> = IoctlConvertError<DqBufIoctlError, CE>;
pub type DqBufResult<O, CE> = IoctlConvertResult<O, DqBufIoctlError, CE>;
/// Safe wrapper around the `VIDIOC_DQBUF` ioctl.
pub fn dqbuf<O>(fd: &impl AsRawFd, queue: QueueType, memory: MemoryType) -> DqBufResult<O, O::Error>
where
O: TryFrom<UncheckedV4l2Buffer>,
O::Error: std::fmt::Debug,
{
let mut v4l2_buf = UncheckedV4l2Buffer::new_for_querybuf(queue, None);
v4l2_buf.0.memory = memory as u32;
ioctl_and_convert(
unsafe { ioctl::vidioc_dqbuf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
.map(|_| v4l2_buf)
.map_err(Into::into),
)
}

View File

@@ -0,0 +1,137 @@
//! Safe wrapper for the `VIDIOC_ENUM_FMT` ioctl.
use super::string_from_cstr;
use crate::bindings;
use crate::bindings::v4l2_fmtdesc;
use crate::{PixelFormat, QueueType};
use bitflags::bitflags;
use log::error;
use nix::errno::Errno;
use std::fmt;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
bitflags! {
/// Flags returned by the `VIDIOC_ENUM_FMT` ioctl into the `flags` field of
/// `struct v4l2_fmtdesc`.
#[derive(Clone, Copy, Debug)]
pub struct FormatFlags: u32 {
const COMPRESSED = bindings::V4L2_FMT_FLAG_COMPRESSED;
const EMULATED = bindings::V4L2_FMT_FLAG_EMULATED;
}
}
/// Quickly get the Fourcc code of a format.
impl From<v4l2_fmtdesc> for PixelFormat {
fn from(fmtdesc: v4l2_fmtdesc) -> Self {
fmtdesc.pixelformat.into()
}
}
/// Safe variant of the `v4l2_fmtdesc` struct, to be used with `enum_fmt`.
#[derive(Debug)]
pub struct FmtDesc {
pub flags: FormatFlags,
pub description: String,
pub pixelformat: PixelFormat,
}
impl fmt::Display for FmtDesc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: {} {}",
self.pixelformat,
self.description,
if self.flags.is_empty() {
"".into()
} else {
format!("({:?})", self.flags)
}
)
}
}
impl From<v4l2_fmtdesc> for FmtDesc {
fn from(fmtdesc: v4l2_fmtdesc) -> Self {
FmtDesc {
flags: FormatFlags::from_bits_truncate(fmtdesc.flags),
description: string_from_cstr(&fmtdesc.description).unwrap_or_else(|_| "".into()),
pixelformat: fmtdesc.pixelformat.into(),
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_fmtdesc;
nix::ioctl_readwrite!(vidioc_enum_fmt, b'V', 2, v4l2_fmtdesc);
}
#[derive(Debug, Error)]
pub enum EnumFmtError {
#[error("ioctl error: {0}")]
IoctlError(#[from] nix::Error),
}
impl From<EnumFmtError> for Errno {
fn from(err: EnumFmtError) -> Self {
match err {
EnumFmtError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_ENUM_FMT` ioctl.
pub fn enum_fmt<T: From<v4l2_fmtdesc>>(
fd: &impl AsRawFd,
queue: QueueType,
index: u32,
) -> Result<T, EnumFmtError> {
let mut fmtdesc = v4l2_fmtdesc {
type_: queue as u32,
index,
..Default::default()
};
unsafe { ioctl::vidioc_enum_fmt(fd.as_raw_fd(), &mut fmtdesc) }?;
Ok(T::from(fmtdesc))
}
/// Iterator over the formats of the given queue. This takes a reference to the
/// device's file descriptor so no operation that could affect the format
/// enumeration can take place while the iterator exists.
pub struct FormatIterator<'a, F: AsRawFd> {
fd: &'a F,
queue: QueueType,
index: u32,
}
impl<'a, F: AsRawFd> FormatIterator<'a, F> {
/// Create a new iterator listing all the currently valid formats on
/// `queue`.
pub fn new(fd: &'a F, queue: QueueType) -> Self {
FormatIterator {
fd,
queue,
index: 0,
}
}
}
impl<'a, F: AsRawFd> Iterator for FormatIterator<'a, F> {
type Item = FmtDesc;
fn next(&mut self) -> Option<Self::Item> {
match enum_fmt(self.fd, self.queue, self.index) {
Ok(fmtdesc) => {
self.index += 1;
Some(fmtdesc)
}
// EINVAL means we have reached the last format.
Err(EnumFmtError::IoctlError(Errno::EINVAL)) => None,
_ => {
error!("Unexpected return value for VIDIOC_ENUM_FMT!");
None
}
}
}
}

View File

@@ -0,0 +1,61 @@
//! Safe wrapper for the `VIDIOC_EXPBUF` ioctl.
use bitflags::bitflags;
use nix::errno::Errno;
use nix::fcntl::OFlag;
use std::os::unix::io::{AsRawFd, FromRawFd};
use thiserror::Error;
use crate::bindings::v4l2_exportbuffer;
use crate::QueueType;
bitflags! {
/// Flags that can be passed when exporting the buffer.
#[derive(Clone, Copy, Debug)]
pub struct ExpbufFlags: u32 {
const CLOEXEC = OFlag::O_CLOEXEC.bits() as u32;
const RDONLY = OFlag::O_RDONLY.bits() as u32;
const WRONLY = OFlag::O_WRONLY.bits() as u32;
const RDWR = OFlag::O_RDWR.bits() as u32;
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_exportbuffer;
nix::ioctl_readwrite!(vidioc_expbuf, b'V', 16, v4l2_exportbuffer);
}
#[derive(Debug, Error)]
pub enum ExpbufError {
#[error("ioctl error: {0}")]
IoctlError(#[from] Errno),
}
impl From<ExpbufError> for Errno {
fn from(err: ExpbufError) -> Self {
match err {
ExpbufError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_EXPBUF` ioctl.
pub fn expbuf<R: FromRawFd>(
fd: &impl AsRawFd,
queue: QueueType,
index: usize,
plane: usize,
flags: ExpbufFlags,
) -> Result<R, ExpbufError> {
let mut v4l2_expbuf = v4l2_exportbuffer {
type_: queue as u32,
index: index as u32,
plane: plane as u32,
flags: flags.bits(),
..Default::default()
};
unsafe { ioctl::vidioc_expbuf(fd.as_raw_fd(), &mut v4l2_expbuf) }?;
Ok(unsafe { R::from_raw_fd(v4l2_expbuf.fd) })
}

View File

@@ -0,0 +1,82 @@
use nix::errno::Errno;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_frmivalenum;
use crate::PixelFormat;
/// A wrapper for the 'v4l2_frmivalenum' union member types
#[derive(Debug)]
pub enum FrmIvalTypes<'a> {
Discrete(&'a bindings::v4l2_fract),
StepWise(&'a bindings::v4l2_frmival_stepwise),
}
impl v4l2_frmivalenum {
/// Safely access the intervals member of the struct based on the
/// returned type.
pub fn intervals(&self) -> Option<FrmIvalTypes<'_>> {
match self.type_ {
// SAFETY: the member of the union that gets used by the driver
// is determined by the type
bindings::v4l2_frmivaltypes_V4L2_FRMIVAL_TYPE_DISCRETE => {
Some(FrmIvalTypes::Discrete(unsafe {
&self.__bindgen_anon_1.discrete
}))
}
// SAFETY: the member of the union that gets used by the driver
// is determined by the type
bindings::v4l2_frmivaltypes_V4L2_FRMIVAL_TYPE_CONTINUOUS
| bindings::v4l2_frmivaltypes_V4L2_FRMIVAL_TYPE_STEPWISE => {
Some(FrmIvalTypes::StepWise(unsafe {
&self.__bindgen_anon_1.stepwise
}))
}
_ => None,
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_frmivalenum;
nix::ioctl_readwrite!(vidioc_enum_frameintervals, b'V', 75, v4l2_frmivalenum);
}
#[derive(Debug, Error)]
pub enum FrameIntervalsError {
#[error("Unexpected ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<FrameIntervalsError> for Errno {
fn from(err: FrameIntervalsError) -> Self {
match err {
FrameIntervalsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_ENUM_FRAMEINTERVALS` ioctl.
pub fn enum_frame_intervals<O: From<v4l2_frmivalenum>>(
fd: &impl AsRawFd,
index: u32,
pixel_format: PixelFormat,
width: u32,
height: u32,
) -> Result<O, FrameIntervalsError> {
let mut frame_interval = v4l2_frmivalenum {
index,
pixel_format: pixel_format.into(),
width,
height,
..Default::default()
};
match unsafe { ioctl::vidioc_enum_frameintervals(fd.as_raw_fd(), &mut frame_interval) } {
Ok(_) => Ok(O::from(frame_interval)),
Err(e) => Err(FrameIntervalsError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,79 @@
use nix::errno::Errno;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_frmsizeenum;
use crate::PixelFormat;
/// A wrapper for the 'v4l2_frmsizeenum' union member types
#[derive(Debug)]
pub enum FrmSizeTypes<'a> {
Discrete(&'a bindings::v4l2_frmsize_discrete),
StepWise(&'a bindings::v4l2_frmsize_stepwise),
}
impl v4l2_frmsizeenum {
/// Safely access the size member of the struct based on the
/// returned type.
pub fn size(&self) -> Option<FrmSizeTypes<'_>> {
match self.type_ {
// SAFETY: the member of the union that gets used by the driver
// is determined by the type
bindings::v4l2_frmsizetypes_V4L2_FRMSIZE_TYPE_DISCRETE => {
Some(FrmSizeTypes::Discrete(unsafe {
&self.__bindgen_anon_1.discrete
}))
}
// SAFETY: the member of the union that gets used by the driver
// is determined by the type
bindings::v4l2_frmsizetypes_V4L2_FRMSIZE_TYPE_CONTINUOUS
| bindings::v4l2_frmsizetypes_V4L2_FRMSIZE_TYPE_STEPWISE => {
Some(FrmSizeTypes::StepWise(unsafe {
&self.__bindgen_anon_1.stepwise
}))
}
_ => None,
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_frmsizeenum;
nix::ioctl_readwrite!(vidioc_enum_framesizes, b'V', 74, v4l2_frmsizeenum);
}
#[derive(Debug, Error)]
pub enum FrameSizeError {
#[error("Unexpected ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<FrameSizeError> for Errno {
fn from(err: FrameSizeError) -> Self {
match err {
FrameSizeError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_ENUM_FRAMESIZES` ioctl.
pub fn enum_frame_sizes<O: From<v4l2_frmsizeenum>>(
fd: &impl AsRawFd,
index: u32,
pixel_format: PixelFormat,
) -> Result<O, FrameSizeError> {
let mut frame_size = v4l2_frmsizeenum {
index,
pixel_format: pixel_format.into(),
..Default::default()
};
match unsafe { ioctl::vidioc_enum_framesizes(fd.as_raw_fd(), &mut frame_size) } {
Ok(_) => Ok(O::from(frame_size)),
Err(e) => Err(FrameSizeError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,189 @@
use std::os::unix::io::AsRawFd;
use enumn::N;
use nix::errno::Errno;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_dv_timings;
use crate::bindings::v4l2_dv_timings_cap;
use crate::bindings::v4l2_enum_dv_timings;
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_dv_timings;
use crate::bindings::v4l2_dv_timings_cap;
use crate::bindings::v4l2_enum_dv_timings;
nix::ioctl_readwrite!(vidioc_s_dv_timings, b'V', 87, v4l2_dv_timings);
nix::ioctl_readwrite!(vidioc_g_dv_timings, b'V', 88, v4l2_dv_timings);
nix::ioctl_readwrite!(vidioc_enum_dv_timings, b'V', 98, v4l2_enum_dv_timings);
nix::ioctl_read!(vidioc_query_dv_timings, b'V', 99, v4l2_dv_timings);
nix::ioctl_readwrite!(vidioc_dv_timings_cap, b'V', 100, v4l2_dv_timings_cap);
}
#[derive(Debug, N)]
#[repr(u32)]
pub enum DvTimingsType {
Bt6561120 = bindings::V4L2_DV_BT_656_1120,
}
#[derive(Debug, Error)]
pub enum GDvTimingsError {
#[error("ioctl not supported or invalid parameters")]
Invalid,
#[error("Digital video timings are not supported on this input or output")]
Unsupported,
#[error("Device is busy and cannot change timings")]
Busy,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<GDvTimingsError> for Errno {
fn from(err: GDvTimingsError) -> Self {
match err {
GDvTimingsError::Invalid => Errno::EINVAL,
GDvTimingsError::Unsupported => Errno::ENODATA,
GDvTimingsError::Busy => Errno::EBUSY,
GDvTimingsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_S_DV_TIMINGS` ioctl.
pub fn s_dv_timings<I: Into<v4l2_dv_timings>, O: From<v4l2_dv_timings>>(
fd: &impl AsRawFd,
timings: I,
) -> Result<O, GDvTimingsError> {
let mut timings: v4l2_dv_timings = timings.into();
match unsafe { ioctl::vidioc_s_dv_timings(fd.as_raw_fd(), &mut timings) } {
Ok(_) => Ok(O::from(timings)),
Err(Errno::EINVAL) => Err(GDvTimingsError::Invalid),
Err(Errno::ENODATA) => Err(GDvTimingsError::Unsupported),
Err(Errno::EBUSY) => Err(GDvTimingsError::Busy),
Err(e) => Err(GDvTimingsError::IoctlError(e)),
}
}
/// Safe wrapper around the `VIDIOC_G_DV_TIMINGS` ioctl.
pub fn g_dv_timings<O: From<v4l2_dv_timings>>(fd: &impl AsRawFd) -> Result<O, GDvTimingsError> {
let mut timings = v4l2_dv_timings {
..Default::default()
};
match unsafe { ioctl::vidioc_g_dv_timings(fd.as_raw_fd(), &mut timings) } {
Ok(_) => Ok(O::from(timings)),
Err(Errno::EINVAL) => Err(GDvTimingsError::Invalid),
Err(Errno::ENODATA) => Err(GDvTimingsError::Unsupported),
Err(Errno::EBUSY) => Err(GDvTimingsError::Busy),
Err(e) => Err(GDvTimingsError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum EnumDvTimingsError {
#[error("timing index is out of bounds")]
Invalid,
#[error("Digital video timings are not supported on this input or output")]
Unsupported,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<EnumDvTimingsError> for Errno {
fn from(err: EnumDvTimingsError) -> Self {
match err {
EnumDvTimingsError::Invalid => Errno::EINVAL,
EnumDvTimingsError::Unsupported => Errno::ENODATA,
EnumDvTimingsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_ENUM_DV_TIMINGS` ioctl.
pub fn enum_dv_timings<O: From<v4l2_dv_timings>>(
fd: &impl AsRawFd,
index: u32,
) -> Result<O, EnumDvTimingsError> {
let mut timings = v4l2_enum_dv_timings {
index,
..Default::default()
};
match unsafe { ioctl::vidioc_enum_dv_timings(fd.as_raw_fd(), &mut timings) } {
Ok(_) => Ok(O::from(timings.timings)),
Err(Errno::EINVAL) => Err(EnumDvTimingsError::Invalid),
Err(Errno::ENODATA) => Err(EnumDvTimingsError::Unsupported),
Err(e) => Err(EnumDvTimingsError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum QueryDvTimingsError {
#[error("Digital video timings are not supported on this input or output")]
Unsupported,
#[error("No timings could be detected because no signal was found")]
NoLink,
#[error("Unstable signal")]
UnstableSignal,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<QueryDvTimingsError> for Errno {
fn from(err: QueryDvTimingsError) -> Self {
match err {
QueryDvTimingsError::Unsupported => Errno::ENODATA,
QueryDvTimingsError::NoLink => Errno::ENOLINK,
QueryDvTimingsError::UnstableSignal => Errno::ENOLCK,
QueryDvTimingsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_QUERY_DV_TIMINGS` ioctl.
pub fn query_dv_timings<O: From<v4l2_dv_timings>>(
fd: &impl AsRawFd,
) -> Result<O, QueryDvTimingsError> {
let mut timings = v4l2_dv_timings {
..Default::default()
};
match unsafe { ioctl::vidioc_query_dv_timings(fd.as_raw_fd(), &mut timings) } {
Ok(_) => Ok(O::from(timings)),
Err(Errno::ENODATA) => Err(QueryDvTimingsError::Unsupported),
Err(Errno::ENOLINK) => Err(QueryDvTimingsError::NoLink),
Err(Errno::ENOLCK) => Err(QueryDvTimingsError::UnstableSignal),
Err(e) => Err(QueryDvTimingsError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum DvTimingsCapError {
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<DvTimingsCapError> for Errno {
fn from(err: DvTimingsCapError) -> Self {
match err {
DvTimingsCapError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_DV_TIMINGS_CAP` ioctl.
pub fn dv_timings_cap<O: From<v4l2_dv_timings_cap>>(
fd: &impl AsRawFd,
) -> Result<O, DvTimingsCapError> {
let mut caps = v4l2_dv_timings_cap {
..Default::default()
};
match unsafe { ioctl::vidioc_dv_timings_cap(fd.as_raw_fd(), &mut caps) } {
Ok(_) => Ok(O::from(caps)),
Err(e) => Err(DvTimingsCapError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,300 @@
//! Safe wrapper for the `VIDIOC_(G|S|TRY)_FMT` ioctls.
use nix::errno::Errno;
use std::convert::{From, Into, TryFrom, TryInto};
use std::default::Default;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_format;
use crate::Format;
use crate::FormatConversionError;
use crate::PlaneLayout;
use crate::QueueType;
impl TryFrom<(QueueType, &Format)> for v4l2_format {
type Error = FormatConversionError;
fn try_from((queue, format): (QueueType, &Format)) -> Result<Self, Self::Error> {
Ok(v4l2_format {
type_: queue as u32,
fmt: match queue {
QueueType::VideoCaptureMplane | QueueType::VideoOutputMplane => {
bindings::v4l2_format__bindgen_ty_1 {
pix_mp: {
if format.plane_fmt.len() > bindings::VIDEO_MAX_PLANES as usize {
return Err(Self::Error::TooManyPlanes(format.plane_fmt.len()));
}
let mut pix_mp = bindings::v4l2_pix_format_mplane {
width: format.width,
height: format.height,
pixelformat: format.pixelformat.into(),
num_planes: format.plane_fmt.len() as u8,
plane_fmt: Default::default(),
..Default::default()
};
for (plane, v4l2_plane) in
format.plane_fmt.iter().zip(pix_mp.plane_fmt.iter_mut())
{
*v4l2_plane = plane.into();
}
pix_mp
},
}
}
_ => bindings::v4l2_format__bindgen_ty_1 {
pix: {
if format.plane_fmt.len() > 1 {
return Err(Self::Error::TooManyPlanes(format.plane_fmt.len()));
}
let (bytesperline, sizeimage) = if !format.plane_fmt.is_empty() {
(
format.plane_fmt[0].bytesperline,
format.plane_fmt[0].sizeimage,
)
} else {
Default::default()
};
bindings::v4l2_pix_format {
width: format.width,
height: format.height,
pixelformat: format.pixelformat.into(),
bytesperline,
sizeimage,
..Default::default()
}
},
},
},
})
}
}
impl From<&PlaneLayout> for bindings::v4l2_plane_pix_format {
fn from(plane: &PlaneLayout) -> Self {
bindings::v4l2_plane_pix_format {
sizeimage: plane.sizeimage,
bytesperline: plane.bytesperline,
..Default::default()
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_format;
nix::ioctl_readwrite!(vidioc_g_fmt, b'V', 4, v4l2_format);
nix::ioctl_readwrite!(vidioc_s_fmt, b'V', 5, v4l2_format);
nix::ioctl_readwrite!(vidioc_try_fmt, b'V', 64, v4l2_format);
}
#[derive(Debug, Error)]
pub enum GFmtError {
#[error("error while converting from V4L2 format")]
FromV4L2FormatConversionError,
#[error("invalid buffer type requested")]
InvalidBufferType,
#[error("unexpected ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<GFmtError> for Errno {
fn from(err: GFmtError) -> Self {
match err {
GFmtError::FromV4L2FormatConversionError => Errno::EINVAL,
GFmtError::InvalidBufferType => Errno::EINVAL,
GFmtError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_G_FMT` ioctl.
pub fn g_fmt<O: TryFrom<v4l2_format>>(fd: &impl AsRawFd, queue: QueueType) -> Result<O, GFmtError> {
let mut fmt = v4l2_format {
type_: queue as u32,
..Default::default()
};
match unsafe { ioctl::vidioc_g_fmt(fd.as_raw_fd(), &mut fmt) } {
Ok(_) => Ok(fmt
.try_into()
.map_err(|_| GFmtError::FromV4L2FormatConversionError)?),
Err(Errno::EINVAL) => Err(GFmtError::InvalidBufferType),
Err(e) => Err(GFmtError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum SFmtError {
#[error("error while converting from V4L2 format")]
FromV4L2FormatConversionError,
#[error("error while converting to V4L2 format")]
ToV4L2FormatConversionError,
#[error("invalid buffer type requested")]
InvalidBufferType,
#[error("device currently busy")]
DeviceBusy,
#[error("ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<SFmtError> for Errno {
fn from(err: SFmtError) -> Self {
match err {
SFmtError::FromV4L2FormatConversionError => Errno::EINVAL,
SFmtError::ToV4L2FormatConversionError => Errno::EINVAL,
SFmtError::InvalidBufferType => Errno::EINVAL,
SFmtError::DeviceBusy => Errno::EBUSY,
SFmtError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_S_FMT` ioctl.
pub fn s_fmt<I: TryInto<v4l2_format>, O: TryFrom<v4l2_format>>(
fd: &mut impl AsRawFd,
format: I,
) -> Result<O, SFmtError> {
let mut fmt: v4l2_format = format
.try_into()
.map_err(|_| SFmtError::ToV4L2FormatConversionError)?;
match unsafe { ioctl::vidioc_s_fmt(fd.as_raw_fd(), &mut fmt) } {
Ok(_) => Ok(fmt
.try_into()
.map_err(|_| SFmtError::FromV4L2FormatConversionError)?),
Err(Errno::EINVAL) => Err(SFmtError::InvalidBufferType),
Err(Errno::EBUSY) => Err(SFmtError::DeviceBusy),
Err(e) => Err(SFmtError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum TryFmtError {
#[error("error while converting from V4L2 format")]
FromV4L2FormatConversionError,
#[error("error while converting to V4L2 format")]
ToV4L2FormatConversionError,
#[error("invalid buffer type requested")]
InvalidBufferType,
#[error("ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<TryFmtError> for Errno {
fn from(err: TryFmtError) -> Self {
match err {
TryFmtError::FromV4L2FormatConversionError => Errno::EINVAL,
TryFmtError::ToV4L2FormatConversionError => Errno::EINVAL,
TryFmtError::InvalidBufferType => Errno::EINVAL,
TryFmtError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_TRY_FMT` ioctl.
pub fn try_fmt<I: TryInto<v4l2_format>, O: TryFrom<v4l2_format>>(
fd: &impl AsRawFd,
format: I,
) -> Result<O, TryFmtError> {
let mut fmt: v4l2_format = format
.try_into()
.map_err(|_| TryFmtError::ToV4L2FormatConversionError)?;
match unsafe { ioctl::vidioc_try_fmt(fd.as_raw_fd(), &mut fmt) } {
Ok(_) => Ok(fmt
.try_into()
.map_err(|_| TryFmtError::FromV4L2FormatConversionError)?),
Err(Errno::EINVAL) => Err(TryFmtError::InvalidBufferType),
Err(e) => Err(TryFmtError::IoctlError(e)),
}
}
#[cfg(test)]
mod test {
use super::*;
use std::convert::TryInto;
#[test]
// Convert from Format to multi-planar v4l2_format and back.
fn mplane_to_v4l2_format() {
// This is not a real format but let us use unique values per field.
let mplane = Format {
width: 632,
height: 480,
pixelformat: b"NM12".into(),
plane_fmt: vec![
PlaneLayout {
sizeimage: 307200,
bytesperline: 640,
},
PlaneLayout {
sizeimage: 153600,
bytesperline: 320,
},
PlaneLayout {
sizeimage: 76800,
bytesperline: 160,
},
],
};
let v4l2_format = v4l2_format {
..(QueueType::VideoCaptureMplane, &mplane).try_into().unwrap()
};
let mplane2: Format = v4l2_format.try_into().unwrap();
assert_eq!(mplane, mplane2);
}
#[test]
// Convert from Format to single-planar v4l2_format and back.
fn splane_to_v4l2_format() {
// This is not a real format but let us use unique values per field.
let splane = Format {
width: 632,
height: 480,
pixelformat: b"NV12".into(),
plane_fmt: vec![PlaneLayout {
sizeimage: 307200,
bytesperline: 640,
}],
};
// Conversion to/from single-planar format.
let v4l2_format = v4l2_format {
..(QueueType::VideoCapture, &splane).try_into().unwrap()
};
let splane2: Format = v4l2_format.try_into().unwrap();
assert_eq!(splane, splane2);
// Trying to use a multi-planar format with the single-planar API should
// fail.
let mplane = Format {
width: 632,
height: 480,
pixelformat: b"NM12".into(),
// This is not a real format but let us use unique values per field.
plane_fmt: vec![
PlaneLayout {
sizeimage: 307200,
bytesperline: 640,
},
PlaneLayout {
sizeimage: 153600,
bytesperline: 320,
},
PlaneLayout {
sizeimage: 76800,
bytesperline: 160,
},
],
};
assert_eq!(
TryInto::<v4l2_format>::try_into((QueueType::VideoCapture, &mplane)).err(),
Some(FormatConversionError::TooManyPlanes(3))
);
}
}

View File

@@ -0,0 +1,149 @@
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use thiserror::Error;
use crate::bindings::v4l2_standard;
use crate::bindings::v4l2_std_id;
use crate::bindings::v4l2_streamparm;
use crate::QueueType;
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_standard;
use crate::bindings::v4l2_std_id;
use crate::bindings::v4l2_streamparm;
nix::ioctl_readwrite!(vidioc_g_parm, b'V', 21, v4l2_streamparm);
nix::ioctl_readwrite!(vidioc_s_parm, b'V', 22, v4l2_streamparm);
nix::ioctl_read!(vidioc_g_std, b'V', 23, v4l2_std_id);
nix::ioctl_write_ptr!(vidioc_s_std, b'V', 24, v4l2_std_id);
nix::ioctl_readwrite!(vidioc_enumstd, b'V', 25, v4l2_standard);
nix::ioctl_read!(vidioc_querystd, b'V', 63, v4l2_std_id);
}
#[derive(Debug, Error)]
pub enum GParmError {
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<GParmError> for Errno {
fn from(err: GParmError) -> Self {
match err {
GParmError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_G_PARM` ioctl.
pub fn g_parm<O: From<v4l2_streamparm>>(
fd: &impl AsRawFd,
queue: QueueType,
) -> Result<O, GParmError> {
let mut parm = v4l2_streamparm {
type_: queue as u32,
..Default::default()
};
match unsafe { ioctl::vidioc_g_parm(fd.as_raw_fd(), &mut parm) } {
Ok(_) => Ok(O::from(parm)),
Err(e) => Err(GParmError::IoctlError(e)),
}
}
/// Safe wrapper around the `VIDIOC_S_PARM` ioctl.
pub fn s_parm<I: Into<v4l2_streamparm>, O: From<v4l2_streamparm>>(
fd: &impl AsRawFd,
parm: I,
) -> Result<O, GParmError> {
let mut parm = parm.into();
match unsafe { ioctl::vidioc_s_parm(fd.as_raw_fd(), &mut parm) } {
Ok(_) => Ok(O::from(parm)),
Err(e) => Err(GParmError::IoctlError(e)),
}
}
/// Safe wrapper around the `VIDIOC_G_STD` ioctl.
pub fn g_std<O: From<v4l2_std_id>>(fd: &impl AsRawFd) -> Result<O, GParmError> {
let mut std_id: v4l2_std_id = 0;
match unsafe { ioctl::vidioc_g_std(fd.as_raw_fd(), &mut std_id) } {
Ok(_) => Ok(O::from(std_id)),
Err(e) => Err(GParmError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum SStdError {
#[error("unsupported standard requested")]
Unsupported,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<SStdError> for Errno {
fn from(err: SStdError) -> Self {
match err {
SStdError::Unsupported => Errno::EINVAL,
SStdError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_S_STD` ioctl.
pub fn s_std<I: Into<v4l2_std_id>>(fd: &impl AsRawFd, std_id: I) -> Result<(), SStdError> {
let std_id = std_id.into();
match unsafe { ioctl::vidioc_s_std(fd.as_raw_fd(), &std_id) } {
Ok(_) => Ok(()),
Err(Errno::EINVAL) => Err(SStdError::Unsupported),
Err(e) => Err(SStdError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum EnumStdError {
#[error("requested index is out of bounds")]
OutOfBounds,
#[error("standard video timings are not supported for this input or output")]
Unsupported,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<EnumStdError> for Errno {
fn from(err: EnumStdError) -> Self {
match err {
EnumStdError::OutOfBounds => Errno::EINVAL,
EnumStdError::Unsupported => Errno::ENODATA,
EnumStdError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_ENUMSTD` ioctl.
pub fn enumstd<O: From<v4l2_standard>>(fd: &impl AsRawFd, index: u32) -> Result<O, EnumStdError> {
let mut standard = v4l2_standard {
index,
..Default::default()
};
match unsafe { ioctl::vidioc_enumstd(fd.as_raw_fd(), &mut standard) } {
Ok(_) => Ok(O::from(standard)),
Err(Errno::EINVAL) => Err(EnumStdError::OutOfBounds),
Err(Errno::ENODATA) => Err(EnumStdError::Unsupported),
Err(e) => Err(EnumStdError::IoctlError(e)),
}
}
/// Safe wrapper around the `VIDIOC_QUERYSTD` ioctl.
pub fn querystd<O: From<v4l2_std_id>>(fd: &impl AsRawFd) -> Result<O, GParmError> {
let mut std_id: v4l2_std_id = 0;
match unsafe { ioctl::vidioc_querystd(fd.as_raw_fd(), &mut std_id) } {
Ok(_) => Ok(O::from(std_id)),
Err(e) => Err(GParmError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,130 @@
use std::os::unix::io::AsRawFd;
use bitflags::bitflags;
use enumn::N;
use nix::errno::Errno;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_rect;
use crate::bindings::v4l2_selection;
#[derive(Debug, N, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum SelectionType {
Capture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_CAPTURE,
Output = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT,
}
#[derive(Debug, N, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum SelectionTarget {
Crop = bindings::V4L2_SEL_TGT_CROP,
CropDefault = bindings::V4L2_SEL_TGT_CROP_DEFAULT,
CropBounds = bindings::V4L2_SEL_TGT_CROP_BOUNDS,
NativeSize = bindings::V4L2_SEL_TGT_NATIVE_SIZE,
Compose = bindings::V4L2_SEL_TGT_COMPOSE,
ComposeDefault = bindings::V4L2_SEL_TGT_COMPOSE_DEFAULT,
ComposeBounds = bindings::V4L2_SEL_TGT_COMPOSE_BOUNDS,
ComposePadded = bindings::V4L2_SEL_TGT_COMPOSE_PADDED,
}
bitflags! {
#[derive(Clone, Copy, Debug)]
pub struct SelectionFlags: u32 {
const GE = bindings::V4L2_SEL_FLAG_GE;
const LE = bindings::V4L2_SEL_FLAG_LE;
const KEEP_CONFIG = bindings::V4L2_SEL_FLAG_KEEP_CONFIG;
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_selection;
nix::ioctl_readwrite!(vidioc_g_selection, b'V', 94, v4l2_selection);
nix::ioctl_readwrite!(vidioc_s_selection, b'V', 95, v4l2_selection);
}
#[derive(Debug, Error)]
pub enum GSelectionError {
#[error("invalid type or target requested")]
Invalid,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<GSelectionError> for Errno {
fn from(err: GSelectionError) -> Self {
match err {
GSelectionError::Invalid => Errno::EINVAL,
GSelectionError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_G_SELECTION` ioctl.
pub fn g_selection<R: From<v4l2_rect>>(
fd: &impl AsRawFd,
selection: SelectionType,
target: SelectionTarget,
) -> Result<R, GSelectionError> {
let mut sel = v4l2_selection {
type_: selection as u32,
target: target as u32,
..Default::default()
};
match unsafe { ioctl::vidioc_g_selection(fd.as_raw_fd(), &mut sel) } {
Ok(_) => Ok(R::from(sel.r)),
Err(Errno::EINVAL) => Err(GSelectionError::Invalid),
Err(e) => Err(GSelectionError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum SSelectionError {
#[error("invalid type or target requested")]
Invalid,
#[error("invalid range requested")]
InvalidRange,
#[error("cannot change selection rectangle currently")]
Busy,
#[error("ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<SSelectionError> for Errno {
fn from(err: SSelectionError) -> Self {
match err {
SSelectionError::Invalid => Errno::EINVAL,
SSelectionError::InvalidRange => Errno::ERANGE,
SSelectionError::Busy => Errno::EBUSY,
SSelectionError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_S_SELECTION` ioctl.
pub fn s_selection<RI: Into<v4l2_rect>, RO: From<v4l2_rect>>(
fd: &impl AsRawFd,
selection: SelectionType,
target: SelectionTarget,
rect: RI,
flags: SelectionFlags,
) -> Result<RO, SSelectionError> {
let mut sel = v4l2_selection {
type_: selection as u32,
target: target as u32,
flags: flags.bits(),
r: rect.into(),
..Default::default()
};
match unsafe { ioctl::vidioc_s_selection(fd.as_raw_fd(), &mut sel) } {
Ok(_) => Ok(RO::from(sel.r)),
Err(Errno::EINVAL) => Err(SSelectionError::Invalid),
Err(Errno::ERANGE) => Err(SSelectionError::InvalidRange),
Err(Errno::EBUSY) => Err(SSelectionError::Busy),
Err(e) => Err(SSelectionError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,117 @@
use core::num::NonZeroUsize;
use std::{
cmp::{max, min},
ops::Deref,
ptr::NonNull,
slice,
};
use std::{ops::DerefMut, os::unix::io::AsFd};
use log::error;
use nix::{errno::Errno, libc::off_t, sys::mman};
use thiserror::Error;
pub struct PlaneMapping {
// A mapping remains valid until we munmap it, that is, until the
// PlaneMapping object is deleted. Hence the static lifetime.
pub data: &'static mut [u8],
start: usize,
end: usize,
}
impl PlaneMapping {
pub fn size(&self) -> usize {
self.end - self.start
}
pub fn restrict(mut self, start: usize, end: usize) -> Self {
self.start = max(self.start, start);
self.end = min(self.end, end);
self
}
}
impl AsRef<[u8]> for PlaneMapping {
fn as_ref(&self) -> &[u8] {
&self.data[self.start..self.end]
}
}
impl AsMut<[u8]> for PlaneMapping {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.data[self.start..self.end]
}
}
impl Deref for PlaneMapping {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.data[self.start..self.end]
}
}
impl DerefMut for PlaneMapping {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data[self.start..self.end]
}
}
impl Drop for PlaneMapping {
fn drop(&mut self) {
// Safe because the pointer and length were constructed in mmap() and
// are always valid.
unsafe {
mman::munmap(
NonNull::new_unchecked(self.data.as_mut_ptr().cast()),
self.data.len(),
)
}
.unwrap_or_else(|e| {
error!("Error while unmapping plane: {}", e);
});
}
}
#[derive(Debug, Error)]
pub enum MmapError {
#[error("provided length was 0")]
ZeroLength,
#[error("ioctl error: {0}")]
IoctlError(#[from] Errno),
}
impl From<MmapError> for Errno {
fn from(err: MmapError) -> Self {
match err {
MmapError::ZeroLength => Errno::EINVAL,
MmapError::IoctlError(e) => e,
}
}
}
// TODO should be unsafe because the mapping can be used after a buffer is queued?
// Or not, since this cannot cause a crash...
pub fn mmap(fd: &impl AsFd, mem_offset: u32, length: u32) -> Result<PlaneMapping, MmapError> {
let non_zero_length = NonZeroUsize::new(length as usize).ok_or(MmapError::ZeroLength)?;
let data = unsafe {
mman::mmap(
None,
non_zero_length,
mman::ProtFlags::PROT_READ | mman::ProtFlags::PROT_WRITE,
mman::MapFlags::MAP_SHARED,
fd,
mem_offset as off_t,
)
}?;
Ok(PlaneMapping {
// Safe because we know the pointer is valid and has enough data mapped
// to cover the length.
data: unsafe { slice::from_raw_parts_mut(data.as_ptr().cast(), length as usize) },
start: 0,
end: length as usize,
})
}

View File

@@ -0,0 +1,197 @@
//! Safe wrapper for the VIDIOC_(D)QBUF and VIDIOC_QUERYBUF ioctls.
use nix::errno::Errno;
use nix::libc::{suseconds_t, time_t};
use nix::sys::time::{TimeVal, TimeValLike};
use std::convert::TryFrom;
use std::fmt::Debug;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
use crate::bindings;
use crate::ioctl::ioctl_and_convert;
use crate::ioctl::BufferFlags;
use crate::ioctl::IoctlConvertError;
use crate::ioctl::IoctlConvertResult;
use crate::ioctl::UncheckedV4l2Buffer;
use crate::memory::Memory;
use crate::memory::PlaneHandle;
use crate::QueueType;
#[derive(Debug, Error)]
pub enum QBufIoctlError {
#[error("invalid number of planes specified for the buffer: got {0}, expected {1}")]
NumPlanesMismatch(usize, usize),
#[error("data offset specified while using the single-planar API")]
DataOffsetNotSupported,
#[error("unexpected ioctl error: {0}")]
Other(Errno),
}
impl From<Errno> for QBufIoctlError {
fn from(errno: Errno) -> Self {
Self::Other(errno)
}
}
impl From<QBufIoctlError> for Errno {
fn from(err: QBufIoctlError) -> Self {
match err {
QBufIoctlError::NumPlanesMismatch(_, _) => Errno::EINVAL,
QBufIoctlError::DataOffsetNotSupported => Errno::EINVAL,
QBufIoctlError::Other(e) => e,
}
}
}
/// Representation of a single plane of a V4L2 buffer.
pub struct QBufPlane(pub bindings::v4l2_plane);
impl QBufPlane {
// TODO remove as this is not safe - we should always specify a handle.
pub fn new(bytes_used: usize) -> Self {
QBufPlane(bindings::v4l2_plane {
bytesused: bytes_used as u32,
data_offset: 0,
..Default::default()
})
}
pub fn new_from_handle<H: PlaneHandle>(handle: &H, bytes_used: usize) -> Self {
let mut plane = Self::new(bytes_used);
handle.fill_v4l2_plane(&mut plane.0);
plane
}
}
impl Debug for QBufPlane {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QBufPlane")
.field("bytesused", &self.0.bytesused)
.field("data_offset", &self.0.data_offset)
.finish()
}
}
/// Contains all the information that can be passed to the `qbuf` ioctl.
// TODO Change this to contain a v4l2_buffer, and create constructors/methods
// to change it? Then during qbuf we just need to set m.planes to planes
// (after resizing it to 8) and we are good to use it as-is.
// We could even turn the trait into AsRef<v4l2_buffer> for good measure.
#[derive(Debug)]
pub struct QBuffer<H: PlaneHandle> {
index: u32,
queue: QueueType,
pub flags: BufferFlags,
pub field: u32,
pub sequence: u32,
pub timestamp: TimeVal,
pub planes: Vec<QBufPlane>,
pub _h: std::marker::PhantomData<H>,
}
impl<H: PlaneHandle> QBuffer<H> {
pub fn new(queue: QueueType, index: u32) -> Self {
QBuffer {
index,
queue,
flags: Default::default(),
field: Default::default(),
sequence: Default::default(),
timestamp: TimeVal::zero(),
planes: Vec::new(),
_h: std::marker::PhantomData,
}
}
}
impl<H: PlaneHandle> QBuffer<H> {
pub fn set_timestamp(mut self, sec: time_t, usec: suseconds_t) -> Self {
self.timestamp = TimeVal::new(sec, usec);
self
}
}
impl<H: PlaneHandle> From<QBuffer<H>> for UncheckedV4l2Buffer {
fn from(qbuf: QBuffer<H>) -> Self {
let mut v4l2_buf = UncheckedV4l2Buffer::new_for_querybuf(qbuf.queue, Some(qbuf.index));
v4l2_buf.0.index = qbuf.index;
v4l2_buf.0.type_ = qbuf.queue as u32;
v4l2_buf.0.memory = H::Memory::MEMORY_TYPE as u32;
v4l2_buf.0.flags = qbuf.flags.bits();
v4l2_buf.0.field = qbuf.field;
v4l2_buf.0.sequence = qbuf.sequence;
v4l2_buf.0.timestamp.tv_sec = qbuf.timestamp.tv_sec();
v4l2_buf.0.timestamp.tv_usec = qbuf.timestamp.tv_usec();
if let Some(planes) = &mut v4l2_buf.1 {
for (dst_plane, src_plane) in planes.iter_mut().zip(qbuf.planes.into_iter()) {
*dst_plane = src_plane.0;
}
} else {
let plane = &qbuf.planes[0];
v4l2_buf.0.length = plane.0.length;
v4l2_buf.0.bytesused = plane.0.bytesused;
v4l2_buf.0.m = (&plane.0.m, H::Memory::MEMORY_TYPE).into();
}
v4l2_buf
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_buffer;
nix::ioctl_readwrite!(vidioc_querybuf, b'V', 9, v4l2_buffer);
nix::ioctl_readwrite!(vidioc_qbuf, b'V', 15, v4l2_buffer);
nix::ioctl_readwrite!(vidioc_dqbuf, b'V', 17, v4l2_buffer);
nix::ioctl_readwrite!(vidioc_prepare_buf, b'V', 93, v4l2_buffer);
}
pub type QBufError<CE> = IoctlConvertError<QBufIoctlError, CE>;
pub type QBufResult<O, CE> = IoctlConvertResult<O, QBufIoctlError, CE>;
/// Safe wrapper around the `VIDIOC_QBUF` ioctl.
///
/// TODO: `qbuf` should be unsafe! The following invariants need to be guaranteed
/// by the caller:
///
/// For MMAP buffers, any mapping must not be accessed by the caller (or any
/// mapping must be unmapped before queueing?). Also if the buffer has been
/// DMABUF-exported, its consumers must likewise not access it.
///
/// For DMABUF buffers, the FD must not be duplicated and accessed anywhere else.
///
/// For USERPTR buffers, things are most tricky. Not only must the data not be
/// accessed by anyone else, the caller also needs to guarantee that the backing
/// memory won't be freed until the corresponding buffer is returned by either
/// `dqbuf` or `streamoff`.
pub fn qbuf<I, O>(fd: &impl AsRawFd, buffer: I) -> QBufResult<O, O::Error>
where
I: Into<UncheckedV4l2Buffer>,
O: TryFrom<UncheckedV4l2Buffer>,
O::Error: std::fmt::Debug,
{
let mut v4l2_buf: UncheckedV4l2Buffer = buffer.into();
ioctl_and_convert(
unsafe { ioctl::vidioc_qbuf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
.map(|_| v4l2_buf)
.map_err(Into::into),
)
}
/// Safe wrapper around the `VIDIOC_PREPARE_BUF` ioctl.
pub fn prepare_buf<I, O>(fd: &impl AsRawFd, buffer: I) -> QBufResult<O, O::Error>
where
I: Into<UncheckedV4l2Buffer>,
O: TryFrom<UncheckedV4l2Buffer>,
O::Error: std::fmt::Debug,
{
let mut v4l2_buf: UncheckedV4l2Buffer = buffer.into();
ioctl_and_convert(
unsafe { ioctl::vidioc_prepare_buf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
.map(|_| v4l2_buf)
.map_err(Into::into),
)
}

View File

@@ -0,0 +1,113 @@
use std::convert::Infallible;
use std::convert::TryFrom;
use std::os::unix::io::AsRawFd;
use nix::errno::Errno;
use thiserror::Error;
use crate::ioctl::ioctl_and_convert;
use crate::ioctl::BufferFlags;
use crate::ioctl::IoctlConvertError;
use crate::ioctl::IoctlConvertResult;
use crate::ioctl::UncheckedV4l2Buffer;
use crate::QueueType;
#[derive(Debug)]
pub struct QueryBufPlane {
/// Offset to pass to `mmap()` in order to obtain a mapping for this plane.
pub mem_offset: u32,
/// Length of this plane.
pub length: u32,
}
/// Contains information about a buffer's layout, as obtained from [`crate::ioctl::querybuf`].
///
/// It is a subset of [`crate::ioctl::V4l2Buffer`], only more convenient on occasion because its
/// conversion from an unchecked v4l2_buffer cannot fail.
///
/// Single-planar buffers have one entry in [`planes`] representing the layout of their unique
/// plane.
#[derive(Debug)]
pub struct QueryBuffer {
pub index: usize,
pub flags: BufferFlags,
pub planes: Vec<QueryBufPlane>,
}
impl TryFrom<UncheckedV4l2Buffer> for QueryBuffer {
type Error = Infallible;
fn try_from(buffer: UncheckedV4l2Buffer) -> Result<Self, Self::Error> {
let v4l2_buf = buffer.0;
let planes = match buffer.1 {
None => vec![QueryBufPlane {
mem_offset: unsafe { v4l2_buf.m.offset },
length: v4l2_buf.length,
}],
Some(v4l2_planes) => v4l2_planes
.iter()
.take(v4l2_buf.length as usize)
.map(|v4l2_plane| QueryBufPlane {
mem_offset: unsafe { v4l2_plane.m.mem_offset },
length: v4l2_plane.length,
})
.collect(),
};
Ok(QueryBuffer {
index: v4l2_buf.index as usize,
flags: BufferFlags::from_bits_truncate(v4l2_buf.flags),
planes,
})
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_buffer;
nix::ioctl_readwrite!(vidioc_querybuf, b'V', 9, v4l2_buffer);
}
#[derive(Debug, Error)]
pub enum QueryBufIoctlError {
#[error("unsupported queue or out-of-bounds index")]
InvalidInput,
#[error("unexpected ioctl error: {0}")]
Other(Errno),
}
impl From<Errno> for QueryBufIoctlError {
fn from(err: Errno) -> Self {
match err {
Errno::EINVAL => QueryBufIoctlError::InvalidInput,
e => QueryBufIoctlError::Other(e),
}
}
}
impl From<QueryBufIoctlError> for Errno {
fn from(err: QueryBufIoctlError) -> Self {
match err {
QueryBufIoctlError::InvalidInput => Errno::EINVAL,
QueryBufIoctlError::Other(e) => e,
}
}
}
pub type QueryBufError<CE> = IoctlConvertError<QueryBufIoctlError, CE>;
pub type QueryBufResult<O, CE> = IoctlConvertResult<O, QueryBufIoctlError, CE>;
/// Safe wrapper around the `VIDIOC_QUERYBUF` ioctl.
pub fn querybuf<O>(fd: &impl AsRawFd, queue: QueueType, index: usize) -> QueryBufResult<O, O::Error>
where
O: TryFrom<UncheckedV4l2Buffer>,
O::Error: std::fmt::Debug,
{
let mut v4l2_buf = UncheckedV4l2Buffer::new_for_querybuf(queue, Some(index as u32));
ioctl_and_convert(
unsafe { ioctl::vidioc_querybuf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
.map(|_| v4l2_buf)
.map_err(Into::into),
)
}

View File

@@ -0,0 +1,136 @@
//! Safe wrapper for the `VIDIOC_QUERYCAP` ioctl.
use super::string_from_cstr;
use crate::bindings;
use crate::bindings::v4l2_capability;
use bitflags::bitflags;
use nix::errno::Errno;
use std::fmt;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
bitflags! {
/// Flags returned by the `VIDIOC_QUERYCAP` ioctl into the `capabilities`
/// or `device_capabilities` field of `v4l2_capability`.
#[derive(Clone, Copy, Debug)]
pub struct Capabilities: u32 {
const VIDEO_CAPTURE = bindings::V4L2_CAP_VIDEO_CAPTURE;
const VIDEO_OUTPUT = bindings::V4L2_CAP_VIDEO_OUTPUT;
const VIDEO_OVERLAY = bindings::V4L2_CAP_VIDEO_OVERLAY;
const VBI_CAPTURE = bindings::V4L2_CAP_VBI_CAPTURE;
const VBI_OUTPUT = bindings::V4L2_CAP_VBI_OUTPUT;
const SLICED_VBI_CAPTURE = bindings::V4L2_CAP_SLICED_VBI_CAPTURE;
const SLICED_VBI_OUTPUT = bindings::V4L2_CAP_SLICED_VBI_OUTPUT;
const RDS_CAPTURE = bindings::V4L2_CAP_RDS_CAPTURE;
const VIDEO_OUTPUT_OVERLAY = bindings::V4L2_CAP_VIDEO_OUTPUT_OVERLAY;
const HW_FREQ_SEEK = bindings::V4L2_CAP_HW_FREQ_SEEK;
const RDS_OUTPUT = bindings::V4L2_CAP_RDS_OUTPUT;
const VIDEO_CAPTURE_MPLANE = bindings::V4L2_CAP_VIDEO_CAPTURE_MPLANE;
const VIDEO_OUTPUT_MPLANE = bindings::V4L2_CAP_VIDEO_OUTPUT_MPLANE;
const VIDEO_M2M_MPLANE = bindings::V4L2_CAP_VIDEO_M2M_MPLANE;
const VIDEO_M2M = bindings::V4L2_CAP_VIDEO_M2M;
const TUNER = bindings::V4L2_CAP_TUNER;
const AUDIO = bindings::V4L2_CAP_AUDIO;
const RADIO = bindings::V4L2_CAP_RADIO;
const MODULATOR = bindings::V4L2_CAP_MODULATOR;
const SDR_CAPTURE = bindings::V4L2_CAP_SDR_CAPTURE;
const EXT_PIX_FORMAT = bindings::V4L2_CAP_EXT_PIX_FORMAT;
const SDR_OUTPUT = bindings::V4L2_CAP_SDR_OUTPUT;
const META_CAPTURE = bindings::V4L2_CAP_META_CAPTURE;
const READWRITE = bindings::V4L2_CAP_READWRITE;
const ASYNCIO = bindings::V4L2_CAP_ASYNCIO;
const STREAMING = bindings::V4L2_CAP_STREAMING;
const META_OUTPUT = bindings::V4L2_CAP_META_OUTPUT;
const TOUCH = bindings::V4L2_CAP_TOUCH;
const DEVICE_CAPS = bindings::V4L2_CAP_DEVICE_CAPS;
}
}
impl fmt::Display for Capabilities {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
/// Used to get the capability flags from a `VIDIOC_QUERYCAP` ioctl.
impl From<v4l2_capability> for Capabilities {
fn from(qcap: v4l2_capability) -> Self {
Capabilities::from_bits_truncate(qcap.capabilities)
}
}
/// Safe variant of the `v4l2_capability` struct, to be used with `querycap`.
#[derive(Debug)]
pub struct Capability {
pub driver: String,
pub card: String,
pub bus_info: String,
pub version: u32,
pub capabilities: Capabilities,
pub device_caps: Option<Capabilities>,
}
impl Capability {
/// Returns the set of capabilities of the hardware as a whole.
pub fn capabilities(&self) -> Capabilities {
self.capabilities
}
/// Returns the capabilities that apply to the currently opened V4L2 node.
pub fn device_caps(&self) -> Capabilities {
self.device_caps
.unwrap_or_else(|| self.capabilities.difference(Capabilities::DEVICE_CAPS))
}
}
impl From<v4l2_capability> for Capability {
fn from(qcap: v4l2_capability) -> Self {
Capability {
driver: string_from_cstr(&qcap.driver).unwrap_or_else(|_| "".into()),
card: string_from_cstr(&qcap.card).unwrap_or_else(|_| "".into()),
bus_info: string_from_cstr(&qcap.bus_info).unwrap_or_else(|_| "".into()),
version: qcap.version,
capabilities: Capabilities::from_bits_truncate(qcap.capabilities),
device_caps: if qcap.capabilities & bindings::V4L2_CAP_DEVICE_CAPS != 0 {
Some(Capabilities::from_bits_truncate(qcap.device_caps))
} else {
None
},
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_capability;
nix::ioctl_read!(vidioc_querycap, b'V', 0, v4l2_capability);
}
#[derive(Debug, Error)]
pub enum QueryCapError {
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<QueryCapError> for Errno {
fn from(err: QueryCapError) -> Self {
match err {
QueryCapError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_QUERYCAP` ioctl.
pub fn querycap<T: From<v4l2_capability>>(fd: &impl AsRawFd) -> Result<T, QueryCapError> {
let mut qcap: v4l2_capability = Default::default();
match unsafe { ioctl::vidioc_querycap(fd.as_raw_fd(), &mut qcap) } {
Ok(_) => Ok(T::from(qcap)),
Err(e) => Err(QueryCapError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,162 @@
//! Safe wrapper for the `VIDIOC_REQBUFS` ioctl.
use crate::bindings;
use crate::bindings::v4l2_create_buffers;
use crate::bindings::v4l2_format;
use crate::bindings::v4l2_requestbuffers;
use crate::memory::MemoryType;
use crate::QueueType;
use bitflags::bitflags;
use nix::{self, errno::Errno};
use std::os::unix::io::AsRawFd;
use thiserror::Error;
bitflags! {
/// Flags returned by the `VIDIOC_REQBUFS` ioctl into the `capabilities`
/// field of `struct v4l2_requestbuffers`.
#[derive(Clone, Copy, Debug)]
pub struct BufferCapabilities: u32 {
const SUPPORTS_MMAP = bindings::V4L2_BUF_CAP_SUPPORTS_MMAP;
const SUPPORTS_USERPTR = bindings::V4L2_BUF_CAP_SUPPORTS_USERPTR;
const SUPPORTS_DMABUF = bindings::V4L2_BUF_CAP_SUPPORTS_DMABUF;
const SUPPORTS_REQUESTS = bindings::V4L2_BUF_CAP_SUPPORTS_REQUESTS;
const SUPPORTS_ORPHANED_BUFS = bindings::V4L2_BUF_CAP_SUPPORTS_ORPHANED_BUFS;
const SUPPORTS_M2M_HOLD_CAPTURE_BUF = bindings::V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF;
const SUPPORTS_MMAP_CACHE_HINTS = bindings::V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS;
}
}
bitflags! {
/// Memory Consistency Flags passed to the `VIDIOC_REQBUFS` ioctl in the `flags`
/// field of `struct v4l2_requestbuffers`.
#[derive(Clone, Copy, Debug)]
pub struct MemoryConsistency: u8 {
const MEMORY_FLAG_NON_COHERENT = bindings::V4L2_MEMORY_FLAG_NON_COHERENT as u8;
}
}
impl From<v4l2_requestbuffers> for () {
fn from(_reqbufs: v4l2_requestbuffers) -> Self {}
}
/// In case we are just interested in the number of buffers that `reqbufs`
/// created.
impl From<v4l2_requestbuffers> for usize {
fn from(reqbufs: v4l2_requestbuffers) -> Self {
reqbufs.count as usize
}
}
/// If we just want to query the buffer capabilities.
impl From<v4l2_requestbuffers> for BufferCapabilities {
fn from(reqbufs: v4l2_requestbuffers) -> Self {
BufferCapabilities::from_bits_truncate(reqbufs.capabilities)
}
}
/// Full result of the `reqbufs` ioctl.
pub struct RequestBuffers {
pub count: u32,
pub capabilities: BufferCapabilities,
pub flags: MemoryConsistency,
}
impl From<v4l2_requestbuffers> for RequestBuffers {
fn from(reqbufs: v4l2_requestbuffers) -> Self {
RequestBuffers {
count: reqbufs.count,
capabilities: BufferCapabilities::from_bits_truncate(reqbufs.capabilities),
flags: MemoryConsistency::from_bits_truncate(reqbufs.flags),
}
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::v4l2_create_buffers;
use crate::bindings::v4l2_requestbuffers;
nix::ioctl_readwrite!(vidioc_reqbufs, b'V', 8, v4l2_requestbuffers);
nix::ioctl_readwrite!(vidioc_create_bufs, b'V', 92, v4l2_create_buffers);
}
#[derive(Debug, Error)]
pub enum ReqbufsError {
#[error("invalid buffer ({0}) or memory type ({1:?}) requested")]
InvalidBufferType(QueueType, MemoryType),
#[error("ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<ReqbufsError> for Errno {
fn from(err: ReqbufsError) -> Self {
match err {
ReqbufsError::InvalidBufferType(_, _) => Errno::EINVAL,
ReqbufsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_REQBUFS` ioctl.
pub fn reqbufs<O: From<v4l2_requestbuffers>>(
fd: &impl AsRawFd,
queue: QueueType,
memory: MemoryType,
count: u32,
flags: MemoryConsistency,
) -> Result<O, ReqbufsError> {
let mut reqbufs = v4l2_requestbuffers {
count,
type_: queue as u32,
memory: memory as u32,
flags: flags.bits(),
..Default::default()
};
match unsafe { ioctl::vidioc_reqbufs(fd.as_raw_fd(), &mut reqbufs) } {
Ok(_) => Ok(O::from(reqbufs)),
Err(Errno::EINVAL) => Err(ReqbufsError::InvalidBufferType(queue, memory)),
Err(e) => Err(ReqbufsError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum CreateBufsError {
#[error("no memory available to allocate MMAP buffers")]
NoMem,
#[error("invalid format or memory type requested")]
Invalid,
#[error("ioctl error: {0}")]
IoctlError(nix::Error),
}
impl From<CreateBufsError> for Errno {
fn from(err: CreateBufsError) -> Self {
match err {
CreateBufsError::NoMem => Errno::ENOMEM,
CreateBufsError::Invalid => Errno::EINVAL,
CreateBufsError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_CREATE_BUFS` ioctl.
pub fn create_bufs<F: Into<v4l2_format>, O: From<v4l2_create_buffers>>(
fd: &impl AsRawFd,
count: u32,
memory: MemoryType,
format: F,
) -> Result<O, CreateBufsError> {
let mut create_bufs = v4l2_create_buffers {
count,
memory: memory as u32,
format: format.into(),
..Default::default()
};
match unsafe { ioctl::vidioc_create_bufs(fd.as_raw_fd(), &mut create_bufs) } {
Ok(_) => Ok(O::from(create_bufs)),
Err(Errno::ENOMEM) => Err(CreateBufsError::NoMem),
Err(Errno::EINVAL) => Err(CreateBufsError::Invalid),
Err(e) => Err(CreateBufsError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,71 @@
//! Safe wrapper for the `VIDIOC_STREAM(ON|OFF)` ioctls.
use crate::QueueType;
use nix::errno::Errno;
use std::os::unix::io::AsRawFd;
use thiserror::Error;
#[doc(hidden)]
mod ioctl {
nix::ioctl_write_ptr!(vidioc_streamon, b'V', 18, u32);
nix::ioctl_write_ptr!(vidioc_streamoff, b'V', 19, u32);
}
#[derive(Debug, Error)]
pub enum StreamOnError {
#[error("queue type ({0}) not supported, or no buffers allocated or enqueued")]
InvalidQueue(QueueType),
#[error("invalid pad configuration")]
InvalidPadConfig,
#[error("invalid pipeline link configuration")]
InvalidPipelineConfig,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<StreamOnError> for Errno {
fn from(err: StreamOnError) -> Self {
match err {
StreamOnError::InvalidQueue(_) => Errno::EINVAL,
StreamOnError::InvalidPadConfig => Errno::EPIPE,
StreamOnError::InvalidPipelineConfig => Errno::ENOLINK,
StreamOnError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_STREAMON` ioctl.
pub fn streamon(fd: &impl AsRawFd, queue: QueueType) -> Result<(), StreamOnError> {
match unsafe { ioctl::vidioc_streamon(fd.as_raw_fd(), &(queue as u32)) } {
Ok(_) => Ok(()),
Err(Errno::EINVAL) => Err(StreamOnError::InvalidQueue(queue)),
Err(Errno::EPIPE) => Err(StreamOnError::InvalidPadConfig),
Err(Errno::ENOLINK) => Err(StreamOnError::InvalidPipelineConfig),
Err(e) => Err(StreamOnError::IoctlError(e)),
}
}
#[derive(Debug, Error)]
pub enum StreamOffError {
#[error("queue type not supported")]
InvalidQueue,
#[error("ioctl error: {0}")]
IoctlError(Errno),
}
impl From<StreamOffError> for Errno {
fn from(err: StreamOffError) -> Self {
match err {
StreamOffError::InvalidQueue => Errno::EINVAL,
StreamOffError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_STREAMOFF` ioctl.
pub fn streamoff(fd: &impl AsRawFd, queue: QueueType) -> Result<(), StreamOffError> {
match unsafe { ioctl::vidioc_streamoff(fd.as_raw_fd(), &(queue as u32)) } {
Ok(_) => Ok(()),
Err(Errno::EINVAL) => Err(StreamOffError::InvalidQueue),
Err(e) => Err(StreamOffError::IoctlError(e)),
}
}

View File

@@ -0,0 +1,210 @@
//! Safe wrapper for the `VIDIOC_SUBSCRIBE_EVENT` and `VIDIOC_UNSUBSCRIBE_EVENT
//! ioctls.
use std::convert::TryFrom;
use std::convert::TryInto;
use std::os::unix::io::AsRawFd;
use bitflags::bitflags;
use nix::errno::Errno;
use thiserror::Error;
use crate::bindings;
use crate::bindings::v4l2_event;
use crate::bindings::v4l2_event_subscription;
bitflags! {
#[derive(Clone, Copy, Debug)]
pub struct SubscribeEventFlags: u32 {
const SEND_INITIAL = bindings::V4L2_EVENT_SUB_FL_SEND_INITIAL;
const ALLOW_FEEDBACK = bindings::V4L2_EVENT_SUB_FL_ALLOW_FEEDBACK;
}
}
#[derive(Debug)]
pub enum EventType {
VSync,
Eos,
Ctrl(u32),
FrameSync,
SourceChange(u32),
MotionDet,
}
#[derive(Debug, Error)]
pub enum EventConversionError {
#[error("unrecognized event {0}")]
UnrecognizedEvent(u32),
#[error("unrecognized source change {0}")]
UnrecognizedSourceChange(u32),
}
impl TryFrom<&v4l2_event_subscription> for EventType {
type Error = EventConversionError;
fn try_from(event: &v4l2_event_subscription) -> Result<Self, Self::Error> {
Ok(match event.type_ {
bindings::V4L2_EVENT_VSYNC => EventType::VSync,
bindings::V4L2_EVENT_EOS => EventType::Eos,
bindings::V4L2_EVENT_CTRL => EventType::Ctrl(event.id),
bindings::V4L2_EVENT_FRAME_SYNC => EventType::FrameSync,
bindings::V4L2_EVENT_SOURCE_CHANGE => EventType::SourceChange(event.id),
bindings::V4L2_EVENT_MOTION_DET => EventType::MotionDet,
e => return Err(EventConversionError::UnrecognizedEvent(e)),
})
}
}
bitflags! {
#[derive(Clone, Copy, Debug)]
pub struct SrcChanges: u32 {
const RESOLUTION = bindings::V4L2_EVENT_SRC_CH_RESOLUTION;
}
}
#[derive(Debug)]
pub enum Event {
SrcChangeEvent(SrcChanges),
Eos,
}
impl TryFrom<v4l2_event> for Event {
type Error = EventConversionError;
fn try_from(value: v4l2_event) -> Result<Self, Self::Error> {
Ok(match value.type_ {
bindings::V4L2_EVENT_VSYNC => todo!(),
bindings::V4L2_EVENT_EOS => Event::Eos,
bindings::V4L2_EVENT_CTRL => todo!(),
bindings::V4L2_EVENT_FRAME_SYNC => todo!(),
bindings::V4L2_EVENT_SOURCE_CHANGE => {
let changes = unsafe { value.u.src_change.changes };
Event::SrcChangeEvent(
SrcChanges::from_bits(changes)
.ok_or(EventConversionError::UnrecognizedSourceChange(changes))?,
)
}
bindings::V4L2_EVENT_MOTION_DET => todo!(),
t => return Err(EventConversionError::UnrecognizedEvent(t)),
})
}
}
fn build_v4l2_event_subscription(
event: EventType,
flags: SubscribeEventFlags,
) -> v4l2_event_subscription {
v4l2_event_subscription {
type_: match event {
EventType::VSync => bindings::V4L2_EVENT_VSYNC,
EventType::Eos => bindings::V4L2_EVENT_EOS,
EventType::Ctrl(_) => bindings::V4L2_EVENT_CTRL,
EventType::FrameSync => bindings::V4L2_EVENT_FRAME_SYNC,
EventType::SourceChange(_) => bindings::V4L2_EVENT_SOURCE_CHANGE,
EventType::MotionDet => bindings::V4L2_EVENT_MOTION_DET,
},
id: match event {
EventType::Ctrl(id) => id,
EventType::SourceChange(id) => id,
_ => 0,
},
flags: flags.bits(),
..Default::default()
}
}
#[doc(hidden)]
mod ioctl {
use crate::bindings::{v4l2_event, v4l2_event_subscription};
nix::ioctl_read!(vidioc_dqevent, b'V', 89, v4l2_event);
nix::ioctl_write_ptr!(vidioc_subscribe_event, b'V', 90, v4l2_event_subscription);
nix::ioctl_write_ptr!(vidioc_unsubscribe_event, b'V', 91, v4l2_event_subscription);
}
#[derive(Debug, Error)]
pub enum SubscribeEventError {
#[error("ioctl error: {0}")]
IoctlError(#[from] Errno),
}
impl From<SubscribeEventError> for Errno {
fn from(err: SubscribeEventError) -> Self {
match err {
SubscribeEventError::IoctlError(e) => e,
}
}
}
/// Safe wrapper around the `VIDIOC_SUBSCRIBE_EVENT` ioctl.
pub fn subscribe_event(
fd: &impl AsRawFd,
event: EventType,
flags: SubscribeEventFlags,
) -> Result<(), SubscribeEventError> {
let subscription = build_v4l2_event_subscription(event, flags);
unsafe { ioctl::vidioc_subscribe_event(fd.as_raw_fd(), &subscription) }?;
Ok(())
}
/// Safe wrapper around the `VIDIOC_UNSUBSCRIBE_EVENT` ioctl.
pub fn unsubscribe_event(fd: &impl AsRawFd, event: EventType) -> Result<(), SubscribeEventError> {
let subscription = build_v4l2_event_subscription(event, SubscribeEventFlags::empty());
unsafe { ioctl::vidioc_unsubscribe_event(fd.as_raw_fd(), &subscription) }?;
Ok(())
}
/// Safe wrapper around the `VIDIOC_UNSUBSCRIBE_EVENT` ioctl to unsubscribe from all events.
pub fn unsubscribe_all_events(fd: &impl AsRawFd) -> Result<(), SubscribeEventError> {
let subscription = v4l2_event_subscription {
type_: bindings::V4L2_EVENT_ALL,
..Default::default()
};
unsafe { ioctl::vidioc_unsubscribe_event(fd.as_raw_fd(), &subscription) }?;
Ok(())
}
#[derive(Debug, Error)]
pub enum DqEventError {
#[error("no event ready for dequeue")]
NotReady,
#[error("error while converting event")]
EventConversionError,
#[error("unexpected ioctl error: {0}")]
IoctlError(Errno),
}
impl From<Errno> for DqEventError {
fn from(error: Errno) -> Self {
match error {
Errno::ENOENT => Self::NotReady,
error => Self::IoctlError(error),
}
}
}
impl From<DqEventError> for Errno {
fn from(err: DqEventError) -> Self {
match err {
DqEventError::NotReady => Errno::ENOENT,
DqEventError::EventConversionError => Errno::EINVAL,
DqEventError::IoctlError(e) => e,
}
}
}
pub fn dqevent<O: TryFrom<v4l2_event>>(fd: &impl AsRawFd) -> Result<O, DqEventError> {
let mut event: v4l2_event = Default::default();
match unsafe { ioctl::vidioc_dqevent(fd.as_raw_fd(), &mut event) } {
Ok(_) => Ok(event
.try_into()
.map_err(|_| DqEventError::EventConversionError)?),
Err(Errno::ENOENT) => Err(DqEventError::NotReady),
Err(e) => Err(DqEventError::IoctlError(e)),
}
}

496
libs/v4l2r/src/lib.rs Normal file
View File

@@ -0,0 +1,496 @@
//! This library provides the V4L2 pieces One-KVM needs for video capture:
//!
//! * The `ioctl` module provides direct, thin wrappers over the V4L2 ioctls
//! with added safety. Note that "safety" here is in terms of memory safety:
//! this layer won't guard against passing invalid data that the ioctls will
//! reject - it just makes sure that data passed from and to the kernel can
//! be accessed safely. Since this is a 1:1 mapping over the V4L2 ioctls,
//! working at this level is a bit laborious, although more comfortable than
//! doing the same in C.
//!
//! The upstream v4l2r crate also contains high-level decoder/encoder and C FFI
//! layers. This vendored copy intentionally excludes those pieces and keeps the
//! capture-oriented ioctl/memory surface only.
//!
#[doc(hidden)]
pub mod bindings;
pub mod ioctl;
pub mod memory;
// This can be needed to match nix errors that we expose.
pub use nix;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::{Debug, Display};
use enumn::N;
use thiserror::Error;
// The goal of this library is to provide two layers of abstraction:
// ioctl: direct, safe counterparts of the V4L2 ioctls.
// device/queue/buffer: higher abstraction, still mapping to core V4L2 mechanics.
/// Possible directions for the queue
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum QueueDirection {
Output,
Capture,
}
/// Possible classes for this queue.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum QueueClass {
Video,
Vbi,
SlicedVbi,
VideoOverlay,
VideoMplane,
Sdr,
Meta,
}
/// Types of queues currently supported by this library.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, N)]
#[repr(u32)]
pub enum QueueType {
VideoCapture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_CAPTURE,
VideoOutput = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT,
VideoOverlay = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OVERLAY,
VbiCapture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VBI_CAPTURE,
VbiOutput = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VBI_OUTPUT,
SlicedVbiCapture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_SLICED_VBI_CAPTURE,
SlicedVbiOutput = bindings::v4l2_buf_type_V4L2_BUF_TYPE_SLICED_VBI_OUTPUT,
VideoOutputOverlay = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY,
VideoCaptureMplane = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
VideoOutputMplane = bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE,
SdrCapture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_SDR_CAPTURE,
SdrOutput = bindings::v4l2_buf_type_V4L2_BUF_TYPE_SDR_OUTPUT,
MetaCapture = bindings::v4l2_buf_type_V4L2_BUF_TYPE_META_CAPTURE,
MetaOutput = bindings::v4l2_buf_type_V4L2_BUF_TYPE_META_OUTPUT,
}
impl QueueType {
/// Returns the queue corresponding to the passed `direction` and `class`.
pub fn from_dir_and_class(direction: QueueDirection, class: QueueClass) -> Self {
match (direction, class) {
(QueueDirection::Capture, QueueClass::Video) => Self::VideoCapture,
(QueueDirection::Output, QueueClass::Video) => Self::VideoOutput,
(QueueDirection::Capture, QueueClass::VideoOverlay) => Self::VideoOverlay,
(QueueDirection::Output, QueueClass::VideoOverlay) => Self::VideoOutputOverlay,
(QueueDirection::Capture, QueueClass::Vbi) => Self::VbiCapture,
(QueueDirection::Output, QueueClass::Vbi) => Self::VbiOutput,
(QueueDirection::Capture, QueueClass::SlicedVbi) => Self::SlicedVbiCapture,
(QueueDirection::Output, QueueClass::SlicedVbi) => Self::SlicedVbiOutput,
(QueueDirection::Capture, QueueClass::VideoMplane) => Self::VideoCaptureMplane,
(QueueDirection::Output, QueueClass::VideoMplane) => Self::VideoOutputMplane,
(QueueDirection::Capture, QueueClass::Sdr) => Self::SdrCapture,
(QueueDirection::Output, QueueClass::Sdr) => Self::SdrOutput,
(QueueDirection::Capture, QueueClass::Meta) => Self::MetaCapture,
(QueueDirection::Output, QueueClass::Meta) => Self::MetaOutput,
}
}
/// Returns whether the queue type is multiplanar.
pub fn is_multiplanar(&self) -> bool {
matches!(
self,
QueueType::VideoCaptureMplane | QueueType::VideoOutputMplane
)
}
/// Returns the direction of the queue type (Output or Capture).
pub fn direction(&self) -> QueueDirection {
match self {
QueueType::VideoOutput
| QueueType::VideoOutputMplane
| QueueType::VideoOverlay
| QueueType::VideoOutputOverlay
| QueueType::VbiOutput
| QueueType::SlicedVbiOutput
| QueueType::SdrOutput
| QueueType::MetaOutput => QueueDirection::Output,
QueueType::VideoCapture
| QueueType::VbiCapture
| QueueType::SlicedVbiCapture
| QueueType::VideoCaptureMplane
| QueueType::SdrCapture
| QueueType::MetaCapture => QueueDirection::Capture,
}
}
pub fn class(&self) -> QueueClass {
match self {
QueueType::VideoCapture | QueueType::VideoOutput => QueueClass::Video,
QueueType::VideoOverlay | QueueType::VideoOutputOverlay => QueueClass::VideoOverlay,
QueueType::VbiCapture | QueueType::VbiOutput => QueueClass::Vbi,
QueueType::SlicedVbiCapture | QueueType::SlicedVbiOutput => QueueClass::SlicedVbi,
QueueType::VideoCaptureMplane | QueueType::VideoOutputMplane => QueueClass::VideoMplane,
QueueType::SdrCapture | QueueType::SdrOutput => QueueClass::Sdr,
QueueType::MetaCapture | QueueType::MetaOutput => QueueClass::Meta,
}
}
}
impl Display for QueueType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(self, f)
}
}
/// A Fourcc pixel format, used to pass formats to V4L2. It can be converted
/// back and forth from a 32-bit integer, or a 4-bytes string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct PixelFormat(u32);
impl PixelFormat {
pub const fn from_u32(v: u32) -> Self {
Self(v)
}
pub const fn to_u32(self) -> u32 {
self.0
}
pub const fn from_fourcc(n: &[u8; 4]) -> Self {
Self(n[0] as u32 | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24)
}
pub const fn to_fourcc(self) -> [u8; 4] {
self.0.to_le_bytes()
}
}
/// Converts a Fourcc in 32-bit integer format (like the ones passed in V4L2
/// structures) into the matching pixel format.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// // Fourcc representation of NV12.
/// let nv12 = u32::from_le(0x3231564e);
/// let f = PixelFormat::from(nv12);
/// assert_eq!(u32::from(f), nv12);
/// ```
impl From<u32> for PixelFormat {
fn from(i: u32) -> Self {
Self::from_u32(i)
}
}
/// Converts a pixel format back to its 32-bit representation.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// // Fourcc representation of NV12.
/// let nv12 = u32::from_le(0x3231564e);
/// let f = PixelFormat::from(nv12);
/// assert_eq!(u32::from(f), nv12);
/// ```
impl From<PixelFormat> for u32 {
fn from(format: PixelFormat) -> Self {
format.to_u32()
}
}
/// Simple way to convert a string litteral (e.g. b"NV12") into a pixel
/// format that can be passed to V4L2.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// let nv12 = b"NV12";
/// let f = PixelFormat::from(nv12);
/// assert_eq!(&<[u8; 4]>::from(f), nv12);
/// ```
impl From<&[u8; 4]> for PixelFormat {
fn from(n: &[u8; 4]) -> Self {
Self::from_fourcc(n)
}
}
/// Convert a pixel format back to its 4-character representation.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// let nv12 = b"NV12";
/// let f = PixelFormat::from(nv12);
/// assert_eq!(&<[u8; 4]>::from(f), nv12);
/// ```
impl From<PixelFormat> for [u8; 4] {
fn from(format: PixelFormat) -> Self {
format.to_fourcc()
}
}
/// Produces a debug string for this PixelFormat, including its hexadecimal
/// and string representation.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// // Fourcc representation of NV12.
/// let nv12 = u32::from_le(0x3231564e);
/// let f = PixelFormat::from(nv12);
/// assert_eq!(format!("{:?}", f), "0x3231564e (NV12)");
/// ```
impl fmt::Debug for PixelFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_fmt(format_args!("0x{:08x} ({})", self.0, self))
}
}
/// Produces a displayable form of this PixelFormat.
///
/// # Examples
///
/// ```
/// # use v4l2r::PixelFormat;
/// // Fourcc representation of NV12.
/// let nv12 = u32::from_le(0x3231564e);
/// let f = PixelFormat::from(nv12);
/// assert_eq!(f.to_string(), "NV12");
/// ```
impl fmt::Display for PixelFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let fourcc = self
.0
.to_le_bytes()
.iter()
.map(|&x| x as char)
.collect::<String>();
f.write_str(fourcc.as_str())
}
}
/// Description of a single plane in a format.
#[derive(Debug, PartialEq, Clone, Default)]
pub struct PlaneLayout {
/// Useful size of the plane ; the backing memory must be at least that large.
pub sizeimage: u32,
/// Bytes per line of data. Only meaningful for image formats.
pub bytesperline: u32,
}
/// Unified representation of a V4L2 format capable of handling both single
/// and multi-planar formats. When the single-planar API is used, only
/// one plane shall be used - attempts to have more will be rejected by the
/// ioctl wrappers.
#[derive(Debug, PartialEq, Clone, Default)]
pub struct Format {
/// Width of the image in pixels.
pub width: u32,
/// Height of the image in pixels.
pub height: u32,
/// Format each pixel is encoded in.
pub pixelformat: PixelFormat,
/// Individual layout of each plane in this format. The exact number of planes
/// is defined by `pixelformat`.
pub plane_fmt: Vec<PlaneLayout>,
}
#[derive(Debug, Error, PartialEq)]
pub enum FormatConversionError {
#[error("too many planes ({0}) specified,")]
TooManyPlanes(usize),
#[error("invalid buffer type requested")]
InvalidBufferType(u32),
}
impl TryFrom<bindings::v4l2_format> for Format {
type Error = FormatConversionError;
fn try_from(fmt: bindings::v4l2_format) -> std::result::Result<Self, Self::Error> {
match fmt.type_ {
bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_CAPTURE
| bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT => {
let pix = unsafe { &fmt.fmt.pix };
Ok(Format {
width: pix.width,
height: pix.height,
pixelformat: PixelFormat::from(pix.pixelformat),
plane_fmt: vec![PlaneLayout {
bytesperline: pix.bytesperline,
sizeimage: pix.sizeimage,
}],
})
}
bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
| bindings::v4l2_buf_type_V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE => {
let pix_mp = unsafe { &fmt.fmt.pix_mp };
// Can only happen if we passed a malformed v4l2_format.
if pix_mp.num_planes as usize > pix_mp.plane_fmt.len() {
return Err(Self::Error::TooManyPlanes(pix_mp.num_planes as usize));
}
let mut plane_fmt = Vec::new();
for i in 0..pix_mp.num_planes as usize {
let plane = &pix_mp.plane_fmt[i];
plane_fmt.push(PlaneLayout {
sizeimage: plane.sizeimage,
bytesperline: plane.bytesperline,
});
}
Ok(Format {
width: pix_mp.width,
height: pix_mp.height,
pixelformat: PixelFormat::from(pix_mp.pixelformat),
plane_fmt,
})
}
t => Err(Self::Error::InvalidBufferType(t)),
}
}
}
/// Quickly build a usable `Format` from a pixel format and resolution.
///
/// # Examples
///
/// ```
/// # use v4l2r::Format;
/// let f = Format::from((b"NV12", (640, 480)));
/// assert_eq!(f.width, 640);
/// assert_eq!(f.height, 480);
/// assert_eq!(f.pixelformat.to_string(), "NV12");
/// assert_eq!(f.plane_fmt.len(), 0);
/// ```
impl<T: Into<PixelFormat>> From<(T, (usize, usize))> for Format {
fn from((pixel_format, (width, height)): (T, (usize, usize))) -> Self {
Format {
width: width as u32,
height: height as u32,
pixelformat: pixel_format.into(),
..Default::default()
}
}
}
/// A more elegant representation for `v4l2_rect`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub left: i32,
pub top: i32,
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn new(left: i32, top: i32, width: u32, height: u32) -> Rect {
Rect {
left,
top,
width,
height,
}
}
}
impl From<bindings::v4l2_rect> for Rect {
fn from(rect: bindings::v4l2_rect) -> Self {
Rect {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
}
}
}
impl From<bindings::v4l2_selection> for Rect {
fn from(selection: bindings::v4l2_selection) -> Self {
Self::from(selection.r)
}
}
impl From<Rect> for bindings::v4l2_rect {
fn from(rect: Rect) -> Self {
bindings::v4l2_rect {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
}
}
}
impl Display for Rect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"({}, {}), {}x{}",
self.left, self.top, self.width, self.height
)
}
}
/// Equivalent of `enum v4l2_colorspace`.
#[repr(u32)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, N)]
pub enum Colorspace {
#[default]
Default = bindings::v4l2_colorspace_V4L2_COLORSPACE_DEFAULT,
Smpte170M = bindings::v4l2_colorspace_V4L2_COLORSPACE_SMPTE170M,
Smpte240M = bindings::v4l2_colorspace_V4L2_COLORSPACE_SMPTE240M,
Rec709 = bindings::v4l2_colorspace_V4L2_COLORSPACE_REC709,
Bt878 = bindings::v4l2_colorspace_V4L2_COLORSPACE_BT878,
SystemM470 = bindings::v4l2_colorspace_V4L2_COLORSPACE_470_SYSTEM_M,
SystemBG470 = bindings::v4l2_colorspace_V4L2_COLORSPACE_470_SYSTEM_BG,
Jpeg = bindings::v4l2_colorspace_V4L2_COLORSPACE_JPEG,
Srgb = bindings::v4l2_colorspace_V4L2_COLORSPACE_SRGB,
OpRgb = bindings::v4l2_colorspace_V4L2_COLORSPACE_OPRGB,
Bt2020 = bindings::v4l2_colorspace_V4L2_COLORSPACE_BT2020,
Raw = bindings::v4l2_colorspace_V4L2_COLORSPACE_RAW,
DciP3 = bindings::v4l2_colorspace_V4L2_COLORSPACE_DCI_P3,
}
/// Equivalent of `enum v4l2_xfer_func`.
#[repr(u32)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, N)]
pub enum XferFunc {
#[default]
Default = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_DEFAULT,
F709 = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_709,
Srgb = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_SRGB,
OpRgb = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_OPRGB,
Smpte240M = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_SMPTE240M,
None = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_NONE,
DciP3 = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_DCI_P3,
Smpte2084 = bindings::v4l2_xfer_func_V4L2_XFER_FUNC_SMPTE2084,
}
/// Equivalent of `enum v4l2_ycbcr_encoding`.
#[repr(u32)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, N)]
pub enum YCbCrEncoding {
#[default]
Default = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_DEFAULT,
E601 = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_601,
E709 = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_709,
Xv601 = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_XV601,
Xv709 = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_XV709,
Sycc = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_SYCC,
Bt2020 = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_BT2020,
Bt2020ConstLum = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_BT2020_CONST_LUM,
Smpte240M = bindings::v4l2_ycbcr_encoding_V4L2_YCBCR_ENC_SMPTE240M,
}
/// Equivalent of `enum v4l2_quantization`.
#[repr(u32)]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, N)]
pub enum Quantization {
#[default]
Default = bindings::v4l2_quantization_V4L2_QUANTIZATION_DEFAULT,
FullRange = bindings::v4l2_quantization_V4L2_QUANTIZATION_FULL_RANGE,
LimRange = bindings::v4l2_quantization_V4L2_QUANTIZATION_LIM_RANGE,
}

279
libs/v4l2r/src/memory.rs Normal file
View File

@@ -0,0 +1,279 @@
//! Abstracts the different kinds of backing memory (`MMAP`, `USERPTR`,
//! `DMABUF`) supported by V4L2.
//!
//! V4L2 allows to use either memory that is provided by the device itself
//! (MMAP) or memory imported via user allocation (USERPTR) or the dma-buf
//! subsystem (DMABUF). This results in 2 very different behaviors and 3 memory
//! types that we need to model.
//!
//! The `Memory` trait represents these memory types and is thus implemented
//! by exacly 3 types: `MMAP`, `UserPtr`, and `DMABuf`. These types do very
//! little apart from providing a constant with the corresponding V4L2 memory
//! type they model, and implement the `SelfBacked` (for MMAP) or `Imported`
//! (for `UserPtr` and `DMABuf`) traits to indicate where their memory comes
//! from.
//!
//! The `PlaneHandle` trait is used by types which can bind to one of these
//! memory types, i.e. a type that can represent a single memory plane of a
//! buffer. For `MMAP` memory this is a void type (since `MMAP` provides its
//! own memory). `UserPtr`, a `Vec<u8>` can adequately be used as backing
//! memory, and for `DMABuf` we will use a file descriptor. For handles that
//! can be mapped into the user address-space (and indeed for `MMAP` this is
//! the only way to access the memory), the `Mappable` trait can be implemented.
//!
//! The set of handles that make all the planes for a given buffer is
//! represented by the `BufferHandles` trait. This trait is more abstract since
//! we may want to decide at runtime the kind of memory we want to use ;
//! therefore this trait does not have any particular kind of memory attached to
//! it. `PrimitiveBufferHandles` is used to represent plane handles which memory
//! type is known at compilation time, and thus includes a reference to a
//! `PlaneHandle` type and by transition its `Memory` type.
mod dmabuf;
mod mmap;
mod userptr;
pub use dmabuf::*;
pub use mmap::*;
pub use userptr::*;
use crate::{
bindings::{self, v4l2_buffer__bindgen_ty_1, v4l2_plane__bindgen_ty_1},
ioctl::{PlaneMapping, QueryBufPlane},
};
use enumn::N;
use std::os::unix::io::AsFd;
use std::{fmt::Debug, ops::Deref};
/// All the supported V4L2 memory types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, N)]
#[repr(u32)]
pub enum MemoryType {
Mmap = bindings::v4l2_memory_V4L2_MEMORY_MMAP,
UserPtr = bindings::v4l2_memory_V4L2_MEMORY_USERPTR,
Overlay = bindings::v4l2_memory_V4L2_MEMORY_OVERLAY,
DmaBuf = bindings::v4l2_memory_V4L2_MEMORY_DMABUF,
}
/// Trait describing a memory type that can be used to back V4L2 buffers.
pub trait Memory: 'static {
/// The memory type represented.
const MEMORY_TYPE: MemoryType;
/// The final type of the memory backing information in `struct v4l2_buffer` or `struct
/// v4l2_plane`.
type RawBacking;
/// Returns a reference to the memory backing information for `m` that is relevant for this
/// memory type.
///
/// # Safety
///
/// The caller must ensure that `m` indeed belongs to a buffer of this memory type.
unsafe fn get_plane_buffer_backing(m: &bindings::v4l2_plane__bindgen_ty_1)
-> &Self::RawBacking;
/// Returns a reference to the memory backing information for `m` that is relevant for this memory type.
///
/// # Safety
///
/// The caller must ensure that `m` indeed belongs to a buffer of this memory type.
unsafe fn get_single_planar_buffer_backing(
m: &bindings::v4l2_buffer__bindgen_ty_1,
) -> &Self::RawBacking;
/// Returns a mutable reference to the memory backing information for `m` that is relevant for
/// this memory type.
///
/// # Safety
///
/// The caller must ensure that `m` indeed belongs to a buffer of this memory type.
unsafe fn get_plane_buffer_backing_mut(
m: &mut bindings::v4l2_plane__bindgen_ty_1,
) -> &mut Self::RawBacking;
/// Returns a mutable reference to the memory backing information for `m` that is relevant for
/// this memory type.
///
/// # Safety
///
/// The caller must ensure that `m` indeed belongs to a buffer of this memory type.
unsafe fn get_single_planar_buffer_backing_mut(
m: &mut bindings::v4l2_buffer__bindgen_ty_1,
) -> &mut Self::RawBacking;
}
/// Trait for memory types that provide their own memory, i.e. MMAP.
pub trait SelfBacked: Memory + Default {}
/// Trait for memory types to which external memory must be attached to, i.e. UserPtr and
/// DMABuf.
pub trait Imported: Memory {}
/// Trait for a handle that represents actual data for a single place. A buffer
/// will have as many of these as it has planes.
pub trait PlaneHandle: Debug + Send + 'static {
/// The kind of memory the handle attaches to.
type Memory: Memory;
/// Fill a plane of a multi-planar V4L2 buffer with the handle's information.
fn fill_v4l2_plane(&self, plane: &mut bindings::v4l2_plane);
}
// Trait for plane handles that provide access to their content through a map()
// method (typically, MMAP buffers).
pub trait Mappable: PlaneHandle {
/// Return a `PlaneMapping` enabling access to the memory of this handle.
fn map<D: AsFd>(device: &D, plane_info: &QueryBufPlane) -> Option<PlaneMapping>;
}
/// Trait for structures providing all the handles of a single buffer.
pub trait BufferHandles: Send + Debug + 'static {
/// Enumeration of all the `MemoryType` supported by this type. Typically
/// a subset of `MemoryType` or `MemoryType` itself.
type SupportedMemoryType: Into<MemoryType> + Send + Clone + Copy;
/// Number of planes.
fn len(&self) -> usize;
/// Fill a plane of a multi-planar V4L2 buffer with the `index` handle's information.
fn fill_v4l2_plane(&self, index: usize, plane: &mut bindings::v4l2_plane);
/// Returns true if there are no handles here (unlikely).
fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Implementation of `BufferHandles` for all indexables of `PlaneHandle` (e.g. [`std::vec::Vec`]).
///
/// This is The simplest way to use primitive handles.
impl<P, Q> BufferHandles for Q
where
P: PlaneHandle,
Q: Send + Debug + 'static + Deref<Target = [P]>,
{
type SupportedMemoryType = MemoryType;
fn len(&self) -> usize {
self.deref().len()
}
fn fill_v4l2_plane(&self, index: usize, plane: &mut bindings::v4l2_plane) {
self.deref()[index].fill_v4l2_plane(plane);
}
}
/// Trait for plane handles for which the final memory type is known at compile
/// time.
pub trait PrimitiveBufferHandles: BufferHandles {
type HandleType: PlaneHandle;
const MEMORY_TYPE: Self::SupportedMemoryType;
}
/// Implementation of `PrimitiveBufferHandles` for all indexables of `PlaneHandle` (e.g.
/// [`std::vec::Vec`]).
impl<P, Q> PrimitiveBufferHandles for Q
where
P: PlaneHandle,
Q: Send + Debug + 'static + Deref<Target = [P]>,
{
type HandleType = P;
const MEMORY_TYPE: Self::SupportedMemoryType = P::Memory::MEMORY_TYPE;
}
/// Conversion from `v4l2_buffer`'s backing information to `v4l2_plane`'s.
impl From<(&v4l2_buffer__bindgen_ty_1, MemoryType)> for v4l2_plane__bindgen_ty_1 {
fn from((m, memory): (&v4l2_buffer__bindgen_ty_1, MemoryType)) -> Self {
match memory {
MemoryType::Mmap => v4l2_plane__bindgen_ty_1 {
// Safe because the buffer type is determined to be MMAP.
mem_offset: unsafe { m.offset },
},
MemoryType::UserPtr => v4l2_plane__bindgen_ty_1 {
// Safe because the buffer type is determined to be USERPTR.
userptr: unsafe { m.userptr },
},
MemoryType::DmaBuf => v4l2_plane__bindgen_ty_1 {
// Safe because the buffer type is determined to be DMABUF.
fd: unsafe { m.fd },
},
MemoryType::Overlay => Default::default(),
}
}
}
/// Conversion from `v4l2_plane`'s backing information to `v4l2_buffer`'s.
impl From<(&v4l2_plane__bindgen_ty_1, MemoryType)> for v4l2_buffer__bindgen_ty_1 {
fn from((m, memory): (&v4l2_plane__bindgen_ty_1, MemoryType)) -> Self {
match memory {
MemoryType::Mmap => v4l2_buffer__bindgen_ty_1 {
// Safe because the buffer type is determined to be MMAP.
offset: unsafe { m.mem_offset },
},
MemoryType::UserPtr => v4l2_buffer__bindgen_ty_1 {
// Safe because the buffer type is determined to be USERPTR.
userptr: unsafe { m.userptr },
},
MemoryType::DmaBuf => v4l2_buffer__bindgen_ty_1 {
// Safe because the buffer type is determined to be DMABUF.
fd: unsafe { m.fd },
},
MemoryType::Overlay => Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use crate::bindings::v4l2_buffer__bindgen_ty_1;
use crate::bindings::v4l2_plane__bindgen_ty_1;
use crate::memory::MemoryType;
#[test]
// Purpose of this test is dubious as the members are overlapping anyway.
fn plane_m_to_buffer_m() {
let plane_m = v4l2_plane__bindgen_ty_1 {
mem_offset: 0xfeedc0fe,
};
assert_eq!(
unsafe { v4l2_buffer__bindgen_ty_1::from((&plane_m, MemoryType::Mmap)).offset },
0xfeedc0fe
);
let plane_m = v4l2_plane__bindgen_ty_1 {
userptr: 0xfeedc0fe,
};
assert_eq!(
unsafe { v4l2_buffer__bindgen_ty_1::from((&plane_m, MemoryType::UserPtr)).userptr },
0xfeedc0fe
);
let plane_m = v4l2_plane__bindgen_ty_1 { fd: 0x76543210 };
assert_eq!(
unsafe { v4l2_buffer__bindgen_ty_1::from((&plane_m, MemoryType::DmaBuf)).fd },
0x76543210
);
}
#[test]
// Purpose of this test is dubious as the members are overlapping anyway.
fn buffer_m_to_plane_m() {
let buffer_m = v4l2_buffer__bindgen_ty_1 { offset: 0xfeedc0fe };
assert_eq!(
unsafe { v4l2_plane__bindgen_ty_1::from((&buffer_m, MemoryType::Mmap)).mem_offset },
0xfeedc0fe
);
let buffer_m = v4l2_buffer__bindgen_ty_1 {
userptr: 0xfeedc0fe,
};
assert_eq!(
unsafe { v4l2_plane__bindgen_ty_1::from((&buffer_m, MemoryType::UserPtr)).userptr },
0xfeedc0fe
);
let buffer_m = v4l2_buffer__bindgen_ty_1 { fd: 0x76543210 };
assert_eq!(
unsafe { v4l2_plane__bindgen_ty_1::from((&buffer_m, MemoryType::DmaBuf)).fd },
0x76543210
);
}
}

View File

@@ -0,0 +1,91 @@
//! Operations specific to DMABuf-type buffers.
use log::warn;
use super::*;
use crate::{bindings, ioctl};
use std::os::fd::RawFd;
use std::os::unix::io::{AsFd, AsRawFd};
pub struct DmaBuf;
pub type DmaBufferHandles<T> = Vec<DmaBufHandle<T>>;
impl Memory for DmaBuf {
const MEMORY_TYPE: MemoryType = MemoryType::DmaBuf;
type RawBacking = RawFd;
unsafe fn get_plane_buffer_backing(
m: &bindings::v4l2_plane__bindgen_ty_1,
) -> &Self::RawBacking {
&m.fd
}
unsafe fn get_single_planar_buffer_backing(
m: &bindings::v4l2_buffer__bindgen_ty_1,
) -> &Self::RawBacking {
&m.fd
}
unsafe fn get_plane_buffer_backing_mut(
m: &mut bindings::v4l2_plane__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.fd
}
unsafe fn get_single_planar_buffer_backing_mut(
m: &mut bindings::v4l2_buffer__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.fd
}
}
impl Imported for DmaBuf {}
pub trait DmaBufSource: AsRawFd + AsFd + Debug + Send {
fn len(&self) -> u64;
/// Make Clippy happy.
fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl DmaBufSource for std::fs::File {
fn len(&self) -> u64 {
match self.metadata() {
Err(_) => {
warn!("Failed to compute File size for use as DMABuf, using 0...");
0
}
Ok(m) => m.len(),
}
}
}
/// Handle for a DMABUF plane. Any type that can provide a file descriptor is
/// valid.
#[derive(Debug)]
pub struct DmaBufHandle<T: DmaBufSource>(pub T);
impl<T: DmaBufSource> From<T> for DmaBufHandle<T> {
fn from(dmabuf: T) -> Self {
DmaBufHandle(dmabuf)
}
}
impl<T: DmaBufSource + 'static> PlaneHandle for DmaBufHandle<T> {
type Memory = DmaBuf;
fn fill_v4l2_plane(&self, plane: &mut bindings::v4l2_plane) {
plane.m.fd = self.0.as_raw_fd();
plane.length = self.0.len() as u32;
}
}
impl<T: DmaBufSource> DmaBufHandle<T> {
pub fn map(&self) -> Result<PlaneMapping, ioctl::MmapError> {
let len = self.0.len();
ioctl::mmap(&self.0, 0, len as u32)
}
}

View File

@@ -0,0 +1,58 @@
//! Operations specific to MMAP-type buffers.
use super::*;
use crate::{bindings, ioctl};
use std::fmt::Debug;
use std::os::fd::AsFd;
#[derive(Default)]
pub struct Mmap;
impl Memory for Mmap {
const MEMORY_TYPE: MemoryType = MemoryType::Mmap;
type RawBacking = u32;
unsafe fn get_plane_buffer_backing(
m: &bindings::v4l2_plane__bindgen_ty_1,
) -> &Self::RawBacking {
&m.mem_offset
}
unsafe fn get_single_planar_buffer_backing(
m: &bindings::v4l2_buffer__bindgen_ty_1,
) -> &Self::RawBacking {
&m.offset
}
unsafe fn get_plane_buffer_backing_mut(
m: &mut bindings::v4l2_plane__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.mem_offset
}
unsafe fn get_single_planar_buffer_backing_mut(
m: &mut bindings::v4l2_buffer__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.offset
}
}
impl SelfBacked for Mmap {}
/// Dummy handle for a MMAP plane, to use with APIs that require handles. MMAP
/// buffers are backed by the device, and thus we don't need to attach any extra
/// information to them.
#[derive(Default, Debug, Clone)]
pub struct MmapHandle;
// There is no information to fill with MMAP buffers ; the index is enough.
impl PlaneHandle for MmapHandle {
type Memory = Mmap;
fn fill_v4l2_plane(&self, _plane: &mut bindings::v4l2_plane) {}
}
impl Mappable for MmapHandle {
fn map<D: AsFd>(device: &D, plane_info: &QueryBufPlane) -> Option<PlaneMapping> {
ioctl::mmap(device, plane_info.mem_offset, plane_info.length).ok()
}
}

View File

@@ -0,0 +1,77 @@
//! Operations specific to UserPtr-type buffers.
use super::*;
use crate::bindings;
pub struct UserPtr;
impl Memory for UserPtr {
const MEMORY_TYPE: MemoryType = MemoryType::UserPtr;
type RawBacking = core::ffi::c_ulong;
unsafe fn get_plane_buffer_backing(
m: &bindings::v4l2_plane__bindgen_ty_1,
) -> &Self::RawBacking {
&m.userptr
}
unsafe fn get_single_planar_buffer_backing(
m: &bindings::v4l2_buffer__bindgen_ty_1,
) -> &Self::RawBacking {
&m.userptr
}
unsafe fn get_plane_buffer_backing_mut(
m: &mut bindings::v4l2_plane__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.userptr
}
unsafe fn get_single_planar_buffer_backing_mut(
m: &mut bindings::v4l2_buffer__bindgen_ty_1,
) -> &mut Self::RawBacking {
&mut m.userptr
}
}
impl Imported for UserPtr {}
/// Handle for a USERPTR plane. These buffers are backed by userspace-allocated
/// memory, which translates well into Rust's slice of `u8`s. Since slices also
/// carry size information, we know that we are not passing unallocated areas
/// of the address-space to the kernel.
///
/// USERPTR buffers have the particularity that the `length` field of `struct
/// v4l2_buffer` must be set before doing a `QBUF` ioctl. This handle struct
/// also takes care of that.
#[derive(Debug)]
pub struct UserPtrHandle<T: AsRef<[u8]> + Debug + Send + 'static>(pub T);
impl<T: AsRef<[u8]> + Debug + Send + Clone> Clone for UserPtrHandle<T> {
fn clone(&self) -> Self {
UserPtrHandle(self.0.clone())
}
}
impl<T: AsRef<[u8]> + Debug + Send + 'static> AsRef<[u8]> for UserPtrHandle<T> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<T: AsRef<[u8]> + Debug + Send> From<T> for UserPtrHandle<T> {
fn from(buffer: T) -> Self {
UserPtrHandle(buffer)
}
}
impl<T: AsRef<[u8]> + Debug + Send + 'static> PlaneHandle for UserPtrHandle<T> {
type Memory = UserPtr;
fn fill_v4l2_plane(&self, plane: &mut bindings::v4l2_plane) {
let slice = AsRef::<[u8]>::as_ref(&self.0);
plane.m.userptr = slice.as_ptr() as std::os::raw::c_ulong;
plane.length = slice.len() as u32;
}
}

View File

@@ -0,0 +1,4 @@
#include <linux/videodev2.h>
#define MARK_FIX_753(name) const unsigned long int Fix753_##name = name;
#include "fix753.h"

View File

@@ -10,9 +10,7 @@ license = "GPL-2.0"
clap = { version = "4", features = ["derive"] }
# Error handling
thiserror = "1"
[dev-dependencies]
thiserror = "2"
tempfile = "3"
[profile.release]

View File

@@ -97,14 +97,14 @@ impl ExfatBootSector {
let heap_sectors = volume_length as u32 - cluster_heap_offset;
let cluster_count = heap_sectors / sectors_per_cluster;
// Calculate root directory cluster based on upcase table size
// Cluster 2: Bitmap (1 cluster)
// Cluster 3...: Upcase table (128KB, may span multiple clusters)
// Next available: Root directory
// Calculate root directory cluster based on bitmap and upcase table size.
const UPCASE_TABLE_SIZE: u64 = 128 * 1024;
let bitmap_size = ((cluster_count + 7) / 8) as u64;
let bitmap_clusters =
((bitmap_size + cluster_size as u64 - 1) / cluster_size as u64).max(1) as u32;
let upcase_clusters =
((UPCASE_TABLE_SIZE + cluster_size as u64 - 1) / cluster_size as u64) as u32;
let first_cluster_of_root = 3 + upcase_clusters;
let first_cluster_of_root = 2 + bitmap_clusters + upcase_clusters;
Self {
jump_boot: [0xEB, 0x76, 0x90],
@@ -211,6 +211,15 @@ const ENTRY_TYPE_VOLUME_LABEL: u8 = 0x83;
const ENTRY_TYPE_BITMAP: u8 = 0x81;
const ENTRY_TYPE_UPCASE: u8 = 0x82;
fn set_cluster_allocated(bitmap: &mut [u8], cluster: u32) {
let index = (cluster - 2) as usize;
let byte_idx = index / 8;
let bit_idx = index % 8;
if byte_idx < bitmap.len() {
bitmap[byte_idx] |= 1 << bit_idx;
}
}
/// Create volume label directory entry
fn create_volume_label_entry(label: &str) -> [u8; 32] {
let mut entry = [0u8; 32];
@@ -301,27 +310,42 @@ pub fn format_exfat<W: Write + Seek>(
let fat_offset = partition_offset + boot_sector.fat_offset as u64 * 512;
writer.seek(SeekFrom::Start(fat_offset))?;
let bitmap_size = (boot_sector.cluster_count + 7) / 8;
let bitmap_clusters =
((bitmap_size as u64 + cluster_size as u64 - 1) / cluster_size as u64).max(1) as u32;
// Calculate how many clusters the upcase table needs (128KB)
const UPCASE_TABLE_SIZE: u64 = 128 * 1024;
let upcase_clusters =
((UPCASE_TABLE_SIZE + cluster_size as u64 - 1) / cluster_size as u64) as u32;
let root_cluster = 3 + upcase_clusters; // Root comes after bitmap and upcase
let bitmap_start_cluster = 2;
let upcase_start_cluster = bitmap_start_cluster + bitmap_clusters;
let root_cluster = upcase_start_cluster + upcase_clusters;
// FAT entries: cluster 0 and 1 are reserved
// 0: Media type (0xFFFFFFF8)
// 1: Reserved (0xFFFFFFFF)
// 2: Bitmap cluster (single cluster, end of chain)
// 3..3+upcase_clusters-1: Upcase table cluster chain
// 3+upcase_clusters: Root directory cluster (end of chain)
// 2..2+bitmap_clusters-1: Bitmap cluster chain
// upcase_start_cluster..upcase_start_cluster+upcase_clusters-1: Upcase table cluster chain
// root_cluster: Root directory cluster (end of chain)
let mut fat_entries = vec![
0xFFFFFFF8, // Media type
0xFFFFFFFF, // Reserved
0xFFFFFFFF, // Bitmap (single cluster, end of chain)
];
// Build allocation bitmap cluster chain
for i in 0..bitmap_clusters {
let cluster_num = bitmap_start_cluster + i;
if i == bitmap_clusters - 1 {
fat_entries.push(0xFFFFFFFF);
} else {
fat_entries.push(cluster_num + 1);
}
}
// Build upcase table cluster chain
for i in 0..upcase_clusters {
let cluster_num = 3 + i;
let cluster_num = upcase_start_cluster + i;
if i == upcase_clusters - 1 {
// Last cluster in chain
fat_entries.push(0xFFFFFFFF);
@@ -345,38 +369,26 @@ pub fn format_exfat<W: Write + Seek>(
// Calculate cluster heap offset
let heap_offset = partition_offset + boot_sector.cluster_heap_offset as u64 * 512;
// Cluster 2: Allocation Bitmap
let bitmap_size = (boot_sector.cluster_count + 7) / 8;
let _bitmap_clusters =
((bitmap_size as u64 + cluster_size as u64 - 1) / cluster_size as u64).max(1);
let mut bitmap = vec![0u8; cluster_size as usize];
// Allocation Bitmap
let mut bitmap = vec![0u8; bitmap_clusters as usize * cluster_size as usize];
// Mark clusters 2, 3..3+upcase_clusters-1, root_cluster as used
// Cluster 2: bitmap
bitmap[0] |= 0b00000100; // Bit 2
// Clusters 3..3+upcase_clusters-1: upcase table
// Mark bitmap, upcase, and root directory clusters as used.
// exFAT allocation bitmap bit 0 describes cluster 2.
for i in 0..bitmap_clusters {
set_cluster_allocated(&mut bitmap, bitmap_start_cluster + i);
}
for i in 0..upcase_clusters {
let cluster = 3 + i;
let byte_idx = (cluster / 8) as usize;
let bit_idx = cluster % 8;
if byte_idx < bitmap.len() {
bitmap[byte_idx] |= 1 << bit_idx;
}
}
// Root directory cluster
let byte_idx = (root_cluster / 8) as usize;
let bit_idx = root_cluster % 8;
if byte_idx < bitmap.len() {
bitmap[byte_idx] |= 1 << bit_idx;
set_cluster_allocated(&mut bitmap, upcase_start_cluster + i);
}
set_cluster_allocated(&mut bitmap, root_cluster);
writer.seek(SeekFrom::Start(heap_offset))?;
writer.write_all(&bitmap)?;
// Cluster 3..3+upcase_clusters-1: Upcase table
// Upcase table
let upcase_data = generate_upcase_table();
let upcase_checksum = calculate_upcase_checksum(&upcase_data);
let upcase_offset = heap_offset + cluster_size as u64; // Start at cluster 3
let upcase_offset = heap_offset + bitmap_clusters as u64 * cluster_size as u64;
writer.seek(SeekFrom::Start(upcase_offset))?;
writer.write_all(&upcase_data)?;
@@ -388,13 +400,18 @@ pub fn format_exfat<W: Write + Seek>(
}
// Root directory cluster
let root_offset = heap_offset + (1 + upcase_clusters as u64) * cluster_size as u64;
let root_offset =
heap_offset + (bitmap_clusters as u64 + upcase_clusters as u64) * cluster_size as u64;
writer.seek(SeekFrom::Start(root_offset))?;
// Write directory entries
let volume_label_entry = create_volume_label_entry(label);
let bitmap_entry = create_bitmap_entry(2, bitmap_size as u64);
let upcase_entry = create_upcase_entry(3, upcase_data.len() as u64, upcase_checksum);
let bitmap_entry = create_bitmap_entry(bitmap_start_cluster, bitmap_size as u64);
let upcase_entry = create_upcase_entry(
upcase_start_cluster,
upcase_data.len() as u64,
upcase_checksum,
);
writer.write_all(&volume_label_entry)?;
writer.write_all(&bitmap_entry)?;
@@ -413,6 +430,9 @@ pub fn format_exfat<W: Write + Seek>(
#[cfg(test)]
mod tests {
use super::*;
use crate::partition::PartitionLayout;
use std::io::Read;
use tempfile::NamedTempFile;
#[test]
fn test_cluster_size() {
@@ -428,4 +448,120 @@ mod tests {
assert_eq!(get_cluster_size(8 * 1024 * 1024 * 1024 / 512), 131072); // 8GB → 128KB
assert_eq!(get_cluster_size(16 * 1024 * 1024 * 1024 / 512), 131072); // 16GB → 128KB
}
#[test]
fn test_format_bitmap_uses_cluster_heap_bit_indices() {
let temp_file = NamedTempFile::new().unwrap();
let path = temp_file.path();
let size = 64 * 1024 * 1024u64;
let layout = PartitionLayout::calculate(size).unwrap();
let mut file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(path)
.unwrap();
file.set_len(size).unwrap();
format_exfat(&mut file, layout.data_offset(), layout.data_size(), "TEST").unwrap();
let mut boot_sector = [0u8; 512];
file.seek(SeekFrom::Start(layout.data_offset())).unwrap();
file.read_exact(&mut boot_sector).unwrap();
let cluster_heap_offset = u32::from_le_bytes(boot_sector[88..92].try_into().unwrap());
let first_cluster_of_root = u32::from_le_bytes(boot_sector[96..100].try_into().unwrap());
let sectors_per_cluster = 1u64 << boot_sector[109];
let cluster_size = sectors_per_cluster * 512;
let bitmap_offset = layout.data_offset() + cluster_heap_offset as u64 * 512;
let mut bitmap = vec![0u8; cluster_size as usize];
file.seek(SeekFrom::Start(bitmap_offset)).unwrap();
file.read_exact(&mut bitmap).unwrap();
let is_allocated = |cluster: u32| {
let index = (cluster - 2) as usize;
(bitmap[index / 8] & (1 << (index % 8))) != 0
};
assert!(
is_allocated(2),
"allocation bitmap cluster must be allocated"
);
assert!(
is_allocated(3),
"upcase table first cluster must be allocated"
);
assert!(
is_allocated(first_cluster_of_root),
"root directory cluster must be allocated"
);
assert!(
!is_allocated(first_cluster_of_root + 1),
"first data cluster after root should be free after formatting"
);
}
#[test]
fn test_format_supports_multi_cluster_allocation_bitmap() {
let temp_file = NamedTempFile::new().unwrap();
let path = temp_file.path();
let size = 240 * 1024 * 1024u64;
let layout = PartitionLayout::calculate(size).unwrap();
let mut file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(path)
.unwrap();
file.set_len(size).unwrap();
format_exfat(&mut file, layout.data_offset(), layout.data_size(), "TEST").unwrap();
let mut boot_sector = [0u8; 512];
file.seek(SeekFrom::Start(layout.data_offset())).unwrap();
file.read_exact(&mut boot_sector).unwrap();
let fat_offset = u32::from_le_bytes(boot_sector[80..84].try_into().unwrap());
let cluster_heap_offset = u32::from_le_bytes(boot_sector[88..92].try_into().unwrap());
let cluster_count = u32::from_le_bytes(boot_sector[92..96].try_into().unwrap());
let first_cluster_of_root = u32::from_le_bytes(boot_sector[96..100].try_into().unwrap());
let sectors_per_cluster = 1u64 << boot_sector[109];
let cluster_size = sectors_per_cluster * 512;
let bitmap_size = ((cluster_count + 7) / 8) as u64;
let bitmap_clusters = bitmap_size.div_ceil(cluster_size) as u32;
assert!(
bitmap_clusters > 1,
"test volume should require a multi-cluster allocation bitmap"
);
let upcase_clusters = (128 * 1024u64).div_ceil(cluster_size) as u32;
assert_eq!(first_cluster_of_root, 2 + bitmap_clusters + upcase_clusters);
let read_fat = |file: &mut std::fs::File, cluster: u32| -> u32 {
let offset = layout.data_offset() + fat_offset as u64 * 512 + cluster as u64 * 4;
let mut bytes = [0u8; 4];
file.seek(SeekFrom::Start(offset)).unwrap();
file.read_exact(&mut bytes).unwrap();
u32::from_le_bytes(bytes)
};
assert_eq!(read_fat(&mut file, 2), 3);
assert_eq!(read_fat(&mut file, 2 + bitmap_clusters - 1), 0xFFFFFFFF);
let root_offset = layout.data_offset()
+ cluster_heap_offset as u64 * 512
+ (first_cluster_of_root - 2) as u64 * cluster_size;
let mut root = vec![0u8; cluster_size as usize];
file.seek(SeekFrom::Start(root_offset)).unwrap();
file.read_exact(&mut root).unwrap();
assert_eq!(root[32], ENTRY_TYPE_BITMAP);
assert_eq!(u32::from_le_bytes(root[52..56].try_into().unwrap()), 2);
assert_eq!(
u64::from_le_bytes(root[56..64].try_into().unwrap()),
bitmap_size
);
assert_eq!(root[64], ENTRY_TYPE_UPCASE);
assert_eq!(
u32::from_le_bytes(root[84..88].try_into().unwrap()),
2 + bitmap_clusters
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -28,8 +28,15 @@ impl VentoyImage {
path.display()
);
// Create sparse file
let mut file = File::create(path)?;
// Build beside the destination so a failed create cannot leave a partial image.
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut temp = tempfile::Builder::new()
.prefix(".ventoy-")
.tempfile_in(parent)?;
let mut file = temp.as_file_mut();
file.set_len(size)?;
// Write boot code
@@ -64,6 +71,8 @@ impl VentoyImage {
format_exfat(&mut file, layout.data_offset(), layout.data_size(), label)?;
file.flush()?;
temp.persist(path)
.map_err(|error| VentoyError::Io(error.error))?;
println!("[INFO] Ventoy IMG created successfully!");
@@ -274,3 +283,20 @@ impl VentoyImage {
&self.path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn failed_create_does_not_publish_partial_image() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ventoy.img");
let error = VentoyImage::create(&path, "64M", "TEST").err().unwrap();
assert!(matches!(error, VentoyError::ResourceNotFound(_)));
assert!(!path.exists());
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}
}

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