Compare commits

...

78 Commits

Author SHA1 Message Date
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
394 changed files with 42819 additions and 8353 deletions

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

@@ -0,0 +1,85 @@
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
cache: npm
cache-dependency-path: web/package-lock.json
- uses: dtolnay/rust-toolchain@stable
- name: Install build dependencies
run: |
sudo apt-get update
sudo apt-get install -y unzip xz-utils
cargo install cross --locked
- name: Build frontend
working-directory: web
run: |
npm ci
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.1"
version = "0.2.5"
edition = "2021"
authors = ["SilentWind"]
description = "A open and lightweight IP-KVM solution written in Rust"
@@ -9,119 +9,188 @@ 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: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: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", "set-header"] }
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"] }
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"
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 }
# Ventoy bootable image support
ventoy-img = { path = "libs/ventoy-img-rs" }
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"
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 }
[target.'cfg(any(unix, windows))'.dependencies]
[target.'cfg(any(target_os = "linux", windows))'.dependencies]
# Video encoding/decoding (FFmpeg/libjpeg-turbo/libyuv; available on Windows and Linux)
hwcodec = { path = "libs/hwcodec" }
libyuv = { path = "res/vcpkg/libyuv" }
turbojpeg = "1.3"
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 = "0.2"
audiopus = { version = "0.2", optional = true }
[target.'cfg(target_os = "linux")'.dependencies]
# Utilities
nix = { version = "0.31", default-features = false, features = ["fs", "socket", "net", "hostname", "poll"], optional = true }
[target.'cfg(unix)'.dependencies]
# Video capture (V4L2)
v4l2r = "0.0.7"
v4l2r = { path = "libs/v4l2r", optional = true }
# Audio (ALSA capture)
alsa = "0.11"
alsa = { version = "0.11", optional = true }
# ATX (GPIO control)
gpio-cdev = "0.6"
gpio-cdev = { version = "0.6", optional = true }
[target.'cfg(windows)'.dependencies]
cpal = { version = "0.17", default-features = false }
cpal = { version = "0.18", default-features = false, optional = true }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
@@ -129,10 +198,7 @@ windows-sys = { version = "0.61", features = [
"Win32_Networking_WinSock",
"Win32_System_SystemInformation",
"Win32_System_Threading",
] }
[dev-dependencies]
tempfile = "3"
], optional = true }
[build-dependencies]
protobuf-codegen = "3.7"

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)** - 提供免登录下载服务

View File

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

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

@@ -21,16 +21,21 @@ build_arch() {
case "${CHINAMIRRO:-}" in
1|true|TRUE|yes|YES|on|ON)
local cross_build_opts="${CROSS_BUILD_OPTS:+$CROSS_BUILD_OPTS }--build-arg CHINAMIRRO=1"
echo "=== China mirror acceleration: enabled (Tsinghua) ==="
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:11}"
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=tuna \
CARGO_SOURCE_TUNA_REGISTRY=sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/ \
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 \
RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup \
RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup \
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
;;
@@ -66,7 +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 Tsinghua mirrors"
echo " CHINAMIRRO=1 $0 arm64 # Build with China mirrors"
exit 0
;;
*)
@@ -83,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,18 +1,28 @@
# Cross-compilation image for ARM64 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
FROM debian:11
ARG DEBIAN_IMAGE=debian:11
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
# Optionally use Tsinghua mirrors for builds in China.
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
sed -i -E \
-e 's|http://deb.debian.org/debian([[:space:]])|http://mirrors.tuna.tsinghua.edu.cn/debian\1|g' \
/etc/apt/sources.list; \
fi
@@ -21,19 +31,23 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
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 = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
"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/*
@@ -69,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 \
libssl1.1 \
libssl1.1:arm64 \
libasound2-dev:arm64 \
libv4l-dev:arm64 \
libudev-dev:arm64 \
@@ -78,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 \
@@ -104,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 \
@@ -113,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++ \
@@ -143,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 \
@@ -159,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 \
@@ -198,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 \
@@ -211,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 .. \
@@ -232,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 \
@@ -259,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 \
@@ -348,8 +394,8 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
# Add Rust target
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
export RUSTUP_DIST_SERVER=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
fi \
&& rustup target add aarch64-unknown-linux-gnu
@@ -365,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,18 +1,28 @@
# Cross-compilation image for ARMv7 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
FROM debian:11
ARG DEBIAN_IMAGE=debian:11
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
# Optionally use Tsinghua mirrors for builds in China.
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
sed -i -E \
-e 's|http://deb.debian.org/debian([[:space:]])|http://mirrors.tuna.tsinghua.edu.cn/debian\1|g' \
/etc/apt/sources.list; \
fi
@@ -21,19 +31,23 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
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 = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
"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/*
@@ -69,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 \
libssl1.1 \
libssl1.1:armhf \
libasound2-dev:armhf \
libv4l-dev:armhf \
libudev-dev:armhf \
@@ -77,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 \
@@ -103,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 \
@@ -112,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 \
@@ -135,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 \
@@ -152,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 \
@@ -187,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 \
@@ -200,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 .. \
@@ -221,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 \
@@ -248,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 \
@@ -337,8 +383,8 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
# Add Rust target
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
export RUSTUP_DIST_SERVER=${RUSTUP_DIST_SERVER_CN}; \
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
fi \
&& rustup target add armv7-unknown-linux-gnueabihf
@@ -354,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,18 +1,26 @@
# Cross-compilation image for x86_64 based on Debian 11
# Build on Debian 11 (GLIBC 2.31) for maximum runtime compatibility
FROM debian:11
ARG DEBIAN_IMAGE=debian:11
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
# Optionally use Tsinghua mirrors for builds in China.
# Optionally use China mirrors for builds in China.
RUN if [ "$CHINAMIRRO" = "1" ]; then \
sed -i \
-e 's|http://deb.debian.org/debian|http://mirrors.tuna.tsinghua.edu.cn/debian|g' \
-e 's|http://security.debian.org/debian-security|http://mirrors.tuna.tsinghua.edu.cn/debian-security|g' \
sed -i -E \
-e 's|http://deb.debian.org/debian([[:space:]])|http://mirrors.tuna.tsinghua.edu.cn/debian\1|g' \
/etc/apt/sources.list; \
fi
@@ -21,19 +29,23 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
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 = 'tuna'" \
'[source.tuna]' \
'registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
'[registries.tuna]' \
'index = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"' \
"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/*
@@ -76,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) \
@@ -125,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 \
@@ -155,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 \
@@ -242,8 +281,8 @@ RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
# Add Rust target
RUN if [ "$CHINAMIRRO" = "1" ]; then \
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup; \
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup; \
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

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
Wants=network-online.target
[Service]

View File

@@ -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.31), 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"

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

