mirror of
https://github.com/mofeng-git/One-KVM.git
synced 2026-09-12 18:44:25 +08:00
Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4073d64cb | ||
|
|
16400df182 | ||
|
|
47af17bebc | ||
|
|
814f23a27c | ||
|
|
6bbe137f09 | ||
|
|
6fdcf5c7c9 | ||
|
|
ce1712ff2e | ||
|
|
8b09824e04 | ||
|
|
9fb23476ac | ||
|
|
971c263bf8 | ||
|
|
cb3fd3e646 | ||
|
|
d414557d74 | ||
|
|
fbcd95b617 | ||
|
|
887f29096f | ||
|
|
e0bddc2faa | ||
|
|
4f770a1eea | ||
|
|
376dc97134 | ||
|
|
27c8da9a75 | ||
|
|
5963dfa01a | ||
|
|
f86cba6ce5 | ||
|
|
e1b82519b9 | ||
|
|
32d8a62fec | ||
|
|
4cd622ff07 | ||
|
|
6ec4361f43 | ||
|
|
e9bed3688f | ||
|
|
8d5366444b | ||
|
|
4e32b05124 | ||
|
|
e0055bf491 | ||
|
|
d60ddb21dc | ||
|
|
219d1ccd08 | ||
|
|
6f697e56c8 | ||
|
|
05535b9bb2 | ||
|
|
5ce2cb658c | ||
|
|
a86df52d9a | ||
|
|
275c2ca343 | ||
|
|
5d871e8b21 | ||
|
|
694afdd07f | ||
|
|
d31e70515a | ||
|
|
701b141347 | ||
|
|
eaa114f40c | ||
|
|
563c808836 | ||
|
|
79b6683817 | ||
|
|
8bd16df6f8 | ||
|
|
fdea52d59d | ||
|
|
4031abd8d6 | ||
|
|
cf2bfaf6a7 | ||
|
|
d35021ee5d | ||
|
|
57d1597264 | ||
|
|
aca847e76c | ||
|
|
8036c164b4 | ||
|
|
0482987bf1 | ||
|
|
50dd419e5a | ||
|
|
213359b6c8 | ||
|
|
63c2bb4ca2 | ||
|
|
6693020e6d | ||
|
|
05c5f45995 | ||
|
|
1ded7a8a66 | ||
|
|
809d0ca65c | ||
|
|
139064de35 | ||
|
|
54e0cbc84e | ||
|
|
7c9166a8cf | ||
|
|
a9a16f2218 | ||
|
|
c9ae9dd893 | ||
|
|
010d50b727 | ||
|
|
c88fb03243 | ||
|
|
7bae9b633c | ||
|
|
fc3f1d6aac | ||
|
|
b719be3e38 | ||
|
|
db2410cc7f | ||
|
|
d9c2854911 | ||
|
|
99c051a874 | ||
|
|
a0ad151fbc | ||
|
|
4806a5e0a9 | ||
|
|
e60152d38b | ||
|
|
f6e97a06f5 | ||
|
|
618599266e | ||
|
|
696c1b4bb2 | ||
|
|
b346af35d3 | ||
|
|
16a65289f2 | ||
|
|
bb2691fe8f | ||
|
|
7753c83e27 | ||
|
|
1d6fb2e3c5 | ||
|
|
6c1bff5d0c | ||
|
|
f1e362a820 | ||
|
|
e2c19d550c | ||
|
|
c101ef1c80 | ||
|
|
4b7be20fe0 | ||
|
|
5c98aea7e3 | ||
|
|
da61644dbc | ||
|
|
5de7ecd4c5 | ||
|
|
3fc6b055a0 | ||
|
|
4b65eebd5d | ||
|
|
921c00c472 | ||
|
|
b6bd76534f | ||
|
|
780cfb4cca | ||
|
|
8f9272d985 | ||
|
|
f679647ec9 | ||
|
|
198552014b | ||
|
|
3e3937605e | ||
|
|
4a85fbfab8 | ||
|
|
87d1110a87 | ||
|
|
b31aae284d | ||
|
|
dc6475776e | ||
|
|
3de72677e6 | ||
|
|
6a1616c32a | ||
|
|
032f47a891 |
20
.github/workflows/build.yml
vendored
20
.github/workflows/build.yml
vendored
@@ -34,13 +34,11 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: web
|
||||
run: |
|
||||
npm ci
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Upload frontend dist
|
||||
@@ -66,8 +64,16 @@ jobs:
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# The Docker workflow builds the same targets with the same Cross images.
|
||||
shared-key: linux-cross-release
|
||||
key: ${{ hashFiles('Cross.toml', 'build/cross/Dockerfile.*') }}
|
||||
cache-all-crates: true
|
||||
|
||||
- name: Install cross
|
||||
run: cargo install cross --locked
|
||||
run: cargo install cross --version 0.2.5 --locked
|
||||
|
||||
- name: Build linux binary
|
||||
run: bash build/build-images.sh
|
||||
@@ -127,6 +133,12 @@ jobs:
|
||||
"TURBOJPEG_LIB_DIR=$env:TURBOJPEG_LIB_DIR" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
"TURBOJPEG_INCLUDE_DIR=$env:TURBOJPEG_INCLUDE_DIR" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: windows-msvc-release
|
||||
key: ${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json') }}
|
||||
|
||||
- name: Build Windows exe
|
||||
shell: pwsh
|
||||
run: .\build\windows\build.ps1 -Configuration release -Package
|
||||
|
||||
91
.github/workflows/docker.yml
vendored
Normal file
91
.github/workflows/docker.yml
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
name: Docker
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Docker image tag
|
||||
required: false
|
||||
default: latest
|
||||
platforms:
|
||||
description: Docker platforms
|
||||
required: false
|
||||
default: linux/amd64,linux/arm64,linux/arm/v7
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
DOCKER_PLATFORMS: ${{ github.event_name == 'workflow_dispatch' && inputs.platforms || 'linux/amd64,linux/arm64,linux/arm/v7' }}
|
||||
DOCKER_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 360
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Reuse dependency artifacts produced by the deb job and vice versa.
|
||||
shared-key: linux-cross-release
|
||||
key: ${{ hashFiles('Cross.toml', 'build/cross/Dockerfile.*') }}
|
||||
cache-all-crates: true
|
||||
|
||||
- name: Install build dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y unzip xz-utils
|
||||
cargo install cross --version 0.2.5 --locked
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: web
|
||||
run: |
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build linux binaries
|
||||
run: bash build/build-images.sh
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Log in to Aliyun Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: registry.cn-hangzhou.aliyuncs.com
|
||||
username: ${{ secrets.ALIYUN_USERNAME }}
|
||||
password: ${{ secrets.ALIYUN_PASSWORD }}
|
||||
|
||||
- name: Publish Docker images
|
||||
run: |
|
||||
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry docker.io/silentwind0 --tag "$DOCKER_TAG" --push
|
||||
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry registry.cn-hangzhou.aliyuncs.com/silentwind --tag "$DOCKER_TAG" --push
|
||||
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry docker.io/silentwind0 --variant full --tag "$DOCKER_TAG" --push
|
||||
./build/package-docker.sh --platform "$DOCKER_PLATFORMS" --registry registry.cn-hangzhou.aliyuncs.com/silentwind --variant full --tag "$DOCKER_TAG" --push
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -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/
|
||||
|
||||
190
Cargo.toml
190
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "one-kvm"
|
||||
version = "0.2.1"
|
||||
version = "0.2.6"
|
||||
edition = "2021"
|
||||
authors = ["SilentWind"]
|
||||
description = "A open and lightweight IP-KVM solution written in Rust"
|
||||
@@ -9,119 +9,190 @@ repository = "https://github.com/mofeng-git/One-KVM"
|
||||
keywords = ["kvm", "ipkvm", "remote-management", "embedded"]
|
||||
categories = ["embedded", "network-programming"]
|
||||
|
||||
[features]
|
||||
default = ["desktop"]
|
||||
desktop = [
|
||||
"dep:tokio",
|
||||
"dep:tokio-util",
|
||||
"dep:axum",
|
||||
"dep:axum-extra",
|
||||
"dep:tower-http",
|
||||
"dep:sqlx",
|
||||
"dep:serde",
|
||||
"dep:serde_json",
|
||||
"dep:toml_edit",
|
||||
"dep:tracing",
|
||||
"dep:tracing-subscriber",
|
||||
"dep:thiserror",
|
||||
"dep:anyhow",
|
||||
"dep:argon2",
|
||||
"dep:rand",
|
||||
"dep:totp-rs",
|
||||
"dep:uuid",
|
||||
"dep:base64",
|
||||
"dep:nix",
|
||||
"dep:reqwest",
|
||||
"dep:urlencoding",
|
||||
"dep:rust-embed",
|
||||
"dep:mime_guess",
|
||||
"dep:rustls",
|
||||
"dep:rcgen",
|
||||
"dep:axum-server",
|
||||
"dep:clap",
|
||||
"dep:time",
|
||||
"dep:tempfile",
|
||||
"dep:bytes",
|
||||
"dep:bytemuck",
|
||||
"dep:xxhash-rust",
|
||||
"dep:async-stream",
|
||||
"dep:futures",
|
||||
"dep:tokio-tungstenite",
|
||||
"dep:parking_lot",
|
||||
"dep:arc-swap",
|
||||
"dep:webrtc",
|
||||
"dep:rtp",
|
||||
"dep:rtsp-types",
|
||||
"dep:sdp-types",
|
||||
"dep:serialport",
|
||||
"dep:async-trait",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ventoy-img",
|
||||
"dep:protobuf",
|
||||
"dep:sodiumoxide",
|
||||
"dep:des",
|
||||
"dep:sha2",
|
||||
"dep:typeshare",
|
||||
"dep:hwcodec",
|
||||
"dep:libyuv",
|
||||
"dep:turbojpeg",
|
||||
"dep:audiopus",
|
||||
"dep:v4l2r",
|
||||
"dep:alsa",
|
||||
"dep:gpio-cdev",
|
||||
"dep: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 }
|
||||
libloading = { version = "0.8", 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 +200,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"
|
||||
|
||||
27
README.en.md
27
README.en.md
@@ -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
|
||||

|
||||
|
||||
林枫云 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
|
||||
|
||||

|
||||
|
||||
Remote computers, consumer GPU servers, and dedicated physical machines with fully automated online delivery.
|
||||
|
||||
27
README.md
27
README.md
@@ -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)** - 提供免登录下载服务
|
||||
|
||||
|
||||
14
agents.md
14
agents.md
@@ -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
|
||||
```
|
||||
31
build.rs
31
build.rs
@@ -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)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ RUN sed -i 's/ main$/ main contrib non-free/' /etc/apt/sources.list && \
|
||||
ca-certificates \
|
||||
libudev1 \
|
||||
libasound2 \
|
||||
# OTG Ethernet bridge control (nmcli talks to the host NetworkManager over D-Bus)
|
||||
network-manager \
|
||||
iproute2 \
|
||||
iputils-ping \
|
||||
# v4l2 is handled by kernel, minimal userspace needed
|
||||
libv4l-0 \
|
||||
&& \
|
||||
|
||||
@@ -19,6 +19,10 @@ RUN sed -i 's/ main$/ main contrib non-free/' /etc/apt/sources.list && \
|
||||
ca-certificates \
|
||||
libudev1 \
|
||||
libasound2 \
|
||||
# OTG Ethernet bridge control (nmcli talks to the host NetworkManager over D-Bus)
|
||||
network-manager \
|
||||
iproute2 \
|
||||
iputils-ping \
|
||||
# v4l2 is handled by kernel, minimal userspace needed
|
||||
libv4l-0 \
|
||||
&& \
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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"
|
||||
|
||||
2
libs/hwcodec/.gitignore
vendored
2
libs/hwcodec/.gitignore
vendored
@@ -8,8 +8,6 @@
|
||||
/ffmpeg/linux/debug
|
||||
!/ffmpeg/mac
|
||||
/ffmpeg/mac/debug
|
||||
!/ffmpeg/android
|
||||
/ffmpeg/android/debug
|
||||
!/ffmpeg/ios
|
||||
/ffmpeg/ios/debug
|
||||
/input
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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() {}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
goto _exit;
|
||||
}
|
||||
if (!pkt_->data || !pkt_->size) {
|
||||
LOG_ERROR(std::string("avcodec_receive_packet failed, pkt size is 0"));
|
||||
goto _exit;
|
||||
}
|
||||
encoded = true;
|
||||
callback_(pkt_->data, pkt_->size, pkt_->pts,
|
||||
pkt_->flags & AV_PKT_FLAG_KEY, obj);
|
||||
ret = receive_available_packets(obj, encoded);
|
||||
if (ret < 0) {
|
||||
return ret;
|
||||
}
|
||||
_exit:
|
||||
av_packet_unref(pkt_);
|
||||
|
||||
// If no packet is produced for this input frame, treat it as EAGAIN.
|
||||
// This is not a fatal error: encoders may buffer internally (e.g., startup delay).
|
||||
return encoded ? 0 : AVERROR(EAGAIN);
|
||||
}
|
||||
|
||||
int fill_frame(AVFrame *frame, uint8_t *data, int data_length,
|
||||
const int *const offset) {
|
||||
int receive_available_packets(const void *obj, bool &encoded) {
|
||||
int ret = 0;
|
||||
auto start = util::now();
|
||||
|
||||
while (util::elapsed_ms(start) < DECODE_TIMEOUT_MS) {
|
||||
ret = avcodec_receive_packet(c_, pkt_);
|
||||
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
|
||||
return 0;
|
||||
}
|
||||
if (ret < 0) {
|
||||
LOG_ERROR(std::string("avcodec_receive_packet failed, ret = ") + av_err2str(ret));
|
||||
av_packet_unref(pkt_);
|
||||
return ret;
|
||||
}
|
||||
if (!pkt_->data || !pkt_->size) {
|
||||
LOG_WARN(std::string("avcodec_receive_packet returned empty packet"));
|
||||
av_packet_unref(pkt_);
|
||||
continue;
|
||||
}
|
||||
encoded = true;
|
||||
if (packet_callback_) {
|
||||
AVPacket *owned_pkt = av_packet_clone(pkt_);
|
||||
if (!owned_pkt) {
|
||||
LOG_ERROR("av_packet_clone failed");
|
||||
av_packet_unref(pkt_);
|
||||
return AVERROR(ENOMEM);
|
||||
}
|
||||
packet_callback_(owned_pkt, owned_pkt->data, owned_pkt->size,
|
||||
owned_pkt->pts, owned_pkt->flags & AV_PKT_FLAG_KEY,
|
||||
obj);
|
||||
} else {
|
||||
callback_(pkt_->data, pkt_->size, pkt_->pts,
|
||||
pkt_->flags & AV_PKT_FLAG_KEY, obj);
|
||||
}
|
||||
av_packet_unref(pkt_);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int copy_plane(uint8_t *dst, int dst_stride, const uint8_t *src,
|
||||
int src_stride, int row_bytes, int rows) {
|
||||
if (!dst || !src || dst_stride < row_bytes || src_stride < row_bytes) {
|
||||
return -1;
|
||||
}
|
||||
if (rows <= 0 || row_bytes <= 0) {
|
||||
return 0;
|
||||
}
|
||||
if (dst_stride == row_bytes && src_stride == row_bytes) {
|
||||
memcpy(dst, src, static_cast<size_t>(row_bytes) * rows);
|
||||
return 0;
|
||||
}
|
||||
for (int y = 0; y < rows; y++) {
|
||||
memcpy(dst + y * dst_stride, src + y * src_stride, row_bytes);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int fill_frame(AVFrame *frame, const uint8_t *data, int data_length,
|
||||
const int *const) {
|
||||
const int src_y_stride = width_;
|
||||
const int src_packed_stride = width_ * bytes_per_pixel(frame->format);
|
||||
const int src_uv_stride = width_;
|
||||
const int src_y_size = width_ * frame->height;
|
||||
const int src_420_chroma_size = (width_ / 2) * (frame->height / 2);
|
||||
switch (frame->format) {
|
||||
case AV_PIX_FMT_NV12:
|
||||
case AV_PIX_FMT_NV21:
|
||||
if (data_length <
|
||||
frame->height * (frame->linesize[0] + frame->linesize[1] / 2)) {
|
||||
frame->height * src_y_stride + frame->height / 2 * src_uv_stride) {
|
||||
LOG_ERROR(std::string("fill_frame: NV12/NV21 data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", linesize[0]:" + std::to_string(frame->linesize[0]) +
|
||||
", linesize[1]:" + std::to_string(frame->linesize[1]));
|
||||
", width:" + std::to_string(width_) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
|
||||
width_, frame->height) != 0 ||
|
||||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
|
||||
src_uv_stride, width_, frame->height / 2) != 0) {
|
||||
LOG_ERROR("fill_frame: NV12/NV21 copy failed");
|
||||
return -1;
|
||||
}
|
||||
frame->data[0] = data;
|
||||
frame->data[1] = data + offset[0];
|
||||
break;
|
||||
case AV_PIX_FMT_NV16:
|
||||
case AV_PIX_FMT_NV24:
|
||||
if (data_length <
|
||||
frame->height * (frame->linesize[0] + frame->linesize[1])) {
|
||||
LOG_ERROR(std::string("fill_frame: NV16/NV24 data length error. data_length:") +
|
||||
frame->height * src_y_stride + frame->height * src_uv_stride) {
|
||||
LOG_ERROR(std::string("fill_frame: NV16 data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", linesize[0]:" + std::to_string(frame->linesize[0]) +
|
||||
", linesize[1]:" + std::to_string(frame->linesize[1]));
|
||||
", width:" + std::to_string(width_) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
|
||||
width_, frame->height) != 0 ||
|
||||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
|
||||
src_uv_stride, width_, frame->height) != 0) {
|
||||
LOG_ERROR("fill_frame: NV16 copy failed");
|
||||
return -1;
|
||||
}
|
||||
frame->data[0] = data;
|
||||
frame->data[1] = data + offset[0];
|
||||
break;
|
||||
case AV_PIX_FMT_NV24: {
|
||||
const int src_nv24_uv_stride = width_ * 2;
|
||||
if (data_length <
|
||||
frame->height * src_y_stride + frame->height * src_nv24_uv_stride) {
|
||||
LOG_ERROR(std::string("fill_frame: NV24 data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", width:" + std::to_string(width_) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data, src_y_stride,
|
||||
width_, frame->height) != 0 ||
|
||||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
|
||||
src_nv24_uv_stride, width_ * 2, frame->height) != 0) {
|
||||
LOG_ERROR("fill_frame: NV24 copy failed");
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case AV_PIX_FMT_YUV420P:
|
||||
if (data_length <
|
||||
frame->height * (frame->linesize[0] + frame->linesize[1] / 2 +
|
||||
frame->linesize[2] / 2)) {
|
||||
width_ * frame->height + (width_ / 2) * (frame->height / 2) * 2) {
|
||||
LOG_ERROR(std::string("fill_frame: 420P data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", linesize[0]:" + std::to_string(frame->linesize[0]) +
|
||||
", linesize[1]:" + std::to_string(frame->linesize[1]) +
|
||||
", linesize[2]:" + std::to_string(frame->linesize[2]));
|
||||
", width:" + std::to_string(width_) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data, width_,
|
||||
width_, frame->height) != 0 ||
|
||||
copy_plane(frame->data[1], frame->linesize[1], data + src_y_size,
|
||||
width_ / 2, width_ / 2, frame->height / 2) != 0 ||
|
||||
copy_plane(frame->data[2], frame->linesize[2],
|
||||
data + src_y_size + src_420_chroma_size,
|
||||
width_ / 2, width_ / 2, frame->height / 2) != 0) {
|
||||
LOG_ERROR("fill_frame: 420P copy failed");
|
||||
return -1;
|
||||
}
|
||||
frame->data[0] = data;
|
||||
frame->data[1] = data + offset[0];
|
||||
frame->data[2] = data + offset[1];
|
||||
break;
|
||||
case AV_PIX_FMT_YUYV422:
|
||||
case AV_PIX_FMT_YVYU422:
|
||||
case AV_PIX_FMT_UYVY422:
|
||||
// Packed YUV 4:2:2 formats: single plane, linesize[0] = width * 2
|
||||
if (data_length < frame->height * frame->linesize[0]) {
|
||||
if (data_length < frame->height * src_packed_stride) {
|
||||
LOG_ERROR(std::string("fill_frame: YUYV422 data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", linesize[0]:" + std::to_string(frame->linesize[0]) +
|
||||
", stride:" + std::to_string(src_packed_stride) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
frame->data[0] = data;
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data,
|
||||
src_packed_stride, src_packed_stride, frame->height) != 0) {
|
||||
LOG_ERROR("fill_frame: YUYV422 copy failed");
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
case AV_PIX_FMT_RGB24:
|
||||
case AV_PIX_FMT_BGR24:
|
||||
if (data_length < frame->height * frame->linesize[0]) {
|
||||
if (data_length < frame->height * src_packed_stride) {
|
||||
LOG_ERROR(std::string("fill_frame: RGB24/BGR24 data length error. data_length:") +
|
||||
std::to_string(data_length) +
|
||||
", linesize[0]:" + std::to_string(frame->linesize[0]) +
|
||||
", stride:" + std::to_string(src_packed_stride) +
|
||||
", height:" + std::to_string(frame->height));
|
||||
return -1;
|
||||
}
|
||||
frame->data[0] = data;
|
||||
if (copy_plane(frame->data[0], frame->linesize[0], data,
|
||||
src_packed_stride, src_packed_stride, frame->height) != 0) {
|
||||
LOG_ERROR("fill_frame: RGB24/BGR24 copy failed");
|
||||
return -1;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR(std::string("fill_frame: unsupported format, ") +
|
||||
@@ -479,23 +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) {
|
||||
if (encoder->init(linesize, offset, length)) {
|
||||
return encoder;
|
||||
}
|
||||
|
||||
// Retry only VAAPI with a fresh context in explicit-QP mode. This avoids
|
||||
// changing rate control on hardware which already supports CBR/VBR while
|
||||
// allowing CQP-only drivers to pass probing and normal encoder creation.
|
||||
if (name && std::string(name).find("vaapi") != std::string::npos &&
|
||||
rc != RC_CQ) {
|
||||
LOG_WARN(std::string("VAAPI bitrate-based rate control failed for ") +
|
||||
name + ", retrying with CQP");
|
||||
encoder = try_create(RC_CQ, 0);
|
||||
if (encoder) {
|
||||
return encoder;
|
||||
}
|
||||
}
|
||||
@@ -532,6 +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();
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
1
libs/v4l2r/.cargo-ok
Normal file
@@ -0,0 +1 @@
|
||||
{"v":1}
|
||||
6
libs/v4l2r/.cargo_vcs_info.json
Normal file
6
libs/v4l2r/.cargo_vcs_info.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "7b441383125ae583017a1c18b3fc9ec6c88ddbe8"
|
||||
},
|
||||
"path_in_vcs": "lib"
|
||||
}
|
||||
65
libs/v4l2r/Cargo.toml
Normal file
65
libs/v4l2r/Cargo.toml
Normal 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
28
libs/v4l2r/Cargo.toml.orig
generated
Normal 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
23
libs/v4l2r/LICENSE
Normal 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
19
libs/v4l2r/README.md
Normal 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
20
libs/v4l2r/bindgen.rs
Normal 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
43
libs/v4l2r/build.rs
Normal 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
55
libs/v4l2r/fix753.h
Normal 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
|
||||
31
libs/v4l2r/include/asm-generic/bitsperlong.h
Normal file
31
libs/v4l2r/include/asm-generic/bitsperlong.h
Normal 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 */
|
||||
40
libs/v4l2r/include/asm-generic/int-ll64.h
Normal file
40
libs/v4l2r/include/asm-generic/int-ll64.h
Normal 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 */
|
||||
105
libs/v4l2r/include/asm-generic/ioctl.h
Normal file
105
libs/v4l2r/include/asm-generic/ioctl.h
Normal 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 */
|
||||
99
libs/v4l2r/include/asm-generic/posix_types.h
Normal file
99
libs/v4l2r/include/asm-generic/posix_types.h
Normal 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 */
|
||||
9
libs/v4l2r/include/asm-generic/types.h
Normal file
9
libs/v4l2r/include/asm-generic/types.h
Normal 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 */
|
||||
53
libs/v4l2r/include/linux/const.h
Normal file
53
libs/v4l2r/include/linux/const.h
Normal 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 */
|
||||
8
libs/v4l2r/include/linux/ioctl.h
Normal file
8
libs/v4l2r/include/linux/ioctl.h
Normal 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 */
|
||||
|
||||
38
libs/v4l2r/include/linux/posix_types.h
Normal file
38
libs/v4l2r/include/linux/posix_types.h
Normal 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 */
|
||||
73
libs/v4l2r/include/linux/stddef.h
Normal file
73
libs/v4l2r/include/linux/stddef.h
Normal 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 */
|
||||
58
libs/v4l2r/include/linux/types.h
Normal file
58
libs/v4l2r/include/linux/types.h
Normal 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 */
|
||||
69
libs/v4l2r/include/linux/v4l2-common.h
Normal file
69
libs/v4l2r/include/linux/v4l2-common.h
Normal 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__ */
|
||||
3499
libs/v4l2r/include/linux/v4l2-controls.h
Normal file
3499
libs/v4l2r/include/linux/v4l2-controls.h
Normal file
File diff suppressed because it is too large
Load Diff
2730
libs/v4l2r/include/linux/videodev2.h
Normal file
2730
libs/v4l2r/include/linux/videodev2.h
Normal file
File diff suppressed because it is too large
Load Diff
8
libs/v4l2r/src/bindings.rs
Normal file
8
libs/v4l2r/src/bindings.rs
Normal 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
1177
libs/v4l2r/src/ioctl.rs
Normal file
File diff suppressed because it is too large
Load Diff
68
libs/v4l2r/src/ioctl/dqbuf.rs
Normal file
68
libs/v4l2r/src/ioctl/dqbuf.rs
Normal 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),
|
||||
)
|
||||
}
|
||||
137
libs/v4l2r/src/ioctl/enum_fmt.rs
Normal file
137
libs/v4l2r/src/ioctl/enum_fmt.rs
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
61
libs/v4l2r/src/ioctl/expbuf.rs
Normal file
61
libs/v4l2r/src/ioctl/expbuf.rs
Normal 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) })
|
||||
}
|
||||
82
libs/v4l2r/src/ioctl/frameintervals.rs
Normal file
82
libs/v4l2r/src/ioctl/frameintervals.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
79
libs/v4l2r/src/ioctl/framesizes.rs
Normal file
79
libs/v4l2r/src/ioctl/framesizes.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
189
libs/v4l2r/src/ioctl/g_dv_timings.rs
Normal file
189
libs/v4l2r/src/ioctl/g_dv_timings.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
300
libs/v4l2r/src/ioctl/g_fmt.rs
Normal file
300
libs/v4l2r/src/ioctl/g_fmt.rs
Normal 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))
|
||||
);
|
||||
}
|
||||
}
|
||||
149
libs/v4l2r/src/ioctl/g_parm.rs
Normal file
149
libs/v4l2r/src/ioctl/g_parm.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
130
libs/v4l2r/src/ioctl/g_selection.rs
Normal file
130
libs/v4l2r/src/ioctl/g_selection.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
117
libs/v4l2r/src/ioctl/mmap.rs
Normal file
117
libs/v4l2r/src/ioctl/mmap.rs
Normal 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,
|
||||
})
|
||||
}
|
||||
197
libs/v4l2r/src/ioctl/qbuf.rs
Normal file
197
libs/v4l2r/src/ioctl/qbuf.rs
Normal 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),
|
||||
)
|
||||
}
|
||||
113
libs/v4l2r/src/ioctl/querybuf.rs
Normal file
113
libs/v4l2r/src/ioctl/querybuf.rs
Normal 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),
|
||||
)
|
||||
}
|
||||
136
libs/v4l2r/src/ioctl/querycap.rs
Normal file
136
libs/v4l2r/src/ioctl/querycap.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
162
libs/v4l2r/src/ioctl/reqbufs.rs
Normal file
162
libs/v4l2r/src/ioctl/reqbufs.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
71
libs/v4l2r/src/ioctl/streamon.rs
Normal file
71
libs/v4l2r/src/ioctl/streamon.rs
Normal 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)),
|
||||
}
|
||||
}
|
||||
210
libs/v4l2r/src/ioctl/subscribe_event.rs
Normal file
210
libs/v4l2r/src/ioctl/subscribe_event.rs
Normal 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
496
libs/v4l2r/src/lib.rs
Normal 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
279
libs/v4l2r/src/memory.rs
Normal 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
|
||||
);
|
||||
}
|
||||
}
|
||||
91
libs/v4l2r/src/memory/dmabuf.rs
Normal file
91
libs/v4l2r/src/memory/dmabuf.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
58
libs/v4l2r/src/memory/mmap.rs
Normal file
58
libs/v4l2r/src/memory/mmap.rs
Normal 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()
|
||||
}
|
||||
}
|
||||
77
libs/v4l2r/src/memory/userptr.rs
Normal file
77
libs/v4l2r/src/memory/userptr.rs
Normal 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;
|
||||
}
|
||||
}
|
||||
4
libs/v4l2r/v4l2r_wrapper.h
Normal file
4
libs/v4l2r/v4l2r_wrapper.h
Normal file
@@ -0,0 +1,4 @@
|
||||
#include <linux/videodev2.h>
|
||||
|
||||
#define MARK_FIX_753(name) const unsigned long int Fix753_##name = name;
|
||||
#include "fix753.h"
|
||||
@@ -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]
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,4 @@ license = "BSD-3-Clause"
|
||||
[dependencies]
|
||||
|
||||
[build-dependencies]
|
||||
bindgen = "0.59"
|
||||
bindgen = "0.72"
|
||||
|
||||
@@ -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")]
|
||||
println!("cargo:rustc-link-lib=stdc++");
|
||||
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")]
|
||||
println!("cargo:rustc-link-lib=stdc++");
|
||||
if target_os == "linux" {
|
||||
println!("cargo:rustc-link-lib=stdc++");
|
||||
}
|
||||
println!("cargo:info=Using libyuv from vcpkg (dynamic linking)");
|
||||
}
|
||||
|
||||
@@ -224,17 +247,21 @@ 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 {
|
||||
match target_arch.as_str() {
|
||||
"x86_64" => "/usr/local/lib",
|
||||
"aarch64" => "/usr/aarch64-linux-gnu/lib",
|
||||
"arm" => "/usr/arm-linux-gnueabihf/lib",
|
||||
_ => "",
|
||||
}
|
||||
.to_string()
|
||||
};
|
||||
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",
|
||||
"arm" => "/usr/arm-linux-gnueabihf/lib",
|
||||
_ => "",
|
||||
}
|
||||
.to_string()
|
||||
});
|
||||
|
||||
// Try common system library paths (custom paths first)
|
||||
let mut lib_paths: Vec<String> = Vec::new();
|
||||
@@ -244,20 +271,22 @@ fn link_system() -> bool {
|
||||
lib_paths.push(custom_lib_path);
|
||||
}
|
||||
|
||||
// Then standard paths
|
||||
lib_paths.extend(
|
||||
[
|
||||
"/usr/local/lib", // Custom builds
|
||||
"/usr/local/lib64",
|
||||
"/usr/lib",
|
||||
"/usr/lib64",
|
||||
"/usr/lib/x86_64-linux-gnu", // Debian/Ubuntu x86_64
|
||||
"/usr/lib/aarch64-linux-gnu", // Debian/Ubuntu ARM64
|
||||
"/usr/lib/arm-linux-gnueabihf", // Debian/Ubuntu ARMv7
|
||||
]
|
||||
.iter()
|
||||
.map(|s| s.to_string()),
|
||||
);
|
||||
// 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
|
||||
"/usr/local/lib64",
|
||||
"/usr/lib",
|
||||
"/usr/lib64",
|
||||
"/usr/lib/x86_64-linux-gnu", // Debian/Ubuntu x86_64
|
||||
"/usr/lib/aarch64-linux-gnu", // Debian/Ubuntu ARM64
|
||||
"/usr/lib/arm-linux-gnueabihf", // Debian/Ubuntu ARMv7
|
||||
]
|
||||
.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
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,119 @@ 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
|
||||
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)
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut i420_buffer = vec![0u8; i420_size(w, h)];
|
||||
bgr24_to_i420(src, &mut i420_buffer, 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<()> {
|
||||
let (y_size, output_size) = mjpg_nv12_plane_sizes(width, height)?;
|
||||
if dst.len() < output_size {
|
||||
return Err(YuvError::BufferTooSmall);
|
||||
}
|
||||
|
||||
let (dst_y, dst_uv) = dst.split_at_mut(y_size);
|
||||
// SAFETY: the length check above guarantees writable storage for both planes.
|
||||
unsafe { mjpg_to_nv12_raw(src, dst_y.as_mut_ptr(), dst_uv.as_mut_ptr(), width, height) }
|
||||
}
|
||||
|
||||
/// Decode MJPEG directly into a reusable `Vec` without zero-filling the output first.
|
||||
///
|
||||
/// `Vec::resize` must initialize every byte before libyuv immediately overwrites the
|
||||
/// complete NV12 frame. This variant lets libyuv initialize spare capacity directly
|
||||
/// and publishes the new length only after a successful conversion.
|
||||
pub fn mjpg_to_nv12_vec(src: &[u8], dst: &mut Vec<u8>, width: i32, height: i32) -> Result<()> {
|
||||
let (y_size, output_size) = mjpg_nv12_plane_sizes(width, height)?;
|
||||
|
||||
dst.clear();
|
||||
dst.reserve(output_size);
|
||||
|
||||
// SAFETY: reserve above guarantees writable capacity for the Y and UV planes.
|
||||
// MJPGToNV12 writes the complete output on success; set_len is deliberately
|
||||
// delayed until then so callers can never observe partially initialized bytes.
|
||||
let result = unsafe {
|
||||
let dst_y = dst.as_mut_ptr();
|
||||
mjpg_to_nv12_raw(src, dst_y, dst_y.add(y_size), width, height)
|
||||
};
|
||||
result?;
|
||||
|
||||
// SAFETY: a successful MJPGToNV12 call initialized exactly output_size bytes.
|
||||
unsafe { dst.set_len(output_size) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn mjpg_nv12_plane_sizes(width: i32, height: i32) -> Result<(usize, usize)> {
|
||||
if width % 2 != 0 || height % 2 != 0 || width <= 0 || height <= 0 {
|
||||
return Err(YuvError::InvalidDimensions);
|
||||
}
|
||||
let y_size = (width as usize)
|
||||
.checked_mul(height as usize)
|
||||
.ok_or(YuvError::InvalidDimensions)?;
|
||||
let output_size = y_size
|
||||
.checked_mul(3)
|
||||
.map(|size| size / 2)
|
||||
.ok_or(YuvError::InvalidDimensions)?;
|
||||
Ok((y_size, output_size))
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// `dst_y` and `dst_uv` must point to writable planes sized for `width` x `height` NV12.
|
||||
#[inline]
|
||||
unsafe fn mjpg_to_nv12_raw(
|
||||
src: &[u8],
|
||||
dst_y: *mut u8,
|
||||
dst_uv: *mut u8,
|
||||
width: i32,
|
||||
height: i32,
|
||||
) -> Result<()> {
|
||||
call_yuv!(MJPGToNV12(
|
||||
src.as_ptr(),
|
||||
usize_to_size_t(src.len()),
|
||||
dst_y,
|
||||
width,
|
||||
dst_uv,
|
||||
width,
|
||||
width,
|
||||
height,
|
||||
width,
|
||||
height,
|
||||
))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -1310,4 +1439,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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
.await;
|
||||
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 {
|
||||
AtxAction::Reset => "Reset button not configured for ATX controller",
|
||||
_ => "Power button not configured for ATX controller",
|
||||
}
|
||||
.to_string()));
|
||||
return Err(AppError::Config(
|
||||
match action {
|
||||
AtxAction::Reset => "Reset button not configured for ATX controller",
|
||||
_ => "Power button not configured for ATX controller",
|
||||
}
|
||||
.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(),
|
||||
pin: 1,
|
||||
active_level: super::super::types::ActiveLevel::High,
|
||||
baud_rate: 9600,
|
||||
};
|
||||
let reset = AtxKeyConfig {
|
||||
driver: AtxDriverType::Serial,
|
||||
device: "/dev/ttyUSB0".to_string(),
|
||||
pin: 2,
|
||||
active_level: super::super::types::ActiveLevel::High,
|
||||
baud_rate: 9600,
|
||||
power: AtxOutputBinding {
|
||||
enabled: true,
|
||||
pin: 1,
|
||||
..Default::default()
|
||||
},
|
||||
reset: AtxOutputBinding {
|
||||
enabled: true,
|
||||
pin: 2,
|
||||
..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(),
|
||||
pin: 2,
|
||||
active_level: super::super::types::ActiveLevel::High,
|
||||
baud_rate: 115200,
|
||||
power: AtxOutputBinding {
|
||||
enabled: true,
|
||||
pin: 1,
|
||||
..Default::default()
|
||||
},
|
||||
reset: AtxOutputBinding {
|
||||
enabled: false,
|
||||
pin: 2,
|
||||
..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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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
|
||||
.flush()
|
||||
.map_err(|e| AppError::Internal(format!("USB relay flush failed: {}", e)))?;
|
||||
}
|
||||
device
|
||||
.write_all(&cmd)
|
||||
.map_err(|e| AppError::Internal(format!("LCUS HID relay write failed: {}", e)))?;
|
||||
device
|
||||
.flush()
|
||||
.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]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,22 +68,31 @@ 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 {
|
||||
PowerStatus::On
|
||||
} else {
|
||||
PowerStatus::Off
|
||||
})
|
||||
Ok(active)
|
||||
}
|
||||
None => Ok(PowerStatus::Unknown),
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn shutdown(&mut self) -> Result<()> {
|
||||
*self.handle.lock().unwrap() = None;
|
||||
self.initialized.store(false, Ordering::Relaxed);
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
136
src/atx/types.rs
136
src/atx/types.rs
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
//! Platform-neutral capture lifecycle and PCM frame types.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::{broadcast, watch, Mutex};
|
||||
use tracing::{debug, info};
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::utils::LogThrottler;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "capture_linux.rs"]
|
||||
mod imp;
|
||||
@@ -6,4 +18,146 @@ mod imp;
|
||||
#[path = "capture_windows.rs"]
|
||||
mod imp;
|
||||
|
||||
pub use imp::*;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioConfig {
|
||||
pub device_name: String,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
pub buffer_frames: u32,
|
||||
pub period_frames: u32,
|
||||
}
|
||||
|
||||
impl Default for AudioConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
device_name: String::new(),
|
||||
sample_rate: 48_000,
|
||||
channels: 2,
|
||||
buffer_frames: 4096,
|
||||
period_frames: 960,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioFrame {
|
||||
pub data: Bytes,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
}
|
||||
|
||||
impl AudioFrame {
|
||||
pub fn new_interleaved(data: Bytes, channels: u32, sample_rate: u32) -> Self {
|
||||
Self {
|
||||
data,
|
||||
sample_rate,
|
||||
channels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CaptureState {
|
||||
Stopped,
|
||||
Starting,
|
||||
Running,
|
||||
Error,
|
||||
}
|
||||
|
||||
pub struct AudioCapturer {
|
||||
config: AudioConfig,
|
||||
state: watch::Sender<CaptureState>,
|
||||
state_rx: watch::Receiver<CaptureState>,
|
||||
frame_tx: broadcast::Sender<AudioFrame>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
task: Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
lifecycle: Mutex<()>,
|
||||
log_throttler: LogThrottler,
|
||||
}
|
||||
|
||||
impl AudioCapturer {
|
||||
pub fn new(config: AudioConfig) -> Self {
|
||||
let (state, state_rx) = watch::channel(CaptureState::Stopped);
|
||||
let (frame_tx, _) = broadcast::channel(16);
|
||||
|
||||
Self {
|
||||
config,
|
||||
state,
|
||||
state_rx,
|
||||
frame_tx,
|
||||
stop_flag: Arc::new(AtomicBool::new(false)),
|
||||
task: Mutex::new(None),
|
||||
lifecycle: Mutex::new(()),
|
||||
log_throttler: LogThrottler::with_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> CaptureState {
|
||||
*self.state_rx.borrow()
|
||||
}
|
||||
|
||||
pub fn state_watch(&self) -> watch::Receiver<CaptureState> {
|
||||
self.state_rx.clone()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<AudioFrame> {
|
||||
self.frame_tx.subscribe()
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> Result<()> {
|
||||
let _lifecycle = self.lifecycle.lock().await;
|
||||
if matches!(self.state(), CaptureState::Starting | CaptureState::Running) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(previous) = self.task.lock().await.take() {
|
||||
let _ = previous.await;
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Starting audio capture on {} at {}Hz {}ch",
|
||||
self.config.device_name, self.config.sample_rate, self.config.channels
|
||||
);
|
||||
|
||||
self.stop_flag.store(false, Ordering::Release);
|
||||
let _ = self.state.send(CaptureState::Starting);
|
||||
|
||||
let config = self.config.clone();
|
||||
let state = self.state.clone();
|
||||
let frame_tx = self.frame_tx.clone();
|
||||
let stop_flag = Arc::clone(&self.stop_flag);
|
||||
let log_throttler = self.log_throttler.clone();
|
||||
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
match imp::run_capture(&config, &state, &frame_tx, &stop_flag, &log_throttler) {
|
||||
Ok(()) => {
|
||||
let _ = state.send(CaptureState::Stopped);
|
||||
}
|
||||
Err(error) => {
|
||||
crate::error_throttled!(
|
||||
log_throttler,
|
||||
"capture_error",
|
||||
"Audio capture error: {}",
|
||||
error
|
||||
);
|
||||
let _ = state.send(CaptureState::Error);
|
||||
}
|
||||
}
|
||||
});
|
||||
*self.task.lock().await = Some(task);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
let _lifecycle = self.lifecycle.lock().await;
|
||||
self.stop_flag.store(true, Ordering::Release);
|
||||
|
||||
if let Some(task) = self.task.lock().await.take() {
|
||||
let _ = task.await;
|
||||
}
|
||||
|
||||
let _ = self.state.send(CaptureState::Stopped);
|
||||
info!("Audio capture stopped");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,271 +1,60 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use alsa::pcm::{Access, Format, Frames, HwParams, State, IO};
|
||||
use alsa::{Direction, ValueOr, PCM};
|
||||
use bytes::Bytes;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::{broadcast, watch, Mutex};
|
||||
use tracing::{debug, info};
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::audio::device::AudioDeviceInfo;
|
||||
use super::{AudioConfig, AudioFrame, CaptureState};
|
||||
use crate::error::{AppError, Result};
|
||||
use crate::utils::LogThrottler;
|
||||
use crate::{error_throttled, warn_throttled};
|
||||
use crate::warn_throttled;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioConfig {
|
||||
pub device_name: String,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
pub frame_size: u32,
|
||||
pub buffer_frames: u32,
|
||||
pub period_frames: u32,
|
||||
}
|
||||
const RETRY_DELAY: Duration = Duration::from_millis(5);
|
||||
const MAX_CONSECUTIVE_READ_ERRORS: u32 = 10;
|
||||
|
||||
impl Default for AudioConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
device_name: String::new(),
|
||||
sample_rate: 48000,
|
||||
channels: 2,
|
||||
frame_size: 960,
|
||||
buffer_frames: 4096,
|
||||
period_frames: 960,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioConfig {
|
||||
pub fn for_device(device: &AudioDeviceInfo) -> Self {
|
||||
Self {
|
||||
device_name: device.name.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bytes_per_sample(&self) -> u32 {
|
||||
2 * self.channels
|
||||
}
|
||||
|
||||
pub fn bytes_per_frame(&self) -> usize {
|
||||
(self.frame_size * self.bytes_per_sample()) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioFrame {
|
||||
pub data: Bytes,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
pub samples: u32,
|
||||
pub sequence: u64,
|
||||
pub timestamp: Instant,
|
||||
}
|
||||
|
||||
impl AudioFrame {
|
||||
pub fn new_interleaved(data: Bytes, channels: u32, sample_rate: u32, sequence: u64) -> Self {
|
||||
let bps = 2 * channels;
|
||||
Self {
|
||||
samples: data.len() as u32 / bps,
|
||||
data,
|
||||
sample_rate,
|
||||
channels,
|
||||
sequence,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CaptureState {
|
||||
Stopped,
|
||||
Running,
|
||||
Error,
|
||||
}
|
||||
|
||||
pub struct AudioCapturer {
|
||||
config: AudioConfig,
|
||||
state: Arc<watch::Sender<CaptureState>>,
|
||||
state_rx: watch::Receiver<CaptureState>,
|
||||
frame_tx: broadcast::Sender<AudioFrame>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
sequence: Arc<AtomicU64>,
|
||||
capture_handle: Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
log_throttler: LogThrottler,
|
||||
}
|
||||
|
||||
impl AudioCapturer {
|
||||
pub fn new(config: AudioConfig) -> Self {
|
||||
let (state_tx, state_rx) = watch::channel(CaptureState::Stopped);
|
||||
let (frame_tx, _) = broadcast::channel(16);
|
||||
|
||||
Self {
|
||||
config,
|
||||
state: Arc::new(state_tx),
|
||||
state_rx,
|
||||
frame_tx,
|
||||
stop_flag: Arc::new(AtomicBool::new(false)),
|
||||
sequence: Arc::new(AtomicU64::new(0)),
|
||||
capture_handle: Mutex::new(None),
|
||||
log_throttler: LogThrottler::with_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> CaptureState {
|
||||
*self.state_rx.borrow()
|
||||
}
|
||||
|
||||
pub fn state_watch(&self) -> watch::Receiver<CaptureState> {
|
||||
self.state_rx.clone()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<AudioFrame> {
|
||||
self.frame_tx.subscribe()
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> Result<()> {
|
||||
if self.state() == CaptureState::Running {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Starting audio capture on {} at {}Hz {}ch",
|
||||
self.config.device_name, self.config.sample_rate, self.config.channels
|
||||
);
|
||||
|
||||
self.stop_flag.store(false, Ordering::SeqCst);
|
||||
|
||||
let config = self.config.clone();
|
||||
let state = self.state.clone();
|
||||
let frame_tx = self.frame_tx.clone();
|
||||
let stop_flag = self.stop_flag.clone();
|
||||
let sequence = self.sequence.clone();
|
||||
let log_throttler = self.log_throttler.clone();
|
||||
|
||||
let handle = tokio::task::spawn_blocking(move || {
|
||||
let result = run_capture(
|
||||
&config,
|
||||
&state,
|
||||
&frame_tx,
|
||||
&stop_flag,
|
||||
&sequence,
|
||||
&log_throttler,
|
||||
);
|
||||
|
||||
if let Err(e) = result {
|
||||
error_throttled!(log_throttler, "capture_error", "Audio capture error: {}", e);
|
||||
let _ = state.send(CaptureState::Error);
|
||||
} else {
|
||||
let _ = state.send(CaptureState::Stopped);
|
||||
}
|
||||
});
|
||||
|
||||
*self.capture_handle.lock().await = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
info!("Stopping audio capture");
|
||||
self.stop_flag.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Some(handle) = self.capture_handle.lock().await.take() {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
let _ = self.state.send(CaptureState::Stopped);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.state() == CaptureState::Running
|
||||
}
|
||||
}
|
||||
|
||||
fn run_capture(
|
||||
pub(super) fn run_capture(
|
||||
config: &AudioConfig,
|
||||
state: &watch::Sender<CaptureState>,
|
||||
frame_tx: &broadcast::Sender<AudioFrame>,
|
||||
stop_flag: &AtomicBool,
|
||||
sequence: &AtomicU64,
|
||||
log_throttler: &LogThrottler,
|
||||
) -> Result<()> {
|
||||
let pcm = PCM::new(&config.device_name, Direction::Capture, false).map_err(|e| {
|
||||
// Non-blocking mode guarantees that stop() can always join the worker.
|
||||
let pcm = PCM::new(&config.device_name, Direction::Capture, true).map_err(|error| {
|
||||
AppError::AudioError(format!(
|
||||
"Failed to open audio device {}: {}",
|
||||
config.device_name, e
|
||||
config.device_name, error
|
||||
))
|
||||
})?;
|
||||
|
||||
{
|
||||
let hwp = HwParams::any(&pcm)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to get HwParams: {}", e)))?;
|
||||
|
||||
hwp.set_channels(config.channels)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set channels: {}", e)))?;
|
||||
|
||||
hwp.set_rate(config.sample_rate, ValueOr::Nearest)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set sample rate: {}", e)))?;
|
||||
|
||||
hwp.set_format(Format::s16())
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set format: {}", e)))?;
|
||||
|
||||
hwp.set_access(Access::RWInterleaved)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set access: {}", e)))?;
|
||||
|
||||
hwp.set_buffer_size_near(config.buffer_frames as Frames)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set buffer size: {}", e)))?;
|
||||
|
||||
hwp.set_period_size_near(config.period_frames as Frames, ValueOr::Nearest)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to set period size: {}", e)))?;
|
||||
|
||||
pcm.hw_params(&hwp)
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to apply hw params: {}", e)))?;
|
||||
}
|
||||
|
||||
let hw_now = pcm.hw_params_current().map_err(|e| {
|
||||
AppError::AudioError(format!("Failed to read hw_params after apply: {}", e))
|
||||
})?;
|
||||
let actual_rate = hw_now
|
||||
.get_rate()
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to read sample rate: {}", e)))?;
|
||||
let actual_ch = hw_now
|
||||
.get_channels()
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to read channels: {}", e)))?;
|
||||
if actual_rate != 48_000 {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio capture requires 48000 Hz; device is {} Hz",
|
||||
actual_rate
|
||||
)));
|
||||
}
|
||||
if actual_ch != 2 {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio capture requires 2 channels (stereo); device has {}",
|
||||
actual_ch
|
||||
)));
|
||||
}
|
||||
debug!("Audio capture: 48000 Hz, 2 ch");
|
||||
|
||||
configure_pcm(&pcm, config)?;
|
||||
pcm.prepare()
|
||||
.map_err(|e| AppError::AudioError(format!("Failed to prepare PCM: {}", e)))?;
|
||||
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to prepare PCM: {error}")))?;
|
||||
let _ = state.send(CaptureState::Running);
|
||||
|
||||
let period_frames = pcm
|
||||
.hw_params_current()
|
||||
.ok()
|
||||
.and_then(|h| h.get_period_size().ok())
|
||||
.map(|f| f as usize)
|
||||
.unwrap_or(1024)
|
||||
.and_then(|params| params.get_period_size().ok())
|
||||
.map(|frames| frames as usize)
|
||||
.unwrap_or(config.period_frames as usize)
|
||||
.max(256);
|
||||
let buf_frames = period_frames.saturating_mul(4).max(2048);
|
||||
let bytes_per_frame = (config.channels as usize) * 2;
|
||||
let mut buffer = vec![0u8; buf_frames * bytes_per_frame];
|
||||
let mut buffer = vec![0u8; period_frames * config.channels as usize * 2];
|
||||
let io: IO<u8> = pcm.io_bytes();
|
||||
let mut consecutive_errors = 0;
|
||||
|
||||
while !stop_flag.load(Ordering::Relaxed) {
|
||||
while !stop_flag.load(Ordering::Acquire) {
|
||||
match pcm.state() {
|
||||
State::XRun => {
|
||||
warn_throttled!(log_throttler, "xrun", "Audio buffer overrun, recovering");
|
||||
let _ = pcm.prepare();
|
||||
pcm.prepare().map_err(|error| {
|
||||
AppError::AudioError(format!("Failed to recover audio xrun: {error}"))
|
||||
})?;
|
||||
consecutive_errors = 0;
|
||||
continue;
|
||||
}
|
||||
State::Suspended => {
|
||||
@@ -274,61 +63,95 @@ fn run_capture(
|
||||
"suspended",
|
||||
"Audio device suspended, recovering"
|
||||
);
|
||||
let _ = pcm.resume();
|
||||
if pcm.resume().is_err() {
|
||||
pcm.prepare().map_err(|error| {
|
||||
AppError::AudioError(format!("Failed to resume audio capture: {error}"))
|
||||
})?;
|
||||
}
|
||||
consecutive_errors = 0;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// io_bytes: USB capture often lacks mmap (io_checked requires it).
|
||||
let io: IO<u8> = pcm.io_bytes();
|
||||
|
||||
match io.readi(&mut buffer) {
|
||||
Ok(0) => thread::sleep(RETRY_DELAY),
|
||||
Ok(frames_read) => {
|
||||
if frames_read == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
consecutive_errors = 0;
|
||||
let byte_count = frames_read * config.channels as usize * 2;
|
||||
|
||||
let seq = sequence.fetch_add(1, Ordering::Relaxed);
|
||||
let frame = AudioFrame::new_interleaved(
|
||||
Bytes::copy_from_slice(&buffer[..byte_count]),
|
||||
config.channels,
|
||||
48_000,
|
||||
seq,
|
||||
config.sample_rate,
|
||||
);
|
||||
|
||||
if frame_tx.receiver_count() > 0 {
|
||||
if let Err(e) = frame_tx.send(frame) {
|
||||
debug!("No audio receivers: {}", e);
|
||||
}
|
||||
let _ = frame_tx.send(frame);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let desc = e.to_string();
|
||||
if is_device_lost_error(&desc) {
|
||||
Err(error) if error.errno() == libc::EAGAIN => thread::sleep(RETRY_DELAY),
|
||||
Err(error) if is_device_lost_errno(error.errno()) => {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio device lost while reading {}: {}",
|
||||
config.device_name, error
|
||||
)));
|
||||
}
|
||||
Err(error) if error.errno() == libc::EPIPE => {
|
||||
warn_throttled!(log_throttler, "buffer_overrun", "Audio buffer overrun");
|
||||
pcm.prepare().map_err(|prepare_error| {
|
||||
AppError::AudioError(format!(
|
||||
"Failed to recover after audio overrun ({error}): {prepare_error}"
|
||||
))
|
||||
})?;
|
||||
consecutive_errors = 0;
|
||||
}
|
||||
Err(error) => {
|
||||
consecutive_errors += 1;
|
||||
warn_throttled!(log_throttler, "read_error", "Audio read error: {}", error);
|
||||
if consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio device lost while reading {}: {}",
|
||||
config.device_name, e
|
||||
"Audio capture failed {consecutive_errors} times consecutively: {error}"
|
||||
)));
|
||||
} else if desc.contains("EPIPE") || desc.contains("Broken pipe") {
|
||||
warn_throttled!(log_throttler, "buffer_overrun", "Audio buffer overrun");
|
||||
let _ = pcm.prepare();
|
||||
} else {
|
||||
error_throttled!(log_throttler, "read_error", "Audio read error: {}", e);
|
||||
}
|
||||
thread::sleep(RETRY_DELAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!("Audio capture stopped");
|
||||
debug!("ALSA capture worker stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_device_lost_error(desc: &str) -> bool {
|
||||
desc.contains("No such device")
|
||||
|| desc.contains("ENODEV")
|
||||
|| desc.contains("ENXIO")
|
||||
|| desc.contains("ESHUTDOWN")
|
||||
fn configure_pcm(pcm: &PCM, config: &AudioConfig) -> Result<()> {
|
||||
let params = HwParams::any(pcm)
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to get HwParams: {error}")))?;
|
||||
params
|
||||
.set_channels(config.channels)
|
||||
.and_then(|_| params.set_rate(config.sample_rate, ValueOr::Nearest))
|
||||
.and_then(|_| params.set_format(Format::s16()))
|
||||
.and_then(|_| params.set_access(Access::RWInterleaved))
|
||||
.and_then(|_| params.set_buffer_size_near(config.buffer_frames as Frames))
|
||||
.and_then(|_| params.set_period_size_near(config.period_frames as Frames, ValueOr::Nearest))
|
||||
.and_then(|_| pcm.hw_params(¶ms))
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to configure audio PCM: {error}")))?;
|
||||
|
||||
let actual = pcm
|
||||
.hw_params_current()
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to read PCM parameters: {error}")))?;
|
||||
let actual_rate = actual
|
||||
.get_rate()
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to read sample rate: {error}")))?;
|
||||
let actual_channels = actual
|
||||
.get_channels()
|
||||
.map_err(|error| AppError::AudioError(format!("Failed to read channels: {error}")))?;
|
||||
if actual_rate != config.sample_rate || actual_channels != config.channels {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio device negotiated {actual_rate} Hz/{actual_channels} ch; expected {} Hz/{} ch",
|
||||
config.sample_rate, config.channels
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_device_lost_errno(errno: i32) -> bool {
|
||||
matches!(errno, libc::ENODEV | libc::ENXIO | libc::ESHUTDOWN)
|
||||
}
|
||||
|
||||
@@ -1,198 +1,23 @@
|
||||
use bytes::Bytes;
|
||||
use cpal::traits::{DeviceTrait, StreamTrait};
|
||||
use cpal::{BufferSize, SampleFormat, StreamConfig};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::{broadcast, watch, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::{debug, info};
|
||||
|
||||
use crate::audio::device::{find_wasapi_device, AudioDeviceInfo};
|
||||
use super::{AudioConfig, AudioFrame, CaptureState};
|
||||
use crate::audio::device::find_wasapi_device;
|
||||
use crate::error::{AppError, Result};
|
||||
use crate::error_throttled;
|
||||
use crate::utils::LogThrottler;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioConfig {
|
||||
pub device_name: String,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
pub frame_size: u32,
|
||||
pub buffer_frames: u32,
|
||||
pub period_frames: u32,
|
||||
}
|
||||
|
||||
impl Default for AudioConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
device_name: String::new(),
|
||||
sample_rate: 48000,
|
||||
channels: 2,
|
||||
frame_size: 960,
|
||||
buffer_frames: 4096,
|
||||
period_frames: 960,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioConfig {
|
||||
pub fn for_device(device: &AudioDeviceInfo) -> Self {
|
||||
Self {
|
||||
device_name: device.name.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bytes_per_sample(&self) -> u32 {
|
||||
2 * self.channels
|
||||
}
|
||||
|
||||
pub fn bytes_per_frame(&self) -> usize {
|
||||
(self.frame_size * self.bytes_per_sample()) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioFrame {
|
||||
pub data: Bytes,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u32,
|
||||
pub samples: u32,
|
||||
pub sequence: u64,
|
||||
pub timestamp: Instant,
|
||||
}
|
||||
|
||||
impl AudioFrame {
|
||||
pub fn new_interleaved(data: Bytes, channels: u32, sample_rate: u32, sequence: u64) -> Self {
|
||||
let bps = 2 * channels;
|
||||
Self {
|
||||
samples: data.len() as u32 / bps,
|
||||
data,
|
||||
sample_rate,
|
||||
channels,
|
||||
sequence,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CaptureState {
|
||||
Stopped,
|
||||
Running,
|
||||
Error,
|
||||
}
|
||||
|
||||
pub struct AudioCapturer {
|
||||
config: AudioConfig,
|
||||
state: Arc<watch::Sender<CaptureState>>,
|
||||
state_rx: watch::Receiver<CaptureState>,
|
||||
frame_tx: broadcast::Sender<AudioFrame>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
sequence: Arc<AtomicU64>,
|
||||
capture_handle: Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
log_throttler: LogThrottler,
|
||||
}
|
||||
|
||||
impl AudioCapturer {
|
||||
pub fn new(config: AudioConfig) -> Self {
|
||||
let (state_tx, state_rx) = watch::channel(CaptureState::Stopped);
|
||||
let (frame_tx, _) = broadcast::channel(16);
|
||||
|
||||
Self {
|
||||
config,
|
||||
state: Arc::new(state_tx),
|
||||
state_rx,
|
||||
frame_tx,
|
||||
stop_flag: Arc::new(AtomicBool::new(false)),
|
||||
sequence: Arc::new(AtomicU64::new(0)),
|
||||
capture_handle: Mutex::new(None),
|
||||
log_throttler: LogThrottler::with_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(&self) -> CaptureState {
|
||||
*self.state_rx.borrow()
|
||||
}
|
||||
|
||||
pub fn state_watch(&self) -> watch::Receiver<CaptureState> {
|
||||
self.state_rx.clone()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<AudioFrame> {
|
||||
self.frame_tx.subscribe()
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> Result<()> {
|
||||
if self.state() == CaptureState::Running {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Starting WASAPI audio capture on {} at {}Hz {}ch",
|
||||
self.config.device_name, self.config.sample_rate, self.config.channels
|
||||
);
|
||||
|
||||
self.stop_flag.store(false, Ordering::SeqCst);
|
||||
|
||||
let config = self.config.clone();
|
||||
let state = self.state.clone();
|
||||
let frame_tx = self.frame_tx.clone();
|
||||
let stop_flag = self.stop_flag.clone();
|
||||
let sequence = self.sequence.clone();
|
||||
let log_throttler = self.log_throttler.clone();
|
||||
|
||||
let handle = tokio::task::spawn_blocking(move || {
|
||||
let result = run_capture(
|
||||
&config,
|
||||
&state,
|
||||
&frame_tx,
|
||||
&stop_flag,
|
||||
&sequence,
|
||||
&log_throttler,
|
||||
);
|
||||
|
||||
if let Err(e) = result {
|
||||
error_throttled!(
|
||||
log_throttler,
|
||||
"capture_error",
|
||||
"WASAPI audio capture error: {}",
|
||||
e
|
||||
);
|
||||
let _ = state.send(CaptureState::Error);
|
||||
} else {
|
||||
let _ = state.send(CaptureState::Stopped);
|
||||
}
|
||||
});
|
||||
|
||||
*self.capture_handle.lock().await = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
info!("Stopping WASAPI audio capture");
|
||||
self.stop_flag.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Some(handle) = self.capture_handle.lock().await.take() {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
let _ = self.state.send(CaptureState::Stopped);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.state() == CaptureState::Running
|
||||
}
|
||||
}
|
||||
|
||||
fn run_capture(
|
||||
pub(super) fn run_capture(
|
||||
config: &AudioConfig,
|
||||
state: &watch::Sender<CaptureState>,
|
||||
frame_tx: &broadcast::Sender<AudioFrame>,
|
||||
stop_flag: &AtomicBool,
|
||||
sequence: &AtomicU64,
|
||||
log_throttler: &LogThrottler,
|
||||
) -> Result<()> {
|
||||
let device = find_wasapi_device(&config.device_name)?;
|
||||
@@ -220,7 +45,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 +54,7 @@ fn run_capture(
|
||||
),
|
||||
SampleFormat::I16 => build_stream::<i16>(
|
||||
&device,
|
||||
&stream_config,
|
||||
stream_config,
|
||||
input_channels,
|
||||
input_rate,
|
||||
tx.clone(),
|
||||
@@ -238,7 +63,7 @@ fn run_capture(
|
||||
),
|
||||
SampleFormat::U16 => build_stream::<u16>(
|
||||
&device,
|
||||
&stream_config,
|
||||
stream_config,
|
||||
input_channels,
|
||||
input_rate,
|
||||
tx.clone(),
|
||||
@@ -272,12 +97,10 @@ fn run_capture(
|
||||
if samples.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let seq = sequence.fetch_add(1, Ordering::Relaxed);
|
||||
let frame = AudioFrame::new_interleaved(
|
||||
Bytes::copy_from_slice(bytemuck::cast_slice(&samples)),
|
||||
2,
|
||||
48_000,
|
||||
seq,
|
||||
);
|
||||
if frame_tx.receiver_count() > 0 {
|
||||
if let Err(e) = frame_tx.send(frame) {
|
||||
@@ -361,7 +184,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 +331,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())
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
//! Device selection, quality presets, streaming.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::{Mutex, 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;
|
||||
@@ -20,23 +21,37 @@ pub(super) type AudioRecoveredCallback = Arc<dyn Fn() + Send + Sync>;
|
||||
pub struct AudioController {
|
||||
config: Arc<RwLock<AudioControllerConfig>>,
|
||||
streamer: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
||||
devices: Arc<RwLock<Vec<AudioDeviceInfo>>>,
|
||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
||||
monitor: Arc<AudioHealthMonitor>,
|
||||
recovery_in_progress: Arc<AtomicBool>,
|
||||
recovery: recovery::AudioRecovery,
|
||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
||||
operation: Arc<Mutex<()>>,
|
||||
}
|
||||
|
||||
impl AudioController {
|
||||
pub fn new(config: AudioControllerConfig) -> Self {
|
||||
let config = Arc::new(RwLock::new(config));
|
||||
let streamer = Arc::new(RwLock::new(None));
|
||||
let event_bus = Arc::new(RwLock::new(None));
|
||||
let monitor = Arc::new(AudioHealthMonitor::new());
|
||||
let recovered_callback = Arc::new(RwLock::new(None));
|
||||
let operation = Arc::new(Mutex::new(()));
|
||||
let recovery = recovery::AudioRecovery::new(
|
||||
config.clone(),
|
||||
streamer.clone(),
|
||||
event_bus.clone(),
|
||||
monitor.clone(),
|
||||
recovered_callback.clone(),
|
||||
operation.clone(),
|
||||
);
|
||||
Self {
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
streamer: Arc::new(RwLock::new(None)),
|
||||
devices: Arc::new(RwLock::new(Vec::new())),
|
||||
event_bus: Arc::new(RwLock::new(None)),
|
||||
monitor: Arc::new(AudioHealthMonitor::new()),
|
||||
recovery_in_progress: Arc::new(AtomicBool::new(false)),
|
||||
recovered_callback: Arc::new(RwLock::new(None)),
|
||||
config,
|
||||
streamer,
|
||||
event_bus,
|
||||
monitor,
|
||||
recovery,
|
||||
recovered_callback,
|
||||
operation,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,31 +68,6 @@ impl AudioController {
|
||||
bus.mark_device_info_dirty();
|
||||
}
|
||||
}
|
||||
fn spawn_recovery_task(&self, lost_device: String, reason: String) {
|
||||
recovery::spawn_recovery_task(
|
||||
self.config.clone(),
|
||||
self.streamer.clone(),
|
||||
self.event_bus.clone(),
|
||||
self.monitor.clone(),
|
||||
self.recovery_in_progress.clone(),
|
||||
self.recovered_callback.clone(),
|
||||
lost_device,
|
||||
reason,
|
||||
);
|
||||
}
|
||||
|
||||
fn spawn_stream_monitor(&self, streamer: Arc<AudioStreamer>, device: String) {
|
||||
recovery::spawn_stream_monitor(
|
||||
self.config.clone(),
|
||||
self.streamer.clone(),
|
||||
self.event_bus.clone(),
|
||||
self.monitor.clone(),
|
||||
self.recovery_in_progress.clone(),
|
||||
self.recovered_callback.clone(),
|
||||
streamer,
|
||||
device,
|
||||
);
|
||||
}
|
||||
|
||||
pub async fn list_devices(&self) -> Result<Vec<AudioDeviceInfo>> {
|
||||
let current_device = if self.is_streaming().await {
|
||||
@@ -86,26 +76,19 @@ impl AudioController {
|
||||
None
|
||||
};
|
||||
|
||||
let devices = enumerate_audio_devices_with_current(current_device.as_deref())?;
|
||||
*self.devices.write().await = devices.clone();
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
pub async fn get_cached_devices(&self) -> Vec<AudioDeviceInfo> {
|
||||
self.devices.read().await.clone()
|
||||
enumerate_audio_devices_with_current(current_device.as_deref())
|
||||
}
|
||||
|
||||
pub async fn select_device(&self, device: &str) -> Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.recovery.cancel();
|
||||
let devices = self.list_devices().await?;
|
||||
let found = devices
|
||||
.iter()
|
||||
.any(|d| d.name == device || d.description.contains(device));
|
||||
|
||||
if !found {
|
||||
return Err(AppError::AudioError(format!(
|
||||
"Audio device not found: {}",
|
||||
device
|
||||
)));
|
||||
return Err(AppError::NotFound(format!("audio device {device}")));
|
||||
}
|
||||
|
||||
{
|
||||
@@ -116,14 +99,15 @@ impl AudioController {
|
||||
info!("Audio device selected: {}", device);
|
||||
|
||||
if self.is_streaming().await {
|
||||
self.stop_streaming().await?;
|
||||
self.start_streaming().await?;
|
||||
self.stop_streaming_inner().await?;
|
||||
self.start_streaming_inner().await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_quality(&self, quality: AudioQuality) -> Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
{
|
||||
let mut config = self.config.write().await;
|
||||
config.quality = quality;
|
||||
@@ -142,6 +126,12 @@ impl AudioController {
|
||||
}
|
||||
|
||||
pub async fn start_streaming(&self) -> Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.recovery.cancel();
|
||||
self.start_streaming_inner().await
|
||||
}
|
||||
|
||||
async fn start_streaming_inner(&self) -> Result<()> {
|
||||
{
|
||||
let config = self.config.read().await;
|
||||
if !config.enabled {
|
||||
@@ -169,7 +159,7 @@ impl AudioController {
|
||||
|
||||
if let Some(error_msg) = select_error {
|
||||
self.monitor.report_error(&error_msg, "start_failed").await;
|
||||
self.spawn_recovery_task("auto".to_string(), error_msg.clone());
|
||||
self.recovery.start("auto".to_string(), error_msg.clone());
|
||||
self.mark_device_info_dirty().await;
|
||||
return Err(AppError::AudioError(error_msg));
|
||||
}
|
||||
@@ -192,7 +182,7 @@ impl AudioController {
|
||||
let error_msg = format!("Failed to start audio: {}", e);
|
||||
|
||||
self.monitor.report_error(&error_msg, "start_failed").await;
|
||||
self.spawn_recovery_task(device_name.clone(), error_msg.clone());
|
||||
self.recovery.start(device_name.clone(), error_msg.clone());
|
||||
|
||||
self.mark_device_info_dirty().await;
|
||||
|
||||
@@ -201,14 +191,13 @@ impl AudioController {
|
||||
|
||||
let streamer_for_monitor = streamer.clone();
|
||||
*self.streamer.write().await = Some(streamer);
|
||||
self.spawn_stream_monitor(streamer_for_monitor, device_name.clone());
|
||||
self.recovery
|
||||
.monitor(streamer_for_monitor, device_name.clone());
|
||||
|
||||
if self.monitor.is_error().await {
|
||||
self.monitor.report_recovered().await;
|
||||
}
|
||||
|
||||
self.recovery_in_progress.store(false, Ordering::SeqCst);
|
||||
|
||||
self.mark_device_info_dirty().await;
|
||||
|
||||
info!("Audio streaming started");
|
||||
@@ -216,7 +205,12 @@ impl AudioController {
|
||||
}
|
||||
|
||||
pub async fn stop_streaming(&self) -> Result<()> {
|
||||
self.recovery_in_progress.store(false, Ordering::SeqCst);
|
||||
let _operation = self.operation.lock().await;
|
||||
self.stop_streaming_inner().await
|
||||
}
|
||||
|
||||
async fn stop_streaming_inner(&self) -> Result<()> {
|
||||
self.recovery.cancel();
|
||||
|
||||
if let Some(streamer) = self.streamer.write().await.take() {
|
||||
streamer.stop().await?;
|
||||
@@ -247,7 +241,7 @@ impl AudioController {
|
||||
let (streaming, subscriber_count) = if let Some(ref streamer) = *self.streamer.read().await
|
||||
{
|
||||
let streaming = streamer.is_running();
|
||||
let subscriber_count = streamer.stats().subscriber_count;
|
||||
let subscriber_count = streamer.subscriber_count();
|
||||
(streaming, subscriber_count)
|
||||
} else {
|
||||
(false, 0)
|
||||
@@ -276,13 +270,15 @@ impl AudioController {
|
||||
}
|
||||
|
||||
pub async fn set_enabled(&self, enabled: bool) -> Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.recovery.cancel();
|
||||
{
|
||||
let mut config = self.config.write().await;
|
||||
config.enabled = enabled;
|
||||
}
|
||||
|
||||
if !enabled && self.is_streaming().await {
|
||||
self.stop_streaming().await?;
|
||||
self.stop_streaming_inner().await?;
|
||||
}
|
||||
|
||||
info!("Audio enabled: {}", enabled);
|
||||
@@ -290,16 +286,18 @@ impl AudioController {
|
||||
}
|
||||
|
||||
pub async fn update_config(&self, new_config: AudioControllerConfig) -> Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.recovery.cancel();
|
||||
let was_streaming = self.is_streaming().await;
|
||||
|
||||
if was_streaming {
|
||||
self.stop_streaming().await?;
|
||||
self.stop_streaming_inner().await?;
|
||||
}
|
||||
|
||||
*self.config.write().await = new_config.clone();
|
||||
|
||||
if new_config.enabled {
|
||||
self.start_streaming().await?;
|
||||
self.start_streaming_inner().await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
//! Shared device description with platform-specific enumeration backends.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "device_linux.rs"]
|
||||
mod imp;
|
||||
@@ -6,4 +12,32 @@ mod imp;
|
||||
#[path = "device_windows.rs"]
|
||||
mod imp;
|
||||
|
||||
pub use imp::*;
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AudioDeviceInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub card_index: i32,
|
||||
pub device_index: i32,
|
||||
pub sample_rates: Vec<u32>,
|
||||
pub channels: Vec<u32>,
|
||||
pub is_capture: bool,
|
||||
pub is_hdmi: bool,
|
||||
pub usb_bus: Option<String>,
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices() -> Result<Vec<AudioDeviceInfo>> {
|
||||
imp::enumerate_audio_devices_with_current(None)
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices_with_current(
|
||||
current_device: Option<&str>,
|
||||
) -> Result<Vec<AudioDeviceInfo>> {
|
||||
imp::enumerate_audio_devices_with_current(current_device)
|
||||
}
|
||||
|
||||
pub(crate) fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||
imp::find_best_audio_device()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) use imp::find_wasapi_device;
|
||||
|
||||
@@ -1,23 +1,10 @@
|
||||
use alsa::pcm::HwParams;
|
||||
use alsa::{Direction, PCM};
|
||||
use serde::Serialize;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::AudioDeviceInfo;
|
||||
use crate::error::{AppError, Result};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AudioDeviceInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub card_index: i32,
|
||||
pub device_index: i32,
|
||||
pub sample_rates: Vec<u32>,
|
||||
pub channels: Vec<u32>,
|
||||
pub is_capture: bool,
|
||||
pub is_hdmi: bool,
|
||||
pub usb_bus: Option<String>,
|
||||
}
|
||||
|
||||
fn get_usb_bus_info(card_index: i32) -> Option<String> {
|
||||
if card_index < 0 {
|
||||
return None;
|
||||
@@ -28,26 +15,18 @@ fn get_usb_bus_info(card_index: i32) -> Option<String> {
|
||||
let link_str = link_target.to_string_lossy();
|
||||
|
||||
for component in link_str.split('/') {
|
||||
if component.contains('-') && !component.contains(':') {
|
||||
if component
|
||||
.chars()
|
||||
.next()
|
||||
.map(|c| c.is_ascii_digit())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Some(component.to_string());
|
||||
}
|
||||
if component.contains('-')
|
||||
&& !component.contains(':')
|
||||
&& component.chars().next().is_some_and(|c| c.is_ascii_digit())
|
||||
{
|
||||
return Some(component.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices() -> Result<Vec<AudioDeviceInfo>> {
|
||||
enumerate_audio_devices_with_current(None)
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices_with_current(
|
||||
pub(super) fn enumerate_audio_devices_with_current(
|
||||
current_device: Option<&str>,
|
||||
) -> Result<Vec<AudioDeviceInfo>> {
|
||||
let mut devices = Vec::new();
|
||||
@@ -153,8 +132,8 @@ fn query_device_caps(pcm: &PCM) -> (Vec<u32>, Vec<u32>) {
|
||||
(supported_rates, supported_channels)
|
||||
}
|
||||
|
||||
pub fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||
let devices = enumerate_audio_devices()?;
|
||||
pub(super) fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||
let devices = enumerate_audio_devices_with_current(None)?;
|
||||
|
||||
if devices.is_empty() {
|
||||
return Err(AppError::AudioError(
|
||||
@@ -194,7 +173,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_enumerate_devices() {
|
||||
let result = enumerate_audio_devices();
|
||||
let result = enumerate_audio_devices_with_current(None);
|
||||
println!("Audio devices: {:?}", result);
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
@@ -1,29 +1,12 @@
|
||||
use cpal::traits::{DeviceTrait, HostTrait};
|
||||
use cpal::DeviceId;
|
||||
use serde::Serialize;
|
||||
use std::str::FromStr;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::AudioDeviceInfo;
|
||||
use crate::error::{AppError, Result};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AudioDeviceInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub card_index: i32,
|
||||
pub device_index: i32,
|
||||
pub sample_rates: Vec<u32>,
|
||||
pub channels: Vec<u32>,
|
||||
pub is_capture: bool,
|
||||
pub is_hdmi: bool,
|
||||
pub usb_bus: Option<String>,
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices() -> Result<Vec<AudioDeviceInfo>> {
|
||||
enumerate_audio_devices_with_current(None)
|
||||
}
|
||||
|
||||
pub fn enumerate_audio_devices_with_current(
|
||||
pub(super) fn enumerate_audio_devices_with_current(
|
||||
current_device: Option<&str>,
|
||||
) -> Result<Vec<AudioDeviceInfo>> {
|
||||
let host = cpal::default_host();
|
||||
@@ -130,11 +113,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 +125,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,
|
||||
@@ -195,8 +175,8 @@ pub(crate) fn find_wasapi_device(requested_device: &str) -> Result<cpal::Device>
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||
let devices = enumerate_audio_devices()?;
|
||||
pub(super) fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||
let devices = enumerate_audio_devices_with_current(None)?;
|
||||
|
||||
if devices.is_empty() {
|
||||
return Err(AppError::AudioError(
|
||||
|
||||
@@ -5,7 +5,6 @@ use audiopus::{coder::Encoder, Application, Bitrate, Channels, SampleRate};
|
||||
use bytes::Bytes;
|
||||
use tracing::debug;
|
||||
|
||||
use super::capture::AudioFrame;
|
||||
use crate::error::{AppError, Result};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -154,11 +153,6 @@ impl OpusEncoder {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn encode_frame(&mut self, frame: &AudioFrame) -> Result<OpusFrame> {
|
||||
let samples: &[i16] = bytemuck::cast_slice(&frame.data);
|
||||
self.encode(samples)
|
||||
}
|
||||
|
||||
pub fn config(&self) -> &OpusConfig {
|
||||
&self.config
|
||||
}
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
//! Platform audio capture, Opus encode, device enumeration, streaming, controller, health monitor.
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
pub mod capture;
|
||||
pub mod controller;
|
||||
mod capture;
|
||||
mod controller;
|
||||
#[cfg(any(unix, windows))]
|
||||
pub mod device;
|
||||
mod device;
|
||||
#[cfg(any(unix, windows))]
|
||||
pub mod encoder;
|
||||
pub mod monitor;
|
||||
pub mod recovery;
|
||||
pub mod streamer;
|
||||
pub mod types;
|
||||
mod encoder;
|
||||
mod monitor;
|
||||
mod recovery;
|
||||
mod streamer;
|
||||
mod types;
|
||||
#[cfg(unix)]
|
||||
pub mod uac;
|
||||
|
||||
pub use capture::{AudioCapturer, AudioConfig, AudioFrame};
|
||||
pub use controller::AudioController;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user