@@ -21,11 +21,12 @@ fn build_common(builder: &mut Build) {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let common_dir = manifest_dir.join("cpp").join("common");
bindgen::builder()
let 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"))
@@ -71,9 +72,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())
@@ -161,7 +162,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
@@ -170,13 +171,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);
}
}
@@ -235,12 +234,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);
@@ -335,7 +328,10 @@ mod ffmpeg {
return;
}
println!("cargo:warning=Windows QSV support library not found in {}", lib_dir.display());
println!(
"cargo:warning=Windows QSV support library not found in {}",
lib_dir.display()
);
}
fn link_os() {
@@ -376,9 +372,8 @@ mod ffmpeg {
let ffi_header_path = ffmpeg_ram_dir.join("ffmpeg_ffi.h");
println!("cargo:rerun-if-changed={}", ffi_header_path.display());
let ffi_header = ffi_header_path.to_string_lossy().to_string();
bindgen::builder()
.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"))
@@ -392,9 +387,8 @@ mod ffmpeg {
.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"))
@@ -409,6 +403,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 {}",
@@ -431,7 +428,7 @@ mod ffmpeg {
.to_string();
bindgen::builder()
.header(capture_header)
.rustified_enum("*")
.rustified_enum(".*")
.generate()
.unwrap()
.write_to_file(
@@ -454,7 +451,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"))

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,90 @@ 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_amlogic_platform = [&]() -> bool {
const char *platform_hints[] = {
"amlogic",
"meson",
"gxl",
"gxbb",
"gxm",
"g12a",
"g12b",
"sm1",
};
const char *platform_files[] = {
"/proc/device-tree/compatible",
"/proc/device-tree/model",
"/sys/firmware/devicetree/base/compatible",
"/sys/firmware/devicetree/base/model",
};
for (size_t i = 0; i < sizeof(platform_files) / sizeof(platform_files[0]); i++) {
std::string value;
if (read_text_file(platform_files[i], &value) &&
contains_any(to_lower(value), platform_hints,
sizeof(platform_hints) / sizeof(platform_hints[0]))) {
return true;
}
}
const char *video_nodes[] = {
"video0",
"video1",
"video2",
"video10",
"video11",
"video32",
};
const char *vdec_hints[] = {
"meson",
"amlogic",
"vdec",
"decoder",
"video-decoder",
"gxl-vdec",
"gx-vdec",
};
for (size_t i = 0; i < sizeof(video_nodes) / sizeof(video_nodes[0]); i++) {
std::string name;
std::string modalias;
const std::string base = std::string("/sys/class/video4linux/") + video_nodes[i];
if (read_text_file((base + "/name").c_str(), &name) &&
contains_any(to_lower(name), vdec_hints, sizeof(vdec_hints) / sizeof(vdec_hints[0]))) {
return true;
}
if (read_text_file((base + "/device/modalias").c_str(), &modalias) &&
contains_any(to_lower(modalias), vdec_hints,
sizeof(vdec_hints) / sizeof(vdec_hints[0]))) {
return true;
}
}
return false;
};
const bool amlogic_platform = is_amlogic_platform();
if (amlogic_platform && !v4l2m2m_allowed()) {
LOG_WARN(std::string(
"V4L2 M2M: skipped probe on Amlogic platform; set ONE_KVM_V4L2M2M_ALLOW=1 to enable"));
return -1;
}
if (amlogic_platform) {
LOG_WARN(std::string("V4L2 M2M: ONE_KVM_V4L2M2M_ALLOW is set; probing Amlogic video nodes"));
}
// Check common V4L2 M2M device paths used by various ARM SoCs
// /dev/video10 - Standard on many SoCs
// /dev/video11 - Standard on many SoCs (often decoder)
@@ -179,13 +239,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

@@ -24,7 +24,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;
@@ -37,7 +37,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;
@@ -305,23 +305,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;
@@ -377,6 +360,25 @@ struct CodecOptions {
bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
int q) {
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;
@@ -384,9 +386,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"}}},
};
@@ -401,13 +400,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;
}

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,13 @@ 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;
LOG_ERROR(message);
}
static int calculate_offset_length(int pix_fmt, int height, const int *linesize,
int *offset, int *length) {
switch (pix_fmt) {
@@ -112,6 +120,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 +130,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 +144,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 +153,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 +189,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 +258,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 +273,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 +304,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 +320,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_);
@@ -376,101 +387,203 @@ private:
frame->pict_type = AV_PICTURE_TYPE_NONE;
}
if ((ret = avcodec_send_frame(c_, frame)) < 0) {
ret = avcodec_send_frame(c_, frame);
if (ret == AVERROR(EAGAIN)) {
int drain_ret = receive_available_packets(obj, encoded);
if (drain_ret < 0) {
return drain_ret;
}
ret = avcodec_send_frame(c_, frame);
}
if (ret == AVERROR(EAGAIN)) {
return encoded ? 0 : AVERROR(EAGAIN);
}
if (ret < 0) {
LOG_ERROR(std::string("avcodec_send_frame failed, ret = ") + av_err2str(ret));
return ret;
}
auto start = util::now();
while (ret >= 0 && util::elapsed_ms(start) < DECODE_TIMEOUT_MS) {
if ((ret = avcodec_receive_packet(c_, pkt_)) < 0) {
if (ret != AVERROR(EAGAIN)) {
LOG_ERROR(std::string("avcodec_receive_packet failed, ret = ") + av_err2str(ret));
ret = receive_available_packets(obj, encoded);
if (ret < 0) {
return 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);
}
_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 +592,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) {
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_WARN(std::string("VAAPI bitrate-based rate control failed for ") +
name + ", retrying with CQP");
encoder = try_create(RC_CQ, 0);
if (encoder) {
if (encoder->init(linesize, offset, length)) {
return encoder;
}
}
@@ -532,6 +686,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 +723,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,

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.
@@ -304,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,13 +343,12 @@ fn log_failed_probe_attempt(
}
fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> bool {
use log::debug;
use log::{debug, warn};
debug!("Testing encoder: {}", codec.name);
let test_ctx = EncodeContext {
name: codec.name.clone(),
mc_name: codec.mc_name.clone(),
..ctx.clone()
};
@@ -390,7 +395,7 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
}
Err(err) => {
last_err = Some(err);
debug!(
warn!(
"Encoder {} test attempt {} returned error: {}",
codec.name, attempt_no, err
);
@@ -408,7 +413,7 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
false
}
Err(_) => {
debug!("Failed to create encoder {}", codec.name);
warn!("Failed to create encoder {}", codec.name);
false
}
}
@@ -431,7 +436,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,
@@ -451,6 +455,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)
@@ -483,10 +520,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,
@@ -506,6 +541,10 @@ impl Encoder {
);
if codec.is_null() {
let message = encoder_last_error_message();
if !message.is_empty() {
log::error!("ffmpeg_ram_new_encoder failed: {}", message);
}
return Err(());
}
@@ -543,6 +582,25 @@ impl Encoder {
}
}
#[cfg(feature = "bytes")]
pub fn encode_bytes(&mut self, data: &[u8], ms: i64) -> Result<Vec<EncodeBytesFrame>, i32> {
unsafe {
let mut frames = Vec::<EncodeBytesFrame>::new();
let result = ffmpeg_ram_encode_packet(
self.codec,
data.as_ptr(),
data.len() as _,
&mut frames as *mut _ as *const c_void,
ms,
Some(Encoder::packet_callback),
);
if result == -11 || result == 0 {
return Ok(frames);
}
Err(result)
}
}
extern "C" fn callback(data: *const u8, size: c_int, pts: i64, key: i32, obj: *const c_void) {
unsafe {
let frames = &mut *(obj as *mut Vec<EncodeFrame>);
@@ -554,6 +612,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 {
@@ -626,6 +708,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 _,

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);
}
}

View File

@@ -8,4 +8,4 @@ license = "BSD-3-Clause"
[dependencies]
[build-dependencies]
bindgen = "0.59"
bindgen = "0.72"

View File

@@ -19,9 +19,9 @@ fn main() {
fn generate_bindings(cpp_dir: &Path) {
let ffi_header = cpp_dir.join("yuv_ffi.h");
let builder = bindgen::builder().header(ffi_header.to_string_lossy().to_string());
bindgen::builder()
.header(ffi_header.to_string_lossy().to_string())
builder
// YUYV conversions
.allowlist_function("YUY2ToI420")
.allowlist_function("YUY2ToNV12")
@@ -38,6 +38,7 @@ fn generate_bindings(cpp_dir: &Path) {
// NV12/NV21 conversions
.allowlist_function("NV12ToI420")
.allowlist_function("NV21ToI420")
.allowlist_function("NV21ToNV12")
.allowlist_function("NV12Copy")
.allowlist_function("SplitUVPlane")
// ARGB/BGRA conversions
@@ -49,6 +50,7 @@ fn generate_bindings(cpp_dir: &Path) {
.allowlist_function("ABGRToARGB")
// RGB24/BGR24 conversions
.allowlist_function("RGB24ToI420")
.allowlist_function("RGB24ToNV12")
.allowlist_function("RAWToI420")
.allowlist_function("RGB24ToARGB")
.allowlist_function("RAWToARGB")
@@ -62,6 +64,9 @@ fn generate_bindings(cpp_dir: &Path) {
.allowlist_function("UYVYToARGB")
.allowlist_function("ARGBToRGB24")
.allowlist_function("ARGBToRAW")
// MJPEG decoding
.allowlist_function("MJPGToNV12")
.allowlist_function("MJPGSize")
// Scaling
.allowlist_function("I420Scale")
.allowlist_function("NV12Scale")
@@ -81,6 +86,21 @@ fn generate_bindings(cpp_dir: &Path) {
}
fn link_libyuv() {
println!("cargo:rerun-if-env-changed=ONE_KVM_LIBS_PATH");
println!("cargo:rerun-if-env-changed=LIBYUV_STATIC");
// An explicit library root must take precedence over host discovery.
if env::var("ONE_KVM_LIBS_PATH")
.ok()
.is_some_and(|path| !path.trim().is_empty())
{
if link_system() {
return;
}
panic!("libyuv not found under ONE_KVM_LIBS_PATH");
}
// Try vcpkg first
if let Some(vcpkg_installed) = vcpkg_installed_root() {
if link_vcpkg(vcpkg_installed) {
@@ -169,14 +189,17 @@ fn link_vcpkg(mut path: PathBuf) -> bool {
if use_static && static_lib.exists() {
// Static linking (for deb packaging)
println!("cargo:rustc-link-lib=static=yuv");
#[cfg(target_os = "linux")]
link_libjpeg_for_static_libyuv(&[lib_path.clone()], &target_os);
if target_os == "linux" {
println!("cargo:rustc-link-lib=stdc++");
}
println!("cargo:info=Using libyuv from vcpkg (static linking)");
} else {
// Dynamic linking (default for development)
println!("cargo:rustc-link-lib=yuv");
#[cfg(target_os = "linux")]
if target_os == "linux" {
println!("cargo:rustc-link-lib=stdc++");
}
println!("cargo:info=Using libyuv from vcpkg (dynamic linking)");
}
@@ -224,9 +247,13 @@ fn link_system() -> bool {
// Build custom library paths based on target architecture:
// 1. Check ONE_KVM_LIBS_PATH environment variable (explicit override)
// 2. Fall back to architecture-based detection
let custom_lib_path = if let Ok(path) = env::var("ONE_KVM_LIBS_PATH") {
format!("{}/lib", path)
} else {
let explicit_lib_root = env::var("ONE_KVM_LIBS_PATH")
.ok()
.filter(|path| !path.trim().is_empty());
let custom_lib_path = explicit_lib_root
.as_ref()
.map(|path| format!("{}/lib", path))
.unwrap_or_else(|| {
match target_arch.as_str() {
"x86_64" => "/usr/local/lib",
"aarch64" => "/usr/aarch64-linux-gnu/lib",
@@ -234,7 +261,7 @@ fn link_system() -> bool {
_ => "",
}
.to_string()
};
});
// Try common system library paths (custom paths first)
let mut lib_paths: Vec<String> = Vec::new();
@@ -244,7 +271,8 @@ fn link_system() -> bool {
lib_paths.push(custom_lib_path);
}
// Then standard paths
// An explicit root is strict: do not silently fall back to host libraries.
if explicit_lib_root.is_none() {
lib_paths.extend(
[
"/usr/local/lib", // Custom builds
@@ -258,6 +286,7 @@ fn link_system() -> bool {
.iter()
.map(|s| s.to_string()),
);
}
for path in &lib_paths {
let lib_path = Path::new(path);
@@ -268,6 +297,7 @@ fn link_system() -> bool {
if use_static && libyuv_static.exists() {
println!("cargo:rustc-link-search=native={}", path);
println!("cargo:rustc-link-lib=static=yuv");
link_libjpeg_for_static_libyuv(&[lib_path.to_path_buf()], "linux");
println!("cargo:rustc-link-lib=stdc++");
println!(
"cargo:info=Using system libyuv from {} (static linking)",
@@ -294,3 +324,58 @@ fn link_system() -> bool {
false
}
fn link_libjpeg_for_static_libyuv(preferred_lib_dirs: &[PathBuf], target_os: &str) {
if target_os != "linux" {
return;
}
println!("cargo:rerun-if-env-changed=ONE_KVM_LIBJPEG_DIR");
let mut lib_dirs = Vec::new();
if let Ok(path) = env::var("ONE_KVM_LIBJPEG_DIR") {
if !path.trim().is_empty() {
lib_dirs.push(PathBuf::from(path));
}
}
lib_dirs.extend(preferred_lib_dirs.iter().cloned());
lib_dirs.extend(
[
"/usr/local/lib",
"/usr/local/lib64",
"/usr/lib",
"/usr/lib64",
"/usr/lib/x86_64-linux-gnu",
"/usr/lib/aarch64-linux-gnu",
"/usr/lib/arm-linux-gnueabihf",
"/usr/aarch64-linux-gnu/lib",
"/usr/arm-linux-gnueabihf/lib",
]
.iter()
.map(PathBuf::from),
);
for lib_dir in dedupe_paths(lib_dirs) {
if lib_dir.join("libjpeg.a").exists() {
println!("cargo:rustc-link-search=native={}", lib_dir.display());
println!("cargo:rustc-link-lib=static=jpeg");
println!(
"cargo:info=Using libjpeg for static libyuv MJPEG from {}",
lib_dir.display()
);
return;
}
}
println!("cargo:warning=libjpeg.a not found; static libyuv built with MJPEG may fail to link");
}
fn dedupe_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
let mut deduped = Vec::new();
for path in paths {
if !deduped.iter().any(|existing| existing == &path) {
deduped.push(path);
}
}
deduped
}

View File

@@ -103,6 +103,13 @@ int NV21ToI420(const uint8_t* src_y, int src_stride_y,
uint8_t* dst_v, int dst_stride_v,
int width, int height);
// NV21 -> NV12
int NV21ToNV12(const uint8_t* src_y, int src_stride_y,
const uint8_t* src_vu, int src_stride_vu,
uint8_t* dst_y, int dst_stride_y,
uint8_t* dst_uv, int dst_stride_uv,
int width, int height);
// Split interleaved UV plane into separate U and V planes
void SplitUVPlane(const uint8_t* src_uv, int src_stride_uv,
uint8_t* dst_u, int dst_stride_u,
@@ -167,6 +174,12 @@ int RAWToI420(const uint8_t* src_raw, int src_stride_raw,
uint8_t* dst_v, int dst_stride_v,
int width, int height);
// BGR24 -> NV12
int RGB24ToNV12(const uint8_t* src_rgb24, int src_stride_rgb24,
uint8_t* dst_y, int dst_stride_y,
uint8_t* dst_uv, int dst_stride_uv,
int width, int height);
// RGB24 -> ARGB
int RGB24ToARGB(const uint8_t* src_rgb24, int src_stride_rgb24,
uint8_t* dst_argb, int dst_stride_argb,
@@ -253,12 +266,6 @@ int MJPGToNV12(const uint8_t* sample, size_t sample_size,
int src_width, int src_height,
int dst_width, int dst_height);
// MJPEG -> ARGB
int MJPGToARGB(const uint8_t* sample, size_t sample_size,
uint8_t* dst_argb, int dst_stride_argb,
int src_width, int src_height,
int dst_width, int dst_height);
// Get MJPEG dimensions without decoding
int MJPGSize(const uint8_t* sample, size_t sample_size,
int* width, int* height);

View File

@@ -32,17 +32,9 @@ use std::fmt;
// Include auto-generated FFI bindings
include!(concat!(env!("OUT_DIR"), "/yuv_ffi.rs"));
// Type alias for C's size_t - adapts to platform pointer width
#[cfg(target_pointer_width = "32")]
type SizeT = u32;
#[cfg(target_pointer_width = "64")]
type SizeT = u64;
// Helper function to convert usize to C's size_t type
#[inline]
fn usize_to_size_t(val: usize) -> SizeT {
val as SizeT
fn usize_to_size_t(val: usize) -> usize {
val
}
// ============================================================================
@@ -522,6 +514,34 @@ pub fn nv21_to_i420(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Resu
))
}
/// Convert NV21 to NV12 by swapping interleaved chroma bytes.
pub fn nv21_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Result<()> {
if width % 2 != 0 || height % 2 != 0 {
return Err(YuvError::InvalidDimensions);
}
let w = width as usize;
let h = height as usize;
let y_size = w * h;
if src.len() < nv12_size(w, h) || dst.len() < nv12_size(w, h) {
return Err(YuvError::BufferTooSmall);
}
call_yuv!(NV21ToNV12(
src.as_ptr(),
width,
src[y_size..].as_ptr(),
width,
dst.as_mut_ptr(),
width,
dst[y_size..].as_mut_ptr(),
width,
width,
height,
))
}
// ============================================================================
// ARGB/BGRA conversions (32-bit)
// Note: libyuv ARGB = BGRA in memory on little-endian systems
@@ -1046,7 +1066,7 @@ pub fn rgb24_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Res
i420_to_nv12(&i420_buffer, dst, width, height)
}
/// Convert BGR24 to NV12 (via two-step conversion: BGR24 → I420 → NV12)
/// Convert BGR24 to NV12.
pub fn bgr24_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Result<()> {
if width % 2 != 0 || height % 2 != 0 {
return Err(YuvError::InvalidDimensions);
@@ -1059,10 +1079,71 @@ pub fn bgr24_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Res
return Err(YuvError::BufferTooSmall);
}
// Two-step conversion: BGR24 → I420 → NV12
#[cfg(windows)]
{
let mut i420_buffer = vec![0u8; i420_size(w, h)];
bgr24_to_i420(src, &mut i420_buffer, width, height)?;
i420_to_nv12(&i420_buffer, dst, width, height)
return i420_to_nv12(&i420_buffer, dst, width, height);
}
#[cfg(not(windows))]
{
let y_size = w * h;
call_yuv!(RGB24ToNV12(
src.as_ptr(),
width * 3,
dst.as_mut_ptr(),
width,
dst[y_size..].as_mut_ptr(),
width,
width,
height,
))
}
}
/// Read MJPEG dimensions without decoding the frame.
pub fn mjpg_size(src: &[u8]) -> Result<(i32, i32)> {
let mut width = 0;
let mut height = 0;
call_yuv!(MJPGSize(
src.as_ptr(),
usize_to_size_t(src.len()),
&mut width,
&mut height,
))?;
Ok((width, height))
}
/// Decode MJPEG directly to NV12.
pub fn mjpg_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Result<()> {
if width % 2 != 0 || height % 2 != 0 {
return Err(YuvError::InvalidDimensions);
}
let w = width as usize;
let h = height as usize;
if dst.len() < nv12_size(w, h) {
return Err(YuvError::BufferTooSmall);
}
let y_size = w * h;
let (dst_y, dst_uv) = dst.split_at_mut(y_size);
call_yuv!(MJPGToNV12(
src.as_ptr(),
usize_to_size_t(src.len()),
dst_y.as_mut_ptr(),
width,
dst_uv.as_mut_ptr(),
width,
width,
height,
width,
height,
))
}
// ============================================================================
@@ -1310,4 +1391,15 @@ mod tests {
assert_eq!(converter.dimensions(), (8, 8));
assert_eq!(converter.nv12_buffer().len(), nv12_size(8, 8));
}
#[test]
fn test_bgr24_to_nv12() {
let src = [0u8; 2 * 2 * 3];
let mut dst = [0xffu8; 2 * 2 * 3 / 2];
bgr24_to_nv12(&src, &mut dst, 2, 2).unwrap();
assert_eq!(&dst[..4], &[16, 16, 16, 16]);
assert_eq!(&dst[4..], &[128, 128]);
}
}

View File

@@ -20,6 +20,9 @@ typeshare "$PROJECT_ROOT/src" \
--lang=typescript \
--output-file="$OUTPUT_FILE"
# Keep generated output stable for git diff --check.
perl -0pi -e 's/\n+\z/\n/' "$OUTPUT_FILE"
echo ""
echo "TypeScript types generated successfully!"
echo "Output: $OUTPUT_FILE"

View File

@@ -8,15 +8,22 @@ use tracing::{debug, info, warn};
use super::executor::{timing, AtxKeyExecutor};
use super::led::LedSensor;
use super::types::{AtxAction, AtxKeyConfig, AtxLedConfig, AtxState, PowerStatus};
use super::types::{
AtxAction, AtxDriverType, AtxInputBinding, AtxKeyConfig, AtxOutputBinding, AtxState, HddStatus,
PowerStatus,
};
use crate::error::{AppError, Result};
#[derive(Debug, Clone, Default)]
pub struct AtxControllerConfig {
pub enabled: bool,
pub power: AtxKeyConfig,
pub reset: AtxKeyConfig,
pub led: AtxLedConfig,
pub driver: AtxDriverType,
pub device: String,
pub baud_rate: u32,
pub power: AtxOutputBinding,
pub reset: AtxOutputBinding,
pub led: AtxInputBinding,
pub hdd: AtxInputBinding,
}
/// Grouped together to reduce lock acquisitions
@@ -25,6 +32,7 @@ struct AtxInner {
power_executor: Option<AtxKeyExecutor>,
reset_executor: Option<AtxKeyExecutor>,
led_sensor: Option<LedSensor>,
hdd_sensor: Option<LedSensor>,
}
/// Manages ATX power control through independent executors for each action.
@@ -34,14 +42,44 @@ pub struct AtxController {
}
impl AtxController {
fn should_share_serial_device(power: &AtxKeyConfig, reset: &AtxKeyConfig) -> bool {
power.is_configured()
&& reset.is_configured()
&& power.driver == super::types::AtxDriverType::Serial
&& reset.driver == super::types::AtxDriverType::Serial
&& !power.device.is_empty()
&& power.device == reset.device
&& power.baud_rate == reset.baud_rate
fn build_key_config(
config: &AtxControllerConfig,
binding: &AtxOutputBinding,
) -> Option<AtxKeyConfig> {
if !binding.is_configured_for(config.driver, &config.device) {
return None;
}
let device = match config.driver {
AtxDriverType::Gpio => binding.device.clone(),
AtxDriverType::UsbRelay | AtxDriverType::Serial => config.device.clone(),
AtxDriverType::None => return None,
};
Some(AtxKeyConfig {
driver: config.driver,
device,
pin: binding.pin,
active_level: binding.active_level,
baud_rate: config.baud_rate,
})
}
fn runtime_key_configs(
config: &AtxControllerConfig,
) -> (Option<AtxKeyConfig>, Option<AtxKeyConfig>) {
(
Self::build_key_config(config, &config.power),
Self::build_key_config(config, &config.reset),
)
}
fn should_share_serial_device(config: &AtxControllerConfig) -> bool {
if config.driver != AtxDriverType::Serial || config.device.trim().is_empty() {
return false;
}
config.power.enabled && config.reset.enabled
}
async fn init_key_executor(
@@ -63,68 +101,80 @@ impl AtxController {
}
async fn init_components(inner: &mut AtxInner) {
if Self::should_share_serial_device(&inner.config.power, &inner.config.reset) {
match AtxKeyExecutor::open_shared_serial(
&inner.config.power.device,
inner.config.power.baud_rate,
) {
let (power_config, reset_config) = Self::runtime_key_configs(&inner.config);
if Self::should_share_serial_device(&inner.config) {
match AtxKeyExecutor::open_shared_serial(&inner.config.device, inner.config.baud_rate) {
Ok(shared_serial) => {
for (slot, warn_label, info_label, config, serial) in [
(
&mut inner.power_executor,
"power",
"Power",
inner.config.power.clone(),
power_config.clone(),
shared_serial.clone(),
),
(
&mut inner.reset_executor,
"reset",
"Reset",
inner.config.reset.clone(),
reset_config.clone(),
shared_serial,
),
] {
let executor = AtxKeyExecutor::new_with_shared_serial(
config.clone(),
serial,
);
*slot = Self::init_key_executor(warn_label, info_label, config, executor)
if let Some(config) = config {
let executor =
AtxKeyExecutor::new_with_shared_serial(config.clone(), serial);
*slot =
Self::init_key_executor(warn_label, info_label, config, executor)
.await;
}
}
}
Err(e) => {
warn!(
"Failed to open shared serial device {} for ATX power/reset: {}",
inner.config.power.device, e
inner.config.device, e
);
}
}
} else {
for (slot, warn_label, info_label, config) in [
(&mut inner.power_executor, "power", "Power", inner.config.power.clone()),
(&mut inner.reset_executor, "reset", "Reset", inner.config.reset.clone()),
(&mut inner.power_executor, "power", "Power", power_config),
(&mut inner.reset_executor, "reset", "Reset", reset_config),
] {
if config.is_configured() {
if let Some(config) = config {
let executor = AtxKeyExecutor::new(config.clone());
*slot = Self::init_key_executor(warn_label, info_label, config, executor)
.await;
*slot = Self::init_key_executor(warn_label, info_label, config, executor).await;
}
}
}
if inner.config.led.is_configured() {
if inner.config.driver == AtxDriverType::Gpio && inner.config.led.is_configured() {
let mut sensor = LedSensor::new(inner.config.led.clone());
if let Err(e) = sensor.init().await {
warn!("Failed to initialize LED sensor: {}", e);
} else {
info!(
"LED sensor initialized on {} pin {}",
inner.config.led.gpio_chip, inner.config.led.gpio_pin
inner.config.led.device, inner.config.led.pin
);
inner.led_sensor = Some(sensor);
}
}
if inner.config.driver == AtxDriverType::Gpio && inner.config.hdd.is_configured() {
let mut sensor = LedSensor::new(inner.config.hdd.clone());
if let Err(e) = sensor.init().await {
warn!("Failed to initialize HDD sensor: {}", e);
} else {
info!(
"HDD sensor initialized on {} pin {}",
inner.config.hdd.device, inner.config.hdd.pin
);
inner.hdd_sensor = Some(sensor);
}
}
}
async fn shutdown_components(inner: &mut AtxInner) {
@@ -146,6 +196,13 @@ impl AtxController {
}
}
inner.led_sensor = None;
if let Some(sensor) = inner.hdd_sensor.as_mut() {
if let Err(e) = sensor.shutdown().await {
warn!("Failed to shutdown HDD sensor: {}", e);
}
}
inner.hdd_sensor = None;
}
async fn read_power_status(sensor: Option<&LedSensor>) -> PowerStatus {
@@ -162,6 +219,21 @@ impl AtxController {
}
}
async fn read_hdd_status(sensor: Option<&LedSensor>) -> HddStatus {
let Some(sensor) = sensor else {
return HddStatus::Unknown;
};
match sensor.read_active().await {
Ok(true) => HddStatus::Active,
Ok(false) => HddStatus::Inactive,
Err(e) => {
debug!("Failed to read ATX HDD sensor: {}", e);
HddStatus::Unknown
}
}
}
pub fn new(config: AtxControllerConfig) -> Self {
Self {
inner: RwLock::new(AtxInner {
@@ -169,6 +241,7 @@ impl AtxController {
power_executor: None,
reset_executor: None,
led_sensor: None,
hdd_sensor: None,
}),
}
}
@@ -229,11 +302,13 @@ impl AtxController {
};
let Some(executor) = executor else {
return Err(AppError::Config(match action {
return Err(AppError::Config(
match action {
AtxAction::Reset => "Reset button not configured for ATX controller",
_ => "Power button not configured for ATX controller",
}
.to_string()));
.to_string(),
));
};
executor.pulse(duration).await?;
@@ -261,13 +336,21 @@ impl AtxController {
let inner = self.inner.read().await;
let power_status = Self::read_power_status(inner.led_sensor.as_ref()).await;
let hdd_status = Self::read_hdd_status(inner.hdd_sensor.as_ref()).await;
AtxState {
available: inner.config.enabled,
driver: if inner.config.enabled {
inner.config.driver
} else {
AtxDriverType::None
},
power_configured: inner.power_executor.is_some(),
reset_configured: inner.reset_executor.is_some(),
power_status,
led_supported: inner.led_sensor.is_some(),
hdd_status,
hdd_supported: inner.hdd_sensor.is_some(),
}
}
}
@@ -275,45 +358,96 @@ impl AtxController {
#[cfg(test)]
mod tests {
use super::*;
use crate::atx::AtxDriverType;
use crate::atx::{AtxDriverType, AtxOutputBinding};
#[test]
fn test_should_share_serial_device_true() {
let power = AtxKeyConfig {
let config = AtxControllerConfig {
driver: AtxDriverType::Serial,
device: "/dev/ttyUSB0".to_string(),
baud_rate: 9600,
power: AtxOutputBinding {
enabled: true,
pin: 1,
active_level: super::super::types::ActiveLevel::High,
baud_rate: 9600,
};
let reset = AtxKeyConfig {
driver: AtxDriverType::Serial,
device: "/dev/ttyUSB0".to_string(),
..Default::default()
},
reset: AtxOutputBinding {
enabled: true,
pin: 2,
active_level: super::super::types::ActiveLevel::High,
baud_rate: 9600,
..Default::default()
},
..Default::default()
};
assert!(AtxController::should_share_serial_device(&power, &reset));
assert!(AtxController::should_share_serial_device(&config));
}
#[test]
fn test_should_share_serial_device_false_on_different_baud() {
let power = AtxKeyConfig {
fn test_should_share_serial_device_false_when_reset_disabled() {
let config = AtxControllerConfig {
driver: AtxDriverType::Serial,
device: "/dev/ttyUSB0".to_string(),
pin: 1,
active_level: super::super::types::ActiveLevel::High,
baud_rate: 9600,
};
let reset = AtxKeyConfig {
driver: AtxDriverType::Serial,
device: "/dev/ttyUSB0".to_string(),
power: AtxOutputBinding {
enabled: true,
pin: 1,
..Default::default()
},
reset: AtxOutputBinding {
enabled: false,
pin: 2,
active_level: super::super::types::ActiveLevel::High,
baud_rate: 115200,
..Default::default()
},
..Default::default()
};
assert!(!AtxController::should_share_serial_device(&power, &reset));
assert!(!AtxController::should_share_serial_device(&config));
}
#[test]
fn test_gpio_runtime_key_uses_binding_device() {
let config = AtxControllerConfig {
driver: AtxDriverType::Gpio,
device: "/dev/ignored".to_string(),
baud_rate: 9600,
power: AtxOutputBinding {
enabled: true,
device: "/dev/gpiochip1".to_string(),
pin: 4,
active_level: super::super::types::ActiveLevel::Low,
},
..Default::default()
};
let (power, reset) = AtxController::runtime_key_configs(&config);
let power = power.unwrap();
assert!(reset.is_none());
assert_eq!(power.driver, AtxDriverType::Gpio);
assert_eq!(power.device, "/dev/gpiochip1");
assert_eq!(power.pin, 4);
assert_eq!(power.active_level, super::super::types::ActiveLevel::Low);
}
#[test]
fn test_serial_runtime_key_uses_top_level_device() {
let config = AtxControllerConfig {
driver: AtxDriverType::Serial,
device: "/dev/ttyUSB0".to_string(),
baud_rate: 115200,
power: AtxOutputBinding {
enabled: true,
device: "/dev/ignored".to_string(),
pin: 3,
..Default::default()
},
..Default::default()
};
let (power, _) = AtxController::runtime_key_configs(&config);
let power = power.unwrap();
assert_eq!(power.driver, AtxDriverType::Serial);
assert_eq!(power.device, "/dev/ttyUSB0");
assert_eq!(power.pin, 3);
assert_eq!(power.baud_rate, 115200);
}
}

View File

@@ -1,14 +1,14 @@
#![allow(dead_code)]
use super::types::{AtxLedConfig, PowerStatus};
use super::types::{AtxInputBinding, PowerStatus};
use crate::error::Result;
pub struct LedSensor {
config: AtxLedConfig,
config: AtxInputBinding,
}
impl LedSensor {
pub fn new(config: AtxLedConfig) -> Self {
pub fn new(config: AtxInputBinding) -> Self {
Self { config }
}
@@ -28,6 +28,10 @@ impl LedSensor {
Ok(PowerStatus::Unknown)
}
pub async fn read_active(&self) -> Result<bool> {
Ok(false)
}
pub async fn shutdown(&mut self) -> Result<()> {
Ok(())
}

View File

@@ -1,7 +1,6 @@
use async_trait::async_trait;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::os::fd::AsRawFd;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Duration;
@@ -9,12 +8,10 @@ use tokio::time::sleep;
use tracing::{debug, info};
use super::traits::AtxKeyBackend;
use super::types::AtxKeyConfig;
use super::types::{AtxKeyConfig, LCUS_RELAY_MAX_CHANNEL};
use crate::error::{AppError, Result};
const USB_RELAY_MAX_CHANNEL: u8 = 8;
const USB_RELAY_REPORT_LEN: usize = 9;
const HIDIOCSFEATURE_9: libc::c_ulong = 0xC009_4806;
const LCUS_RELAY_COMMAND_LEN: usize = 4;
pub struct HidrawLinuxRelayBackend {
config: AtxKeyConfig,
@@ -34,13 +31,13 @@ impl HidrawLinuxRelayBackend {
fn validate_config(&self) -> Result<()> {
if self.config.pin == 0 {
return Err(AppError::Config(
"USB relay channel must be 1-based (>= 1)".to_string(),
"LCUS HID relay channel must be 1-based (>= 1)".to_string(),
));
}
if self.config.pin > USB_RELAY_MAX_CHANNEL as u32 {
if self.config.pin > LCUS_RELAY_MAX_CHANNEL as u32 {
return Err(AppError::Config(format!(
"USB HID relay channel must be <= {}",
USB_RELAY_MAX_CHANNEL
"LCUS HID relay channel must be <= {}",
LCUS_RELAY_MAX_CHANNEL
)));
}
Ok(())
@@ -49,20 +46,19 @@ impl HidrawLinuxRelayBackend {
fn send_command(&self, on: bool) -> Result<()> {
let channel = u8::try_from(self.config.pin).map_err(|_| {
AppError::Config(format!(
"USB relay channel {} exceeds max {}",
self.config.pin,
u8::MAX
"LCUS HID relay channel {} exceeds max {}",
self.config.pin, LCUS_RELAY_MAX_CHANNEL
))
})?;
if channel == 0 {
return Err(AppError::Config(
"USB relay channel must be 1-based (>= 1)".to_string(),
"LCUS HID relay channel must be 1-based (>= 1)".to_string(),
));
}
if channel > USB_RELAY_MAX_CHANNEL {
if channel > LCUS_RELAY_MAX_CHANNEL {
return Err(AppError::Config(format!(
"USB HID relay channel must be <= {}",
USB_RELAY_MAX_CHANNEL
"LCUS HID relay channel must be <= {}",
LCUS_RELAY_MAX_CHANNEL
)));
}
@@ -70,44 +66,22 @@ impl HidrawLinuxRelayBackend {
let mut guard = self.handle.lock().unwrap();
let device = guard
.as_mut()
.ok_or_else(|| AppError::Internal("USB relay not initialized".to_string()))?;
.ok_or_else(|| AppError::Internal("LCUS HID relay not initialized".to_string()))?;
if let Err(feature_err) = Self::send_feature_report(device, &cmd) {
debug!(
"USB relay feature report failed ({}), falling back to hidraw write",
feature_err
);
device.write_all(&cmd).map_err(|write_err| {
AppError::Internal(format!(
"USB relay feature report failed: {}; raw write failed: {}",
feature_err, write_err
))
})?;
device
.write_all(&cmd)
.map_err(|e| AppError::Internal(format!("LCUS HID relay write failed: {}", e)))?;
device
.flush()
.map_err(|e| AppError::Internal(format!("USB relay flush failed: {}", e)))?;
}
.map_err(|e| AppError::Internal(format!("LCUS HID relay flush failed: {}", e)))?;
Ok(())
}
pub fn build_command(channel: u8, on: bool) -> [u8; USB_RELAY_REPORT_LEN] {
let mut cmd = [0x00; USB_RELAY_REPORT_LEN];
cmd[1] = if on { 0xFF } else { 0xFD };
cmd[2] = channel;
cmd
}
fn send_feature_report(
device: &File,
report: &[u8; USB_RELAY_REPORT_LEN],
) -> std::io::Result<()> {
let rc = unsafe { libc::ioctl(device.as_raw_fd(), HIDIOCSFEATURE_9, report.as_ptr()) };
if rc < 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
pub fn build_command(channel: u8, on: bool) -> [u8; LCUS_RELAY_COMMAND_LEN] {
let state = if on { 1 } else { 0 };
let checksum = 0xA0u8.wrapping_add(channel).wrapping_add(state);
[0xA0, channel, state, checksum]
}
}
@@ -117,7 +91,7 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
self.validate_config()?;
info!(
"Initializing USB relay ATX backend on {} channel {}",
"Initializing LCUS HID relay ATX backend on {} channel {}",
self.config.device, self.config.pin
);
@@ -125,14 +99,14 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
.read(true)
.write(true)
.open(&self.config.device)
.map_err(|e| AppError::Internal(format!("USB relay device open failed: {}", e)))?;
.map_err(|e| AppError::Internal(format!("LCUS HID relay device open failed: {}", e)))?;
*self.handle.lock().unwrap() = Some(device);
self.send_command(false)?;
self.initialized.store(true, Ordering::Relaxed);
debug!(
"USB relay channel {} configured successfully",
"LCUS HID relay channel {} configured successfully",
self.config.pin
);
Ok(())
@@ -140,7 +114,9 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
async fn pulse(&self, duration: Duration) -> Result<()> {
if !self.is_initialized() {
return Err(AppError::Internal("USB relay not initialized".to_string()));
return Err(AppError::Internal(
"LCUS HID relay not initialized".to_string(),
));
}
self.send_command(true)?;
@@ -177,14 +153,14 @@ mod tests {
use super::HidrawLinuxRelayBackend;
#[test]
fn usb_relay_command_format() {
fn lcus_hid_relay_command_format() {
assert_eq!(
HidrawLinuxRelayBackend::build_command(1, true),
[0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
[0xA0, 0x01, 0x01, 0xA2]
);
assert_eq!(
HidrawLinuxRelayBackend::build_command(1, false),
[0x00, 0xFD, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
[0xA0, 0x01, 0x00, 0xA1]
);
}
}

View File

@@ -7,17 +7,17 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use tracing::{debug, info};
use super::types::{AtxLedConfig, PowerStatus};
use super::types::{ActiveLevel, AtxInputBinding, PowerStatus};
use crate::error::{AppError, Result};
pub struct LedSensor {
config: AtxLedConfig,
config: AtxInputBinding,
handle: Mutex<Option<LineHandle>>,
initialized: AtomicBool,
}
impl LedSensor {
pub fn new(config: AtxLedConfig) -> Self {
pub fn new(config: AtxInputBinding) -> Self {
Self {
config,
handle: Mutex::new(None),
@@ -33,17 +33,14 @@ impl LedSensor {
info!(
"Initializing LED sensor on {} pin {}",
self.config.gpio_chip, self.config.gpio_pin
self.config.device, self.config.pin
);
let mut chip = Chip::new(&self.config.gpio_chip)
let mut chip = Chip::new(&self.config.device)
.map_err(|e| AppError::Internal(format!("LED GPIO chip failed: {}", e)))?;
let line = chip.get_line(self.config.gpio_pin).map_err(|e| {
AppError::Internal(format!(
"LED GPIO line {} failed: {}",
self.config.gpio_pin, e
))
let line = chip.get_line(self.config.pin).map_err(|e| {
AppError::Internal(format!("LED GPIO line {} failed: {}", self.config.pin, e))
})?;
let handle = line
@@ -57,9 +54,11 @@ impl LedSensor {
Ok(())
}
pub async fn read(&self) -> Result<PowerStatus> {
pub async fn read_active(&self) -> Result<bool> {
if !self.config.is_configured() || !self.initialized.load(Ordering::Relaxed) {
return Ok(PowerStatus::Unknown);
return Err(AppError::Internal(
"GPIO input sensor not initialized".to_string(),
));
}
let guard = self.handle.lock().unwrap();
@@ -69,21 +68,30 @@ impl LedSensor {
.get_value()
.map_err(|e| AppError::Internal(format!("LED read failed: {}", e)))?;
let is_on = if self.config.inverted {
value == 0
} else {
value == 1
let active = match self.config.active_level {
ActiveLevel::High => value == 1,
ActiveLevel::Low => value == 0,
};
Ok(if is_on {
Ok(active)
}
None => Err(AppError::Internal(
"GPIO input sensor not initialized".to_string(),
)),
}
}
pub async fn read(&self) -> Result<PowerStatus> {
if !self.config.is_configured() || !self.initialized.load(Ordering::Relaxed) {
return Ok(PowerStatus::Unknown);
}
Ok(if self.read_active().await? {
PowerStatus::On
} else {
PowerStatus::Off
})
}
None => Ok(PowerStatus::Unknown),
}
}
pub async fn shutdown(&mut self) -> Result<()> {
*self.handle.lock().unwrap() = None;
@@ -105,7 +113,7 @@ mod tests {
#[test]
fn test_led_sensor_creation() {
let config = AtxLedConfig::default();
let config = AtxInputBinding::default();
let sensor = LedSensor::new(config);
assert!(!sensor.config.is_configured());
assert!(!sensor.initialized.load(Ordering::Relaxed));
@@ -113,11 +121,11 @@ mod tests {
#[test]
fn test_led_sensor_with_config() {
let config = AtxLedConfig {
let config = AtxInputBinding {
enabled: true,
gpio_chip: "/dev/gpiochip0".to_string(),
gpio_pin: 7,
inverted: false,
device: "/dev/gpiochip0".to_string(),
pin: 7,
active_level: ActiveLevel::High,
};
let sensor = LedSensor::new(config);
assert!(sensor.config.is_configured());
@@ -126,13 +134,13 @@ mod tests {
#[test]
fn test_led_sensor_inverted_config() {
let config = AtxLedConfig {
let config = AtxInputBinding {
enabled: true,
gpio_chip: "/dev/gpiochip0".to_string(),
gpio_pin: 7,
inverted: true,
device: "/dev/gpiochip0".to_string(),
pin: 7,
active_level: ActiveLevel::Low,
};
let sensor = LedSensor::new(config);
assert!(sensor.config.inverted);
assert_eq!(sensor.config.active_level, ActiveLevel::Low);
}
}

View File

@@ -24,22 +24,17 @@ mod wol;
pub use controller::{AtxController, AtxControllerConfig};
pub use executor::timing;
pub use types::{
ActiveLevel, AtxAction, AtxDevices, AtxDriverType, AtxKeyConfig, AtxLedConfig, AtxPowerRequest,
AtxState, PowerStatus,
ActiveLevel, AtxAction, AtxDevices, AtxDriverType, AtxInputBinding, AtxKeyConfig,
AtxOutputBinding, AtxPowerRequest, AtxState, HddStatus, PowerStatus, LCUS_RELAY_MAX_CHANNEL,
};
pub use wol::{list_wol_history, record_wol_history, send_wol};
#[cfg(any(unix, test))]
fn hidraw_uevent_is_usb_relay(uevent: &str) -> bool {
let upper = uevent.to_ascii_uppercase();
upper.contains("000016C0:000005DF")
|| upper.contains("00005131:00002007")
|| upper.contains("16C0:05DF")
upper.contains("00005131:00002007")
|| upper.contains("5131:2007")
|| upper.contains("PRODUCT=16C0/5DF")
|| upper.contains("PRODUCT=5131/2007")
|| upper.contains("USBRELAY")
|| upper.contains("USB RELAY")
}
#[cfg(unix)]
@@ -65,9 +60,12 @@ pub fn discover_devices() -> AtxDevices {
let name_str = name.to_string_lossy();
if name_str.starts_with("gpiochip") {
devices.gpio_chips.push(format!("/dev/{}", name_str));
} else if name_str.starts_with("hidraw") && is_usb_relay_hidraw(&name_str) {
}
#[cfg(unix)]
if name_str.starts_with("hidraw") && is_usb_relay_hidraw(&name_str) {
devices.usb_relays.push(format!("/dev/{}", name_str));
} else if name_str.starts_with("ttyUSB") || name_str.starts_with("ttyACM") {
}
if name_str.starts_with("ttyUSB") || name_str.starts_with("ttyACM") {
devices.serial_ports.push(format!("/dev/{}", name_str));
}
}
@@ -91,14 +89,14 @@ mod tests {
}
#[test]
fn test_hidraw_uevent_detects_usb_relay_id() {
assert!(hidraw_uevent_is_usb_relay(
fn test_hidraw_uevent_rejects_non_lcus_usb_relay_id() {
assert!(!hidraw_uevent_is_usb_relay(
"HID_ID=0003:000016C0:000005DF\nHID_NAME=www.dcttech.com USBRelay2\n"
));
}
#[test]
fn test_hidraw_uevent_detects_5131_usb_relay_id() {
fn test_hidraw_uevent_detects_lcus_hid_relay_id() {
assert!(hidraw_uevent_is_usb_relay(
"HID_ID=0003:00005131:00002007\n"
));
@@ -117,7 +115,8 @@ mod tests {
let _: AtxDriverType = AtxDriverType::None;
let _: ActiveLevel = ActiveLevel::High;
let _: AtxKeyConfig = AtxKeyConfig::default();
let _: AtxLedConfig = AtxLedConfig::default();
let _: AtxInputBinding = AtxInputBinding::default();
let _: AtxOutputBinding = AtxOutputBinding::default();
let _: AtxState = AtxState::default();
let _: AtxDevices = AtxDevices::default();
}

View File

@@ -7,7 +7,7 @@ use tokio::time::sleep;
use tracing::{debug, info};
use super::traits::{validate_serial_config, AtxKeyBackend, SharedSerialHandle};
use super::types::AtxKeyConfig;
use super::types::{AtxKeyConfig, LCUS_RELAY_MAX_CHANNEL};
use crate::error::{AppError, Result};
pub struct SerialRelayBackend {
@@ -44,15 +44,23 @@ impl SerialRelayBackend {
fn send_command(&self, on: bool) -> Result<()> {
let channel = u8::try_from(self.config.pin).map_err(|_| {
AppError::Config(format!(
"Serial relay channel {} exceeds max {}",
self.config.pin,
u8::MAX
"LCUS serial relay channel {} exceeds max {}",
self.config.pin, LCUS_RELAY_MAX_CHANNEL
))
})?;
if channel == 0 {
return Err(AppError::Config(
"LCUS serial relay channel must be 1-based (>= 1)".to_string(),
));
}
if channel > LCUS_RELAY_MAX_CHANNEL {
return Err(AppError::Config(format!(
"LCUS serial relay channel must be <= {}",
LCUS_RELAY_MAX_CHANNEL
)));
}
let state = if on { 1 } else { 0 };
let checksum = 0xA0u8.wrapping_add(channel).wrapping_add(state);
let cmd = [0xA0, channel, state, checksum];
let cmd = Self::build_command(channel, on);
let serial_handle = self
.serial_handle
@@ -60,16 +68,22 @@ impl SerialRelayBackend {
.unwrap()
.as_ref()
.cloned()
.ok_or_else(|| AppError::Internal("Serial relay not initialized".to_string()))?;
.ok_or_else(|| AppError::Internal("LCUS serial relay not initialized".to_string()))?;
let mut port = serial_handle.lock().unwrap();
port.write_all(&cmd)
.map_err(|e| AppError::Internal(format!("Serial relay write failed: {}", e)))?;
.map_err(|e| AppError::Internal(format!("LCUS serial relay write failed: {}", e)))?;
port.flush()
.map_err(|e| AppError::Internal(format!("Serial relay flush failed: {}", e)))?;
.map_err(|e| AppError::Internal(format!("LCUS serial relay flush failed: {}", e)))?;
Ok(())
}
pub fn build_command(channel: u8, on: bool) -> [u8; 4] {
let state = if on { 1 } else { 0 };
let checksum = 0xA0u8.wrapping_add(channel).wrapping_add(state);
[0xA0, channel, state, checksum]
}
}
#[async_trait]
@@ -78,7 +92,7 @@ impl AtxKeyBackend for SerialRelayBackend {
validate_serial_config(&self.config)?;
info!(
"Initializing Serial relay ATX backend on {} channel {}",
"Initializing LCUS serial relay ATX backend on {} channel {}",
self.config.device, self.config.pin
);
@@ -92,7 +106,7 @@ impl AtxKeyBackend for SerialRelayBackend {
self.initialized.store(true, Ordering::Relaxed);
debug!(
"Serial relay channel {} configured successfully",
"LCUS serial relay channel {} configured successfully",
self.config.pin
);
Ok(())
@@ -101,12 +115,12 @@ impl AtxKeyBackend for SerialRelayBackend {
async fn pulse(&self, duration: Duration) -> Result<()> {
if !self.is_initialized() {
return Err(AppError::Internal(
"Serial relay not initialized".to_string(),
"LCUS serial relay not initialized".to_string(),
));
}
info!(
"Pulse serial relay on {} pin {}",
"Pulse LCUS serial relay on {} channel {}",
self.config.device, self.config.pin
);
self.send_command(true)?;
@@ -131,6 +145,23 @@ impl AtxKeyBackend for SerialRelayBackend {
}
}
#[cfg(test)]
mod tests {
use super::SerialRelayBackend;
#[test]
fn lcus_serial_relay_command_format() {
assert_eq!(
SerialRelayBackend::build_command(1, true),
[0xA0, 0x01, 0x01, 0xA2]
);
assert_eq!(
SerialRelayBackend::build_command(1, false),
[0xA0, 0x01, 0x00, 0xA1]
);
}
}
impl Drop for SerialRelayBackend {
fn drop(&mut self) {
if self.is_initialized() {

View File

@@ -3,7 +3,7 @@ use serialport::SerialPort;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::types::AtxKeyConfig;
use super::types::{AtxKeyConfig, LCUS_RELAY_MAX_CHANNEL};
use crate::error::Result;
pub type SharedSerialHandle = Arc<Mutex<Box<dyn SerialPort>>>;
@@ -36,10 +36,10 @@ pub fn validate_serial_config(config: &AtxKeyConfig) -> Result<()> {
"Serial ATX channel must be 1-based (>= 1)".to_string(),
));
}
if config.pin > u8::MAX as u32 {
if config.pin > LCUS_RELAY_MAX_CHANNEL as u32 {
return Err(crate::error::AppError::Config(format!(
"Serial ATX channel must be <= {}",
u8::MAX
"LCUS serial relay channel must be <= {}",
LCUS_RELAY_MAX_CHANNEL
)));
}
if config.baud_rate == 0 {

View File

@@ -1,11 +1,12 @@
//! ATX data types and structures
//!
//! Defines the configuration and state types for the flexible ATX power control system.
//! Each ATX action (power, reset) can be independently configured with different hardware.
//! Defines the configuration and state types for the ATX power control system.
use serde::{Deserialize, Serialize};
use typeshare::typeshare;
pub const LCUS_RELAY_MAX_CHANNEL: u8 = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PowerStatus {
@@ -15,6 +16,15 @@ pub enum PowerStatus {
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum HddStatus {
Active,
Inactive,
#[default]
Unknown,
}
#[typeshare]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
@@ -36,6 +46,56 @@ pub enum ActiveLevel {
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct AtxOutputBinding {
pub enabled: bool,
pub device: String,
pub pin: u32,
pub active_level: ActiveLevel,
}
impl Default for AtxOutputBinding {
fn default() -> Self {
Self {
enabled: false,
device: String::new(),
pin: 1,
active_level: ActiveLevel::High,
}
}
}
impl AtxOutputBinding {
pub fn is_configured_for(&self, driver: AtxDriverType, top_level_device: &str) -> bool {
if !self.enabled || driver == AtxDriverType::None {
return false;
}
match driver {
AtxDriverType::Gpio => !self.device.trim().is_empty(),
AtxDriverType::UsbRelay | AtxDriverType::Serial => !top_level_device.trim().is_empty(),
AtxDriverType::None => false,
}
}
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(default)]
pub struct AtxInputBinding {
pub enabled: bool,
pub device: String,
pub pin: u32,
pub active_level: ActiveLevel,
}
impl AtxInputBinding {
pub fn is_configured(&self) -> bool {
self.enabled && !self.device.trim().is_empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct AtxKeyConfig {
@@ -64,29 +124,16 @@ impl AtxKeyConfig {
}
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(default)]
pub struct AtxLedConfig {
pub enabled: bool,
pub gpio_chip: String,
pub gpio_pin: u32,
pub inverted: bool,
}
impl AtxLedConfig {
pub fn is_configured(&self) -> bool {
self.enabled && !self.gpio_chip.is_empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AtxState {
pub available: bool,
pub driver: AtxDriverType,
pub power_configured: bool,
pub reset_configured: bool,
pub power_status: PowerStatus,
pub led_supported: bool,
pub hdd_status: HddStatus,
pub hdd_supported: bool,
}
#[derive(Debug, Clone, Deserialize)]
@@ -139,6 +186,29 @@ mod tests {
assert_eq!(ActiveLevel::default(), ActiveLevel::High);
}
#[test]
fn test_atx_output_binding_default() {
let config = AtxOutputBinding::default();
assert!(!config.enabled);
assert!(config.device.is_empty());
assert_eq!(config.pin, 1);
assert!(!config.is_configured_for(AtxDriverType::Gpio, ""));
}
#[test]
fn test_atx_output_binding_is_configured() {
let mut config = AtxOutputBinding::default();
assert!(!config.is_configured_for(AtxDriverType::Gpio, ""));
config.enabled = true;
assert!(!config.is_configured_for(AtxDriverType::Gpio, ""));
config.device = "/dev/gpiochip0".to_string();
assert!(config.is_configured_for(AtxDriverType::Gpio, ""));
assert!(!config.is_configured_for(AtxDriverType::Serial, ""));
assert!(config.is_configured_for(AtxDriverType::Serial, "/dev/ttyUSB0"));
}
#[test]
fn test_atx_key_config_default() {
let config = AtxKeyConfig::default();
@@ -149,37 +219,22 @@ mod tests {
}
#[test]
fn test_atx_key_config_is_configured() {
let mut config = AtxKeyConfig::default();
assert!(!config.is_configured());
config.driver = AtxDriverType::Gpio;
assert!(!config.is_configured());
config.device = "/dev/gpiochip0".to_string();
assert!(config.is_configured());
config.driver = AtxDriverType::None;
assert!(!config.is_configured());
}
#[test]
fn test_atx_led_config_default() {
let config = AtxLedConfig::default();
fn test_atx_input_binding_default() {
let config = AtxInputBinding::default();
assert!(!config.enabled);
assert!(config.gpio_chip.is_empty());
assert!(config.device.is_empty());
assert!(!config.is_configured());
}
#[test]
fn test_atx_led_config_is_configured() {
let mut config = AtxLedConfig::default();
fn test_atx_input_binding_is_configured() {
let mut config = AtxInputBinding::default();
assert!(!config.is_configured());
config.enabled = true;
assert!(!config.is_configured());
config.gpio_chip = "/dev/gpiochip0".to_string();
config.device = "/dev/gpiochip0".to_string();
assert!(config.is_configured());
}
@@ -187,9 +242,12 @@ mod tests {
fn test_atx_state_default() {
let state = AtxState::default();
assert!(!state.available);
assert_eq!(state.driver, AtxDriverType::None);
assert!(!state.power_configured);
assert!(!state.reset_configured);
assert_eq!(state.power_status, PowerStatus::Unknown);
assert!(!state.led_supported);
assert_eq!(state.hdd_status, HddStatus::Unknown);
assert!(!state.hdd_supported);
}
}

View File

@@ -220,7 +220,7 @@ fn run_capture(
let stream = match sample_format {
SampleFormat::F32 => build_stream::<f32>(
&device,
&stream_config,
stream_config,
input_channels,
input_rate,
tx.clone(),
@@ -229,7 +229,7 @@ fn run_capture(
),
SampleFormat::I16 => build_stream::<i16>(
&device,
&stream_config,
stream_config,
input_channels,
input_rate,
tx.clone(),
@@ -238,7 +238,7 @@ fn run_capture(
),
SampleFormat::U16 => build_stream::<u16>(
&device,
&stream_config,
stream_config,
input_channels,
input_rate,
tx.clone(),
@@ -361,7 +361,7 @@ fn select_input_config(
fn build_stream<T>(
device: &cpal::Device,
config: &StreamConfig,
config: StreamConfig,
input_channels: u32,
input_rate: u32,
tx: mpsc::SyncSender<Vec<i16>>,
@@ -508,9 +508,5 @@ fn device_label(device: &cpal::Device) -> String {
device
.description()
.map(|desc| desc.to_string())
.or_else(|_| {
#[allow(deprecated)]
device.name()
})
.unwrap_or_else(|_| "Unknown WASAPI capture device".to_string())
}

View File

@@ -6,11 +6,13 @@ use tokio::sync::RwLock;
use tracing::{debug, info};
use super::capture::AudioConfig;
use super::device::{enumerate_audio_devices_with_current, find_best_audio_device, AudioDeviceInfo};
use super::device::{
enumerate_audio_devices_with_current, find_best_audio_device, AudioDeviceInfo,
};
use super::encoder::OpusFrame;
use super::monitor::AudioHealthMonitor;
use super::streamer::{AudioStreamer, AudioStreamerConfig};
use super::recovery;
use super::streamer::{AudioStreamer, AudioStreamerConfig};
use super::types::{AudioControllerConfig, AudioQuality, AudioStatus};
use crate::error::{AppError, Result};
use crate::events::EventBus;

View File

@@ -130,11 +130,11 @@ fn device_labels(device: &cpal::Device) -> DeviceLabels {
let formatted = desc.to_string();
let display = desc
.extended()
.first()
.cloned()
.next()
.map(str::to_owned)
.unwrap_or_else(|| formatted.clone());
let mut parts = vec![formatted, desc.name().to_string(), display.clone()];
parts.extend(desc.extended().iter().cloned());
parts.extend(desc.extended().map(str::to_owned));
DeviceLabels {
display,
@@ -142,10 +142,7 @@ fn device_labels(device: &cpal::Device) -> DeviceLabels {
}
}
Err(_) => {
#[allow(deprecated)]
let display = device
.name()
.unwrap_or_else(|_| "Unknown WASAPI capture device".to_string());
let display = "Unknown WASAPI capture device".to_string();
DeviceLabels {
display: display.clone(),
search_text: display,

View File

@@ -4,11 +4,11 @@ use tokio::sync::RwLock;
use tracing::{debug, info, warn};
use super::capture::AudioConfig;
use super::controller::AudioRecoveredCallback;
use super::device::{enumerate_audio_devices, AudioDeviceInfo};
use super::monitor::AudioHealthMonitor;
use super::streamer::{AudioStreamState, AudioStreamer, AudioStreamerConfig};
use super::types::AudioControllerConfig;
use super::controller::AudioRecoveredCallback;
use crate::events::{EventBus, StreamDeviceLostKind, SystemEvent};
const AUDIO_RECOVERY_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1);

View File

@@ -79,7 +79,7 @@ fn unauthorized_response(message: &str) -> Response {
fn is_public_endpoint(path: &str) -> bool {
matches!(
path,
"/" | "/auth/login" | "/health" | "/setup" | "/setup/init"
"/" | "/auth/login" | "/auth/login/totp" | "/health" | "/setup" | "/setup/init"
) || path.starts_with("/assets/")
|| path.starts_with("/static/")
|| path.ends_with(".js")

View File

@@ -1,9 +1,11 @@
pub mod middleware;
mod password;
mod session;
mod two_factor;
mod user;
pub use middleware::{auth_middleware, SESSION_COOKIE};
pub use password::{hash_password, verify_password};
pub use session::{Session, SessionStore};
pub use two_factor::{server_time_unix_ms, ChallengeInfo, EnrollmentInfo, TwoFactorService};
pub use user::{User, UserStore};

View File

@@ -39,18 +39,39 @@ impl SessionStore {
}
pub async fn create(&self, user_id: &str) -> Result<Session> {
let session = self.new_session(user_id);
let mut guard = self.inner.write().await;
guard.insert(session.id.clone(), session.clone());
Ok(session)
}
pub async fn create_for_login(
&self,
user_id: &str,
allow_multiple_sessions: bool,
) -> Result<(Session, Vec<String>)> {
let session = self.new_session(user_id);
let mut guard = self.inner.write().await;
let revoked = if allow_multiple_sessions {
Vec::new()
} else {
let ids = guard.keys().cloned().collect();
guard.clear();
ids
};
guard.insert(session.id.clone(), session.clone());
Ok((session, revoked))
}
fn new_session(&self, user_id: &str) -> Session {
let now = OffsetDateTime::now_utc();
let session = Session {
Session {
id: Uuid::new_v4().to_string(),
user_id: user_id.to_string(),
created_at: now,
expires_at: now + self.default_ttl,
data: None,
};
let mut guard = self.inner.write().await;
guard.insert(session.id.clone(), session.clone());
Ok(session)
}
}
pub async fn get(&self, session_id: &str) -> Result<Option<Session>> {
@@ -85,6 +106,17 @@ impl SessionStore {
Ok(n)
}
pub async fn delete_all_except(&self, session_id: &str) -> Result<Vec<String>> {
let mut guard = self.inner.write().await;
let revoked: Vec<String> = guard
.keys()
.filter(|id| id.as_str() != session_id)
.cloned()
.collect();
guard.retain(|id, _| id == session_id);
Ok(revoked)
}
pub async fn list_ids(&self) -> Result<Vec<String>> {
let guard = self.inner.read().await;
Ok(guard.keys().cloned().collect())
@@ -102,3 +134,38 @@ impl SessionStore {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn delete_all_except_preserves_only_current_session() {
let sessions = SessionStore::new(60);
let current = sessions.create("user").await.unwrap();
let other = sessions.create("user").await.unwrap();
let revoked = sessions.delete_all_except(&current.id).await.unwrap();
assert_eq!(revoked, vec![other.id.clone()]);
assert!(sessions.get(&current.id).await.unwrap().is_some());
assert!(sessions.get(&other.id).await.unwrap().is_none());
}
#[tokio::test]
async fn login_creation_applies_session_policy_atomically() {
let sessions = SessionStore::new(60);
let existing = sessions.create("user").await.unwrap();
let (multiple, revoked) = sessions.create_for_login("user", true).await.unwrap();
assert!(revoked.is_empty());
assert!(sessions.get(&existing.id).await.unwrap().is_some());
assert!(sessions.get(&multiple.id).await.unwrap().is_some());
let (single, mut revoked) = sessions.create_for_login("user", false).await.unwrap();
revoked.sort();
let mut expected = vec![existing.id, multiple.id];
expected.sort();
assert_eq!(revoked, expected);
assert_eq!(sessions.list_ids().await.unwrap(), vec![single.id]);
}
}

498
src/auth/two_factor.rs Normal file
View File

@@ -0,0 +1,498 @@
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use sqlx::{Pool, Sqlite};
use tokio::sync::Mutex;
use totp_rs::{Algorithm, Secret, TOTP};
use uuid::Uuid;
use crate::error::{AppError, Result};
const LOGIN_TTL: Duration = Duration::from_secs(5 * 60);
const ENROLLMENT_TTL: Duration = Duration::from_secs(10 * 60);
const FAILURE_WINDOW: Duration = Duration::from_secs(60);
const MAX_FAILURES: usize = 5;
struct LoginChallenge {
id: String,
user_id: String,
expires_at: Instant,
expires_at_unix_ms: u64,
failures: usize,
}
struct EnrollmentChallenge {
id: String,
user_id: String,
secret: Secret,
expires_at: Instant,
expires_at_unix_ms: u64,
failures: usize,
}
#[derive(Clone)]
pub struct ChallengeInfo {
pub id: String,
pub expires_at_unix_ms: u64,
}
#[derive(Clone)]
pub struct EnrollmentInfo {
pub id: String,
pub secret: String,
pub otpauth_uri: String,
pub expires_at_unix_ms: u64,
}
#[derive(Clone)]
pub struct TwoFactorService {
pool: Pool<Sqlite>,
login_challenges: std::sync::Arc<Mutex<HashMap<String, LoginChallenge>>>,
enrollment_challenges: std::sync::Arc<Mutex<HashMap<String, EnrollmentChallenge>>>,
failures: std::sync::Arc<Mutex<HashMap<String, VecDeque<Instant>>>>,
}
impl TwoFactorService {
pub fn new(pool: Pool<Sqlite>) -> Self {
Self {
pool,
login_challenges: Default::default(),
enrollment_challenges: Default::default(),
failures: Default::default(),
}
}
pub async fn is_enabled(&self, user_id: &str) -> Result<bool> {
let exists: Option<(i64,)> =
sqlx::query_as("SELECT 1 FROM user_totp_credentials WHERE user_id = ?1 LIMIT 1")
.bind(user_id)
.fetch_optional(&self.pool)
.await?;
Ok(exists.is_some())
}
pub async fn begin_login(&self, user_id: &str) -> Result<Option<ChallengeInfo>> {
if !self.is_enabled(user_id).await? {
return Ok(None);
}
let challenge = LoginChallenge {
id: Uuid::new_v4().to_string(),
user_id: user_id.to_string(),
expires_at: Instant::now() + LOGIN_TTL,
expires_at_unix_ms: expires_at_unix_ms(LOGIN_TTL),
failures: 0,
};
let info = ChallengeInfo {
id: challenge.id.clone(),
expires_at_unix_ms: challenge.expires_at_unix_ms,
};
self.login_challenges
.lock()
.await
.insert(user_id.to_string(), challenge);
Ok(Some(info))
}
pub async fn complete_login(&self, challenge_id: &str, code: &str) -> Result<String> {
validate_code_format(code)?;
let (user_id, expired) = {
let challenges = self.login_challenges.lock().await;
let challenge = challenges
.values()
.find(|challenge| challenge.id == challenge_id)
.ok_or_else(|| AppError::AuthError("TOTP challenge expired".to_string()))?;
(
challenge.user_id.clone(),
Instant::now() >= challenge.expires_at,
)
};
if expired {
self.login_challenges.lock().await.remove(&user_id);
return Err(AppError::AuthError("TOTP challenge expired".to_string()));
}
self.enforce_failure_limit(&user_id).await?;
let valid = match self.credential_secret(&user_id).await? {
Some(secret) => verify_at(&secret, code, unix_time_secs())?,
None => {
self.login_challenges.lock().await.remove(&user_id);
return Err(AppError::AuthError("TOTP challenge expired".to_string()));
}
};
if !valid {
self.record_failure(&user_id).await;
let mut challenges = self.login_challenges.lock().await;
let mut exhausted = false;
if let Some(challenge) = challenges.get_mut(&user_id) {
challenge.failures += 1;
if challenge.failures >= MAX_FAILURES {
exhausted = true;
challenges.remove(&user_id);
}
}
if exhausted {
return Err(AppError::AuthError("TOTP challenge expired".to_string()));
}
return Err(AppError::AuthError("Invalid TOTP code".to_string()));
}
let consumed = self
.login_challenges
.lock()
.await
.remove(&user_id)
.is_some_and(|challenge| challenge.id == challenge_id);
if !consumed {
return Err(AppError::AuthError("TOTP challenge expired".to_string()));
}
Ok(user_id)
}
pub async fn begin_enrollment(
&self,
session_id: &str,
user_id: &str,
username: &str,
) -> Result<EnrollmentInfo> {
if self.is_enabled(user_id).await? {
return Err(AppError::Conflict("TOTP is already enabled".to_string()));
}
let secret = Secret::generate_secret().to_encoded();
let totp = totp(&secret, username)?;
let challenge = EnrollmentChallenge {
id: Uuid::new_v4().to_string(),
user_id: user_id.to_string(),
secret,
expires_at: Instant::now() + ENROLLMENT_TTL,
expires_at_unix_ms: expires_at_unix_ms(ENROLLMENT_TTL),
failures: 0,
};
let info = EnrollmentInfo {
id: challenge.id.clone(),
secret: challenge.secret.to_string(),
otpauth_uri: totp.get_url(),
expires_at_unix_ms: challenge.expires_at_unix_ms,
};
self.enrollment_challenges
.lock()
.await
.insert(session_id.to_string(), challenge);
Ok(info)
}
pub async fn confirm_enrollment(
&self,
session_id: &str,
user_id: &str,
enrollment_id: &str,
code: &str,
) -> Result<()> {
validate_code_format(code)?;
self.enforce_failure_limit(user_id).await?;
let (secret, expired) = {
let challenges = self.enrollment_challenges.lock().await;
let challenge = challenges
.get(session_id)
.filter(|challenge| challenge.id == enrollment_id && challenge.user_id == user_id)
.ok_or_else(|| AppError::AuthError("TOTP enrollment expired".to_string()))?;
(
challenge.secret.clone(),
Instant::now() >= challenge.expires_at,
)
};
if expired {
self.enrollment_challenges.lock().await.remove(session_id);
return Err(AppError::AuthError("TOTP enrollment expired".to_string()));
}
if !verify_at(&secret, code, unix_time_secs())? {
self.record_failure(user_id).await;
let mut challenges = self.enrollment_challenges.lock().await;
let mut exhausted = false;
if let Some(challenge) = challenges.get_mut(session_id) {
challenge.failures += 1;
if challenge.failures >= MAX_FAILURES {
exhausted = true;
challenges.remove(session_id);
}
}
if exhausted {
return Err(AppError::AuthError("TOTP enrollment expired".to_string()));
}
return Err(AppError::AuthError("Invalid TOTP code".to_string()));
}
let mut transaction = self.pool.begin().await?;
let result =
sqlx::query("INSERT INTO user_totp_credentials (user_id, secret) VALUES (?1, ?2)")
.bind(user_id)
.bind(secret.to_string())
.execute(&mut *transaction)
.await;
match result {
Ok(_) => transaction.commit().await?,
Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
return Err(AppError::Conflict("TOTP is already enabled".to_string()));
}
Err(error) => return Err(error.into()),
}
self.enrollment_challenges.lock().await.remove(session_id);
Ok(())
}
pub async fn disable(&self, user_id: &str, code: &str) -> Result<()> {
validate_code_format(code)?;
self.enforce_failure_limit(user_id).await?;
let secret = self
.credential_secret(user_id)
.await?
.ok_or_else(|| AppError::Conflict("TOTP is not enabled".to_string()))?;
if !verify_at(&secret, code, unix_time_secs())? {
self.record_failure(user_id).await;
return Err(AppError::AuthError("Invalid TOTP code".to_string()));
}
let result = sqlx::query("DELETE FROM user_totp_credentials WHERE user_id = ?1")
.bind(user_id)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(AppError::Conflict("TOTP is not enabled".to_string()));
}
self.clear_user_challenges(user_id).await;
Ok(())
}
pub async fn disable_without_code(&self, user_id: &str) -> Result<bool> {
let result = sqlx::query("DELETE FROM user_totp_credentials WHERE user_id = ?1")
.bind(user_id)
.execute(&self.pool)
.await?;
self.clear_user_challenges(user_id).await;
Ok(result.rows_affected() > 0)
}
async fn credential_secret(&self, user_id: &str) -> Result<Option<Secret>> {
let row: Option<(String,)> =
sqlx::query_as("SELECT secret FROM user_totp_credentials WHERE user_id = ?1")
.bind(user_id)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|(secret,)| Secret::Encoded(secret)))
}
async fn enforce_failure_limit(&self, user_id: &str) -> Result<()> {
let now = Instant::now();
let mut failures = self.failures.lock().await;
let attempts = failures.entry(user_id.to_string()).or_default();
while attempts
.front()
.is_some_and(|attempt| now.duration_since(*attempt) >= FAILURE_WINDOW)
{
attempts.pop_front();
}
if attempts.len() >= MAX_FAILURES {
return Err(AppError::RateLimited(
"TOTP verification is temporarily limited".to_string(),
));
}
Ok(())
}
async fn record_failure(&self, user_id: &str) {
self.failures
.lock()
.await
.entry(user_id.to_string())
.or_default()
.push_back(Instant::now());
}
async fn clear_user_challenges(&self, user_id: &str) {
self.login_challenges.lock().await.remove(user_id);
self.enrollment_challenges
.lock()
.await
.retain(|_, challenge| challenge.user_id != user_id);
self.failures.lock().await.remove(user_id);
}
}
fn totp(secret: &Secret, account_name: &str) -> Result<TOTP> {
let account_name = account_name.replace(':', "_");
TOTP::new(
Algorithm::SHA1,
6,
1,
30,
secret
.to_bytes()
.map_err(|error| AppError::Internal(error.to_string()))?,
Some("One-KVM".to_string()),
account_name,
)
.map_err(|error| AppError::Internal(error.to_string()))
}
fn verify_at(secret: &Secret, code: &str, unix_time: u64) -> Result<bool> {
validate_code_format(code)?;
Ok(totp(secret, "user")?.check(code, unix_time))
}
fn validate_code_format(code: &str) -> Result<()> {
if code.len() != 6 || !code.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(AppError::BadRequest(
"TOTP code must contain exactly 6 digits".to_string(),
));
}
Ok(())
}
pub fn server_time_unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn unix_time_secs() -> u64 {
server_time_unix_ms() / 1000
}
fn expires_at_unix_ms(ttl: Duration) -> u64 {
server_time_unix_ms().saturating_add(ttl.as_millis() as u64)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::DatabasePool;
use tempfile::tempdir;
async fn test_service() -> (tempfile::TempDir, TwoFactorService, String) {
let dir = tempdir().unwrap();
let db = DatabasePool::new(&dir.path().join("test.db"))
.await
.unwrap();
db.init_schema().await.unwrap();
let user_id = "user-1".to_string();
sqlx::query("INSERT INTO users (id, username, password_hash) VALUES (?1, 'admin', 'hash')")
.bind(&user_id)
.execute(db.pool())
.await
.unwrap();
let service = TwoFactorService::new(db.clone_pool());
(dir, service, user_id)
}
async fn install_known_credential(service: &TwoFactorService, user_id: &str) -> Secret {
let secret = Secret::Raw(b"12345678901234567890".to_vec()).to_encoded();
sqlx::query("INSERT INTO user_totp_credentials (user_id, secret) VALUES (?1, ?2)")
.bind(user_id)
.bind(secret.to_string())
.execute(&service.pool)
.await
.unwrap();
secret
}
#[test]
fn accepts_rfc_vector_and_adjacent_window() {
let secret = Secret::Raw(b"12345678901234567890".to_vec());
assert!(verify_at(&secret, "287082", 59).unwrap());
let code = totp(&secret, "user").unwrap().generate(30);
assert!(verify_at(&secret, &code, 60).unwrap());
}
#[test]
fn rejects_malformed_codes() {
let secret = Secret::Raw(b"12345678901234567890".to_vec());
assert!(verify_at(&secret, "12345", 59).is_err());
assert!(verify_at(&secret, "12345x", 59).is_err());
}
#[tokio::test]
async fn login_challenges_are_replaced_expire_and_are_consumed_once() {
let (_dir, service, user_id) = test_service().await;
let secret = install_known_credential(&service, &user_id).await;
let first = service.begin_login(&user_id).await.unwrap().unwrap();
let second = service.begin_login(&user_id).await.unwrap().unwrap();
let code = totp(&secret, "user").unwrap().generate_current().unwrap();
assert!(service.complete_login(&first.id, &code).await.is_err());
assert_eq!(
service.complete_login(&second.id, &code).await.unwrap(),
user_id
);
assert!(service.complete_login(&second.id, &code).await.is_err());
let expired = service.begin_login(&user_id).await.unwrap().unwrap();
service
.login_challenges
.lock()
.await
.get_mut(&user_id)
.unwrap()
.expires_at = Instant::now() - Duration::from_secs(1);
assert!(service.complete_login(&expired.id, &code).await.is_err());
}
#[tokio::test]
async fn challenge_failure_limit_is_shared_across_new_challenges() {
let (_dir, service, user_id) = test_service().await;
let secret = install_known_credential(&service, &user_id).await;
let valid = totp(&secret, "user").unwrap().generate_current().unwrap();
let invalid = if valid == "000000" {
"000001"
} else {
"000000"
};
let challenge = service.begin_login(&user_id).await.unwrap().unwrap();
for _ in 0..4 {
let error = service
.complete_login(&challenge.id, invalid)
.await
.unwrap_err();
assert!(matches!(error, AppError::AuthError(_)));
}
let error = service
.complete_login(&challenge.id, invalid)
.await
.unwrap_err();
assert!(error.to_string().contains("challenge expired"));
let replacement = service.begin_login(&user_id).await.unwrap().unwrap();
let error = service
.complete_login(&replacement.id, &valid)
.await
.unwrap_err();
assert!(matches!(error, AppError::RateLimited(_)));
}
#[tokio::test]
async fn enrollment_persists_and_disable_is_idempotent_for_cli() {
let (_dir, service, user_id) = test_service().await;
let enrollment = service
.begin_enrollment("session-1", &user_id, "admin")
.await
.unwrap();
let secret = Secret::Encoded(enrollment.secret.clone());
let code = totp(&secret, "admin").unwrap().generate_current().unwrap();
service
.confirm_enrollment("session-1", &user_id, &enrollment.id, &code)
.await
.unwrap();
let restarted = TwoFactorService::new(service.pool.clone());
assert!(restarted.is_enabled(&user_id).await.unwrap());
restarted.disable(&user_id, &code).await.unwrap();
assert!(!restarted.is_enabled(&user_id).await.unwrap());
assert!(!restarted.disable_without_code(&user_id).await.unwrap());
}
}

218
src/computer_use/actions.rs Normal file
View File

@@ -0,0 +1,218 @@
use serde::{Deserialize, Serialize};
use typeshare::typeshare;
#[typeshare]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComputerUseSessionStatus {
Idle,
WaitingScreenshot,
Thinking,
Executing,
Completed,
Failed,
Stopped,
}
#[typeshare]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComputerUseButton {
Left,
Middle,
Right,
}
impl Default for ComputerUseButton {
fn default() -> Self {
Self::Left
}
}
// Kept out of typeshare because these internally tagged enums are consumed by
// manually maintained frontend types and changing serde shape would break WS/API.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ComputerUseAction {
Click {
x: u32,
y: u32,
#[serde(default)]
button: ComputerUseButton,
},
DoubleClick {
x: u32,
y: u32,
#[serde(default)]
button: ComputerUseButton,
},
Move {
x: u32,
y: u32,
},
Drag {
path: Vec<ComputerUsePoint>,
#[serde(default)]
button: ComputerUseButton,
},
Scroll {
x: u32,
y: u32,
#[serde(default)]
dx: i32,
#[serde(default)]
dy: i32,
},
Type {
text: String,
},
Keypress {
keys: Vec<String>,
},
Wait {
ms: u64,
},
Screenshot,
}
#[typeshare]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct ComputerUsePoint {
pub x: u32,
pub y: u32,
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerUseScreenshot {
pub data_url: String,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum ComputerUseConversationMessage {
User { text: String },
Assistant { text: String },
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerUseStartRequest {
pub prompt: String,
#[serde(default)]
pub continue_conversation: bool,
pub client_id: String,
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerUseConfigResponse {
pub enabled: bool,
pub base_url: String,
pub model: String,
pub api_key_configured: bool,
pub api_key_source: String,
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerUseConfigUpdate {
pub enabled: Option<bool>,
pub base_url: Option<String>,
pub model: Option<String>,
#[serde(alias = "openai_api_key")]
pub api_key: Option<String>,
#[serde(alias = "clear_openai_api_key")]
pub clear_api_key: Option<bool>,
}
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerUseSessionSummary {
pub id: Option<String>,
pub status: ComputerUseSessionStatus,
pub prompt: Option<String>,
pub step: u32,
pub last_error: Option<String>,
pub final_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ComputerUseWsClientMessage {
ScreenshotResult {
request_id: String,
screenshot: ComputerUseScreenshot,
},
ScreenshotError {
request_id: String,
message: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ComputerUseWsServerMessage {
SessionUpdated { session: ComputerUseSessionSummary },
ScreenshotRequested { request_id: String },
ScreenshotCaptured { screenshot: ComputerUseScreenshot },
StepStarted { step: u32 },
ReasoningDelta { delta: String },
ReasoningCompleted { failed: bool },
ActionsExecuted { actions: Vec<ComputerUseAction> },
Error { message: String },
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn computer_use_action_keeps_flat_tagged_json_shape() {
let action = ComputerUseAction::Click {
x: 10,
y: 20,
button: ComputerUseButton::Left,
};
assert_eq!(
serde_json::to_value(action).unwrap(),
json!({
"type": "click",
"x": 10,
"y": 20,
"button": "left"
})
);
}
#[test]
fn computer_use_ws_message_keeps_flat_tagged_json_shape() {
let message = ComputerUseWsServerMessage::ScreenshotRequested {
request_id: "req-1".to_string(),
};
assert_eq!(
serde_json::to_value(message).unwrap(),
json!({
"type": "screenshot_requested",
"request_id": "req-1"
})
);
}
#[test]
fn config_update_accepts_legacy_api_key_names() {
let update: ComputerUseConfigUpdate = serde_json::from_value(json!({
"openai_api_key": "legacy-key",
"clear_openai_api_key": true
}))
.unwrap();
assert_eq!(update.api_key.as_deref(), Some("legacy-key"));
assert_eq!(update.clear_api_key, Some(true));
}
}

983
src/computer_use/manager.rs Normal file
View File

@@ -0,0 +1,983 @@
use std::sync::Arc;
use std::time::Duration;
use axum::extract::ws::{Message, WebSocket};
use futures::{SinkExt, StreamExt};
use tokio::sync::{broadcast, oneshot, watch, Mutex};
use tokio::task::JoinHandle;
use uuid::Uuid;
use super::actions::*;
use super::openai::{normalize_data_url, OpenAiComputerProvider};
use crate::config::ConfigStore;
use crate::error::{AppError, Result};
use crate::hid::{
CanonicalKey, HidController, KeyEventType, KeyboardEvent, KeyboardModifiers, MouseButton,
MouseEvent,
};
const SCREENSHOT_TIMEOUT: Duration = Duration::from_secs(10);
const KEY_DELAY: Duration = Duration::from_millis(35);
const ACTION_DELAY: Duration = Duration::from_millis(120);
const STOPPED_MESSAGE: &str = "Computer use task was stopped";
#[derive(Clone)]
pub struct ComputerUseManager {
config: ConfigStore,
hid: Arc<HidController>,
state: Arc<Mutex<ManagerState>>,
event_tx: broadcast::Sender<ComputerUseWsServerMessage>,
screenshot_tx: broadcast::Sender<ScreenshotRequest>,
}
struct ManagerState {
session: ComputerUseSessionSummary,
conversation: Vec<ComputerUseConversationMessage>,
screenshot_waiter: Option<ScreenshotWaiter>,
stop_tx: Option<oneshot::Sender<()>>,
cancel_tx: Option<watch::Sender<bool>>,
task: Option<JoinHandle<()>>,
}
struct ScreenshotWaiter {
request_id: String,
client_id: String,
tx: oneshot::Sender<Result<ComputerUseScreenshot>>,
}
#[derive(Debug, Clone)]
struct ScreenshotRequest {
request_id: String,
client_id: String,
}
impl ComputerUseManager {
pub fn new(config: ConfigStore, hid: Arc<HidController>) -> Arc<Self> {
let (event_tx, _) = broadcast::channel(128);
let (screenshot_tx, _) = broadcast::channel(8);
Arc::new(Self {
config,
hid,
state: Arc::new(Mutex::new(ManagerState {
session: empty_session(),
conversation: Vec::new(),
screenshot_waiter: None,
stop_tx: None,
cancel_tx: None,
task: None,
})),
event_tx,
screenshot_tx,
})
}
pub fn config_response(&self) -> ComputerUseConfigResponse {
let config = self.config.get();
let key_env = cua_api_key_env();
let key_db = config
.computer_use
.api_key
.as_ref()
.filter(|key| !key.is_empty());
ComputerUseConfigResponse {
enabled: config.computer_use.enabled,
base_url: cua_base_url_env().unwrap_or_else(|| config.computer_use.base_url.clone()),
model: config.computer_use.model.clone(),
api_key_configured: key_env.is_some() || key_db.is_some(),
api_key_source: if key_env.is_some() {
"env".to_string()
} else if key_db.is_some() {
"config".to_string()
} else {
"none".to_string()
},
}
}
pub async fn update_config(
&self,
req: ComputerUseConfigUpdate,
) -> Result<ComputerUseConfigResponse> {
if let Some(base_url) = req
.base_url
.as_ref()
.filter(|base_url| !base_url.trim().is_empty())
{
validate_endpoint_url(base_url)?;
}
self.config
.update(|config| {
if let Some(enabled) = req.enabled {
config.computer_use.enabled = enabled;
}
if let Some(model) = req.model.as_ref().filter(|model| !model.trim().is_empty()) {
config.computer_use.model = model.trim().to_string();
}
if let Some(base_url) = req
.base_url
.as_ref()
.filter(|base_url| !base_url.trim().is_empty())
{
config.computer_use.base_url = base_url.trim().to_string();
}
if req.clear_api_key.unwrap_or(false) {
config.computer_use.api_key = None;
}
if let Some(key) = req.api_key.as_ref() {
config.computer_use.api_key = if key.trim().is_empty() {
None
} else {
Some(key.trim().to_string())
};
}
})
.await?;
Ok(self.config_response())
}
pub async fn summary(&self) -> ComputerUseSessionSummary {
self.state.lock().await.session.clone()
}
pub async fn start(
self: &Arc<Self>,
req: ComputerUseStartRequest,
) -> Result<ComputerUseSessionSummary> {
let app_config = self.config.get();
let config = app_config.computer_use.clone();
if !config.enabled {
return Err(AppError::BadRequest("Computer use is disabled".to_string()));
}
if req.prompt.trim().is_empty() {
return Err(AppError::BadRequest("Task prompt is required".to_string()));
}
let client_id = req.client_id.trim();
if client_id.is_empty() {
return Err(AppError::BadRequest(
"Computer use client_id is required".to_string(),
));
}
let client_id = client_id.to_string();
let hid = self.hid.snapshot().await;
if !hid.initialized || !hid.supports_absolute_mouse {
return Err(AppError::BadRequest(
"Computer use requires an initialized absolute mouse HID backend".to_string(),
));
}
let api_key = cua_api_key_env()
.or(config.api_key.clone())
.ok_or_else(|| {
AppError::BadRequest("Computer Use API key is not configured".to_string())
})?;
let base_url = cua_base_url_env().unwrap_or_else(|| config.base_url.clone());
validate_endpoint_url(&base_url)?;
let mut state = self.state.lock().await;
if matches!(
state.session.status,
ComputerUseSessionStatus::WaitingScreenshot
| ComputerUseSessionStatus::Thinking
| ComputerUseSessionStatus::Executing
) {
return Err(AppError::BadRequest(
"A computer use session is already running".to_string(),
));
}
if let Some(handle) = state.task.take() {
handle.abort();
}
if !req.continue_conversation {
state.conversation.clear();
}
let conversation = state.conversation.clone();
state
.conversation
.push(ComputerUseConversationMessage::User {
text: req.prompt.trim().to_string(),
});
let (stop_tx, stop_rx) = oneshot::channel();
let (cancel_tx, cancel_rx) = watch::channel(false);
let session_id = Uuid::new_v4().to_string();
state.session = ComputerUseSessionSummary {
id: Some(session_id),
status: ComputerUseSessionStatus::Thinking,
prompt: Some(req.prompt.trim().to_string()),
step: 0,
last_error: None,
final_message: None,
};
state.stop_tx = Some(stop_tx);
state.cancel_tx = Some(cancel_tx);
let summary = state.session.clone();
drop(state);
self.publish_session().await;
let manager = self.clone();
let prompt = req.prompt.trim().to_string();
let model = config.model.clone();
let handle = tokio::spawn(async move {
manager
.run_loop(
prompt,
api_key,
base_url,
model,
conversation,
client_id,
cancel_rx,
stop_rx,
)
.await;
});
self.state.lock().await.task = Some(handle);
Ok(summary)
}
pub async fn stop(&self) -> Result<ComputerUseSessionSummary> {
let mut state = self.state.lock().await;
if let Some(tx) = state.stop_tx.take() {
let _ = tx.send(());
}
if let Some(tx) = state.cancel_tx.take() {
let _ = tx.send(true);
}
if let Some(waiter) = state.screenshot_waiter.take() {
drop(waiter.tx);
}
state.session.status = ComputerUseSessionStatus::Stopped;
drop(state);
let _ = self.hid.reset().await;
self.publish_session().await;
Ok(self.summary().await)
}
pub async fn submit_screenshot(
&self,
client_id: &str,
request_id: String,
mut screenshot: ComputerUseScreenshot,
) -> Result<()> {
if screenshot.width == 0 || screenshot.height == 0 {
return Err(AppError::BadRequest(
"Screenshot dimensions are invalid".to_string(),
));
}
screenshot.data_url = normalize_data_url(&screenshot.data_url)?;
let mut state = self.state.lock().await;
let Some(waiter) = state.screenshot_waiter.take() else {
return Ok(());
};
if waiter.request_id != request_id || waiter.client_id != client_id {
state.screenshot_waiter = Some(waiter);
return Ok(());
}
let _ = waiter.tx.send(Ok(screenshot));
Ok(())
}
async fn submit_screenshot_error(&self, client_id: &str, request_id: String, message: String) {
let mut state = self.state.lock().await;
let Some(waiter) = state.screenshot_waiter.take() else {
return;
};
if waiter.request_id != request_id || waiter.client_id != client_id {
state.screenshot_waiter = Some(waiter);
return;
}
let message: String = message.chars().take(300).collect();
let _ = waiter.tx.send(Err(AppError::ServiceUnavailable(format!(
"Screenshot capture failed: {}",
if message.trim().is_empty() {
"client did not provide an error"
} else {
message.trim()
}
))));
}
pub async fn handle_socket(self: Arc<Self>, socket: WebSocket, client_id: Option<String>) {
let (mut sender, mut receiver) = socket.split();
let mut event_rx = self.event_tx.subscribe();
let client_id = client_id
.as_deref()
.map(str::trim)
.filter(|client_id| !client_id.is_empty())
.map(str::to_string)
.unwrap_or_else(|| Uuid::new_v4().to_string());
let mut screenshot_rx = self.screenshot_tx.subscribe();
let _ = sender
.send(Message::Text(
serde_json::to_string(&ComputerUseWsServerMessage::SessionUpdated {
session: self.summary().await,
})
.unwrap_or_default()
.into(),
))
.await;
loop {
tokio::select! {
Ok(event) = event_rx.recv() => {
if let Ok(text) = serde_json::to_string(&event) {
if sender.send(Message::Text(text.into())).await.is_err() {
break;
}
}
}
Ok(req) = screenshot_rx.recv() => {
if req.client_id != client_id {
continue;
}
let event = ComputerUseWsServerMessage::ScreenshotRequested { request_id: req.request_id };
if let Ok(text) = serde_json::to_string(&event) {
if sender.send(Message::Text(text.into())).await.is_err() {
break;
}
}
}
msg = receiver.next() => {
match msg {
Some(Ok(Message::Text(text))) => {
match serde_json::from_str::<ComputerUseWsClientMessage>(&text) {
Ok(ComputerUseWsClientMessage::ScreenshotResult { request_id, screenshot }) => {
let _ = self.submit_screenshot(&client_id, request_id, screenshot).await;
}
Ok(ComputerUseWsClientMessage::ScreenshotError { request_id, message }) => {
self.submit_screenshot_error(&client_id, request_id, message).await;
}
Err(_) => {}
}
}
Some(Ok(Message::Close(_))) | None => break,
Some(Err(_)) => break,
_ => {}
}
}
}
}
}
async fn run_loop(
&self,
prompt: String,
api_key: String,
base_url: String,
model: String,
conversation: Vec<ComputerUseConversationMessage>,
client_id: String,
cancel_rx: watch::Receiver<bool>,
mut stop_rx: oneshot::Receiver<()>,
) {
let provider = OpenAiComputerProvider::new(api_key, base_url, model);
let mut latest_screenshot: Option<ComputerUseScreenshot> = None;
let mut action_history: Vec<String> = Vec::new();
let mut step = 0_u32;
loop {
step = step.saturating_add(1);
self.set_status(ComputerUseSessionStatus::Thinking, step, None)
.await;
let response = tokio::select! {
_ = &mut stop_rx => {
let _ = self.event_tx.send(ComputerUseWsServerMessage::ReasoningCompleted {
failed: true,
});
self.set_stopped().await;
return;
}
response = provider.next_actions(
&prompt,
&conversation,
&action_history,
latest_screenshot.as_ref(),
|delta| {
let _ = self.event_tx.send(ComputerUseWsServerMessage::ReasoningDelta {
delta: delta.to_string(),
});
},
) => response,
};
let response = match response {
Ok(response) => {
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::ReasoningCompleted { failed: false });
response
}
Err(err) => {
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::ReasoningCompleted { failed: true });
self.fail(&err.to_string()).await;
return;
}
};
if *cancel_rx.borrow() {
self.set_stopped().await;
return;
}
if response.done {
self.complete(response.message).await;
return;
}
let executable = &response.actions[..response.actions.len().saturating_sub(1)];
action_history.push(format!(
"Step {step}: {}",
serde_json::to_string(&response.actions).unwrap_or_else(|_| "[]".to_string())
));
if !executable.is_empty() {
let Some(screenshot) = latest_screenshot.as_ref() else {
self.fail("Computer Use protocol error: actions require a screenshot")
.await;
return;
};
self.set_status(ComputerUseSessionStatus::Executing, step, None)
.await;
if let Err(err) = self
.execute_actions(
executable,
screenshot.width,
screenshot.height,
cancel_rx.clone(),
)
.await
{
if *cancel_rx.borrow() {
self.set_stopped().await;
} else {
self.fail(&err.to_string()).await;
}
return;
}
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::ActionsExecuted {
actions: executable.to_vec(),
});
}
self.set_status(ComputerUseSessionStatus::WaitingScreenshot, step, None)
.await;
let screenshot = tokio::select! {
_ = &mut stop_rx => {
self.set_stopped().await;
return;
}
screenshot = self.request_screenshot(&client_id) => screenshot,
};
let screenshot = match screenshot {
Ok(screenshot) => screenshot,
Err(err) => {
self.fail(&err.to_string()).await;
return;
}
};
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::ScreenshotCaptured {
screenshot: screenshot.clone(),
});
latest_screenshot = Some(screenshot);
}
}
async fn request_screenshot(&self, client_id: &str) -> Result<ComputerUseScreenshot> {
let request_id = Uuid::new_v4().to_string();
let (tx, rx) = oneshot::channel();
{
let mut state = self.state.lock().await;
state.screenshot_waiter = Some(ScreenshotWaiter {
request_id: request_id.clone(),
client_id: client_id.to_string(),
tx,
});
}
let _ = self.screenshot_tx.send(ScreenshotRequest {
request_id,
client_id: client_id.to_string(),
});
let reply = tokio::time::timeout(SCREENSHOT_TIMEOUT, rx)
.await
.map_err(|_| {
AppError::ServiceUnavailable("Timed out waiting for screenshot".to_string())
})?
.map_err(|_| {
AppError::ServiceUnavailable("Screenshot request was cancelled".to_string())
})?;
reply
}
async fn execute_actions(
&self,
actions: &[ComputerUseAction],
width: u32,
height: u32,
mut cancel_rx: watch::Receiver<bool>,
) -> Result<()> {
for action in actions {
if *cancel_rx.borrow() {
return Err(stopped_error());
}
match action {
ComputerUseAction::Click { x, y, button } => {
self.move_abs(*x, *y, width, height).await?;
self.mouse_button(*button, true).await?;
let click_result = sleep_or_cancel(KEY_DELAY, &mut cancel_rx).await;
self.mouse_button(*button, false).await?;
click_result?;
}
ComputerUseAction::DoubleClick { x, y, button } => {
for _ in 0..2 {
self.move_abs(*x, *y, width, height).await?;
self.mouse_button(*button, true).await?;
let click_result = sleep_or_cancel(KEY_DELAY, &mut cancel_rx).await;
self.mouse_button(*button, false).await?;
click_result?;
sleep_or_cancel(KEY_DELAY, &mut cancel_rx).await?;
}
}
ComputerUseAction::Move { x, y } => self.move_abs(*x, *y, width, height).await?,
ComputerUseAction::Drag { path, button } => {
if let Some(first) = path.first() {
self.move_abs(first.x, first.y, width, height).await?;
self.mouse_button(*button, true).await?;
let drag_result = async {
for point in path.iter().skip(1) {
sleep_or_cancel(KEY_DELAY, &mut cancel_rx).await?;
self.move_abs(point.x, point.y, width, height).await?;
}
Result::<()>::Ok(())
}
.await;
self.mouse_button(*button, false).await?;
drag_result?;
}
}
ComputerUseAction::Scroll { x, y, dy, .. } => {
self.move_abs(*x, *y, width, height).await?;
let ticks = ((*dy).clamp(-1200, 1200) / 120).clamp(-10, 10);
let ticks = if ticks == 0 { dy.signum() } else { ticks };
for _ in 0..ticks.abs() {
if *cancel_rx.borrow() {
return Err(stopped_error());
}
self.hid
.send_mouse(MouseEvent::scroll(if ticks > 0 { 1 } else { -1 }))
.await?;
}
}
ComputerUseAction::Type { text } => self.type_text(text, &mut cancel_rx).await?,
ComputerUseAction::Keypress { keys } => self.keypress(keys, &mut cancel_rx).await?,
ComputerUseAction::Wait { ms } => {
sleep_or_cancel(Duration::from_millis((*ms).min(5000)), &mut cancel_rx).await?
}
ComputerUseAction::Screenshot => {}
}
sleep_or_cancel(ACTION_DELAY, &mut cancel_rx).await?;
}
Ok(())
}
async fn move_abs(&self, x: u32, y: u32, width: u32, height: u32) -> Result<()> {
let hid_x = ((x.min(width.saturating_sub(1)) as f64 / width.max(1) as f64) * 32767.0)
.round() as i32;
let hid_y = ((y.min(height.saturating_sub(1)) as f64 / height.max(1) as f64) * 32767.0)
.round() as i32;
self.hid
.send_mouse(MouseEvent::move_abs(hid_x, hid_y))
.await
}
async fn mouse_button(&self, button: ComputerUseButton, down: bool) -> Result<()> {
let button = match button {
ComputerUseButton::Left => MouseButton::Left,
ComputerUseButton::Middle => MouseButton::Middle,
ComputerUseButton::Right => MouseButton::Right,
};
let event = if down {
MouseEvent::button_down(button)
} else {
MouseEvent::button_up(button)
};
self.hid.send_mouse(event).await
}
async fn type_text(&self, text: &str, cancel_rx: &mut watch::Receiver<bool>) -> Result<()> {
for ch in text.chars() {
if *cancel_rx.borrow() {
return Err(stopped_error());
}
let (key, mods) = char_to_key(ch).ok_or_else(|| {
AppError::BadRequest(format!(
"Cannot type unsupported character {ch:?} through HID keyboard mapping"
))
})?;
self.key_down_up(key, mods, cancel_rx).await?;
}
Ok(())
}
async fn keypress(&self, keys: &[String], cancel_rx: &mut watch::Receiver<bool>) -> Result<()> {
let mut mods = KeyboardModifiers::default();
let mut key = None;
for item in keys {
match item.to_lowercase().as_str() {
"ctrl" | "control" | "controlleft" => mods.left_ctrl = true,
"shift" | "shiftleft" => mods.left_shift = true,
"alt" | "altleft" => mods.left_alt = true,
"meta" | "win" | "cmd" | "super" => mods.left_meta = true,
other => key = key_name_to_canonical(other),
}
}
if let Some(key) = key {
self.key_down_up(key, mods, cancel_rx).await?;
}
Ok(())
}
async fn key_down_up(
&self,
key: CanonicalKey,
mods: KeyboardModifiers,
cancel_rx: &mut watch::Receiver<bool>,
) -> Result<()> {
self.hid
.send_keyboard(KeyboardEvent {
event_type: KeyEventType::Down,
key,
modifiers: mods,
})
.await?;
let key_result = sleep_or_cancel(KEY_DELAY, cancel_rx).await;
self.hid
.send_keyboard(KeyboardEvent {
event_type: KeyEventType::Up,
key,
modifiers: KeyboardModifiers::default(),
})
.await?;
key_result
}
async fn publish_session(&self) {
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::SessionUpdated {
session: self.summary().await,
});
}
async fn set_status(&self, status: ComputerUseSessionStatus, step: u32, error: Option<String>) {
{
let mut state = self.state.lock().await;
state.session.status = status;
state.session.step = step;
state.session.last_error = error;
}
if matches!(status, ComputerUseSessionStatus::Thinking) {
let _ = self
.event_tx
.send(ComputerUseWsServerMessage::StepStarted { step });
}
self.publish_session().await;
}
async fn complete(&self, message: Option<String>) {
{
let mut state = self.state.lock().await;
if let Some(message) = message.as_ref().filter(|message| !message.is_empty()) {
state
.conversation
.push(ComputerUseConversationMessage::Assistant {
text: message.clone(),
});
}
state.session.status = ComputerUseSessionStatus::Completed;
state.session.final_message = message;
state.stop_tx = None;
}
self.publish_session().await;
let _ = self.hid.reset().await;
}
async fn fail(&self, message: &str) {
{
let mut state = self.state.lock().await;
state.session.status = ComputerUseSessionStatus::Failed;
state.session.last_error = Some(message.to_string());
state.stop_tx = None;
}
let _ = self.event_tx.send(ComputerUseWsServerMessage::Error {
message: message.to_string(),
});
self.publish_session().await;
let _ = self.hid.reset().await;
}
async fn set_stopped(&self) {
{
let mut state = self.state.lock().await;
state.session.status = ComputerUseSessionStatus::Stopped;
state.stop_tx = None;
}
self.publish_session().await;
let _ = self.hid.reset().await;
}
}
async fn sleep_or_cancel(duration: Duration, cancel_rx: &mut watch::Receiver<bool>) -> Result<()> {
if *cancel_rx.borrow() {
return Err(stopped_error());
}
tokio::select! {
_ = tokio::time::sleep(duration) => Ok(()),
changed = cancel_rx.changed() => {
match changed {
Ok(()) if *cancel_rx.borrow() => {
Err(stopped_error())
}
Ok(()) => Ok(()),
Err(_) => Err(stopped_error()),
}
}
}
}
fn stopped_error() -> AppError {
AppError::BadRequest(STOPPED_MESSAGE.to_string())
}
fn empty_session() -> ComputerUseSessionSummary {
ComputerUseSessionSummary {
id: None,
status: ComputerUseSessionStatus::Idle,
prompt: None,
step: 0,
last_error: None,
final_message: None,
}
}
fn cua_api_key_env() -> Option<String> {
std::env::var("ONE_KVM_CUA_API_KEY")
.ok()
.filter(|key| !key.trim().is_empty())
.or_else(|| {
std::env::var("OPENAI_API_KEY")
.ok()
.filter(|key| !key.trim().is_empty())
})
}
fn cua_base_url_env() -> Option<String> {
std::env::var("ONE_KVM_CUA_BASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
.or_else(|| {
std::env::var("ONE_KVM_OPENAI_BASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
})
}
fn validate_endpoint_url(url: &str) -> Result<()> {
let trimmed = url.trim();
if !(trimmed.starts_with("https://") || trimmed.starts_with("http://")) {
return Err(AppError::BadRequest(
"API URL must be a complete http(s) endpoint".to_string(),
));
}
if trimmed.ends_with('/') {
return Err(AppError::BadRequest(
"API URL must include the full endpoint path without a trailing slash".to_string(),
));
}
if !trimmed.contains("/responses") && !trimmed.contains("/chat/completions") {
return Err(AppError::BadRequest(
"API URL must include /responses or /chat/completions".to_string(),
));
}
Ok(())
}
fn char_to_key(ch: char) -> Option<(CanonicalKey, KeyboardModifiers)> {
let mut mods = KeyboardModifiers::default();
let key = match ch {
'a'..='z' => key_name_to_canonical(&ch.to_string())?,
'A'..='Z' => {
mods.left_shift = true;
key_name_to_canonical(&ch.to_ascii_lowercase().to_string())?
}
'0' => CanonicalKey::Digit0,
'1' => CanonicalKey::Digit1,
'2' => CanonicalKey::Digit2,
'3' => CanonicalKey::Digit3,
'4' => CanonicalKey::Digit4,
'5' => CanonicalKey::Digit5,
'6' => CanonicalKey::Digit6,
'7' => CanonicalKey::Digit7,
'8' => CanonicalKey::Digit8,
'9' => CanonicalKey::Digit9,
' ' => CanonicalKey::Space,
'\n' => CanonicalKey::Enter,
'-' => CanonicalKey::Minus,
'_' => {
mods.left_shift = true;
CanonicalKey::Minus
}
'=' => CanonicalKey::Equal,
'+' => {
mods.left_shift = true;
CanonicalKey::Equal
}
'.' => CanonicalKey::Period,
',' => CanonicalKey::Comma,
'/' => CanonicalKey::Slash,
'?' => {
mods.left_shift = true;
CanonicalKey::Slash
}
';' => CanonicalKey::Semicolon,
':' => {
mods.left_shift = true;
CanonicalKey::Semicolon
}
'\'' => CanonicalKey::Quote,
'"' => {
mods.left_shift = true;
CanonicalKey::Quote
}
'[' => CanonicalKey::BracketLeft,
'{' => {
mods.left_shift = true;
CanonicalKey::BracketLeft
}
']' => CanonicalKey::BracketRight,
'}' => {
mods.left_shift = true;
CanonicalKey::BracketRight
}
'\\' => CanonicalKey::Backslash,
'|' => {
mods.left_shift = true;
CanonicalKey::Backslash
}
'`' => CanonicalKey::Backquote,
'~' => {
mods.left_shift = true;
CanonicalKey::Backquote
}
'!' => {
mods.left_shift = true;
CanonicalKey::Digit1
}
'@' => {
mods.left_shift = true;
CanonicalKey::Digit2
}
'#' => {
mods.left_shift = true;
CanonicalKey::Digit3
}
'$' => {
mods.left_shift = true;
CanonicalKey::Digit4
}
'%' => {
mods.left_shift = true;
CanonicalKey::Digit5
}
'^' => {
mods.left_shift = true;
CanonicalKey::Digit6
}
'&' => {
mods.left_shift = true;
CanonicalKey::Digit7
}
'*' => {
mods.left_shift = true;
CanonicalKey::Digit8
}
'(' => {
mods.left_shift = true;
CanonicalKey::Digit9
}
')' => {
mods.left_shift = true;
CanonicalKey::Digit0
}
_ => return None,
};
Some((key, mods))
}
fn key_name_to_canonical(name: &str) -> Option<CanonicalKey> {
match name.trim().to_lowercase().as_str() {
"a" => Some(CanonicalKey::KeyA),
"b" => Some(CanonicalKey::KeyB),
"c" => Some(CanonicalKey::KeyC),
"d" => Some(CanonicalKey::KeyD),
"e" => Some(CanonicalKey::KeyE),
"f" => Some(CanonicalKey::KeyF),
"g" => Some(CanonicalKey::KeyG),
"h" => Some(CanonicalKey::KeyH),
"i" => Some(CanonicalKey::KeyI),
"j" => Some(CanonicalKey::KeyJ),
"k" => Some(CanonicalKey::KeyK),
"l" => Some(CanonicalKey::KeyL),
"m" => Some(CanonicalKey::KeyM),
"n" => Some(CanonicalKey::KeyN),
"o" => Some(CanonicalKey::KeyO),
"p" => Some(CanonicalKey::KeyP),
"q" => Some(CanonicalKey::KeyQ),
"r" => Some(CanonicalKey::KeyR),
"s" => Some(CanonicalKey::KeyS),
"t" => Some(CanonicalKey::KeyT),
"u" => Some(CanonicalKey::KeyU),
"v" => Some(CanonicalKey::KeyV),
"w" => Some(CanonicalKey::KeyW),
"x" => Some(CanonicalKey::KeyX),
"y" => Some(CanonicalKey::KeyY),
"z" => Some(CanonicalKey::KeyZ),
"enter" | "return" => Some(CanonicalKey::Enter),
"escape" | "esc" => Some(CanonicalKey::Escape),
"backspace" => Some(CanonicalKey::Backspace),
"tab" => Some(CanonicalKey::Tab),
"space" => Some(CanonicalKey::Space),
"delete" | "del" => Some(CanonicalKey::Delete),
"arrowup" | "up" => Some(CanonicalKey::ArrowUp),
"arrowdown" | "down" => Some(CanonicalKey::ArrowDown),
"arrowleft" | "left" => Some(CanonicalKey::ArrowLeft),
"arrowright" | "right" => Some(CanonicalKey::ArrowRight),
"home" => Some(CanonicalKey::Home),
"end" => Some(CanonicalKey::End),
"pageup" => Some(CanonicalKey::PageUp),
"pagedown" => Some(CanonicalKey::PageDown),
"f1" => Some(CanonicalKey::F1),
"f2" => Some(CanonicalKey::F2),
"f3" => Some(CanonicalKey::F3),
"f4" => Some(CanonicalKey::F4),
"f5" => Some(CanonicalKey::F5),
"f6" => Some(CanonicalKey::F6),
"f7" => Some(CanonicalKey::F7),
"f8" => Some(CanonicalKey::F8),
"f9" => Some(CanonicalKey::F9),
"f10" => Some(CanonicalKey::F10),
"f11" => Some(CanonicalKey::F11),
"f12" => Some(CanonicalKey::F12),
_ => None,
}
}

6
src/computer_use/mod.rs Normal file
View File

@@ -0,0 +1,6 @@
mod actions;
mod manager;
mod openai;
pub use actions::*;
pub use manager::*;

1219
src/computer_use/openai.rs Normal file

File diff suppressed because it is too large Load Diff

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