mirror of
https://github.com/mofeng-git/One-KVM.git
synced 2026-09-12 18:44:25 +08:00
Compare commits
80 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 |
146
.github/workflows/build.yml
vendored
146
.github/workflows/build.yml
vendored
@@ -34,13 +34,11 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 24
|
node-version: 24
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
|
|
||||||
- name: Build frontend
|
- name: Build frontend
|
||||||
working-directory: web
|
working-directory: web
|
||||||
run: |
|
run: |
|
||||||
npm ci
|
npm install
|
||||||
npm run build
|
npm run build
|
||||||
|
|
||||||
- name: Upload frontend dist
|
- name: Upload frontend dist
|
||||||
@@ -66,8 +64,16 @@ jobs:
|
|||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- 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
|
- name: Install cross
|
||||||
run: cargo install cross --locked
|
run: cargo install cross --version 0.2.5 --locked
|
||||||
|
|
||||||
- name: Build linux binary
|
- name: Build linux binary
|
||||||
run: bash build/build-images.sh
|
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_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
|
"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
|
- name: Build Windows exe
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: .\build\windows\build.ps1 -Configuration release -Package
|
run: .\build\windows\build.ps1 -Configuration release -Package
|
||||||
@@ -139,126 +151,9 @@ jobs:
|
|||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 7
|
retention-days: 7
|
||||||
|
|
||||||
android:
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
needs: frontend
|
|
||||||
timeout-minutes: 240
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Download frontend dist
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: web-dist
|
|
||||||
path: web/dist
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Cache Android Docker layers
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: /tmp/.buildx-cache/android
|
|
||||||
key: android-buildx-${{ runner.os }}-${{ hashFiles('build/cross/Dockerfile.android') }}
|
|
||||||
restore-keys: |
|
|
||||||
android-buildx-${{ runner.os }}-
|
|
||||||
|
|
||||||
- name: Build Android Docker image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: build/cross
|
|
||||||
file: build/cross/Dockerfile.android
|
|
||||||
tags: one-kvm-android-build:ci
|
|
||||||
load: true
|
|
||||||
cache-from: type=local,src=/tmp/.buildx-cache/android
|
|
||||||
cache-to: type=local,dest=/tmp/.buildx-cache/android-new,mode=max
|
|
||||||
|
|
||||||
- name: Rotate Android Docker layer cache
|
|
||||||
run: |
|
|
||||||
rm -rf /tmp/.buildx-cache/android
|
|
||||||
mv /tmp/.buildx-cache/android-new /tmp/.buildx-cache/android
|
|
||||||
|
|
||||||
- name: Cache Android build dependencies
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
.github/android-cache/gradle
|
|
||||||
.github/android-cache/cargo-registry
|
|
||||||
.github/android-cache/cargo-git
|
|
||||||
.tmp/android-ffmpeg-check
|
|
||||||
.tmp/android-turbojpeg-src
|
|
||||||
.tmp/android-libyuv-src
|
|
||||||
.tmp/android-alsa-src
|
|
||||||
.tmp/android-opus-src
|
|
||||||
dist/android-ffmpeg-mediacodec
|
|
||||||
dist/android-turbojpeg
|
|
||||||
dist/android-libyuv
|
|
||||||
dist/android-alsa
|
|
||||||
dist/android-opus
|
|
||||||
key: android-deps-${{ runner.os }}-${{ hashFiles('android/**/*.gradle.kts', 'android/gradle/wrapper/gradle-wrapper.properties', 'android/native/Cargo.lock', 'Cargo.lock', 'scripts/build-android-*.sh') }}
|
|
||||||
restore-keys: |
|
|
||||||
android-deps-${{ runner.os }}-
|
|
||||||
|
|
||||||
- name: Prepare Android FFmpeg source
|
|
||||||
run: |
|
|
||||||
chmod +x android/gradlew
|
|
||||||
if [ ! -x .tmp/android-ffmpeg-check/src/ffmpeg-rockchip/configure ]; then
|
|
||||||
rm -rf .tmp/android-ffmpeg-check/src
|
|
||||||
mkdir -p .tmp/android-ffmpeg-check/src
|
|
||||||
wget -q https://files.mofeng.run/src/image/other/ffmpeg.tar.gz -O .tmp/android-ffmpeg-check/ffmpeg.tar.gz
|
|
||||||
tar -xzf .tmp/android-ffmpeg-check/ffmpeg.tar.gz -C .tmp/android-ffmpeg-check/src --strip-components=1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Build Android APK
|
|
||||||
env:
|
|
||||||
ONE_KVM_ANDROID_DOCKER_IMAGE: one-kvm-android-build:ci
|
|
||||||
ONE_KVM_ANDROID_SKIP_DOCKER_BUILD: "1"
|
|
||||||
ONE_KVM_ANDROID_GRADLE_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/gradle
|
|
||||||
ONE_KVM_ANDROID_CARGO_REGISTRY_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/cargo-registry
|
|
||||||
ONE_KVM_ANDROID_CARGO_GIT_CACHE_DIR: ${{ github.workspace }}/.github/android-cache/cargo-git
|
|
||||||
run: bash build/build-android.sh all
|
|
||||||
|
|
||||||
- name: Fix Android build permissions
|
|
||||||
if: ${{ always() }}
|
|
||||||
run: |
|
|
||||||
paths=(
|
|
||||||
.github/android-cache
|
|
||||||
.tmp/android-ffmpeg-check
|
|
||||||
.tmp/android-turbojpeg-src
|
|
||||||
.tmp/android-libyuv-src
|
|
||||||
.tmp/android-alsa-src
|
|
||||||
.tmp/android-opus-src
|
|
||||||
dist/android-ffmpeg-mediacodec
|
|
||||||
dist/android-turbojpeg
|
|
||||||
dist/android-libyuv
|
|
||||||
dist/android-alsa
|
|
||||||
dist/android-opus
|
|
||||||
target/android
|
|
||||||
android/.gradle
|
|
||||||
android/app/build
|
|
||||||
android/native/target
|
|
||||||
)
|
|
||||||
existing=()
|
|
||||||
for path in "${paths[@]}"; do
|
|
||||||
if [ -e "$path" ]; then
|
|
||||||
existing+=("$path")
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
if [ "${#existing[@]}" -gt 0 ]; then
|
|
||||||
sudo chown -R "$USER:$USER" "${existing[@]}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Upload Android APK
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: one-kvm-android-apk
|
|
||||||
path: target/android/one-kvm_*.apk
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 7
|
|
||||||
|
|
||||||
release:
|
release:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
needs: [deb, windows, android]
|
needs: [deb, windows]
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_release }}
|
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_release }}
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
permissions:
|
permissions:
|
||||||
@@ -283,12 +178,6 @@ jobs:
|
|||||||
name: one-kvm-windows-exe
|
name: one-kvm-windows-exe
|
||||||
path: release-artifacts/windows
|
path: release-artifacts/windows
|
||||||
|
|
||||||
- name: Download Android artifact
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: one-kvm-android-apk
|
|
||||||
path: release-artifacts/android
|
|
||||||
|
|
||||||
- name: Publish GitHub Release
|
- name: Publish GitHub Release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
@@ -298,4 +187,3 @@ jobs:
|
|||||||
files: |
|
files: |
|
||||||
release-artifacts/deb/*.deb
|
release-artifacts/deb/*.deb
|
||||||
release-artifacts/windows/*.exe
|
release-artifacts/windows/*.exe
|
||||||
release-artifacts/android/*.apk
|
|
||||||
|
|||||||
14
.github/workflows/docker.yml
vendored
14
.github/workflows/docker.yml
vendored
@@ -37,21 +37,27 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 24
|
node-version: 24
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: web/package-lock.json
|
|
||||||
|
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- 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
|
- name: Install build dependencies
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y unzip xz-utils
|
sudo apt-get install -y unzip xz-utils
|
||||||
cargo install cross --locked
|
cargo install cross --version 0.2.5 --locked
|
||||||
|
|
||||||
- name: Build frontend
|
- name: Build frontend
|
||||||
working-directory: web
|
working-directory: web
|
||||||
run: |
|
run: |
|
||||||
npm ci
|
npm install
|
||||||
npm run build
|
npm run build
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
|
|||||||
107
Cargo.toml
107
Cargo.toml
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "one-kvm"
|
name = "one-kvm"
|
||||||
version = "0.2.3"
|
version = "0.2.6"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["SilentWind"]
|
authors = ["SilentWind"]
|
||||||
description = "A open and lightweight IP-KVM solution written in Rust"
|
description = "A open and lightweight IP-KVM solution written in Rust"
|
||||||
@@ -27,6 +27,7 @@ desktop = [
|
|||||||
"dep:anyhow",
|
"dep:anyhow",
|
||||||
"dep:argon2",
|
"dep:argon2",
|
||||||
"dep:rand",
|
"dep:rand",
|
||||||
|
"dep:totp-rs",
|
||||||
"dep:uuid",
|
"dep:uuid",
|
||||||
"dep:base64",
|
"dep:base64",
|
||||||
"dep:nix",
|
"dep:nix",
|
||||||
@@ -55,6 +56,7 @@ desktop = [
|
|||||||
"dep:serialport",
|
"dep:serialport",
|
||||||
"dep:async-trait",
|
"dep:async-trait",
|
||||||
"dep:libc",
|
"dep:libc",
|
||||||
|
"dep:libloading",
|
||||||
"dep:ventoy-img",
|
"dep:ventoy-img",
|
||||||
"dep:protobuf",
|
"dep:protobuf",
|
||||||
"dep:sodiumoxide",
|
"dep:sodiumoxide",
|
||||||
@@ -71,71 +73,9 @@ desktop = [
|
|||||||
"dep:cpal",
|
"dep:cpal",
|
||||||
"dep:windows-sys",
|
"dep:windows-sys",
|
||||||
]
|
]
|
||||||
android = [
|
|
||||||
"dep:anyhow",
|
|
||||||
"dep:argon2",
|
|
||||||
"dep:arc-swap",
|
|
||||||
"dep:async-stream",
|
|
||||||
"dep:async-trait",
|
|
||||||
"dep:axum",
|
|
||||||
"dep:axum-extra",
|
|
||||||
"dep:base64",
|
|
||||||
"dep:bytemuck",
|
|
||||||
"dep:bytes",
|
|
||||||
"dep:futures",
|
|
||||||
"dep:gpio-cdev",
|
|
||||||
"dep:hwcodec",
|
|
||||||
"dep:libc",
|
|
||||||
"dep:libyuv",
|
|
||||||
"dep:mime_guess",
|
|
||||||
"dep:nix",
|
|
||||||
"dep:parking_lot",
|
|
||||||
"dep:protobuf",
|
|
||||||
"dep:rand",
|
|
||||||
"dep:rcgen",
|
|
||||||
"dep:reqwest",
|
|
||||||
"dep:rtp",
|
|
||||||
"dep:rtsp-types",
|
|
||||||
"dep:rust-embed",
|
|
||||||
"dep:rustls",
|
|
||||||
"dep:sdp-types",
|
|
||||||
"dep:serde",
|
|
||||||
"dep:serde_json",
|
|
||||||
"dep:toml_edit",
|
|
||||||
"dep:serialport",
|
|
||||||
"dep:sha2",
|
|
||||||
"dep:sodiumoxide",
|
|
||||||
"dep:des",
|
|
||||||
"dep:sqlx",
|
|
||||||
"dep:alsa",
|
|
||||||
"dep:audiopus",
|
|
||||||
"dep:thiserror",
|
|
||||||
"dep:time",
|
|
||||||
"dep:tempfile",
|
|
||||||
"dep:tokio",
|
|
||||||
"dep:tokio-tungstenite",
|
|
||||||
"dep:tokio-util",
|
|
||||||
"dep:axum-server",
|
|
||||||
"dep:tower-http",
|
|
||||||
"dep:tracing",
|
|
||||||
"dep:tracing-log",
|
|
||||||
"dep:tracing-subscriber",
|
|
||||||
"dep:turbojpeg",
|
|
||||||
"dep:typeshare",
|
|
||||||
"dep:urlencoding",
|
|
||||||
"dep:uuid",
|
|
||||||
"dep:ventoy-img",
|
|
||||||
"dep:v4l2r",
|
|
||||||
"dep:webrtc",
|
|
||||||
"dep:xxhash-rust",
|
|
||||||
]
|
|
||||||
android-mediacodec = [
|
|
||||||
"android",
|
|
||||||
]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Async runtime
|
# Async runtime
|
||||||
tokio = { version = "1", features = ["full"], optional = true }
|
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 }
|
tokio-util = { version = "0.7", features = ["rt"], optional = true }
|
||||||
|
|
||||||
# Web framework
|
# Web framework
|
||||||
@@ -144,7 +84,7 @@ axum-extra = { version = "0.12", features = ["cookie"], optional = true }
|
|||||||
tower-http = { version = "0.6", features = ["cors", "trace", "set-header"], optional = true }
|
tower-http = { version = "0.6", features = ["cors", "trace", "set-header"], optional = true }
|
||||||
|
|
||||||
# Database - Use bundled SQLite for static linking
|
# Database - Use bundled SQLite for static linking
|
||||||
sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite"], optional = true }
|
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite-bundled"], optional = true }
|
||||||
|
|
||||||
# Serialization
|
# Serialization
|
||||||
serde = { version = "1", features = ["derive"], optional = true }
|
serde = { version = "1", features = ["derive"], optional = true }
|
||||||
@@ -153,7 +93,6 @@ toml_edit = { version = "0.25", optional = true }
|
|||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
tracing = { version = "0.1", optional = true }
|
tracing = { version = "0.1", optional = true }
|
||||||
tracing-log = { version = "0.2", optional = true }
|
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "tracing-log"], optional = true }
|
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "tracing-log"], optional = true }
|
||||||
|
|
||||||
# Error handling
|
# Error handling
|
||||||
@@ -162,7 +101,8 @@ anyhow = { version = "1", optional = true }
|
|||||||
|
|
||||||
# Authentication
|
# Authentication
|
||||||
argon2 = { version = "0.5", optional = true }
|
argon2 = { version = "0.5", optional = true }
|
||||||
rand = { version = "0.9", optional = true }
|
rand = { version = "0.10", optional = true }
|
||||||
|
totp-rs = { version = "5.7", features = ["gen_secret", "otpauth", "zeroize"], optional = true }
|
||||||
|
|
||||||
# Utilities
|
# Utilities
|
||||||
uuid = { version = "1", features = ["v4", "serde"], optional = true }
|
uuid = { version = "1", features = ["v4", "serde"], optional = true }
|
||||||
@@ -171,7 +111,7 @@ tempfile = { version = "3", optional = true }
|
|||||||
|
|
||||||
# HTTP client (for URL downloads)
|
# HTTP client (for URL downloads)
|
||||||
# Use rustls by default, but allow native-tls for systems with older GLIBC
|
# Use rustls by default, but allow native-tls for systems with older GLIBC
|
||||||
reqwest = { version = "0.13", features = ["stream", "rustls", "json"], default-features = false, optional = true }
|
reqwest = { version = "0.13", features = ["stream", "rustls-no-provider", "json"], default-features = false, optional = true }
|
||||||
urlencoding = { version = "2", optional = true }
|
urlencoding = { version = "2", optional = true }
|
||||||
|
|
||||||
# Static file embedding
|
# Static file embedding
|
||||||
@@ -179,9 +119,9 @@ rust-embed = { version = "8", features = ["compression", "debug-embed"], optiona
|
|||||||
mime_guess = { version = "2", optional = true }
|
mime_guess = { version = "2", optional = true }
|
||||||
|
|
||||||
# TLS/HTTPS
|
# TLS/HTTPS
|
||||||
rustls = { version = "0.23", features = ["ring"], optional = true }
|
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"], optional = true }
|
||||||
rcgen = { version = "0.14", optional = true }
|
rcgen = { version = "0.14", optional = true }
|
||||||
axum-server = { version = "0.8", features = ["tls-rustls"], optional = true }
|
axum-server = { version = "0.8", features = ["tls-rustls-no-provider"], optional = true }
|
||||||
|
|
||||||
# CLI argument parsing
|
# CLI argument parsing
|
||||||
clap = { version = "4", features = ["derive"], optional = true }
|
clap = { version = "4", features = ["derive"], optional = true }
|
||||||
@@ -201,15 +141,15 @@ async-stream = { version = "0.3", optional = true }
|
|||||||
futures = { version = "0.3", optional = true }
|
futures = { version = "0.3", optional = true }
|
||||||
|
|
||||||
# WebSocket client (for ttyd proxy)
|
# WebSocket client (for ttyd proxy)
|
||||||
tokio-tungstenite = { version = "0.28", optional = true }
|
tokio-tungstenite = { version = "0.29", optional = true }
|
||||||
|
|
||||||
# High-performance synchronization
|
# High-performance synchronization
|
||||||
parking_lot = { version = "0.12", optional = true }
|
parking_lot = { version = "0.12", optional = true }
|
||||||
arc-swap = { version = "1.8", optional = true }
|
arc-swap = { version = "1.8", optional = true }
|
||||||
|
|
||||||
# WebRTC
|
# WebRTC
|
||||||
webrtc = { version = "0.14", optional = true }
|
webrtc = { version = "0.17", optional = true }
|
||||||
rtp = { version = "0.14", optional = true }
|
rtp = { version = "0.17", optional = true }
|
||||||
rtsp-types = { version = "0.1", optional = true }
|
rtsp-types = { version = "0.1", optional = true }
|
||||||
sdp-types = { version = "0.1", optional = true }
|
sdp-types = { version = "0.1", optional = true }
|
||||||
|
|
||||||
@@ -217,6 +157,7 @@ sdp-types = { version = "0.1", optional = true }
|
|||||||
serialport = { version = "4", optional = true }
|
serialport = { version = "4", optional = true }
|
||||||
async-trait = { version = "0.1", optional = true }
|
async-trait = { version = "0.1", optional = true }
|
||||||
libc = { version = "0.2", optional = true }
|
libc = { version = "0.2", optional = true }
|
||||||
|
libloading = { version = "0.8", optional = true }
|
||||||
|
|
||||||
# Ventoy bootable image support
|
# Ventoy bootable image support
|
||||||
ventoy-img = { path = "libs/ventoy-img-rs", optional = true }
|
ventoy-img = { path = "libs/ventoy-img-rs", optional = true }
|
||||||
@@ -224,12 +165,12 @@ ventoy-img = { path = "libs/ventoy-img-rs", optional = true }
|
|||||||
# RustDesk protocol support
|
# RustDesk protocol support
|
||||||
protobuf = { version = "3.7", features = ["with-bytes"], optional = true }
|
protobuf = { version = "3.7", features = ["with-bytes"], optional = true }
|
||||||
sodiumoxide = { version = "0.2", optional = true }
|
sodiumoxide = { version = "0.2", optional = true }
|
||||||
des = { version = "0.8", optional = true }
|
des = { version = "0.9", optional = true }
|
||||||
sha2 = { version = "0.10", optional = true }
|
sha2 = { version = "0.11", optional = true }
|
||||||
# TypeScript type generation
|
# TypeScript type generation
|
||||||
typeshare = { version = "1.0", optional = true }
|
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)
|
# Video encoding/decoding (FFmpeg/libjpeg-turbo/libyuv; available on Windows and Linux)
|
||||||
hwcodec = { path = "libs/hwcodec", features = ["bytes"], optional = true }
|
hwcodec = { path = "libs/hwcodec", features = ["bytes"], optional = true }
|
||||||
libyuv = { path = "res/vcpkg/libyuv", optional = true }
|
libyuv = { path = "res/vcpkg/libyuv", optional = true }
|
||||||
@@ -237,15 +178,10 @@ turbojpeg = { version = "1.3", optional = true }
|
|||||||
# Note: audiopus links to libopus.so (unavoidable for audio support)
|
# Note: audiopus links to libopus.so (unavoidable for audio support)
|
||||||
audiopus = { version = "0.2", optional = true }
|
audiopus = { version = "0.2", optional = true }
|
||||||
|
|
||||||
[target.'cfg(all(unix, not(target_os = "android")))'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
# Utilities
|
# Utilities
|
||||||
nix = { version = "0.30", default-features = false, features = ["fs", "socket", "net", "hostname", "poll"], optional = true }
|
nix = { version = "0.31", default-features = false, features = ["fs", "socket", "net", "hostname", "poll"], optional = true }
|
||||||
|
|
||||||
[target.'cfg(target_os = "android")'.dependencies]
|
|
||||||
# Utilities
|
|
||||||
nix = { version = "0.30", default-features = false, features = ["fs", "socket", "hostname", "poll"], optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(unix)'.dependencies]
|
|
||||||
# Video capture (V4L2)
|
# Video capture (V4L2)
|
||||||
v4l2r = { path = "libs/v4l2r", optional = true }
|
v4l2r = { path = "libs/v4l2r", optional = true }
|
||||||
|
|
||||||
@@ -256,7 +192,7 @@ alsa = { version = "0.11", optional = true }
|
|||||||
gpio-cdev = { version = "0.6", optional = true }
|
gpio-cdev = { version = "0.6", optional = true }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
cpal = { version = "0.17", default-features = false, optional = true }
|
cpal = { version = "0.18", default-features = false, optional = true }
|
||||||
windows-sys = { version = "0.61", features = [
|
windows-sys = { version = "0.61", features = [
|
||||||
"Win32_Foundation",
|
"Win32_Foundation",
|
||||||
"Win32_NetworkManagement_IpHelper",
|
"Win32_NetworkManagement_IpHelper",
|
||||||
@@ -266,9 +202,6 @@ windows-sys = { version = "0.61", features = [
|
|||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
], optional = true }
|
], optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tempfile = "3"
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
protobuf-codegen = "3.7"
|
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.
|
- **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.
|
- **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>.
|
> **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">
|
<div align="center">
|
||||||
@@ -32,7 +34,7 @@ Goals: an open, lightweight, easy-to-use IP-KVM stack.
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### Core
|
**Core**
|
||||||
|
|
||||||
| Area | Capabilities |
|
| 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 |
|
| Video encoding | VAAPI / QSV / RKMPP / V4L2 M2M hardware paths, with software fallback |
|
||||||
| Keyboard & mouse | USB OTG HID or CH340 + CH9329 HID; absolute / relative mouse |
|
| 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 |
|
| 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) |
|
| 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
|
## 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).
|
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
|
- 爱发电用户_d3d9c
|
||||||
|
|
||||||
|
- 爱发电用户_97b41
|
||||||
|
|
||||||
|
- 偶然
|
||||||
|
|
||||||
|
- 爱发电用户_dba45
|
||||||
|
|
||||||
|
- 爱发电用户_d4f8b
|
||||||
|
|
||||||
|
- 故人。
|
||||||
|
|
||||||
- ......
|
- ......
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
### Sponsors
|
### Sponsors
|
||||||
|
|
||||||
**Mirror Download Services:**
|
|
||||||
- **[Chongqing University Open Source Software Mirror](https://mirrors.cqu.edu.cn/)** — provides mirror download services
|
|
||||||
|
|
||||||
**File hosting**
|
**File hosting**
|
||||||
|
|
||||||
- **[Huang1111 public-interest program](https://pan.huang1111.cn/s/mxkx3T1)** — login-free downloads
|
- **[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.
|
林枫云 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 级远程控制。
|
**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>。
|
> **One-KVM Python** 已停止开发,如有需要可访问 <https://github.com/mofeng-git/One-KVM/tree/python>。
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
@@ -30,9 +32,9 @@
|
|||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## 📊 功能介绍
|
## 功能介绍
|
||||||
|
|
||||||
### 核心功能
|
**核心功能**
|
||||||
|
|
||||||
| 功能 | 能力说明 |
|
| 功能 | 能力说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
@@ -40,12 +42,10 @@
|
|||||||
| 视频编码 | VAAPI/QSV/RKMPP/V4L2M2M 硬件编码支持,以及软件编码兜底 |
|
| 视频编码 | VAAPI/QSV/RKMPP/V4L2M2M 硬件编码支持,以及软件编码兜底 |
|
||||||
| 键鼠控制 | USB OTG HID 或 CH340 + CH9329 HID,支持绝对/相对鼠标模式 |
|
| 键鼠控制 | USB OTG HID 或 CH340 + CH9329 HID,支持绝对/相对鼠标模式 |
|
||||||
| 虚拟媒体 | USB Mass Storage,支持 ISO/IMG 镜像挂载和 Ventoy 虚拟U盘模式 |
|
| 虚拟媒体 | USB Mass Storage,支持 ISO/IMG 镜像挂载和 Ventoy 虚拟U盘模式 |
|
||||||
| ATX 电源控制 | GPIO /USB 继电器,支持控制电源、重启按钮 |
|
| ATX 电源控制 | GPIO/USB 继电器,支持电源控制 |
|
||||||
| 音频传输 | ALSA 采集 + Opus 编码(HTTP/WebRTC) |
|
| 音频传输 | 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/)。
|
构建产物见 [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
|
- 爱发电用户_d3d9c
|
||||||
|
|
||||||
|
- 爱发电用户_97b41
|
||||||
|
|
||||||
|
- 偶然
|
||||||
|
|
||||||
|
- 爱发电用户_dba45
|
||||||
|
|
||||||
|
- 爱发电用户_d4f8b
|
||||||
|
|
||||||
|
- 故人。
|
||||||
|
|
||||||
- ......
|
- ......
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
@@ -218,9 +228,6 @@ One-KVM 已上架飞牛 **应用市场**,在 NAS 上直接搜索安装即可
|
|||||||
|
|
||||||
本项目得到以下赞助商的支持:
|
本项目得到以下赞助商的支持:
|
||||||
|
|
||||||
**镜像下载服务:**
|
|
||||||
- **[重庆大学开源软件镜像站](https://mirrors.cqu.edu.cn/)** - 提供镜像站下载服务
|
|
||||||
|
|
||||||
**文件存储服务:**
|
**文件存储服务:**
|
||||||
- **[Huang1111公益计划](https://pan.huang1111.cn/s/mxkx3T1)** - 提供免登录下载服务
|
- **[Huang1111公益计划](https://pan.huang1111.cn/s/mxkx3T1)** - 提供免登录下载服务
|
||||||
|
|
||||||
|
|||||||
7
android/.gitignore
vendored
7
android/.gitignore
vendored
@@ -1,7 +0,0 @@
|
|||||||
.gradle/
|
|
||||||
.kotlin/
|
|
||||||
build/
|
|
||||||
local.properties
|
|
||||||
app/build/
|
|
||||||
app/src/main/jniLibs/
|
|
||||||
native/target/
|
|
||||||
@@ -1,559 +0,0 @@
|
|||||||
import org.gradle.api.tasks.Exec
|
|
||||||
import java.security.MessageDigest
|
|
||||||
import java.util.Properties
|
|
||||||
|
|
||||||
plugins {
|
|
||||||
id("com.android.application")
|
|
||||||
}
|
|
||||||
|
|
||||||
val androidNdkVersion = "27.3.13750724"
|
|
||||||
val androidApiLevel = 21
|
|
||||||
val nativeCrateDir = layout.projectDirectory.dir("../native")
|
|
||||||
val rootCrateDir = layout.projectDirectory.dir("../..")
|
|
||||||
val nativeCargoOutputDir = layout.buildDirectory.dir("generated/oneKvm/cargoJniLibs")
|
|
||||||
val nativeOutputRoot = layout.buildDirectory.dir("generated/oneKvm/jniLibs")
|
|
||||||
val nativeAssetRoot = layout.buildDirectory.dir("generated/oneKvm/assets")
|
|
||||||
val defaultAndroidFfmpegRoot = rootProject.layout.projectDirectory.dir("../dist/android-ffmpeg-mediacodec")
|
|
||||||
val defaultAndroidLibyuvRoot = rootProject.layout.projectDirectory.dir("../dist/android-libyuv")
|
|
||||||
val defaultAndroidTurbojpegRoot = rootProject.layout.projectDirectory.dir("../dist/android-turbojpeg")
|
|
||||||
val defaultAndroidAlsaRoot = rootProject.layout.projectDirectory.dir("../dist/android-alsa")
|
|
||||||
val defaultAndroidOpusRoot = rootProject.layout.projectDirectory.dir("../dist/android-opus")
|
|
||||||
val androidFfmpegRoot = providers.environmentVariable("ONE_KVM_ANDROID_FFMPEG_ROOT")
|
|
||||||
.orElse(defaultAndroidFfmpegRoot.asFile.absolutePath)
|
|
||||||
val androidLibyuvRoot = providers.environmentVariable("ONE_KVM_ANDROID_LIBYUV_ROOT")
|
|
||||||
.orElse(defaultAndroidLibyuvRoot.asFile.absolutePath)
|
|
||||||
val androidTurbojpegRoot = providers.environmentVariable("ONE_KVM_ANDROID_TURBOJPEG_ROOT")
|
|
||||||
.orElse(defaultAndroidTurbojpegRoot.asFile.absolutePath)
|
|
||||||
val androidAlsaRoot = providers.environmentVariable("ONE_KVM_ANDROID_ALSA_ROOT")
|
|
||||||
.orElse(defaultAndroidAlsaRoot.asFile.absolutePath)
|
|
||||||
val androidOpusRoot = providers.environmentVariable("ONE_KVM_ANDROID_OPUS_ROOT")
|
|
||||||
.orElse(defaultAndroidOpusRoot.asFile.absolutePath)
|
|
||||||
val selectedAndroidAbis = providers.environmentVariable("ONE_KVM_ANDROID_ABIS")
|
|
||||||
.orElse("arm64-v8a,armeabi-v7a")
|
|
||||||
.get()
|
|
||||||
.split(',', ' ', ';')
|
|
||||||
.map { it.trim() }
|
|
||||||
.filter { it.isNotEmpty() }
|
|
||||||
.distinct()
|
|
||||||
val androidBuildProfile = providers.environmentVariable("ONE_KVM_ANDROID_PROFILE")
|
|
||||||
.orElse("debug")
|
|
||||||
.get()
|
|
||||||
.lowercase()
|
|
||||||
val oneKvmVersion = Regex("""(?m)^version\s*=\s*"([^"]+)"""")
|
|
||||||
.find(rootCrateDir.file("Cargo.toml").asFile.readText())
|
|
||||||
?.groupValues
|
|
||||||
?.get(1)
|
|
||||||
?: throw GradleException("Failed to resolve version from root Cargo.toml")
|
|
||||||
val localProperties = Properties().apply {
|
|
||||||
val file = rootProject.file("local.properties")
|
|
||||||
if (file.exists()) {
|
|
||||||
file.inputStream().use { load(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val androidSdkDir = file(
|
|
||||||
providers.environmentVariable("ANDROID_HOME")
|
|
||||||
.orElse(providers.environmentVariable("ANDROID_SDK_ROOT"))
|
|
||||||
.orElse(localProperties.getProperty("sdk.dir") ?: "/root/android-sdk")
|
|
||||||
.get(),
|
|
||||||
)
|
|
||||||
val androidNdkDir = androidSdkDir.resolve("ndk/$androidNdkVersion")
|
|
||||||
|
|
||||||
val androidFfmpegBuildScript = rootProject.layout.projectDirectory
|
|
||||||
.dir("..")
|
|
||||||
.file("scripts/build-android-ffmpeg-mediacodec.sh")
|
|
||||||
val androidLibyuvBuildScript = rootProject.layout.projectDirectory
|
|
||||||
.dir("..")
|
|
||||||
.file("scripts/build-android-libyuv.sh")
|
|
||||||
val androidTurbojpegBuildScript = rootProject.layout.projectDirectory
|
|
||||||
.dir("..")
|
|
||||||
.file("scripts/build-android-turbojpeg.sh")
|
|
||||||
val androidAlsaBuildScript = rootProject.layout.projectDirectory
|
|
||||||
.dir("..")
|
|
||||||
.file("scripts/build-android-alsa.sh")
|
|
||||||
val androidOpusBuildScript = rootProject.layout.projectDirectory
|
|
||||||
.dir("..")
|
|
||||||
.file("scripts/build-android-opus.sh")
|
|
||||||
|
|
||||||
val androidAbiTargets = mapOf(
|
|
||||||
"arm64-v8a" to Triple("arm64", "aarch64-linux-android", "aarch64-linux-android"),
|
|
||||||
"armeabi-v7a" to Triple("arm32", "armv7-linux-androideabi", "arm-linux-androideabi"),
|
|
||||||
)
|
|
||||||
|
|
||||||
val selectedAndroidAbiTargets = selectedAndroidAbis.associateWith { abi ->
|
|
||||||
androidAbiTargets[abi] ?: throw GradleException(
|
|
||||||
"Unsupported ONE_KVM_ANDROID_ABIS entry: $abi. Supported values: ${androidAbiTargets.keys.joinToString(", ")}",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (androidBuildProfile != "debug" && androidBuildProfile != "release") {
|
|
||||||
throw GradleException("Unsupported ONE_KVM_ANDROID_PROFILE: $androidBuildProfile. Use debug or release.")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidFfmpegBuildStamp(script: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(script.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidFfmpegRequiredFiles(root: File): List<File> = listOf(
|
|
||||||
"include/libavcodec/avcodec.h",
|
|
||||||
"lib/libavcodec.a",
|
|
||||||
"lib/libavutil.a",
|
|
||||||
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
|
|
||||||
|
|
||||||
fun androidLibyuvBuildStamp(script: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(script.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
val turbojpegScriptDigest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(androidTurbojpegBuildScript.asFile.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest;turbojpegScript=$turbojpegScriptDigest"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidLibyuvRequiredFiles(root: File): List<File> = listOf(
|
|
||||||
"include/libyuv.h",
|
|
||||||
"lib/libyuv.a",
|
|
||||||
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
|
|
||||||
|
|
||||||
fun androidTurbojpegBuildStamp(script: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(script.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidAlsaBuildStamp(script: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(script.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidOpusBuildStamp(script: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(script.readBytes())
|
|
||||||
.joinToString("") { "%02x".format(it) }
|
|
||||||
return "api=$androidApiLevel;abis=${selectedAndroidAbis.joinToString(",")};script=$digest"
|
|
||||||
}
|
|
||||||
|
|
||||||
fun androidTurbojpegRequiredFiles(root: File): List<File> = listOf(
|
|
||||||
"include/turbojpeg.h",
|
|
||||||
"include/jpeglib.h",
|
|
||||||
"lib/libjpeg.a",
|
|
||||||
"lib/libturbojpeg.a",
|
|
||||||
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
|
|
||||||
|
|
||||||
fun androidAlsaRequiredFiles(root: File): List<File> = listOf(
|
|
||||||
"include/alsa/asoundlib.h",
|
|
||||||
"lib/libasound.so",
|
|
||||||
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
|
|
||||||
|
|
||||||
fun androidOpusRequiredFiles(root: File): List<File> = listOf(
|
|
||||||
"include/opus/opus.h",
|
|
||||||
"lib/libopus.so",
|
|
||||||
).flatMap { path -> selectedAndroidAbis.map { abi -> root.resolve("$abi/$path") } }
|
|
||||||
|
|
||||||
android {
|
|
||||||
namespace = "cn.one_kvm.androidhost"
|
|
||||||
compileSdk = 36
|
|
||||||
ndkVersion = androidNdkVersion
|
|
||||||
flavorDimensions += "abi"
|
|
||||||
|
|
||||||
defaultConfig {
|
|
||||||
applicationId = "cn.one_kvm.androidhost"
|
|
||||||
minSdk = androidApiLevel
|
|
||||||
targetSdk = 36
|
|
||||||
versionCode = 1
|
|
||||||
versionName = oneKvmVersion
|
|
||||||
}
|
|
||||||
|
|
||||||
productFlavors {
|
|
||||||
create("arm32") {
|
|
||||||
dimension = "abi"
|
|
||||||
ndk {
|
|
||||||
abiFilters += "armeabi-v7a"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
create("arm64") {
|
|
||||||
dimension = "abi"
|
|
||||||
ndk {
|
|
||||||
abiFilters += "arm64-v8a"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceSets {
|
|
||||||
getByName("main") {
|
|
||||||
assets.directories.clear()
|
|
||||||
jniLibs.directories.clear()
|
|
||||||
}
|
|
||||||
getByName("arm32") {
|
|
||||||
assets.directories.add("build/generated/oneKvm/assets/arm32")
|
|
||||||
jniLibs.directories.add("build/generated/oneKvm/jniLibs/arm32")
|
|
||||||
}
|
|
||||||
getByName("arm64") {
|
|
||||||
assets.directories.add("build/generated/oneKvm/assets/arm64")
|
|
||||||
jniLibs.directories.add("build/generated/oneKvm/jniLibs/arm64")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>("buildAndroidFfmpegMediaCodec") {
|
|
||||||
description = "Builds the default Android FFmpeg MediaCodec static libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
val ffmpegRoot = file(androidFfmpegRoot.get())
|
|
||||||
val scriptFile = androidFfmpegBuildScript.asFile
|
|
||||||
val stampFile = ffmpegRoot.resolve(".one-kvm-android-ffmpeg.stamp")
|
|
||||||
|
|
||||||
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
|
|
||||||
commandLine(
|
|
||||||
"bash",
|
|
||||||
scriptFile.absolutePath,
|
|
||||||
"--output",
|
|
||||||
ffmpegRoot.absolutePath,
|
|
||||||
"--ndk",
|
|
||||||
androidNdkDir.absolutePath,
|
|
||||||
"--api",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"--abis",
|
|
||||||
selectedAndroidAbis.joinToString(","),
|
|
||||||
)
|
|
||||||
|
|
||||||
inputs.file(scriptFile)
|
|
||||||
outputs.dir(ffmpegRoot)
|
|
||||||
|
|
||||||
onlyIf {
|
|
||||||
val hasAndroidFfmpeg = androidFfmpegRequiredFiles(ffmpegRoot).all { it.exists() }
|
|
||||||
val hasCurrentBuildStamp =
|
|
||||||
stampFile.exists() && stampFile.readText() == androidFfmpegBuildStamp(scriptFile)
|
|
||||||
!hasAndroidFfmpeg || !hasCurrentBuildStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
stampFile.writeText(androidFfmpegBuildStamp(scriptFile))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>("buildAndroidLibyuv") {
|
|
||||||
description = "Builds Android libyuv static libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
val libyuvRoot = file(androidLibyuvRoot.get())
|
|
||||||
val turbojpegRoot = file(androidTurbojpegRoot.get())
|
|
||||||
val scriptFile = androidLibyuvBuildScript.asFile
|
|
||||||
val stampFile = libyuvRoot.resolve(".one-kvm-android-libyuv.stamp")
|
|
||||||
|
|
||||||
dependsOn("buildAndroidTurbojpeg")
|
|
||||||
|
|
||||||
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
|
|
||||||
commandLine(
|
|
||||||
"bash",
|
|
||||||
scriptFile.absolutePath,
|
|
||||||
"--output",
|
|
||||||
libyuvRoot.absolutePath,
|
|
||||||
"--ndk",
|
|
||||||
androidNdkDir.absolutePath,
|
|
||||||
"--api",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"--abis",
|
|
||||||
selectedAndroidAbis.joinToString(","),
|
|
||||||
"--jpeg-root",
|
|
||||||
turbojpegRoot.absolutePath,
|
|
||||||
)
|
|
||||||
|
|
||||||
inputs.file(scriptFile)
|
|
||||||
outputs.dir(libyuvRoot)
|
|
||||||
|
|
||||||
onlyIf {
|
|
||||||
val hasAndroidLibyuv = androidLibyuvRequiredFiles(libyuvRoot).all { it.exists() }
|
|
||||||
val hasCurrentBuildStamp =
|
|
||||||
stampFile.exists() && stampFile.readText() == androidLibyuvBuildStamp(scriptFile)
|
|
||||||
!hasAndroidLibyuv || !hasCurrentBuildStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
stampFile.writeText(androidLibyuvBuildStamp(scriptFile))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>("buildAndroidTurbojpeg") {
|
|
||||||
description = "Builds Android TurboJPEG static libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
val turbojpegRoot = file(androidTurbojpegRoot.get())
|
|
||||||
val scriptFile = androidTurbojpegBuildScript.asFile
|
|
||||||
val stampFile = turbojpegRoot.resolve(".one-kvm-android-turbojpeg.stamp")
|
|
||||||
|
|
||||||
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
|
|
||||||
commandLine(
|
|
||||||
"bash",
|
|
||||||
scriptFile.absolutePath,
|
|
||||||
"--output",
|
|
||||||
turbojpegRoot.absolutePath,
|
|
||||||
"--ndk",
|
|
||||||
androidNdkDir.absolutePath,
|
|
||||||
"--api",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"--abis",
|
|
||||||
selectedAndroidAbis.joinToString(","),
|
|
||||||
)
|
|
||||||
|
|
||||||
inputs.file(scriptFile)
|
|
||||||
outputs.dir(turbojpegRoot)
|
|
||||||
|
|
||||||
onlyIf {
|
|
||||||
val hasAndroidTurbojpeg = androidTurbojpegRequiredFiles(turbojpegRoot).all { it.exists() }
|
|
||||||
val hasCurrentBuildStamp =
|
|
||||||
stampFile.exists() && stampFile.readText() == androidTurbojpegBuildStamp(scriptFile)
|
|
||||||
!hasAndroidTurbojpeg || !hasCurrentBuildStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
stampFile.writeText(androidTurbojpegBuildStamp(scriptFile))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>("buildAndroidAlsa") {
|
|
||||||
description = "Builds Android ALSA shared libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
val alsaRoot = file(androidAlsaRoot.get())
|
|
||||||
val scriptFile = androidAlsaBuildScript.asFile
|
|
||||||
val stampFile = alsaRoot.resolve(".one-kvm-android-alsa.stamp")
|
|
||||||
|
|
||||||
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
|
|
||||||
commandLine(
|
|
||||||
"bash",
|
|
||||||
scriptFile.absolutePath,
|
|
||||||
"--output",
|
|
||||||
alsaRoot.absolutePath,
|
|
||||||
"--ndk",
|
|
||||||
androidNdkDir.absolutePath,
|
|
||||||
"--api",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"--abis",
|
|
||||||
selectedAndroidAbis.joinToString(","),
|
|
||||||
)
|
|
||||||
|
|
||||||
inputs.file(scriptFile)
|
|
||||||
outputs.dir(alsaRoot)
|
|
||||||
|
|
||||||
onlyIf {
|
|
||||||
val hasAndroidAlsa = androidAlsaRequiredFiles(alsaRoot).all { it.exists() }
|
|
||||||
val hasCurrentBuildStamp =
|
|
||||||
stampFile.exists() && stampFile.readText() == androidAlsaBuildStamp(scriptFile)
|
|
||||||
!hasAndroidAlsa || !hasCurrentBuildStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
stampFile.writeText(androidAlsaBuildStamp(scriptFile))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>("buildAndroidOpus") {
|
|
||||||
description = "Builds Android Opus shared libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
val opusRoot = file(androidOpusRoot.get())
|
|
||||||
val scriptFile = androidOpusBuildScript.asFile
|
|
||||||
val stampFile = opusRoot.resolve(".one-kvm-android-opus.stamp")
|
|
||||||
|
|
||||||
workingDir = rootProject.layout.projectDirectory.dir("..").asFile
|
|
||||||
commandLine(
|
|
||||||
"bash",
|
|
||||||
scriptFile.absolutePath,
|
|
||||||
"--output",
|
|
||||||
opusRoot.absolutePath,
|
|
||||||
"--ndk",
|
|
||||||
androidNdkDir.absolutePath,
|
|
||||||
"--api",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"--abis",
|
|
||||||
selectedAndroidAbis.joinToString(","),
|
|
||||||
)
|
|
||||||
|
|
||||||
inputs.file(scriptFile)
|
|
||||||
outputs.dir(opusRoot)
|
|
||||||
|
|
||||||
onlyIf {
|
|
||||||
val hasAndroidOpus = androidOpusRequiredFiles(opusRoot).all { it.exists() }
|
|
||||||
val hasCurrentBuildStamp =
|
|
||||||
stampFile.exists() && stampFile.readText() == androidOpusBuildStamp(scriptFile)
|
|
||||||
!hasAndroidOpus || !hasCurrentBuildStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
stampFile.writeText(androidOpusBuildStamp(scriptFile))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val cargoBuildAndroidAbiTaskNames = selectedAndroidAbiTargets.map { (abi, targets) ->
|
|
||||||
val (flavor, _, _) = targets
|
|
||||||
val taskName = "cargoBuildAndroid" + flavor.replaceFirstChar {
|
|
||||||
if (it.isLowerCase()) it.titlecase() else it.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register<Exec>(taskName) {
|
|
||||||
description = "Builds the Android Rust bootstrap libraries for $abi."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
dependsOn(
|
|
||||||
"buildAndroidFfmpegMediaCodec",
|
|
||||||
"buildAndroidLibyuv",
|
|
||||||
"buildAndroidTurbojpeg",
|
|
||||||
"buildAndroidAlsa",
|
|
||||||
"buildAndroidOpus",
|
|
||||||
)
|
|
||||||
|
|
||||||
val cargoCommand = mutableListOf(
|
|
||||||
"cargo",
|
|
||||||
"ndk",
|
|
||||||
"-t",
|
|
||||||
abi,
|
|
||||||
"-P",
|
|
||||||
androidApiLevel.toString(),
|
|
||||||
"-o",
|
|
||||||
nativeCargoOutputDir.get().asFile.absolutePath,
|
|
||||||
"build",
|
|
||||||
"--lib",
|
|
||||||
"--bins",
|
|
||||||
)
|
|
||||||
if (androidBuildProfile == "release") {
|
|
||||||
cargoCommand.add("--release")
|
|
||||||
}
|
|
||||||
|
|
||||||
workingDir = nativeCrateDir.asFile
|
|
||||||
commandLine(cargoCommand)
|
|
||||||
args("--features", "android-mediacodec")
|
|
||||||
environment("ONE_KVM_ANDROID_FFMPEG_ROOT", androidFfmpegRoot.get())
|
|
||||||
environment("ONE_KVM_ANDROID_LIBYUV_ROOT", androidLibyuvRoot.get())
|
|
||||||
environment("ONE_KVM_ANDROID_LIBYUV_STATIC", "1")
|
|
||||||
environment("TURBOJPEG_SOURCE", "explicit")
|
|
||||||
environment("TURBOJPEG_STATIC", "1")
|
|
||||||
environment(
|
|
||||||
"TURBOJPEG_LIB_DIR",
|
|
||||||
file(androidTurbojpegRoot.get()).resolve("$abi/lib").absolutePath,
|
|
||||||
)
|
|
||||||
environment(
|
|
||||||
"TURBOJPEG_INCLUDE_DIR",
|
|
||||||
file(androidTurbojpegRoot.get()).resolve("$abi/include").absolutePath,
|
|
||||||
)
|
|
||||||
environment("PKG_CONFIG_ALLOW_CROSS", "1")
|
|
||||||
environment(
|
|
||||||
"PKG_CONFIG_LIBDIR",
|
|
||||||
file(androidAlsaRoot.get()).resolve("$abi/lib/pkgconfig").absolutePath,
|
|
||||||
)
|
|
||||||
environment("PKG_CONFIG_SYSROOT_DIR", "")
|
|
||||||
environment("LIBOPUS_NO_PKG", "1")
|
|
||||||
environment("LIBOPUS_LIB_DIR", file(androidOpusRoot.get()).resolve("$abi/lib").absolutePath)
|
|
||||||
environment("ANDROID_HOME", androidSdkDir.absolutePath)
|
|
||||||
environment("ANDROID_SDK_ROOT", androidSdkDir.absolutePath)
|
|
||||||
environment("ANDROID_NDK_HOME", androidNdkDir.absolutePath)
|
|
||||||
environment("ANDROID_NDK", androidNdkDir.absolutePath)
|
|
||||||
environment("ANDROID_NDK_ROOT", androidNdkDir.absolutePath)
|
|
||||||
|
|
||||||
inputs.files(
|
|
||||||
nativeCrateDir.file("Cargo.toml"),
|
|
||||||
nativeCrateDir.dir("src"),
|
|
||||||
rootCrateDir.file("Cargo.lock"),
|
|
||||||
rootCrateDir.file("Cargo.toml"),
|
|
||||||
rootCrateDir.file("build.rs"),
|
|
||||||
rootCrateDir.dir("libs"),
|
|
||||||
rootCrateDir.dir("res/vcpkg/libyuv"),
|
|
||||||
rootCrateDir.dir("src"),
|
|
||||||
)
|
|
||||||
outputs.dir(nativeCargoOutputDir)
|
|
||||||
outputs.dir(file(androidFfmpegRoot.get()))
|
|
||||||
outputs.dir(file(androidLibyuvRoot.get()))
|
|
||||||
outputs.dir(file(androidTurbojpegRoot.get()))
|
|
||||||
outputs.dir(file(androidAlsaRoot.get()))
|
|
||||||
outputs.dir(file(androidOpusRoot.get()))
|
|
||||||
}
|
|
||||||
|
|
||||||
taskName
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register("cargoBuildAndroid") {
|
|
||||||
description = "Builds the Android Rust bootstrap libraries."
|
|
||||||
group = "build"
|
|
||||||
|
|
||||||
dependsOn(cargoBuildAndroidAbiTaskNames)
|
|
||||||
|
|
||||||
outputs.dir(nativeOutputRoot)
|
|
||||||
outputs.dir(nativeAssetRoot)
|
|
||||||
|
|
||||||
doLast {
|
|
||||||
selectedAndroidAbiTargets.forEach { (abi, targets) ->
|
|
||||||
val (flavor, rustTriple, ndkTriple) = targets
|
|
||||||
val nativeLibSource = nativeCargoOutputDir.get().file("$abi/libone_kvm_android_bootstrap.so").asFile
|
|
||||||
if (!nativeLibSource.exists()) {
|
|
||||||
throw GradleException("Missing Android JNI library: ${nativeLibSource.absolutePath}")
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(nativeLibSource)
|
|
||||||
into(nativeOutputRoot.get().dir(flavor).dir(abi))
|
|
||||||
}
|
|
||||||
|
|
||||||
val source = nativeCrateDir.file("target/$rustTriple/$androidBuildProfile/one-kvm-android-host").asFile
|
|
||||||
if (!source.exists()) {
|
|
||||||
throw GradleException("Missing Android host binary: ${source.absolutePath}")
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(source)
|
|
||||||
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
|
|
||||||
rename { "one-kvm-android-host" }
|
|
||||||
}
|
|
||||||
|
|
||||||
val cxxShared = androidNdkDir
|
|
||||||
.resolve("toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/$ndkTriple/libc++_shared.so")
|
|
||||||
if (!cxxShared.exists()) {
|
|
||||||
throw GradleException("Missing NDK libc++_shared.so: ${cxxShared.absolutePath}")
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(cxxShared)
|
|
||||||
into(nativeOutputRoot.get().dir(flavor).dir(abi))
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(cxxShared)
|
|
||||||
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
|
|
||||||
}
|
|
||||||
|
|
||||||
val alsaShared = file(androidAlsaRoot.get()).resolve("$abi/lib/libasound.so")
|
|
||||||
if (!alsaShared.exists()) {
|
|
||||||
throw GradleException("Missing Android ALSA library: ${alsaShared.absolutePath}")
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(alsaShared)
|
|
||||||
into(nativeOutputRoot.get().dir(flavor).dir(abi))
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(alsaShared)
|
|
||||||
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(file(androidAlsaRoot.get()).resolve("$abi/share/alsa"))
|
|
||||||
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi/alsa"))
|
|
||||||
}
|
|
||||||
|
|
||||||
val opusShared = file(androidOpusRoot.get()).resolve("$abi/lib/libopus.so")
|
|
||||||
if (!opusShared.exists()) {
|
|
||||||
throw GradleException("Missing Android Opus library: ${opusShared.absolutePath}")
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(opusShared)
|
|
||||||
into(nativeOutputRoot.get().dir(flavor).dir(abi))
|
|
||||||
}
|
|
||||||
copy {
|
|
||||||
from(opusShared)
|
|
||||||
into(nativeAssetRoot.get().dir(flavor).dir("bin/$abi"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.named("preBuild") {
|
|
||||||
dependsOn("cargoBuildAndroid")
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
|
||||||
|
|
||||||
<application
|
|
||||||
android:allowBackup="false"
|
|
||||||
android:icon="@drawable/ic_launcher_one_kvm"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:theme="@style/AppTheme">
|
|
||||||
<service
|
|
||||||
android:name=".OneKvmService"
|
|
||||||
android:exported="false"
|
|
||||||
android:foregroundServiceType="connectedDevice" />
|
|
||||||
<receiver
|
|
||||||
android:name=".BootReceiver"
|
|
||||||
android:enabled="true"
|
|
||||||
android:exported="false">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
|
||||||
</intent-filter>
|
|
||||||
</receiver>
|
|
||||||
<activity
|
|
||||||
android:name=".MainActivity"
|
|
||||||
android:exported="true">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.MAIN" />
|
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
|
||||||
</intent-filter>
|
|
||||||
</activity>
|
|
||||||
</application>
|
|
||||||
</manifest>
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
|
|
||||||
class BootReceiver : BroadcastReceiver() {
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
if (intent.action == Intent.ACTION_BOOT_COMPLETED && HostSettings.getAutoStart(context)) {
|
|
||||||
OneKvmService.start(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
|
|
||||||
object HostSettings {
|
|
||||||
private const val PREFS = "one_kvm_android"
|
|
||||||
private const val KEY_AUTO_START = "auto_start"
|
|
||||||
private const val KEY_CLEAR_EXISTING_OTG = "clear_existing_otg"
|
|
||||||
|
|
||||||
fun getAutoStart(context: Context): Boolean {
|
|
||||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.getBoolean(KEY_AUTO_START, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setAutoStart(context: Context, enabled: Boolean) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.edit()
|
|
||||||
.putBoolean(KEY_AUTO_START, enabled)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getClearExistingOtg(context: Context): Boolean {
|
|
||||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.getBoolean(KEY_CLEAR_EXISTING_OTG, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setClearExistingOtg(context: Context, enabled: Boolean) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.edit()
|
|
||||||
.putBoolean(KEY_CLEAR_EXISTING_OTG, enabled)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
|
|
||||||
object LogConfig {
|
|
||||||
private const val PREFS = "one_kvm_android"
|
|
||||||
private const val KEY_LOG_LEVEL = "log_level"
|
|
||||||
const val DEFAULT_LEVEL = "info"
|
|
||||||
val LEVELS = arrayOf("error", "warn", "info", "debug", "trace")
|
|
||||||
|
|
||||||
fun getLevel(context: Context): String {
|
|
||||||
val value = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.getString(KEY_LOG_LEVEL, DEFAULT_LEVEL)
|
|
||||||
?: DEFAULT_LEVEL
|
|
||||||
return if (LEVELS.contains(value)) value else DEFAULT_LEVEL
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setLevel(context: Context, level: String) {
|
|
||||||
val safeLevel = if (LEVELS.contains(level)) level else DEFAULT_LEVEL
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.edit()
|
|
||||||
.putString(KEY_LOG_LEVEL, safeLevel)
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun rustLogFilter(level: String): String {
|
|
||||||
val safeLevel = if (LEVELS.contains(level)) level else DEFAULT_LEVEL
|
|
||||||
return "one_kvm=$safeLevel,hwcodec=$safeLevel,tower_http=$safeLevel,webrtc_sctp=warn"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import java.io.File
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
object LogStore {
|
|
||||||
private const val FLUSH_DELAY_MS = 250L
|
|
||||||
private const val MAX_BUFFER_CHARS = 64 * 1024
|
|
||||||
|
|
||||||
private val lock = Any()
|
|
||||||
private val buffer = StringBuilder()
|
|
||||||
private val executor = Executors.newSingleThreadScheduledExecutor { runnable ->
|
|
||||||
Thread(runnable, "OneKvmLogStore").apply { isDaemon = true }
|
|
||||||
}
|
|
||||||
|
|
||||||
private var logFile: File? = null
|
|
||||||
private var flushScheduled = false
|
|
||||||
|
|
||||||
fun defaultLogFile(context: Context): File {
|
|
||||||
return File(File(context.getExternalFilesDir(null), "runtime"), "one-kvm.log")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun configure(file: File) {
|
|
||||||
synchronized(lock) {
|
|
||||||
flushLocked()
|
|
||||||
file.parentFile?.mkdirs()
|
|
||||||
file.writeText("")
|
|
||||||
buffer.clear()
|
|
||||||
logFile = file
|
|
||||||
flushScheduled = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun append(line: String) {
|
|
||||||
synchronized(lock) {
|
|
||||||
if (logFile == null) return
|
|
||||||
|
|
||||||
buffer.append(line).append('\n')
|
|
||||||
if (buffer.length >= MAX_BUFFER_CHARS) {
|
|
||||||
flushLocked()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!flushScheduled) {
|
|
||||||
flushScheduled = true
|
|
||||||
executor.schedule({ flush() }, FLUSH_DELAY_MS, TimeUnit.MILLISECONDS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun flush() {
|
|
||||||
synchronized(lock) {
|
|
||||||
flushLocked()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun flushLocked() {
|
|
||||||
val file = logFile ?: return
|
|
||||||
if (buffer.isEmpty()) {
|
|
||||||
flushScheduled = false
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val text = buffer.toString()
|
|
||||||
buffer.clear()
|
|
||||||
flushScheduled = false
|
|
||||||
file.appendText(text)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,452 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.app.Activity
|
|
||||||
import android.graphics.Color
|
|
||||||
import android.graphics.Typeface
|
|
||||||
import android.graphics.drawable.GradientDrawable
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.view.Gravity
|
|
||||||
import android.view.View
|
|
||||||
import android.widget.AdapterView
|
|
||||||
import android.widget.ArrayAdapter
|
|
||||||
import android.widget.Button
|
|
||||||
import android.widget.CompoundButton
|
|
||||||
import android.widget.LinearLayout
|
|
||||||
import android.widget.ScrollView
|
|
||||||
import android.widget.Spinner
|
|
||||||
import android.widget.Switch
|
|
||||||
import android.widget.TextView
|
|
||||||
import java.net.Inet4Address
|
|
||||||
import java.net.InetSocketAddress
|
|
||||||
import java.net.NetworkInterface
|
|
||||||
import java.net.Socket
|
|
||||||
import java.util.Collections
|
|
||||||
|
|
||||||
class MainActivity : Activity() {
|
|
||||||
private lateinit var statusValue: TextView
|
|
||||||
private lateinit var hostActionButton: Button
|
|
||||||
private lateinit var logLevelSpinner: Spinner
|
|
||||||
private lateinit var autoStartSwitch: Switch
|
|
||||||
private lateinit var clearOtgSwitch: Switch
|
|
||||||
private val statusHandler = Handler(Looper.getMainLooper())
|
|
||||||
private var statusPollsRemaining = 0
|
|
||||||
private val statusPoller = object : Runnable {
|
|
||||||
override fun run() {
|
|
||||||
refreshStatus()
|
|
||||||
statusPollsRemaining -= 1
|
|
||||||
if (statusPollsRemaining > 0) {
|
|
||||||
statusHandler.postDelayed(this, STATUS_POLL_INTERVAL_MS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
|
|
||||||
window.statusBarColor = color("#F8FAFC")
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
window.navigationBarColor = color("#F8FAFC")
|
|
||||||
}
|
|
||||||
|
|
||||||
val content = LinearLayout(this).apply {
|
|
||||||
orientation = LinearLayout.VERTICAL
|
|
||||||
setPadding(20.dp(), 24.dp(), 20.dp(), 28.dp())
|
|
||||||
background = solid("#F8FAFC")
|
|
||||||
}
|
|
||||||
|
|
||||||
content.addView(startCard())
|
|
||||||
content.addView(settingsCard())
|
|
||||||
content.addView(infoCard())
|
|
||||||
|
|
||||||
setContentView(ScrollView(this).apply {
|
|
||||||
isFillViewport = true
|
|
||||||
setBackgroundColor(color("#F8FAFC"))
|
|
||||||
addView(content)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResume() {
|
|
||||||
super.onResume()
|
|
||||||
reconcilePersistedStatus()
|
|
||||||
refreshStatus()
|
|
||||||
autoStartSwitch.isChecked = HostSettings.getAutoStart(this)
|
|
||||||
clearOtgSwitch.isChecked = HostSettings.getClearExistingOtg(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPause() {
|
|
||||||
statusHandler.removeCallbacks(statusPoller)
|
|
||||||
super.onPause()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startCard(): View {
|
|
||||||
return card {
|
|
||||||
addView(sectionTitle("启动管理"))
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = "管理本机 One-KVM 服务进程。暂停会停止前台服务并释放运行资源。"
|
|
||||||
textSize = 14f
|
|
||||||
setTextColor(color("#64748B"))
|
|
||||||
setPadding(0, 6.dp(), 0, 14.dp())
|
|
||||||
})
|
|
||||||
|
|
||||||
statusValue = TextView(this@MainActivity).apply {
|
|
||||||
textSize = 14f
|
|
||||||
typeface = Typeface.DEFAULT_BOLD
|
|
||||||
setTextColor(color("#0F172A"))
|
|
||||||
background = rounded("#EFF6FF", "#BFDBFE", 8)
|
|
||||||
setPadding(12.dp(), 8.dp(), 12.dp(), 8.dp())
|
|
||||||
}
|
|
||||||
addView(statusValue, matchWrap())
|
|
||||||
|
|
||||||
addView(LinearLayout(this@MainActivity).apply {
|
|
||||||
orientation = LinearLayout.HORIZONTAL
|
|
||||||
gravity = Gravity.CENTER_VERTICAL
|
|
||||||
setPadding(0, 14.dp(), 0, 0)
|
|
||||||
hostActionButton = actionButton("启动", primary = true) { toggleHost() }
|
|
||||||
addView(hostActionButton, matchButton())
|
|
||||||
})
|
|
||||||
refreshStatus()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun settingsCard(): View {
|
|
||||||
return card {
|
|
||||||
addView(sectionTitle("运行设置"))
|
|
||||||
|
|
||||||
val (autoStartRow, autoStartControl) = settingSwitchRow(
|
|
||||||
title = "开机自启动",
|
|
||||||
subtitle = "系统启动完成后自动拉起 One-KVM 前台服务。",
|
|
||||||
checked = HostSettings.getAutoStart(this@MainActivity),
|
|
||||||
) { _, checked ->
|
|
||||||
HostSettings.setAutoStart(this@MainActivity, checked)
|
|
||||||
LogStore.append("Boot auto-start ${if (checked) "enabled" else "disabled"}")
|
|
||||||
}
|
|
||||||
autoStartSwitch = autoStartControl
|
|
||||||
addView(autoStartRow)
|
|
||||||
|
|
||||||
addView(divider())
|
|
||||||
|
|
||||||
val (clearOtgRow, clearOtgControl) = settingSwitchRow(
|
|
||||||
title = "清除已有 OTG Gadget",
|
|
||||||
subtitle = "启动 root host 前尝试解绑并删除 configfs 中已有的 USB gadget。",
|
|
||||||
checked = HostSettings.getClearExistingOtg(this@MainActivity),
|
|
||||||
) { _, checked ->
|
|
||||||
HostSettings.setClearExistingOtg(this@MainActivity, checked)
|
|
||||||
LogStore.append("Clear existing OTG gadget ${if (checked) "enabled" else "disabled"}")
|
|
||||||
}
|
|
||||||
clearOtgSwitch = clearOtgControl
|
|
||||||
addView(clearOtgRow)
|
|
||||||
|
|
||||||
addView(divider())
|
|
||||||
addView(logLevelRow())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun infoCard(): View {
|
|
||||||
return card {
|
|
||||||
addView(sectionTitle("应用信息"))
|
|
||||||
addView(infoRow("软件内核版本", kernelVersion()))
|
|
||||||
addView(infoRow("访问地址", accessAddresses(), selectable = true))
|
|
||||||
addView(infoRow("日志文件", LogStore.defaultLogFile(this@MainActivity).absolutePath, selectable = true))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun settingSwitchRow(
|
|
||||||
title: String,
|
|
||||||
subtitle: String,
|
|
||||||
checked: Boolean,
|
|
||||||
listener: CompoundButton.OnCheckedChangeListener,
|
|
||||||
): Pair<View, Switch> {
|
|
||||||
val switch = Switch(this).apply {
|
|
||||||
isChecked = checked
|
|
||||||
setOnCheckedChangeListener(listener)
|
|
||||||
}
|
|
||||||
|
|
||||||
val row = LinearLayout(this).apply {
|
|
||||||
orientation = LinearLayout.HORIZONTAL
|
|
||||||
gravity = Gravity.CENTER_VERTICAL
|
|
||||||
setPadding(0, 12.dp(), 0, 12.dp())
|
|
||||||
addView(LinearLayout(this@MainActivity).apply {
|
|
||||||
orientation = LinearLayout.VERTICAL
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = title
|
|
||||||
textSize = 15f
|
|
||||||
typeface = Typeface.DEFAULT_BOLD
|
|
||||||
setTextColor(color("#0F172A"))
|
|
||||||
})
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = subtitle
|
|
||||||
textSize = 13f
|
|
||||||
setTextColor(color("#64748B"))
|
|
||||||
setPadding(0, 4.dp(), 12.dp(), 0)
|
|
||||||
})
|
|
||||||
}, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
|
|
||||||
addView(switch)
|
|
||||||
}
|
|
||||||
|
|
||||||
return row to switch
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun infoRow(label: String, value: String, selectable: Boolean = false): View {
|
|
||||||
return LinearLayout(this).apply {
|
|
||||||
orientation = LinearLayout.VERTICAL
|
|
||||||
setPadding(0, 12.dp(), 0, 12.dp())
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = label
|
|
||||||
textSize = 13f
|
|
||||||
setTextColor(color("#64748B"))
|
|
||||||
})
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = value
|
|
||||||
textSize = 15f
|
|
||||||
setTextColor(color("#0F172A"))
|
|
||||||
setPadding(0, 4.dp(), 0, 0)
|
|
||||||
setTextIsSelectable(selectable)
|
|
||||||
})
|
|
||||||
addView(divider())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun logLevelRow(): View {
|
|
||||||
return LinearLayout(this).apply {
|
|
||||||
orientation = LinearLayout.HORIZONTAL
|
|
||||||
gravity = Gravity.CENTER_VERTICAL
|
|
||||||
setPadding(0, 12.dp(), 0, 0)
|
|
||||||
addView(TextView(this@MainActivity).apply {
|
|
||||||
text = "日志级别"
|
|
||||||
textSize = 15f
|
|
||||||
typeface = Typeface.DEFAULT_BOLD
|
|
||||||
setTextColor(color("#0F172A"))
|
|
||||||
}, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
|
|
||||||
|
|
||||||
logLevelSpinner = Spinner(this@MainActivity).apply {
|
|
||||||
adapter = ArrayAdapter(
|
|
||||||
this@MainActivity,
|
|
||||||
android.R.layout.simple_spinner_dropdown_item,
|
|
||||||
LogConfig.LEVELS,
|
|
||||||
)
|
|
||||||
setSelection(LogConfig.LEVELS.indexOf(LogConfig.getLevel(this@MainActivity)).coerceAtLeast(0))
|
|
||||||
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
|
||||||
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
|
|
||||||
val level = LogConfig.LEVELS[position]
|
|
||||||
if (level != LogConfig.getLevel(this@MainActivity)) {
|
|
||||||
LogConfig.setLevel(this@MainActivity, level)
|
|
||||||
LogStore.append("Log level set to $level; restart service to apply")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addView(logLevelSpinner)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun card(build: LinearLayout.() -> Unit): View {
|
|
||||||
return LinearLayout(this).apply {
|
|
||||||
orientation = LinearLayout.VERTICAL
|
|
||||||
setPadding(16.dp(), 16.dp(), 16.dp(), 16.dp())
|
|
||||||
background = rounded("#FFFFFF", "#E2E8F0", 10)
|
|
||||||
elevation = 1.5f.dpFloat()
|
|
||||||
build()
|
|
||||||
}.also {
|
|
||||||
it.layoutParams = LinearLayout.LayoutParams(
|
|
||||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
|
||||||
).apply { setMargins(0, 0, 0, 14.dp()) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun sectionTitle(text: String): View {
|
|
||||||
return TextView(this).apply {
|
|
||||||
this.text = text
|
|
||||||
textSize = 17f
|
|
||||||
typeface = Typeface.DEFAULT_BOLD
|
|
||||||
setTextColor(color("#0F172A"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun actionButton(text: String, primary: Boolean, action: () -> Unit): Button {
|
|
||||||
return Button(this).apply {
|
|
||||||
this.text = text
|
|
||||||
textSize = 15f
|
|
||||||
isAllCaps = false
|
|
||||||
minHeight = 44.dp()
|
|
||||||
setTextColor(color(if (primary) "#FFFFFF" else "#0F172A"))
|
|
||||||
background = if (primary) rounded("#2563EB", "#2563EB", 8) else rounded("#FFFFFF", "#CBD5E1", 8)
|
|
||||||
setOnClickListener { action() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun toggleHost() {
|
|
||||||
when (ServiceStatusStore.snapshot(this).state) {
|
|
||||||
ServiceStatusStore.STATE_RUNNING -> pauseHost()
|
|
||||||
ServiceStatusStore.STATE_STOPPED, ServiceStatusStore.STATE_ERROR -> startHost()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startHost() {
|
|
||||||
ServiceStatusStore.setStarting(this)
|
|
||||||
refreshStatus()
|
|
||||||
OneKvmService.start(this)
|
|
||||||
LogStore.append("Start requested from app UI")
|
|
||||||
pollStatusForAWhile()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun pauseHost() {
|
|
||||||
ServiceStatusStore.setStopping(this)
|
|
||||||
refreshStatus()
|
|
||||||
OneKvmService.stop(this)
|
|
||||||
LogStore.append("Pause requested from app UI")
|
|
||||||
pollStatusForAWhile()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshStatus() {
|
|
||||||
if (::statusValue.isInitialized) {
|
|
||||||
statusValue.text = "状态:${hostStatusSummary()}"
|
|
||||||
}
|
|
||||||
updateHostActionButton()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun hostStatusSummary(): String {
|
|
||||||
val serviceStatus = ServiceStatusStore.snapshot(this)
|
|
||||||
if (serviceStatus.state != ServiceStatusStore.STATE_STOPPED) {
|
|
||||||
return serviceStatus.labelText()
|
|
||||||
}
|
|
||||||
|
|
||||||
val nativeRunning = runCatching {
|
|
||||||
NativeBridge.hostStatus().contains("running", ignoreCase = true)
|
|
||||||
}.getOrDefault(false)
|
|
||||||
|
|
||||||
return if (nativeRunning) "运行中" else "已停止"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun reconcilePersistedStatus() {
|
|
||||||
val serviceStatus = ServiceStatusStore.snapshot(this)
|
|
||||||
if (serviceStatus.state == ServiceStatusStore.STATE_STOPPED) return
|
|
||||||
if (
|
|
||||||
serviceStatus.state == ServiceStatusStore.STATE_STARTING &&
|
|
||||||
System.currentTimeMillis() - serviceStatus.updatedAt < STARTING_RECONCILE_GRACE_MS
|
|
||||||
) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
Thread {
|
|
||||||
val portOpen = isLocalWebPortOpen()
|
|
||||||
val nativeRunning = runCatching { NativeBridge.hostStatus().contains("running", ignoreCase = true) }
|
|
||||||
.getOrDefault(false)
|
|
||||||
if (!portOpen && !nativeRunning) {
|
|
||||||
ServiceStatusStore.setStopped(this, "服务未运行")
|
|
||||||
runOnUiThread { refreshStatus() }
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isLocalWebPortOpen(): Boolean {
|
|
||||||
return runCatching {
|
|
||||||
Socket().use { socket ->
|
|
||||||
socket.connect(InetSocketAddress("127.0.0.1", 8080), 250)
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}.getOrDefault(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun updateHostActionButton() {
|
|
||||||
if (!::hostActionButton.isInitialized) return
|
|
||||||
|
|
||||||
when (ServiceStatusStore.snapshot(this).state) {
|
|
||||||
ServiceStatusStore.STATE_STARTING -> setHostActionButton("启动中...", enabled = false, primary = true)
|
|
||||||
ServiceStatusStore.STATE_RUNNING -> setHostActionButton("停止", enabled = true, primary = false)
|
|
||||||
ServiceStatusStore.STATE_STOPPING -> setHostActionButton("停止中...", enabled = false, primary = false)
|
|
||||||
else -> setHostActionButton("启动", enabled = true, primary = true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun setHostActionButton(text: String, enabled: Boolean, primary: Boolean) {
|
|
||||||
hostActionButton.text = text
|
|
||||||
hostActionButton.isEnabled = enabled
|
|
||||||
hostActionButton.alpha = if (enabled) 1f else 0.65f
|
|
||||||
hostActionButton.setTextColor(color(if (primary) "#FFFFFF" else "#0F172A"))
|
|
||||||
hostActionButton.background = if (primary) {
|
|
||||||
rounded("#2563EB", "#2563EB", 8)
|
|
||||||
} else {
|
|
||||||
rounded("#FFFFFF", "#CBD5E1", 8)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun pollStatusForAWhile() {
|
|
||||||
statusPollsRemaining = 20
|
|
||||||
statusHandler.removeCallbacks(statusPoller)
|
|
||||||
statusHandler.postDelayed(statusPoller, STATUS_POLL_INTERVAL_MS)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun kernelVersion(): String {
|
|
||||||
return runCatching { NativeBridge.kernelVersion() }
|
|
||||||
.getOrElse { "unknown" }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun accessAddresses(): String {
|
|
||||||
val addresses = runCatching {
|
|
||||||
Collections.list(NetworkInterface.getNetworkInterfaces())
|
|
||||||
.filter { it.isUp && !it.isLoopback }
|
|
||||||
.flatMap { iface -> Collections.list(iface.inetAddresses) }
|
|
||||||
.filterIsInstance<Inet4Address>()
|
|
||||||
.filter { !it.isLoopbackAddress }
|
|
||||||
.map { "http://${it.hostAddress}:8080" }
|
|
||||||
.distinct()
|
|
||||||
}.getOrDefault(emptyList())
|
|
||||||
|
|
||||||
return (addresses.ifEmpty { listOf("http://127.0.0.1:8080") }).joinToString("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun divider(): View {
|
|
||||||
return View(this).apply {
|
|
||||||
setBackgroundColor(color("#E2E8F0"))
|
|
||||||
layoutParams = LinearLayout.LayoutParams(
|
|
||||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
1,
|
|
||||||
).apply { setMargins(0, 0, 0, 0) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun matchWrap(): LinearLayout.LayoutParams {
|
|
||||||
return LinearLayout.LayoutParams(
|
|
||||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun matchButton(): LinearLayout.LayoutParams {
|
|
||||||
return LinearLayout.LayoutParams(
|
|
||||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
48.dp(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun solid(hex: String): GradientDrawable = GradientDrawable().apply {
|
|
||||||
setColor(color(hex))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun rounded(fill: String, stroke: String, radiusDp: Int): GradientDrawable {
|
|
||||||
return GradientDrawable().apply {
|
|
||||||
setColor(color(fill))
|
|
||||||
cornerRadius = radiusDp.dpFloat()
|
|
||||||
setStroke(1.dp(), color(stroke))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun color(hex: String): Int = Color.parseColor(hex)
|
|
||||||
|
|
||||||
private fun Int.dp(): Int = (this * resources.displayMetrics.density + 0.5f).toInt()
|
|
||||||
|
|
||||||
private fun Int.dpFloat(): Float = this * resources.displayMetrics.density
|
|
||||||
|
|
||||||
private fun Float.dpFloat(): Float = this * resources.displayMetrics.density
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val STATUS_POLL_INTERVAL_MS = 500L
|
|
||||||
private const val STARTING_RECONCILE_GRACE_MS = 15_000L
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
|
|
||||||
object NativeBridge {
|
|
||||||
init {
|
|
||||||
System.loadLibrary("one_kvm_android_bootstrap")
|
|
||||||
}
|
|
||||||
|
|
||||||
external fun initTlsVerifier(context: Context): Int
|
|
||||||
|
|
||||||
external fun setEnv(name: String, value: String): Int
|
|
||||||
|
|
||||||
external fun startHost(dataDir: String, bindAddress: String, port: Int): String
|
|
||||||
|
|
||||||
external fun stopHost(): String
|
|
||||||
|
|
||||||
external fun hostStatus(): String
|
|
||||||
|
|
||||||
external fun kernelVersion(): String
|
|
||||||
}
|
|
||||||
@@ -1,413 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.app.Notification
|
|
||||||
import android.app.NotificationChannel
|
|
||||||
import android.app.NotificationManager
|
|
||||||
import android.app.PendingIntent
|
|
||||||
import android.app.Service
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.IBinder
|
|
||||||
import java.io.BufferedReader
|
|
||||||
import java.io.File
|
|
||||||
import java.io.InputStreamReader
|
|
||||||
import java.io.InterruptedIOException
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
|
|
||||||
class OneKvmService : Service() {
|
|
||||||
private var rootProcess: Process? = null
|
|
||||||
private val commandExecutor = Executors.newSingleThreadExecutor { runnable ->
|
|
||||||
Thread(runnable, "OneKvmServiceCommand")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate() {
|
|
||||||
super.onCreate()
|
|
||||||
ensureNotificationChannel()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
|
||||||
when (intent?.action ?: ACTION_START) {
|
|
||||||
ACTION_STOP -> {
|
|
||||||
ServiceStatusStore.setStopping(this)
|
|
||||||
commandExecutor.execute {
|
|
||||||
stopHostRuntime()
|
|
||||||
stopSelfResult(startId)
|
|
||||||
}
|
|
||||||
return START_NOT_STICKY
|
|
||||||
}
|
|
||||||
ACTION_START -> {
|
|
||||||
ServiceStatusStore.setStarting(this)
|
|
||||||
startForegroundCompat(NOTIFICATION_ID, notification("启动中"))
|
|
||||||
commandExecutor.execute {
|
|
||||||
val currentState = ServiceStatusStore.snapshot(this).state
|
|
||||||
if (currentState == ServiceStatusStore.STATE_RUNNING && isPortOpen(8080, 100)) {
|
|
||||||
return@execute
|
|
||||||
}
|
|
||||||
val dataDir = File(getExternalFilesDir(null), "runtime")
|
|
||||||
if (!dataDir.exists()) dataDir.mkdirs()
|
|
||||||
val result = startRustHost(dataDir)
|
|
||||||
if (result.startsWith("Running") && !result.contains("start failed", ignoreCase = true)) {
|
|
||||||
ServiceStatusStore.setRunning(this, "服务已启动")
|
|
||||||
notificationManager().notify(NOTIFICATION_ID, notification("运行中"))
|
|
||||||
} else {
|
|
||||||
ServiceStatusStore.setError(this, "启动失败")
|
|
||||||
notificationManager().notify(NOTIFICATION_ID, notification("启动失败"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return START_STICKY
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDestroy() {
|
|
||||||
stopHostRuntime(updateNotification = false)
|
|
||||||
commandExecutor.shutdownNow()
|
|
||||||
ServiceStatusStore.setStopped(this)
|
|
||||||
super.onDestroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
|
||||||
|
|
||||||
private fun notification(state: String): Notification {
|
|
||||||
val intent = Intent(this, MainActivity::class.java)
|
|
||||||
val pendingIntent = createContentIntent(intent)
|
|
||||||
val builder = createNotificationBuilder()
|
|
||||||
return builder
|
|
||||||
.setSmallIcon(R.drawable.ic_stat_one_kvm)
|
|
||||||
.setContentTitle("One-KVM Android Host")
|
|
||||||
.setContentText(state)
|
|
||||||
.setContentIntent(pendingIntent)
|
|
||||||
.setOngoing(true)
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ensureNotificationChannel() {
|
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
|
||||||
val channel = NotificationChannel(
|
|
||||||
CHANNEL_ID,
|
|
||||||
"One-KVM Host",
|
|
||||||
NotificationManager.IMPORTANCE_LOW,
|
|
||||||
)
|
|
||||||
notificationManager().createNotificationChannel(channel)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
private fun createNotificationBuilder(): Notification.Builder {
|
|
||||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
Notification.Builder(this, CHANNEL_ID)
|
|
||||||
} else {
|
|
||||||
Notification.Builder(this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun createContentIntent(intent: Intent): PendingIntent {
|
|
||||||
val flags = pendingIntentFlags()
|
|
||||||
return PendingIntent.getActivity(this, 0, intent, flags)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun pendingIntentFlags(): Int {
|
|
||||||
var flags = PendingIntent.FLAG_UPDATE_CURRENT
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
|
||||||
flags = flags or pendingIntentImmutableFlag()
|
|
||||||
}
|
|
||||||
return flags
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun pendingIntentImmutableFlag(): Int {
|
|
||||||
return try {
|
|
||||||
PendingIntent::class.java.getField("FLAG_IMMUTABLE").getInt(null)
|
|
||||||
} catch (_: ReflectiveOperationException) {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun notificationManager(): NotificationManager {
|
|
||||||
return getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun stopHostRuntime(updateNotification: Boolean = true) {
|
|
||||||
stopRootHost()
|
|
||||||
NativeBridge.stopHost()
|
|
||||||
waitForPortRelease(8080, 2_000)
|
|
||||||
LogStore.flush()
|
|
||||||
ServiceStatusStore.setStopped(this)
|
|
||||||
if (updateNotification) {
|
|
||||||
notificationManager().notify(NOTIFICATION_ID, notification("已停止"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startRustHost(dataDir: File): String {
|
|
||||||
val logLevel = LogConfig.getLevel(this)
|
|
||||||
val rustLog = LogConfig.rustLogFilter(logLevel)
|
|
||||||
val appLogFile = LogStore.defaultLogFile(this)
|
|
||||||
LogStore.configure(appLogFile)
|
|
||||||
val rustLogFile = appLogFile
|
|
||||||
LogStore.append("Starting One-KVM Rust host, data_dir=${dataDir.absolutePath}, log_level=$logLevel")
|
|
||||||
val executable = extractHostBinary()
|
|
||||||
return runCatching {
|
|
||||||
val tlsInit = NativeBridge.initTlsVerifier(this)
|
|
||||||
if (tlsInit != 0) {
|
|
||||||
throw IllegalStateException("rustls platform verifier init failed with code $tlsInit")
|
|
||||||
}
|
|
||||||
stopRootHost(executable)
|
|
||||||
clearExistingOtgGadgetsIfEnabled()
|
|
||||||
startRootHost(executable, dataDir, rustLog, rustLogFile, logLevel)
|
|
||||||
LogStore.append("Rust host running as root on port 8080")
|
|
||||||
"Running as root on port 8080"
|
|
||||||
}.getOrElse { rootError ->
|
|
||||||
LogStore.append("Root host unavailable: ${rootError.message ?: rootError::class.java.simpleName}")
|
|
||||||
configureAlsaEnvironment(executable)
|
|
||||||
NativeBridge.setEnv("RUST_LOG", rustLog)
|
|
||||||
NativeBridge.setEnv("ONE_KVM_FFMPEG_LOG", ffmpegLogLevel(logLevel))
|
|
||||||
NativeBridge.setEnv("ONE_KVM_ANDROID_LOG_FILE", rustLogFile.absolutePath)
|
|
||||||
val jniResult = NativeBridge.startHost(dataDir.absolutePath, "0.0.0.0", 8080)
|
|
||||||
LogStore.append("Rust host running in app process on port 8080: $jniResult")
|
|
||||||
"Running in app process on port 8080 (${rootError.message ?: "root unavailable"}; $jniResult)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun clearExistingOtgGadgetsIfEnabled() {
|
|
||||||
if (!HostSettings.getClearExistingOtg(this)) return
|
|
||||||
|
|
||||||
val command = """
|
|
||||||
root=/sys/kernel/config/usb_gadget
|
|
||||||
[ -d "${'$'}root" ] || exit 0
|
|
||||||
for gadget in "${'$'}root"/*; do
|
|
||||||
[ -d "${'$'}gadget" ] || continue
|
|
||||||
[ -w "${'$'}gadget/UDC" ] && echo "" > "${'$'}gadget/UDC" 2>/dev/null || true
|
|
||||||
find "${'$'}gadget/configs" -type l -delete 2>/dev/null || true
|
|
||||||
rm -rf "${'$'}gadget" 2>/dev/null || true
|
|
||||||
done
|
|
||||||
""".trimIndent()
|
|
||||||
|
|
||||||
runCatching {
|
|
||||||
ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
|
|
||||||
.redirectErrorStream(true)
|
|
||||||
.start()
|
|
||||||
.waitFor()
|
|
||||||
}.onSuccess { exit ->
|
|
||||||
LogStore.append("Existing OTG gadget cleanup finished with exit code $exit")
|
|
||||||
}.onFailure { err ->
|
|
||||||
LogStore.append("Existing OTG gadget cleanup failed: ${err.message ?: err::class.java.simpleName}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun configureAlsaEnvironment(executable: File) {
|
|
||||||
val binDir = executable.parentFile
|
|
||||||
?: throw IllegalStateException("host binary has no parent directory")
|
|
||||||
val alsaConfigDir = File(binDir, "alsa")
|
|
||||||
val alsaConfigPath = File(alsaConfigDir, "alsa.conf")
|
|
||||||
NativeBridge.setEnv("ALSA_CONFIG_DIR", alsaConfigDir.absolutePath)
|
|
||||||
NativeBridge.setEnv("ALSA_CONFIG_PATH", alsaConfigPath.absolutePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun extractHostBinary(): File {
|
|
||||||
val abi = Build.SUPPORTED_ABIS.firstOrNull { it == "arm64-v8a" || it == "armeabi-v7a" }
|
|
||||||
?: throw IllegalStateException("unsupported ABI: ${Build.SUPPORTED_ABIS.joinToString()}")
|
|
||||||
val binDir = File(filesDir, "bin/$abi")
|
|
||||||
val target = File(binDir, "one-kvm-android-host")
|
|
||||||
copyAssetIfChanged("bin/$abi/one-kvm-android-host", target)
|
|
||||||
copyAssetIfChanged("bin/$abi/libc++_shared.so", File(binDir, "libc++_shared.so"))
|
|
||||||
copyAssetIfChanged("bin/$abi/libasound.so", File(binDir, "libasound.so"))
|
|
||||||
copyAssetIfChanged("bin/$abi/libopus.so", File(binDir, "libopus.so"))
|
|
||||||
copyAssetDirectoryIfChanged("bin/$abi/alsa", File(binDir, "alsa"))
|
|
||||||
if (!target.setExecutable(true, false)) {
|
|
||||||
throw IllegalStateException("cannot mark host binary executable")
|
|
||||||
}
|
|
||||||
return target
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun copyAssetIfChanged(assetPath: String, target: File) {
|
|
||||||
val stamp = File(target.parentFile, "${target.name}.stamp")
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
val packageInfo = packageManager.getPackageInfo(packageName, 0)
|
|
||||||
val expectedStamp = "${packageInfo.lastUpdateTime}:$assetPath"
|
|
||||||
if (target.exists() && stamp.exists() && stamp.readText() == expectedStamp) return
|
|
||||||
target.parentFile?.mkdirs()
|
|
||||||
assets.open(assetPath).use { input ->
|
|
||||||
target.outputStream().use { output -> input.copyTo(output) }
|
|
||||||
}
|
|
||||||
stamp.writeText(expectedStamp)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun copyAssetDirectoryIfChanged(assetDir: String, targetDir: File) {
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
val packageInfo = packageManager.getPackageInfo(packageName, 0)
|
|
||||||
val stamp = File(targetDir, ".stamp")
|
|
||||||
val expectedStamp = "${packageInfo.lastUpdateTime}:$assetDir"
|
|
||||||
if (targetDir.exists() && stamp.exists() && stamp.readText() == expectedStamp) return
|
|
||||||
if (targetDir.exists()) targetDir.deleteRecursively()
|
|
||||||
copyAssetDirectory(assetDir, targetDir)
|
|
||||||
stamp.writeText(expectedStamp)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun copyAssetDirectory(assetDir: String, targetDir: File) {
|
|
||||||
targetDir.mkdirs()
|
|
||||||
val children = assets.list(assetDir)?.filter { it.isNotEmpty() }.orEmpty()
|
|
||||||
for (child in children) {
|
|
||||||
val childAsset = "$assetDir/$child"
|
|
||||||
val childTarget = File(targetDir, child)
|
|
||||||
val grandChildren = assets.list(childAsset)?.filter { it.isNotEmpty() }.orEmpty()
|
|
||||||
if (grandChildren.isEmpty()) {
|
|
||||||
copyAssetIfChanged(childAsset, childTarget)
|
|
||||||
} else {
|
|
||||||
copyAssetDirectory(childAsset, childTarget)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startRootHost(
|
|
||||||
executable: File,
|
|
||||||
dataDir: File,
|
|
||||||
rustLog: String,
|
|
||||||
rustLogFile: File,
|
|
||||||
logLevel: String,
|
|
||||||
) {
|
|
||||||
stopRootHost(executable)
|
|
||||||
waitForPortRelease(8080, 2_000)
|
|
||||||
val libDir = executable.parentFile?.absolutePath
|
|
||||||
?: throw IllegalStateException("host binary has no parent directory")
|
|
||||||
val alsaConfigDir = File(executable.parentFile, "alsa")
|
|
||||||
val alsaConfigPath = File(alsaConfigDir, "alsa.conf")
|
|
||||||
val command =
|
|
||||||
"export LD_LIBRARY_PATH=${shellQuote(libDir)}:\${LD_LIBRARY_PATH:-}; " +
|
|
||||||
"export ALSA_CONFIG_DIR=${shellQuote(alsaConfigDir.absolutePath)}; " +
|
|
||||||
"export ALSA_CONFIG_PATH=${shellQuote(alsaConfigPath.absolutePath)}; " +
|
|
||||||
"export RUST_LOG=${shellQuote(rustLog)}; " +
|
|
||||||
"export ONE_KVM_FFMPEG_LOG=${shellQuote(ffmpegLogLevel(logLevel))}; " +
|
|
||||||
"export ONE_KVM_ANDROID_LOG_FILE=${shellQuote(rustLogFile.absolutePath)}; " +
|
|
||||||
"${shellQuote(executable.absolutePath)} ${shellQuote(dataDir.absolutePath)} 0.0.0.0 8080"
|
|
||||||
val process = ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
|
|
||||||
.redirectErrorStream(true)
|
|
||||||
.start()
|
|
||||||
rootProcess = process
|
|
||||||
|
|
||||||
Thread {
|
|
||||||
val readError = runCatching {
|
|
||||||
BufferedReader(InputStreamReader(process.inputStream)).useLines { lines ->
|
|
||||||
lines.forEach {
|
|
||||||
android.util.Log.i("OneKvmService", it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.exceptionOrNull()
|
|
||||||
if (readError != null && readError !is InterruptedIOException) {
|
|
||||||
android.util.Log.w("OneKvmService", "Root host log reader stopped", readError)
|
|
||||||
LogStore.append("Root host log reader stopped: ${readError.message ?: readError::class.java.simpleName}")
|
|
||||||
}
|
|
||||||
val exit = runCatching { process.waitFor() }.getOrNull()
|
|
||||||
if (rootProcess === process && exit != null) {
|
|
||||||
rootProcess = null
|
|
||||||
ServiceStatusStore.setError(this, "Root host exited with code $exit")
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
|
|
||||||
Thread.sleep(500)
|
|
||||||
val exit = runCatching { process.exitValue() }.getOrNull()
|
|
||||||
if (exit != null) {
|
|
||||||
rootProcess = null
|
|
||||||
throw IllegalStateException("root host exited immediately: $exit")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun startForegroundCompat(id: Int, notification: Notification) {
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
|
||||||
val invoked = runCatching {
|
|
||||||
val method = Service::class.java.getMethod(
|
|
||||||
"startForeground",
|
|
||||||
Int::class.javaPrimitiveType,
|
|
||||||
Notification::class.java,
|
|
||||||
Int::class.javaPrimitiveType,
|
|
||||||
)
|
|
||||||
method.invoke(this, id, notification, foregroundServiceTypeConnectedDevice())
|
|
||||||
}.isSuccess
|
|
||||||
if (invoked) return
|
|
||||||
}
|
|
||||||
super.startForeground(id, notification)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun foregroundServiceTypeConnectedDevice(): Int {
|
|
||||||
return try {
|
|
||||||
Service::class.java.getField("FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE").getInt(null)
|
|
||||||
} catch (_: ReflectiveOperationException) {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun stopRootHost(executable: File? = null) {
|
|
||||||
rootProcess?.destroy()
|
|
||||||
rootProcess = null
|
|
||||||
stopRootHostProcess(executable)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun stopRootHostProcess(executable: File? = null) {
|
|
||||||
val command = buildString {
|
|
||||||
append("pkill -TERM -f '[o]ne-kvm-android-host' 2>/dev/null || true; ")
|
|
||||||
append("for pid in $(pidof one-kvm-android-host 2>/dev/null); do kill -TERM \"${'$'}pid\" 2>/dev/null || true; done; ")
|
|
||||||
append("sleep 0.2; ")
|
|
||||||
append("pkill -KILL -f '[o]ne-kvm-android-host' 2>/dev/null || true; ")
|
|
||||||
append("for pid in $(pidof one-kvm-android-host 2>/dev/null); do kill -KILL \"${'$'}pid\" 2>/dev/null || true; done; ")
|
|
||||||
}
|
|
||||||
|
|
||||||
runCatching {
|
|
||||||
ProcessBuilder("/system/xbin/su", "0", "sh", "-c", command)
|
|
||||||
.redirectErrorStream(true)
|
|
||||||
.start()
|
|
||||||
.waitFor()
|
|
||||||
}.onFailure { err ->
|
|
||||||
LogStore.append("Failed to stop stale root host: ${err.message ?: err::class.java.simpleName}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun waitForPortRelease(port: Int, timeoutMs: Long) {
|
|
||||||
val deadline = System.currentTimeMillis() + timeoutMs
|
|
||||||
while (System.currentTimeMillis() < deadline) {
|
|
||||||
val inUse = isPortOpen(port, 100)
|
|
||||||
if (!inUse) return
|
|
||||||
Thread.sleep(100)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isPortOpen(port: Int, timeoutMs: Int): Boolean {
|
|
||||||
return runCatching {
|
|
||||||
java.net.Socket().use { socket ->
|
|
||||||
socket.connect(java.net.InetSocketAddress("127.0.0.1", port), timeoutMs)
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}.getOrDefault(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun shellQuote(value: String): String {
|
|
||||||
return "'" + value.replace("'", "'\\''") + "'"
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ffmpegLogLevel(level: String): String {
|
|
||||||
return when (level) {
|
|
||||||
"trace" -> "trace"
|
|
||||||
"debug" -> "debug"
|
|
||||||
"info" -> "info"
|
|
||||||
"warn" -> "warning"
|
|
||||||
else -> "error"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val CHANNEL_ID = "one_kvm_host"
|
|
||||||
private const val NOTIFICATION_ID = 1001
|
|
||||||
const val ACTION_START = "cn.one_kvm.androidhost.START"
|
|
||||||
const val ACTION_STOP = "cn.one_kvm.androidhost.STOP"
|
|
||||||
|
|
||||||
fun start(context: Context) {
|
|
||||||
val intent = Intent(context, OneKvmService::class.java).setAction(ACTION_START)
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
||||||
context.startForegroundService(intent)
|
|
||||||
} else {
|
|
||||||
context.startService(intent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun stop(context: Context) {
|
|
||||||
context.startService(Intent(context, OneKvmService::class.java).setAction(ACTION_STOP))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package cn.one_kvm.androidhost
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
|
|
||||||
object ServiceStatusStore {
|
|
||||||
private const val PREFS = "one_kvm_android_status"
|
|
||||||
private const val KEY_STATE = "state"
|
|
||||||
private const val KEY_MESSAGE = "message"
|
|
||||||
private const val KEY_UPDATED_AT = "updated_at"
|
|
||||||
|
|
||||||
const val STATE_STOPPED = "stopped"
|
|
||||||
const val STATE_STARTING = "starting"
|
|
||||||
const val STATE_RUNNING = "running"
|
|
||||||
const val STATE_STOPPING = "stopping"
|
|
||||||
const val STATE_ERROR = "error"
|
|
||||||
|
|
||||||
data class Snapshot(
|
|
||||||
val state: String,
|
|
||||||
val message: String,
|
|
||||||
val updatedAt: Long,
|
|
||||||
) {
|
|
||||||
fun labelText(): String {
|
|
||||||
return when (state) {
|
|
||||||
STATE_STARTING -> "启动中"
|
|
||||||
STATE_RUNNING -> "运行中"
|
|
||||||
STATE_STOPPING -> "停止中"
|
|
||||||
STATE_ERROR -> "错误"
|
|
||||||
else -> "已停止"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun displayText(): String {
|
|
||||||
val label = labelText()
|
|
||||||
return if (message.isBlank()) label else "$label:$message"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setStarting(context: Context, message: String = "正在启动服务") {
|
|
||||||
write(context, STATE_STARTING, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setRunning(context: Context, message: String) {
|
|
||||||
write(context, STATE_RUNNING, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setStopping(context: Context, message: String = "正在停止服务") {
|
|
||||||
write(context, STATE_STOPPING, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setStopped(context: Context, message: String = "服务已停止") {
|
|
||||||
write(context, STATE_STOPPED, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setError(context: Context, message: String) {
|
|
||||||
write(context, STATE_ERROR, message)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun snapshot(context: Context): Snapshot {
|
|
||||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
return Snapshot(
|
|
||||||
state = prefs.getString(KEY_STATE, STATE_STOPPED) ?: STATE_STOPPED,
|
|
||||||
message = prefs.getString(KEY_MESSAGE, "") ?: "",
|
|
||||||
updatedAt = prefs.getLong(KEY_UPDATED_AT, 0L),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun write(context: Context, state: String, message: String) {
|
|
||||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
||||||
.edit()
|
|
||||||
.putString(KEY_STATE, state)
|
|
||||||
.putString(KEY_MESSAGE, message)
|
|
||||||
.putLong(KEY_UPDATED_AT, System.currentTimeMillis())
|
|
||||||
.apply()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path
|
|
||||||
android:fillColor="#1D7BF2"
|
|
||||||
android:pathData="M24,0h60a24,24 0,0 1,24 24v60a24,24 0,0 1,-24 24H24a24,24 0,0 1,-24 -24V24a24,24 0,0 1,24 -24z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#AED8E8"
|
|
||||||
android:pathData="M29,25h50a3,3 0,0 1,3 3v31a3,3 0,0 1,-3 3H29a3,3 0,0 1,-3 -3V28a3,3 0,0 1,3 -3z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#3F3F3D"
|
|
||||||
android:pathData="M31,30h46v27H31z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#E7F1F4"
|
|
||||||
android:pathData="M31,26h10a1.4,1.4 0,0 1,0 2.8H31a1.4,1.4 0,0 1,0 -2.8z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#8BBFD1"
|
|
||||||
android:pathData="M49,62h10l1.5,8h-13z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#9FCFE0"
|
|
||||||
android:pathData="M40,70a14,4.5 0,1 0,28 0a14,4.5 0,1 0,-28 0z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#E8F5F8"
|
|
||||||
android:pathData="M45,70a7,1.8 0,1 0,14 0a7,1.8 0,1 0,-14 0z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#BFE6F1"
|
|
||||||
android:pathData="M32,76h38l5,8H27z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#76ADC2"
|
|
||||||
android:pathData="M28,84h47v2H28z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:fillAlpha="0.82"
|
|
||||||
android:pathData="M37,79h6v2h-6zM46,79h5v2h-5zM54,79h5v2h-5zM62,79h6v2h-6zM34,82h7v2h-7zM44,82h6v2h-6zM53,82h11v2H53zM67,82h4v2h-4z" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="24dp"
|
|
||||||
android:height="24dp"
|
|
||||||
android:viewportWidth="24"
|
|
||||||
android:viewportHeight="24">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:pathData="M4,5h16v10H4z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFFFF"
|
|
||||||
android:pathData="M9,17h6v2h3v2H6v-2h3z" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<string name="app_name">One-KVM Android Host</string>
|
|
||||||
</resources>
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
|
|
||||||
<item name="android:fontFamily">sans</item>
|
|
||||||
<item name="android:colorAccent">#2563EB</item>
|
|
||||||
</style>
|
|
||||||
</resources>
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
plugins {
|
|
||||||
id("com.android.application") version "9.0.0" apply false
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
android.useAndroidX=true
|
|
||||||
android.nonTransitiveRClass=true
|
|
||||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
|
||||||
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
@@ -1,7 +0,0 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
|
||||||
distributionPath=wrapper/dists
|
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
|
|
||||||
networkTimeout=10000
|
|
||||||
validateDistributionUrl=true
|
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
|
||||||
zipStorePath=wrapper/dists
|
|
||||||
251
android/gradlew
vendored
251
android/gradlew
vendored
@@ -1,251 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
#
|
|
||||||
# Copyright © 2015 the original authors.
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
#
|
|
||||||
# SPDX-License-Identifier: Apache-2.0
|
|
||||||
#
|
|
||||||
|
|
||||||
##############################################################################
|
|
||||||
#
|
|
||||||
# Gradle start up script for POSIX generated by Gradle.
|
|
||||||
#
|
|
||||||
# Important for running:
|
|
||||||
#
|
|
||||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
|
||||||
# noncompliant, but you have some other compliant shell such as ksh or
|
|
||||||
# bash, then to run this script, type that shell name before the whole
|
|
||||||
# command line, like:
|
|
||||||
#
|
|
||||||
# ksh Gradle
|
|
||||||
#
|
|
||||||
# Busybox and similar reduced shells will NOT work, because this script
|
|
||||||
# requires all of these POSIX shell features:
|
|
||||||
# * functions;
|
|
||||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
|
||||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
|
||||||
# * compound commands having a testable exit status, especially «case»;
|
|
||||||
# * various built-in commands including «command», «set», and «ulimit».
|
|
||||||
#
|
|
||||||
# Important for patching:
|
|
||||||
#
|
|
||||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
|
||||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
|
||||||
#
|
|
||||||
# The "traditional" practice of packing multiple parameters into a
|
|
||||||
# space-separated string is a well documented source of bugs and security
|
|
||||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
|
||||||
# options in "$@", and eventually passing that to Java.
|
|
||||||
#
|
|
||||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
|
||||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
|
||||||
# see the in-line comments for details.
|
|
||||||
#
|
|
||||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
|
||||||
# Darwin, MinGW, and NonStop.
|
|
||||||
#
|
|
||||||
# (3) This script is generated from the Groovy template
|
|
||||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
|
||||||
# within the Gradle project.
|
|
||||||
#
|
|
||||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
|
||||||
#
|
|
||||||
##############################################################################
|
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
|
||||||
|
|
||||||
# Resolve links: $0 may be a link
|
|
||||||
app_path=$0
|
|
||||||
|
|
||||||
# Need this for daisy-chained symlinks.
|
|
||||||
while
|
|
||||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
|
||||||
[ -h "$app_path" ]
|
|
||||||
do
|
|
||||||
ls=$( ls -ld "$app_path" )
|
|
||||||
link=${ls#*' -> '}
|
|
||||||
case $link in #(
|
|
||||||
/*) app_path=$link ;; #(
|
|
||||||
*) app_path=$APP_HOME$link ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# This is normally unused
|
|
||||||
# shellcheck disable=SC2034
|
|
||||||
APP_BASE_NAME=${0##*/}
|
|
||||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
|
||||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
|
||||||
MAX_FD=maximum
|
|
||||||
|
|
||||||
warn () {
|
|
||||||
echo "$*"
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
die () {
|
|
||||||
echo
|
|
||||||
echo "$*"
|
|
||||||
echo
|
|
||||||
exit 1
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
|
||||||
cygwin=false
|
|
||||||
msys=false
|
|
||||||
darwin=false
|
|
||||||
nonstop=false
|
|
||||||
case "$( uname )" in #(
|
|
||||||
CYGWIN* ) cygwin=true ;; #(
|
|
||||||
Darwin* ) darwin=true ;; #(
|
|
||||||
MSYS* | MINGW* ) msys=true ;; #(
|
|
||||||
NONSTOP* ) nonstop=true ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
CLASSPATH="\\\"\\\""
|
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
|
||||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
|
||||||
else
|
|
||||||
JAVACMD=$JAVA_HOME/bin/java
|
|
||||||
fi
|
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
JAVACMD=java
|
|
||||||
if ! command -v java >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
|
||||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|
||||||
case $MAX_FD in #(
|
|
||||||
max*)
|
|
||||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
|
||||||
warn "Could not query maximum file descriptor limit"
|
|
||||||
esac
|
|
||||||
case $MAX_FD in #(
|
|
||||||
'' | soft) :;; #(
|
|
||||||
*)
|
|
||||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
ulimit -n "$MAX_FD" ||
|
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Collect all arguments for the java command, stacking in reverse order:
|
|
||||||
# * args from the command line
|
|
||||||
# * the main class name
|
|
||||||
# * -classpath
|
|
||||||
# * -D...appname settings
|
|
||||||
# * --module-path (only if needed)
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
|
||||||
|
|
||||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
|
||||||
if "$cygwin" || "$msys" ; then
|
|
||||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
|
||||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
|
||||||
|
|
||||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
|
||||||
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
|
||||||
for arg do
|
|
||||||
if
|
|
||||||
case $arg in #(
|
|
||||||
-*) false ;; # don't mess with options #(
|
|
||||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
|
||||||
[ -e "$t" ] ;; #(
|
|
||||||
*) false ;;
|
|
||||||
esac
|
|
||||||
then
|
|
||||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
|
||||||
fi
|
|
||||||
# Roll the args list around exactly as many times as the number of
|
|
||||||
# args, so each arg winds up back in the position where it started, but
|
|
||||||
# possibly modified.
|
|
||||||
#
|
|
||||||
# NB: a `for` loop captures its iteration list before it begins, so
|
|
||||||
# changing the positional parameters here affects neither the number of
|
|
||||||
# iterations, nor the values presented in `arg`.
|
|
||||||
shift # remove old arg
|
|
||||||
set -- "$@" "$arg" # push replacement arg
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
|
||||||
|
|
||||||
# Collect all arguments for the java command:
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
|
||||||
# and any embedded shellness will be escaped.
|
|
||||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
|
||||||
# treated as '${Hostname}' itself on the command line.
|
|
||||||
|
|
||||||
set -- \
|
|
||||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
|
||||||
-classpath "$CLASSPATH" \
|
|
||||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
|
||||||
"$@"
|
|
||||||
|
|
||||||
# Stop when "xargs" is not available.
|
|
||||||
if ! command -v xargs >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "xargs is not available"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Use "xargs" to parse quoted args.
|
|
||||||
#
|
|
||||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
|
||||||
#
|
|
||||||
# In Bash we could simply go:
|
|
||||||
#
|
|
||||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
|
||||||
# set -- "${ARGS[@]}" "$@"
|
|
||||||
#
|
|
||||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
|
||||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
|
||||||
# character that might be a shell metacharacter, then use eval to reverse
|
|
||||||
# that process (while maintaining the separation between arguments), and wrap
|
|
||||||
# the whole thing up as a single "set" statement.
|
|
||||||
#
|
|
||||||
# This will of course break if any of these variables contains a newline or
|
|
||||||
# an unmatched quote.
|
|
||||||
#
|
|
||||||
|
|
||||||
eval "set -- $(
|
|
||||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
|
||||||
xargs -n1 |
|
|
||||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
|
||||||
tr '\n' ' '
|
|
||||||
)" '"$@"'
|
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
|
||||||
94
android/gradlew.bat
vendored
94
android/gradlew.bat
vendored
@@ -1,94 +0,0 @@
|
|||||||
@rem
|
|
||||||
@rem Copyright 2015 the original author or authors.
|
|
||||||
@rem
|
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
@rem you may not use this file except in compliance with the License.
|
|
||||||
@rem You may obtain a copy of the License at
|
|
||||||
@rem
|
|
||||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
@rem
|
|
||||||
@rem Unless required by applicable law or agreed to in writing, software
|
|
||||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
@rem See the License for the specific language governing permissions and
|
|
||||||
@rem limitations under the License.
|
|
||||||
@rem
|
|
||||||
@rem SPDX-License-Identifier: Apache-2.0
|
|
||||||
@rem
|
|
||||||
|
|
||||||
@if "%DEBUG%"=="" @echo off
|
|
||||||
@rem ##########################################################################
|
|
||||||
@rem
|
|
||||||
@rem Gradle startup script for Windows
|
|
||||||
@rem
|
|
||||||
@rem ##########################################################################
|
|
||||||
|
|
||||||
@rem Set local scope for the variables with windows NT shell
|
|
||||||
if "%OS%"=="Windows_NT" setlocal
|
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
|
||||||
if "%DIRNAME%"=="" set DIRNAME=.
|
|
||||||
@rem This is normally unused
|
|
||||||
set APP_BASE_NAME=%~n0
|
|
||||||
set APP_HOME=%DIRNAME%
|
|
||||||
|
|
||||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
|
||||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
|
||||||
|
|
||||||
@rem Find java.exe
|
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
|
||||||
if %ERRORLEVEL% equ 0 goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:findJavaFromJavaHome
|
|
||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:execute
|
|
||||||
@rem Setup the command line
|
|
||||||
|
|
||||||
set CLASSPATH=
|
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
|
||||||
|
|
||||||
:end
|
|
||||||
@rem End local scope for the variables with windows NT shell
|
|
||||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
|
||||||
|
|
||||||
:fail
|
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
|
||||||
rem the _cmd.exe /c_ return code!
|
|
||||||
set EXIT_CODE=%ERRORLEVEL%
|
|
||||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
|
||||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
|
||||||
exit /b %EXIT_CODE%
|
|
||||||
|
|
||||||
:mainEnd
|
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
|
||||||
|
|
||||||
:omega
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "one-kvm-android-bootstrap"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "one_kvm_android_bootstrap"
|
|
||||||
crate-type = ["cdylib"]
|
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "one-kvm-android-host"
|
|
||||||
path = "src/bin/one-kvm-android-host.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
jni = "0.22.4"
|
|
||||||
one-kvm = { path = "../..", default-features = false, features = ["android", "android-mediacodec"] }
|
|
||||||
rustls-platform-verifier = "0.7"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
android-mediacodec = ["one-kvm/android-mediacodec"]
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
use one_kvm::runtime::android::{self, AndroidRuntimeConfig};
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
let mut args = std::env::args().skip(1);
|
|
||||||
let data_dir = args
|
|
||||||
.next()
|
|
||||||
.unwrap_or_else(|| "/data/local/tmp/one-kvm".to_string());
|
|
||||||
let bind_address = args.next().unwrap_or_else(|| "0.0.0.0".to_string());
|
|
||||||
let port = args
|
|
||||||
.next()
|
|
||||||
.and_then(|value| value.parse::<u16>().ok())
|
|
||||||
.unwrap_or(8080);
|
|
||||||
|
|
||||||
one_kvm::runtime::android::init_rustls_provider();
|
|
||||||
|
|
||||||
if let Err(err) = android::run_foreground(AndroidRuntimeConfig {
|
|
||||||
data_dir,
|
|
||||||
bind_address,
|
|
||||||
port,
|
|
||||||
}) {
|
|
||||||
eprintln!("one-kvm android host failed: {err}");
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
use jni::errors::{ErrorPolicy, ThrowRuntimeExAndDefault};
|
|
||||||
use jni::objects::{JClass, JObject, JString};
|
|
||||||
use jni::sys::{jint, jstring};
|
|
||||||
use jni::{Env, EnvOutcome, EnvUnowned};
|
|
||||||
use one_kvm::runtime::android::{self, AndroidRuntimeConfig};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct BridgeError(String);
|
|
||||||
|
|
||||||
impl From<jni::errors::Error> for BridgeError {
|
|
||||||
fn from(err: jni::errors::Error) -> Self {
|
|
||||||
Self(err.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<String> for BridgeError {
|
|
||||||
fn from(err: String) -> Self {
|
|
||||||
Self(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for BridgeError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.write_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct StatusPolicy;
|
|
||||||
|
|
||||||
impl ErrorPolicy<jint, BridgeError> for StatusPolicy {
|
|
||||||
type Captures<'unowned_env_local: 'native_method, 'native_method> = ();
|
|
||||||
|
|
||||||
fn on_error<'unowned_env_local: 'native_method, 'native_method>(
|
|
||||||
_env: &mut Env<'unowned_env_local>,
|
|
||||||
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
|
|
||||||
_err: BridgeError,
|
|
||||||
) -> jni::errors::Result<jint> {
|
|
||||||
Ok(-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
|
|
||||||
_env: &mut Env<'unowned_env_local>,
|
|
||||||
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
|
|
||||||
_payload: Box<dyn std::any::Any + Send + 'static>,
|
|
||||||
) -> jni::errors::Result<jint> {
|
|
||||||
Ok(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct StringResultPolicy;
|
|
||||||
|
|
||||||
impl ErrorPolicy<String, BridgeError> for StringResultPolicy {
|
|
||||||
type Captures<'unowned_env_local: 'native_method, 'native_method> = ();
|
|
||||||
|
|
||||||
fn on_error<'unowned_env_local: 'native_method, 'native_method>(
|
|
||||||
_env: &mut Env<'unowned_env_local>,
|
|
||||||
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
|
|
||||||
err: BridgeError,
|
|
||||||
) -> jni::errors::Result<String> {
|
|
||||||
Ok(format!("start failed: {err}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
|
|
||||||
_env: &mut Env<'unowned_env_local>,
|
|
||||||
_cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
|
|
||||||
_payload: Box<dyn std::any::Any + Send + 'static>,
|
|
||||||
) -> jni::errors::Result<String> {
|
|
||||||
Ok("start failed: panic in native bridge".to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_setEnv<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
name: JString<'local>,
|
|
||||||
value: JString<'local>,
|
|
||||||
) -> jint {
|
|
||||||
let outcome: EnvOutcome<'local, jint, BridgeError> = env.with_env_no_catch(|env| {
|
|
||||||
let name = name
|
|
||||||
.try_to_string(env)
|
|
||||||
.map_err(|err| BridgeError(format!("invalid env name: {err}")))?;
|
|
||||||
let value = value
|
|
||||||
.try_to_string(env)
|
|
||||||
.map_err(|err| BridgeError(format!("invalid env value: {err}")))?;
|
|
||||||
if name.contains('\0') || value.contains('\0') {
|
|
||||||
return Err(BridgeError("env contains NUL".to_string()));
|
|
||||||
}
|
|
||||||
std::env::set_var(name, value);
|
|
||||||
Ok(0)
|
|
||||||
});
|
|
||||||
|
|
||||||
outcome.resolve_with::<StatusPolicy, _>(|| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_initTlsVerifier<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
context: JObject<'local>,
|
|
||||||
) -> jint {
|
|
||||||
let outcome: EnvOutcome<'local, jint, BridgeError> =
|
|
||||||
env.with_env_no_catch(|env| init_tls_verifier(env, context));
|
|
||||||
|
|
||||||
outcome.resolve_with::<StatusPolicy, _>(|| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(target_os = "android")]
|
|
||||||
fn init_tls_verifier(env: &mut Env<'_>, context: JObject<'_>) -> Result<jint, BridgeError> {
|
|
||||||
rustls_platform_verifier::android::init_with_env(env, context)
|
|
||||||
.map_err(|err| BridgeError(format!("failed to initialize rustls platform verifier: {err}")))?;
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "android"))]
|
|
||||||
fn init_tls_verifier(_env: &mut Env<'_>, _context: JObject<'_>) -> Result<jint, BridgeError> {
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_startHost<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
data_dir: JString<'local>,
|
|
||||||
bind_address: JString<'local>,
|
|
||||||
port: i32,
|
|
||||||
) -> jstring {
|
|
||||||
let outcome: EnvOutcome<'local, String, BridgeError> = env.with_env_no_catch(|env| {
|
|
||||||
let data_dir = data_dir
|
|
||||||
.try_to_string(env)
|
|
||||||
.map_err(|err| BridgeError(format!("invalid data dir: {err}")))?;
|
|
||||||
let bind_address = bind_address
|
|
||||||
.try_to_string(env)
|
|
||||||
.map_err(|err| BridgeError(format!("invalid bind address: {err}")))?;
|
|
||||||
let port = u16::try_from(port).map_err(|_| BridgeError("invalid port".to_string()))?;
|
|
||||||
|
|
||||||
android::start(AndroidRuntimeConfig {
|
|
||||||
data_dir,
|
|
||||||
bind_address,
|
|
||||||
port,
|
|
||||||
})
|
|
||||||
.map_err(BridgeError)
|
|
||||||
});
|
|
||||||
|
|
||||||
let result = outcome.resolve_with::<StringResultPolicy, _>(|| ());
|
|
||||||
|
|
||||||
env.with_env_no_catch(|env| env.new_string(result))
|
|
||||||
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
|
|
||||||
.into_raw()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_stopHost<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
) -> jstring {
|
|
||||||
env.with_env_no_catch(|env| env.new_string(android::stop()))
|
|
||||||
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
|
|
||||||
.into_raw()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_hostStatus<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
) -> jstring {
|
|
||||||
env.with_env_no_catch(|env| env.new_string(android::status()))
|
|
||||||
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
|
|
||||||
.into_raw()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_cn_one_1kvm_androidhost_NativeBridge_kernelVersion<'local>(
|
|
||||||
mut env: EnvUnowned<'local>,
|
|
||||||
_class: JClass<'local>,
|
|
||||||
) -> jstring {
|
|
||||||
env.with_env_no_catch(|env| env.new_string(env!("CARGO_PKG_VERSION")))
|
|
||||||
.resolve_with::<ThrowRuntimeExAndDefault, _>(|| ())
|
|
||||||
.into_raw()
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
pluginManagement {
|
|
||||||
fun isEnabled(value: String?): Boolean = when (value?.lowercase()) {
|
|
||||||
"1", "true", "yes", "on" -> true
|
|
||||||
else -> false
|
|
||||||
}
|
|
||||||
val mirrorAcceleration = isEnabled(System.getenv("CHINAMIRRO"))
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
if (mirrorAcceleration) {
|
|
||||||
maven("https://maven.aliyun.com/repository/google")
|
|
||||||
maven("https://maven.aliyun.com/repository/public")
|
|
||||||
maven("https://maven.aliyun.com/repository/gradle-plugin")
|
|
||||||
}
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
gradlePluginPortal()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencyResolutionManagement {
|
|
||||||
fun isEnabled(value: String?): Boolean = when (value?.lowercase()) {
|
|
||||||
"1", "true", "yes", "on" -> true
|
|
||||||
else -> false
|
|
||||||
}
|
|
||||||
val mirrorAcceleration = isEnabled(System.getenv("CHINAMIRRO"))
|
|
||||||
|
|
||||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
|
||||||
repositories {
|
|
||||||
if (mirrorAcceleration) {
|
|
||||||
maven("https://maven.aliyun.com/repository/google")
|
|
||||||
maven("https://maven.aliyun.com/repository/public")
|
|
||||||
}
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rootProject.name = "OneKvmAndroidHost"
|
|
||||||
include(":app")
|
|
||||||
31
build.rs
31
build.rs
@@ -2,21 +2,6 @@ use std::fs;
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
fn main() {
|
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 protobuf files for RustDesk protocol
|
||||||
compile_protos();
|
compile_protos();
|
||||||
|
|
||||||
@@ -86,19 +71,3 @@ pub mod rustdesk {
|
|||||||
|
|
||||||
fs::write(&dest_path, code).expect("Failed to write secrets_generated.rs");
|
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 \
|
ca-certificates \
|
||||||
libudev1 \
|
libudev1 \
|
||||||
libasound2 \
|
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
|
# v4l2 is handled by kernel, minimal userspace needed
|
||||||
libv4l-0 \
|
libv4l-0 \
|
||||||
&& \
|
&& \
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ RUN sed -i 's/ main$/ main contrib non-free/' /etc/apt/sources.list && \
|
|||||||
ca-certificates \
|
ca-certificates \
|
||||||
libudev1 \
|
libudev1 \
|
||||||
libasound2 \
|
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
|
# v4l2 is handled by kernel, minimal userspace needed
|
||||||
libv4l-0 \
|
libv4l-0 \
|
||||||
&& \
|
&& \
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Build Android APKs using the Docker build image.
|
|
||||||
# Usage: ./build/build-android.sh [arm64|armv7|all|help]
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
|
||||||
DOCKERFILE="$PROJECT_ROOT/build/cross/Dockerfile.android"
|
|
||||||
IMAGE_NAME="${ONE_KVM_ANDROID_DOCKER_IMAGE:-one-kvm-android-build:cn}"
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
build_android() {
|
|
||||||
local arch="$1"
|
|
||||||
local docker_build_args=()
|
|
||||||
local gradle_distribution_url="${ONE_KVM_GRADLE_DISTRIBUTION_URL:-}"
|
|
||||||
local gradle_distribution_url_cn="${ONE_KVM_GRADLE_DISTRIBUTION_URL_CN:-https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip}"
|
|
||||||
local gradle_network_timeout="${ONE_KVM_GRADLE_NETWORK_TIMEOUT:-120000}"
|
|
||||||
|
|
||||||
if [[ "${CHINAMIRRO:-}" == "1" ]]; then
|
|
||||||
docker_build_args+=("--build-arg" "CHINAMIRRO=1")
|
|
||||||
docker_build_args+=("--build-arg" "DEBIAN_IMAGE=${DEBIAN_IMAGE:-docker.1ms.run/library/debian:11}")
|
|
||||||
docker_build_args+=("--build-arg" "RUSTUP_DIST_SERVER_CN=${RUSTUP_DIST_SERVER_CN:-https://rsproxy.cn}")
|
|
||||||
docker_build_args+=("--build-arg" "RUSTUP_UPDATE_ROOT_CN=${RUSTUP_UPDATE_ROOT_CN:-https://rsproxy.cn/rustup}")
|
|
||||||
docker_build_args+=("--build-arg" "CARGO_INDEX_CN=${CARGO_INDEX_CN:-https://rsproxy.cn/crates.io-index}")
|
|
||||||
docker_build_args+=("--build-arg" "CARGO_REGISTRY_CN=${CARGO_REGISTRY_CN:-sparse+https://rsproxy.cn/index/}")
|
|
||||||
docker_build_args+=("--build-arg" "MAVEN_REPOSITORY_CN=${MAVEN_REPOSITORY_CN:-https://maven.aliyun.com/repository/public}")
|
|
||||||
docker_build_args+=("--build-arg" "GOOGLE_MAVEN_REPOSITORY_CN=${GOOGLE_MAVEN_REPOSITORY_CN:-https://maven.aliyun.com/repository/google}")
|
|
||||||
docker_build_args+=("--build-arg" "GRADLE_PLUGIN_REPOSITORY_CN=${GRADLE_PLUGIN_REPOSITORY_CN:-https://maven.aliyun.com/repository/gradle-plugin}")
|
|
||||||
docker_build_args+=("--build-arg" "GRADLE_DISTRIBUTION_URL_CN=$gradle_distribution_url_cn")
|
|
||||||
if [[ -z "$gradle_distribution_url" ]]; then
|
|
||||||
gradle_distribution_url="$gradle_distribution_url_cn"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "${ONE_KVM_ANDROID_SKIP_DOCKER_BUILD:-0}" == "1" ]]; then
|
|
||||||
echo "=== Skipping Android image build: $IMAGE_NAME ==="
|
|
||||||
else
|
|
||||||
echo "=== Building Android image: $IMAGE_NAME ==="
|
|
||||||
docker build \
|
|
||||||
-f "$DOCKERFILE" \
|
|
||||||
-t "$IMAGE_NAME" \
|
|
||||||
"${docker_build_args[@]}" \
|
|
||||||
"$PROJECT_ROOT/build/cross"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "=== Building Android APK: $arch ==="
|
|
||||||
docker run --rm \
|
|
||||||
-v "$PROJECT_ROOT:/workspace" \
|
|
||||||
-w /workspace \
|
|
||||||
-e "CHINAMIRRO=${CHINAMIRRO:-0}" \
|
|
||||||
-e "GH_PROXY=${GH_PROXY:-https://gh-proxy.com}" \
|
|
||||||
-e "ONE_KVM_GRADLE_DISTRIBUTION_URL=$gradle_distribution_url" \
|
|
||||||
-e "ONE_KVM_GRADLE_DISTRIBUTION_URL_CN=$gradle_distribution_url_cn" \
|
|
||||||
-e "ONE_KVM_GRADLE_NETWORK_TIMEOUT=$gradle_network_timeout" \
|
|
||||||
"$IMAGE_NAME" \
|
|
||||||
"$arch"
|
|
||||||
}
|
|
||||||
|
|
||||||
[[ -f "$DOCKERFILE" ]] || fail "Android Dockerfile not found: $DOCKERFILE"
|
|
||||||
command -v docker >/dev/null 2>&1 || fail "docker is required"
|
|
||||||
|
|
||||||
case "${1:-all}" in
|
|
||||||
all)
|
|
||||||
build_android all
|
|
||||||
;;
|
|
||||||
arm64)
|
|
||||||
build_android arm64
|
|
||||||
;;
|
|
||||||
armv7)
|
|
||||||
build_android armv7
|
|
||||||
;;
|
|
||||||
help | --help | -h)
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage: build/build-android.sh [arch|help]
|
|
||||||
|
|
||||||
Commands:
|
|
||||||
all (default) Build arm64 and armv7 APKs
|
|
||||||
arm64 Build only arm64 APK
|
|
||||||
armv7 Build only ARMv7 APK
|
|
||||||
help Show this help
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
build/build-android.sh
|
|
||||||
build/build-android.sh arm64
|
|
||||||
CHINAMIRRO=1 build/build-android.sh all
|
|
||||||
CHINAMIRRO=1 ONE_KVM_GRADLE_DISTRIBUTION_URL=https://mirrors.aliyun.com/macports/distfiles/gradle/gradle-9.1.0-bin.zip build/build-android.sh all
|
|
||||||
|
|
||||||
Environment:
|
|
||||||
ONE_KVM_ANDROID_SKIP_DOCKER_BUILD=1 Reuse an already loaded Docker image
|
|
||||||
|
|
||||||
APK output:
|
|
||||||
target/android/one-kvm_<version>_<arm32|arm64>.apk
|
|
||||||
EOF
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
@@ -1,319 +0,0 @@
|
|||||||
# Android build image for One-KVM
|
|
||||||
# Based on Debian 11 for stable toolchain/runtime compatibility
|
|
||||||
|
|
||||||
ARG DEBIAN_IMAGE=debian:11
|
|
||||||
FROM ${DEBIAN_IMAGE}
|
|
||||||
|
|
||||||
ARG CHINAMIRRO=0
|
|
||||||
ARG ANDROID_SDK_ROOT=/root/android-sdk
|
|
||||||
ARG ANDROID_CMDLINE_TOOLS_VERSION=11076708_latest
|
|
||||||
ARG ANDROID_NDK_VERSION=27.3.13750724
|
|
||||||
ARG ANDROID_PLATFORM=36
|
|
||||||
ARG ANDROID_BUILD_TOOLS=36.0.0
|
|
||||||
ARG CARGO_NDK_VERSION=4.1.2
|
|
||||||
ARG RUSTUP_DIST_SERVER_CN=https://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 MAVEN_REPOSITORY_CN=https://maven.aliyun.com/repository/public
|
|
||||||
ARG GOOGLE_MAVEN_REPOSITORY_CN=https://maven.aliyun.com/repository/google
|
|
||||||
ARG GRADLE_PLUGIN_REPOSITORY_CN=https://maven.aliyun.com/repository/gradle-plugin
|
|
||||||
ARG GRADLE_DISTRIBUTION_URL_CN=https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip
|
|
||||||
ARG ANDROID_CMDLINE_TOOLS_URL=
|
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND=noninteractive
|
|
||||||
ENV ANDROID_HOME=${ANDROID_SDK_ROOT}
|
|
||||||
ENV ANDROID_SDK_ROOT=${ANDROID_SDK_ROOT}
|
|
||||||
ENV ANDROID_NDK_HOME=${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}
|
|
||||||
ENV ANDROID_NDK_ROOT=${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}
|
|
||||||
ENV ANDROID_BUILD_TOOLS=${ANDROID_BUILD_TOOLS}
|
|
||||||
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
|
|
||||||
ENV PATH=/root/.cargo/bin:${PATH}
|
|
||||||
ENV ONE_KVM_GRADLE_DISTRIBUTION_URL_CN=${GRADLE_DISTRIBUTION_URL_CN}
|
|
||||||
|
|
||||||
RUN if [ "$CHINAMIRRO" = "1" ]; then \
|
|
||||||
sed -i -E \
|
|
||||||
-e 's|http://deb.debian.org/debian([[:space:]])|http://mirrors.tuna.tsinghua.edu.cn/debian\1|g' \
|
|
||||||
/etc/apt/sources.list; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
||||||
ca-certificates \
|
|
||||||
curl \
|
|
||||||
wget \
|
|
||||||
bzip2 \
|
|
||||||
unzip \
|
|
||||||
zip \
|
|
||||||
git \
|
|
||||||
bash \
|
|
||||||
build-essential \
|
|
||||||
pkg-config \
|
|
||||||
cmake \
|
|
||||||
ninja-build \
|
|
||||||
autoconf \
|
|
||||||
automake \
|
|
||||||
libtool \
|
|
||||||
nasm \
|
|
||||||
yasm \
|
|
||||||
python3 \
|
|
||||||
openjdk-17-jdk-headless \
|
|
||||||
libstdc++6 \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
RUN if [ "$CHINAMIRRO" = "1" ]; then \
|
|
||||||
export RUSTUP_DIST_SERVER=${RUSTUP_DIST_SERVER_CN}; \
|
|
||||||
export RUSTUP_UPDATE_ROOT=${RUSTUP_UPDATE_ROOT_CN}; \
|
|
||||||
mkdir -p /root/.cargo; \
|
|
||||||
printf '%s\n' \
|
|
||||||
'[source.crates-io]' \
|
|
||||||
"replace-with = '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 \
|
|
||||||
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable \
|
|
||||||
&& cargo install cargo-ndk --version ${CARGO_NDK_VERSION} --locked \
|
|
||||||
&& rustup target add armv7-linux-androideabi aarch64-linux-android
|
|
||||||
|
|
||||||
RUN mkdir -p /opt/android-cmdline-tools \
|
|
||||||
&& cd /tmp \
|
|
||||||
&& if [ -n "$ANDROID_CMDLINE_TOOLS_URL" ]; then \
|
|
||||||
wget -q "$ANDROID_CMDLINE_TOOLS_URL" -O cmdline-tools.zip; \
|
|
||||||
else \
|
|
||||||
wget -q https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS_VERSION}.zip -O cmdline-tools.zip; \
|
|
||||||
fi \
|
|
||||||
&& unzip -q cmdline-tools.zip -d /opt/android-cmdline-tools \
|
|
||||||
&& mkdir -p ${ANDROID_SDK_ROOT}/cmdline-tools/latest \
|
|
||||||
&& mv /opt/android-cmdline-tools/cmdline-tools/* ${ANDROID_SDK_ROOT}/cmdline-tools/latest/ \
|
|
||||||
&& rm -rf /tmp/cmdline-tools.zip /opt/android-cmdline-tools
|
|
||||||
|
|
||||||
RUN mkdir -p ${ANDROID_SDK_ROOT}/licenses \
|
|
||||||
&& yes | ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=${ANDROID_SDK_ROOT} --licenses >/dev/null \
|
|
||||||
&& ${ANDROID_SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager --sdk_root=${ANDROID_SDK_ROOT} \
|
|
||||||
"platform-tools" \
|
|
||||||
"platforms;android-${ANDROID_PLATFORM}" \
|
|
||||||
"build-tools;${ANDROID_BUILD_TOOLS}" \
|
|
||||||
"ndk;${ANDROID_NDK_VERSION}" \
|
|
||||||
"cmake;3.22.1" \
|
|
||||||
&& mkdir -p ${ANDROID_NDK_HOME}
|
|
||||||
|
|
||||||
RUN if [ "$CHINAMIRRO" = "1" ]; then \
|
|
||||||
mkdir -p /root/.gradle; \
|
|
||||||
printf '%s\n' \
|
|
||||||
"beforeSettings { settings ->" \
|
|
||||||
" settings.pluginManagement.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
" settings.pluginManagement.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
" settings.pluginManagement.repositories.maven { url = uri('${GRADLE_PLUGIN_REPOSITORY_CN}') }" \
|
|
||||||
" settings.dependencyResolutionManagement.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
" settings.dependencyResolutionManagement.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
"}" \
|
|
||||||
"allprojects {" \
|
|
||||||
" buildscript.repositories.maven { url = uri('${GOOGLE_MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
" buildscript.repositories.maven { url = uri('${MAVEN_REPOSITORY_CN}') }" \
|
|
||||||
"}" \
|
|
||||||
> /root/.gradle/init.gradle; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
||||||
libclang-dev \
|
|
||||||
llvm \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
ENV LIBCLANG_PATH=/usr/lib/llvm-11/lib
|
|
||||||
|
|
||||||
RUN printf '%s\n' \
|
|
||||||
'#!/usr/bin/env bash' \
|
|
||||||
'set -euo pipefail' \
|
|
||||||
'' \
|
|
||||||
'PROJECT_ROOT="${ONE_KVM_ANDROID_PROJECT_ROOT:-/workspace}"' \
|
|
||||||
'ANDROID_DIR="${PROJECT_ROOT}/android"' \
|
|
||||||
'BUILD_TYPE="release"' \
|
|
||||||
'ARCH="${1:-all}"' \
|
|
||||||
'FFMPEG_ROOT="${ONE_KVM_ANDROID_FFMPEG_ROOT:-${PROJECT_ROOT}/dist/android-ffmpeg-mediacodec}"' \
|
|
||||||
'OUTPUT_DIR="${PROJECT_ROOT}/target/android"' \
|
|
||||||
'SIGNING_DIR="${PROJECT_ROOT}/target/android-signing"' \
|
|
||||||
'KEYSTORE_PATH="${SIGNING_DIR}/one-kvm-release.jks"' \
|
|
||||||
'KEY_ALIAS="one-kvm-release"' \
|
|
||||||
'KEY_PASSWORD="one-kvm-release"' \
|
|
||||||
'ANDROID_BUILD_TOOLS_DIR="${ANDROID_SDK_ROOT}/build-tools/${ANDROID_BUILD_TOOLS}"' \
|
|
||||||
'WRAPPER_PROPERTIES="$ANDROID_DIR/gradle/wrapper/gradle-wrapper.properties"' \
|
|
||||||
'GRADLE_DISTRIBUTION_URL="${ONE_KVM_GRADLE_DISTRIBUTION_URL:-}"' \
|
|
||||||
'GRADLE_DISTRIBUTION_URL_CN="${ONE_KVM_GRADLE_DISTRIBUTION_URL_CN:-https://mirrors.cloud.tencent.com/gradle/gradle-9.1.0-bin.zip}"' \
|
|
||||||
'GRADLE_NETWORK_TIMEOUT="${ONE_KVM_GRADLE_NETWORK_TIMEOUT:-120000}"' \
|
|
||||||
'' \
|
|
||||||
'usage() {' \
|
|
||||||
' cat <<EOF' \
|
|
||||||
'Usage:' \
|
|
||||||
' docker run --rm -v "$PWD:/workspace" one-kvm-android-build:cn [arm64|armv7|all|help]' \
|
|
||||||
'' \
|
|
||||||
'Commands:' \
|
|
||||||
' all Build arm64 and armv7 APKs. Default.' \
|
|
||||||
' arm64 Build only arm64 APK.' \
|
|
||||||
' armv7 Build only ARMv7 APK.' \
|
|
||||||
' help Show this help.' \
|
|
||||||
'' \
|
|
||||||
'APK output:' \
|
|
||||||
' target/android/one-kvm_<version>_<arm32|arm64>.apk' \
|
|
||||||
'EOF' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'fail() {' \
|
|
||||||
' echo "Error: $*" >&2' \
|
|
||||||
' exit 1' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'read_project_version() {' \
|
|
||||||
' local version' \
|
|
||||||
' version="$(awk -F "\"" '"'"'/^version[[:space:]]*=/ { print $2; exit }'"'"' "$PROJECT_ROOT/Cargo.toml")"' \
|
|
||||||
' [[ -n "$version" ]] || fail "Failed to resolve version from $PROJECT_ROOT/Cargo.toml"' \
|
|
||||||
' printf "%s\n" "$version"' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'copy_apks() {' \
|
|
||||||
' local flavor="$1"' \
|
|
||||||
' local src_dir="$ANDROID_DIR/app/build/outputs/apk/$flavor/$BUILD_TYPE"' \
|
|
||||||
' local found=0' \
|
|
||||||
' mkdir -p "$OUTPUT_DIR"' \
|
|
||||||
' for apk in "$src_dir"/*.apk; do' \
|
|
||||||
' [[ -f "$apk" ]] || continue' \
|
|
||||||
' sign_apk "$apk" "$OUTPUT_DIR/one-kvm_${PROJECT_VERSION}_${flavor}.apk"' \
|
|
||||||
' found=1' \
|
|
||||||
' done' \
|
|
||||||
' [[ "$found" == "1" ]] || fail "No APK files found in: $src_dir"' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'ensure_keystore() {' \
|
|
||||||
' if [[ -f "$KEYSTORE_PATH" ]]; then' \
|
|
||||||
' return' \
|
|
||||||
' fi' \
|
|
||||||
' mkdir -p "$SIGNING_DIR"' \
|
|
||||||
' keytool -genkeypair -noprompt -keystore "$KEYSTORE_PATH" -storetype PKCS12 -alias "$KEY_ALIAS" -keyalg RSA -keysize 2048 -validity 10000 -storepass "$KEY_PASSWORD" -keypass "$KEY_PASSWORD" -dname "CN=One-KVM, OU=One-KVM, O=One-KVM, L=Local, S=Local, C=US" >/dev/null' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'sign_apk() {' \
|
|
||||||
' local input_apk="$1"' \
|
|
||||||
' local output_apk="$2"' \
|
|
||||||
' local aligned_apk' \
|
|
||||||
' aligned_apk="$(mktemp --suffix=.apk)"' \
|
|
||||||
' "$ANDROID_BUILD_TOOLS_DIR/zipalign" -f -p 4 "$input_apk" "$aligned_apk"' \
|
|
||||||
' "$ANDROID_BUILD_TOOLS_DIR/apksigner" sign --ks "$KEYSTORE_PATH" --ks-key-alias "$KEY_ALIAS" --ks-pass "pass:$KEY_PASSWORD" --key-pass "pass:$KEY_PASSWORD" --out "$output_apk" "$aligned_apk"' \
|
|
||||||
' "$ANDROID_BUILD_TOOLS_DIR/apksigner" verify --verbose "$output_apk" >/dev/null' \
|
|
||||||
' rm -f "$aligned_apk"' \
|
|
||||||
'}' \
|
|
||||||
'' \
|
|
||||||
'cd "$PROJECT_ROOT"' \
|
|
||||||
'' \
|
|
||||||
'case "$ARCH" in' \
|
|
||||||
'help | --help | -h)' \
|
|
||||||
' usage' \
|
|
||||||
' exit 0' \
|
|
||||||
' ;;' \
|
|
||||||
'esac' \
|
|
||||||
'' \
|
|
||||||
'[[ -d "$ANDROID_DIR" ]] || fail "Android project not found: $ANDROID_DIR"' \
|
|
||||||
'[[ -x "$ANDROID_DIR/gradlew" ]] || fail "Gradle wrapper is not executable: $ANDROID_DIR/gradlew"' \
|
|
||||||
'[[ -f "$WRAPPER_PROPERTIES" ]] || fail "Gradle wrapper properties not found: $WRAPPER_PROPERTIES"' \
|
|
||||||
'' \
|
|
||||||
'ORIGINAL_WRAPPER_PROPERTIES="$(mktemp)"' \
|
|
||||||
'cp "$WRAPPER_PROPERTIES" "$ORIGINAL_WRAPPER_PROPERTIES"' \
|
|
||||||
'cleanup_wrapper_properties() {' \
|
|
||||||
' cp "$ORIGINAL_WRAPPER_PROPERTIES" "$WRAPPER_PROPERTIES"' \
|
|
||||||
' rm -f "$ORIGINAL_WRAPPER_PROPERTIES"' \
|
|
||||||
'}' \
|
|
||||||
'trap cleanup_wrapper_properties EXIT' \
|
|
||||||
'' \
|
|
||||||
'if [[ "${CHINAMIRRO:-0}" == "1" && -z "$GRADLE_DISTRIBUTION_URL" ]]; then' \
|
|
||||||
' GRADLE_DISTRIBUTION_URL="$GRADLE_DISTRIBUTION_URL_CN"' \
|
|
||||||
'fi' \
|
|
||||||
'' \
|
|
||||||
'if [[ -n "$GRADLE_DISTRIBUTION_URL" ]]; then' \
|
|
||||||
' WRAPPER_PROPERTIES_TMP="$(mktemp)"' \
|
|
||||||
' awk -v url="$GRADLE_DISTRIBUTION_URL" -v timeout="$GRADLE_NETWORK_TIMEOUT" '"'"'' \
|
|
||||||
' BEGIN { seen_url = 0; seen_timeout = 0 }' \
|
|
||||||
' /^distributionUrl=/ { print "distributionUrl=" url; seen_url = 1; next }' \
|
|
||||||
' /^networkTimeout=/ { print "networkTimeout=" timeout; seen_timeout = 1; next }' \
|
|
||||||
' { print }' \
|
|
||||||
' END {' \
|
|
||||||
' if (!seen_url) print "distributionUrl=" url;' \
|
|
||||||
' if (!seen_timeout) print "networkTimeout=" timeout;' \
|
|
||||||
' }' \
|
|
||||||
' '"'"' "$WRAPPER_PROPERTIES" > "$WRAPPER_PROPERTIES_TMP"' \
|
|
||||||
' cp "$WRAPPER_PROPERTIES_TMP" "$WRAPPER_PROPERTIES"' \
|
|
||||||
' rm -f "$WRAPPER_PROPERTIES_TMP"' \
|
|
||||||
' if [[ -d /root/.gradle/wrapper/dists ]]; then' \
|
|
||||||
' find /root/.gradle/wrapper/dists \( -name "*.lck" -o -name "*.part" \) -print0 | xargs -0 -r rm -f' \
|
|
||||||
' fi' \
|
|
||||||
'fi' \
|
|
||||||
'' \
|
|
||||||
'ensure_keystore' \
|
|
||||||
'' \
|
|
||||||
'case "$ARCH" in' \
|
|
||||||
'arm64)' \
|
|
||||||
' ANDROID_ABIS="arm64-v8a"' \
|
|
||||||
' GRADLE_TASK=":app:assembleArm64Release"' \
|
|
||||||
' APK_FLAVORS="arm64"' \
|
|
||||||
' ;;' \
|
|
||||||
'armv7)' \
|
|
||||||
' ANDROID_ABIS="armeabi-v7a"' \
|
|
||||||
' GRADLE_TASK=":app:assembleArm32Release"' \
|
|
||||||
' APK_FLAVORS="arm32"' \
|
|
||||||
' ;;' \
|
|
||||||
'all)' \
|
|
||||||
' ANDROID_ABIS="arm64-v8a,armeabi-v7a"' \
|
|
||||||
' GRADLE_TASK=":app:assembleRelease"' \
|
|
||||||
' APK_FLAVORS="arm64 arm32"' \
|
|
||||||
' ;;' \
|
|
||||||
'*) fail "Unsupported architecture: $ARCH (expected arm64, armv7, or all)" ;;' \
|
|
||||||
'esac' \
|
|
||||||
'' \
|
|
||||||
'printf "sdk.dir=%s\n" "$ANDROID_HOME" > "$ANDROID_DIR/local.properties"' \
|
|
||||||
'mkdir -p "$OUTPUT_DIR"' \
|
|
||||||
'PROJECT_VERSION="$(read_project_version)"' \
|
|
||||||
'' \
|
|
||||||
'export ONE_KVM_ANDROID_PROFILE="$BUILD_TYPE"' \
|
|
||||||
'export ONE_KVM_ANDROID_ABIS="$ANDROID_ABIS"' \
|
|
||||||
'export ONE_KVM_ANDROID_FFMPEG_ROOT="$FFMPEG_ROOT"' \
|
|
||||||
'export ANDROID_HOME' \
|
|
||||||
'export ANDROID_SDK_ROOT' \
|
|
||||||
'export ANDROID_NDK_HOME' \
|
|
||||||
'export ANDROID_NDK_ROOT' \
|
|
||||||
'' \
|
|
||||||
'echo "Building Android APK"' \
|
|
||||||
'echo " task: $GRADLE_TASK"' \
|
|
||||||
'echo " profile: $ONE_KVM_ANDROID_PROFILE"' \
|
|
||||||
'echo " version: $PROJECT_VERSION"' \
|
|
||||||
'echo " abis: $ONE_KVM_ANDROID_ABIS"' \
|
|
||||||
'echo " output: $OUTPUT_DIR"' \
|
|
||||||
'echo " sdk: $ANDROID_HOME"' \
|
|
||||||
'echo " ndk: $ANDROID_NDK_HOME"' \
|
|
||||||
'echo " build tools: $ANDROID_BUILD_TOOLS_DIR"' \
|
|
||||||
'echo " ffmpeg root: $ONE_KVM_ANDROID_FFMPEG_ROOT"' \
|
|
||||||
'if [[ -n "$GRADLE_DISTRIBUTION_URL" ]]; then' \
|
|
||||||
' echo " gradle distribution: $GRADLE_DISTRIBUTION_URL"' \
|
|
||||||
'fi' \
|
|
||||||
'' \
|
|
||||||
'(' \
|
|
||||||
' cd "$ANDROID_DIR"' \
|
|
||||||
' ./gradlew "$GRADLE_TASK"' \
|
|
||||||
')' \
|
|
||||||
'' \
|
|
||||||
'for flavor in $APK_FLAVORS; do' \
|
|
||||||
' copy_apks "$flavor"' \
|
|
||||||
'done' \
|
|
||||||
'' \
|
|
||||||
'echo' \
|
|
||||||
'echo "APK output:"' \
|
|
||||||
'ls -1 "$OUTPUT_DIR"' \
|
|
||||||
> /usr/local/bin/build-one-kvm-android \
|
|
||||||
&& chmod +x /usr/local/bin/build-one-kvm-android
|
|
||||||
|
|
||||||
WORKDIR /workspace
|
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/local/bin/build-one-kvm-android"]
|
|
||||||
CMD ["all"]
|
|
||||||
@@ -15,6 +15,8 @@ ARG LIBYUV_REV=957f295ea946cbbd13fcfc46e7066f2efa801233
|
|||||||
ARG LIBVPX_VERSION=1.16.0
|
ARG LIBVPX_VERSION=1.16.0
|
||||||
ARG X265_VERSION=3.4
|
ARG X265_VERSION=3.4
|
||||||
ARG OPUS_VERSION=1.5.2
|
ARG OPUS_VERSION=1.5.2
|
||||||
|
ARG RKMPP_BRANCH=jellyfin-mpp
|
||||||
|
ARG RKRGA_BRANCH=jellyfin-rga
|
||||||
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
|
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
|
||||||
|
|
||||||
# Optionally use China mirrors for builds in China.
|
# Optionally use China mirrors for builds in China.
|
||||||
@@ -252,8 +254,8 @@ RUN github_prefix="" \
|
|||||||
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
|
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
|
||||||
&& github_prefix="" \
|
&& github_prefix="" \
|
||||||
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
|
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
|
||||||
&& git clone --depth 1 "https://gitee.com/nyanmisaka/mpp.git" rkmpp \
|
&& git clone --depth 1 --branch ${RKMPP_BRANCH} "${github_prefix}https://github.com/nyanmisaka/mpp.git" rkmpp \
|
||||||
&& git clone --depth 1 "https://gitee.com/nyanmisaka/rga.git" rkrga \
|
&& git clone --depth 1 --branch ${RKRGA_BRANCH} "${github_prefix}https://github.com/nyanmisaka/rk-mirrors.git" rkrga \
|
||||||
&& git init ffmpeg-rockchip \
|
&& git init ffmpeg-rockchip \
|
||||||
&& cd ffmpeg-rockchip \
|
&& cd ffmpeg-rockchip \
|
||||||
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
|
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ ARG LIBYUV_REV=957f295ea946cbbd13fcfc46e7066f2efa801233
|
|||||||
ARG LIBVPX_VERSION=1.16.0
|
ARG LIBVPX_VERSION=1.16.0
|
||||||
ARG X265_VERSION=3.4
|
ARG X265_VERSION=3.4
|
||||||
ARG OPUS_VERSION=1.5.2
|
ARG OPUS_VERSION=1.5.2
|
||||||
|
ARG RKMPP_BRANCH=jellyfin-mpp
|
||||||
|
ARG RKRGA_BRANCH=jellyfin-rga
|
||||||
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
|
ARG FFMPEG_ROCKCHIP_REV=40c412daccf08164493da0de990eb99a8948116b
|
||||||
|
|
||||||
# Optionally use China mirrors for builds in China.
|
# Optionally use China mirrors for builds in China.
|
||||||
@@ -241,8 +243,8 @@ RUN github_prefix="" \
|
|||||||
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
|
RUN mkdir -p /tmp/ffmpeg-build && cd /tmp/ffmpeg-build \
|
||||||
&& github_prefix="" \
|
&& github_prefix="" \
|
||||||
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
|
&& if [ "$CHINAMIRRO" = "1" ]; then github_prefix="${GH_PROXY%/}/"; fi \
|
||||||
&& git clone --depth 1 "https://gitee.com/nyanmisaka/mpp.git" rkmpp \
|
&& git clone --depth 1 --branch ${RKMPP_BRANCH} "${github_prefix}https://github.com/nyanmisaka/mpp.git" rkmpp \
|
||||||
&& git clone --depth 1 "https://gitee.com/nyanmisaka/rga.git" rkrga \
|
&& git clone --depth 1 --branch ${RKRGA_BRANCH} "${github_prefix}https://github.com/nyanmisaka/rk-mirrors.git" rkrga \
|
||||||
&& git init ffmpeg-rockchip \
|
&& git init ffmpeg-rockchip \
|
||||||
&& cd ffmpeg-rockchip \
|
&& cd ffmpeg-rockchip \
|
||||||
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
|
&& git remote add origin "${github_prefix}https://github.com/nyanmisaka/ffmpeg-rockchip.git" \
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=One-KVM IP-KVM Service
|
Description=One-KVM IP-KVM Service
|
||||||
Documentation=https://github.com/mofeng-git/One-KVM
|
Documentation=https://github.com/mofeng-git/One-KVM
|
||||||
After=network.target
|
After=network-online.target
|
||||||
Wants=network-online.target
|
Wants=network-online.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
|
|||||||
2
libs/hwcodec/.gitignore
vendored
2
libs/hwcodec/.gitignore
vendored
@@ -8,8 +8,6 @@
|
|||||||
/ffmpeg/linux/debug
|
/ffmpeg/linux/debug
|
||||||
!/ffmpeg/mac
|
!/ffmpeg/mac
|
||||||
/ffmpeg/mac/debug
|
/ffmpeg/mac/debug
|
||||||
!/ffmpeg/android
|
|
||||||
/ffmpeg/android/debug
|
|
||||||
!/ffmpeg/ios
|
!/ffmpeg/ios
|
||||||
/ffmpeg/ios/debug
|
/ffmpeg/ios/debug
|
||||||
/input
|
/input
|
||||||
|
|||||||
@@ -21,4 +21,4 @@ serde_json = "1.0"
|
|||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
cc = "1.0"
|
cc = "1.0"
|
||||||
bindgen = "0.70.1"
|
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
|
* remove hevc_vaapi because of possible poor quality
|
||||||
* amf: not tested, https://github.com/GPUOpen-LibrariesAndSDKs/AMF/issues/378
|
* 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
|
## System requirements
|
||||||
|
|
||||||
* intel
|
* 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://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
|
https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new?ncid=em-prod-816193
|
||||||
|
|
||||||
|
|||||||
@@ -21,15 +21,11 @@ fn build_common(builder: &mut Build) {
|
|||||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||||
let common_dir = manifest_dir.join("cpp").join("common");
|
let common_dir = manifest_dir.join("cpp").join("common");
|
||||||
|
|
||||||
let mut bindings = bindgen::builder()
|
let bindings = bindgen::builder()
|
||||||
.header(common_dir.join("common.h").to_string_lossy().to_string())
|
.header(common_dir.join("common.h").to_string_lossy().to_string())
|
||||||
.header(common_dir.join("callback.h").to_string_lossy().to_string())
|
.header(common_dir.join("callback.h").to_string_lossy().to_string())
|
||||||
.rustified_enum(".*")
|
.rustified_enum(".*")
|
||||||
.parse_callbacks(Box::new(CommonCallbacks));
|
.parse_callbacks(Box::new(CommonCallbacks));
|
||||||
if target_os == "android" {
|
|
||||||
print_android_bindgen_env();
|
|
||||||
bindings = bindings.clang_args(android_clang_args());
|
|
||||||
}
|
|
||||||
bindings
|
bindings
|
||||||
.generate()
|
.generate()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -62,9 +58,9 @@ fn build_common(builder: &mut Build) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unsupported platforms
|
// Unsupported platforms
|
||||||
if target_os != "windows" && target_os != "linux" && target_os != "android" {
|
if target_os != "windows" && target_os != "linux" {
|
||||||
panic!(
|
panic!(
|
||||||
"Unsupported OS: {}. Only Windows, Linux, and Android are supported.",
|
"Unsupported OS: {}. Only Windows and Linux are supported.",
|
||||||
target_os
|
target_os
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -89,123 +85,12 @@ impl bindgen::callbacks::ParseCallbacks for CommonCallbacks {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_android_bindgen_env() {
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_NDK_ROOT");
|
|
||||||
println!("cargo:rerun-if-env-changed=NDK_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_SDK_ROOT");
|
|
||||||
println!("cargo:rerun-if-env-changed=CARGO_NDK_PLATFORM");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_clang_args() -> Vec<String> {
|
|
||||||
let ndk = android_ndk_home();
|
|
||||||
let target = env::var("TARGET").unwrap_or_default();
|
|
||||||
let toolchain = ndk.join("toolchains/llvm/prebuilt").join(host_tag());
|
|
||||||
let sysroot = toolchain.join("sysroot");
|
|
||||||
let clang_include = toolchain
|
|
||||||
.join("lib/clang")
|
|
||||||
.join(clang_version(&toolchain))
|
|
||||||
.join("include");
|
|
||||||
let api = env::var("CARGO_NDK_PLATFORM")
|
|
||||||
.ok()
|
|
||||||
.and_then(|value| value.parse::<u32>().ok())
|
|
||||||
.unwrap_or(21);
|
|
||||||
let clang_target = android_clang_target(&target);
|
|
||||||
|
|
||||||
vec![
|
|
||||||
format!("--target={clang_target}"),
|
|
||||||
format!("--sysroot={}", sysroot.display()),
|
|
||||||
format!("-D__ANDROID_API__={api}"),
|
|
||||||
format!("-isystem{}", clang_include.display()),
|
|
||||||
format!("-isystem{}", sysroot.join("usr/include").display()),
|
|
||||||
format!(
|
|
||||||
"-isystem{}",
|
|
||||||
sysroot.join("usr/include").join(clang_target).display()
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_clang_target(target: &str) -> &'static str {
|
|
||||||
match target {
|
|
||||||
"aarch64-linux-android" => "aarch64-linux-android",
|
|
||||||
"armv7-linux-androideabi" => "armv7a-linux-androideabi",
|
|
||||||
"i686-linux-android" => "i686-linux-android",
|
|
||||||
"x86_64-linux-android" => "x86_64-linux-android",
|
|
||||||
other => panic!("unsupported Android target for hwcodec bindgen: {other}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_ndk_home() -> PathBuf {
|
|
||||||
for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
return PathBuf::from(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
let ndk_dir = PathBuf::from(value).join("ndk");
|
|
||||||
if let Some(newest) = newest_child_dir(&ndk_dir) {
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!(
|
|
||||||
"hwcodec Android bindgen requires ANDROID_NDK_HOME, ANDROID_NDK_ROOT, NDK_HOME, \
|
|
||||||
or ANDROID_HOME/ANDROID_SDK_ROOT with an ndk directory"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn newest_child_dir(path: &Path) -> Option<PathBuf> {
|
|
||||||
let mut entries = std::fs::read_dir(path)
|
|
||||||
.ok()?
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.filter(|path| path.is_dir())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries.pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn host_tag() -> &'static str {
|
|
||||||
if cfg!(target_os = "linux") {
|
|
||||||
"linux-x86_64"
|
|
||||||
} else if cfg!(target_os = "macos") {
|
|
||||||
"darwin-x86_64"
|
|
||||||
} else if cfg!(target_os = "windows") {
|
|
||||||
"windows-x86_64"
|
|
||||||
} else {
|
|
||||||
panic!("unsupported host OS for Android NDK");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clang_version(toolchain: &Path) -> String {
|
|
||||||
let clang_dir = toolchain.join("lib/clang");
|
|
||||||
let mut entries = std::fs::read_dir(&clang_dir)
|
|
||||||
.unwrap_or_else(|_| panic!("missing NDK clang directory: {}", clang_dir.display()))
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries
|
|
||||||
.pop()
|
|
||||||
.unwrap_or_else(|| panic!("no clang versions found under: {}", clang_dir.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
mod ffmpeg {
|
mod ffmpeg {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
pub fn build_ffmpeg(builder: &mut Build) {
|
pub fn build_ffmpeg(builder: &mut Build) {
|
||||||
ffmpeg_ffi();
|
ffmpeg_ffi();
|
||||||
|
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
|
|
||||||
link_android_ffmpeg(builder);
|
|
||||||
build_ffmpeg_ram(builder);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try VCPKG first, fallback to system FFmpeg via pkg-config
|
// Try VCPKG first, fallback to system FFmpeg via pkg-config
|
||||||
if let Some(vcpkg_installed) = vcpkg_installed_root() {
|
if let Some(vcpkg_installed) = vcpkg_installed_root() {
|
||||||
link_vcpkg(builder, vcpkg_installed);
|
link_vcpkg(builder, vcpkg_installed);
|
||||||
@@ -220,67 +105,6 @@ mod ffmpeg {
|
|||||||
build_ffmpeg_capture(builder);
|
build_ffmpeg_capture(builder);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn link_android_ffmpeg(builder: &mut Build) {
|
|
||||||
let root = std::env::var("ONE_KVM_ANDROID_FFMPEG_ROOT").unwrap_or_else(|_| {
|
|
||||||
panic!(
|
|
||||||
"ONE_KVM_ANDROID_FFMPEG_ROOT is required when building hwcodec for Android. \
|
|
||||||
It must point to an FFmpeg Android build with MediaCodec enabled."
|
|
||||||
)
|
|
||||||
});
|
|
||||||
let root = PathBuf::from(root);
|
|
||||||
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
|
||||||
let abi = match target_arch.as_str() {
|
|
||||||
"aarch64" => "arm64-v8a",
|
|
||||||
"arm" => "armeabi-v7a",
|
|
||||||
"x86" => "x86",
|
|
||||||
"x86_64" => "x86_64",
|
|
||||||
_ => target_arch.as_str(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let abi_root = root.join(abi);
|
|
||||||
let lib_dir = if abi_root.join("lib").exists() {
|
|
||||||
abi_root.join("lib")
|
|
||||||
} else {
|
|
||||||
root.join("lib")
|
|
||||||
};
|
|
||||||
let include_dir = if abi_root.join("include").exists() {
|
|
||||||
abi_root.join("include")
|
|
||||||
} else {
|
|
||||||
root.join("include")
|
|
||||||
};
|
|
||||||
|
|
||||||
if !include_dir.exists() || !lib_dir.exists() {
|
|
||||||
panic!(
|
|
||||||
"Invalid ONE_KVM_ANDROID_FFMPEG_ROOT: include/lib not found for ABI {} under {}",
|
|
||||||
abi,
|
|
||||||
root.display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("cargo:rustc-link-search=native={}", lib_dir.display());
|
|
||||||
builder.include(&include_dir);
|
|
||||||
|
|
||||||
let use_static = std::env::var("ONE_KVM_ANDROID_FFMPEG_STATIC")
|
|
||||||
.map(|value| value != "0")
|
|
||||||
.unwrap_or(true);
|
|
||||||
for lib in ["avcodec", "avutil"] {
|
|
||||||
if use_static {
|
|
||||||
println!("cargo:rustc-link-lib=static={}", lib);
|
|
||||||
} else {
|
|
||||||
println!("cargo:rustc-link-lib={}", lib);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("cargo:rustc-link-lib=log");
|
|
||||||
println!("cargo:rustc-link-lib=mediandk");
|
|
||||||
println!("cargo:rustc-link-lib=android");
|
|
||||||
println!("cargo:rustc-link-lib=dl");
|
|
||||||
println!("cargo:rustc-link-lib=m");
|
|
||||||
println!("cargo:rustc-link-lib=z");
|
|
||||||
println!("cargo:rustc-link-lib=c++_shared");
|
|
||||||
println!("cargo:info=Using Android FFmpeg from {}", root.display());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn vcpkg_installed_root() -> Option<PathBuf> {
|
fn vcpkg_installed_root() -> Option<PathBuf> {
|
||||||
println!("cargo:rerun-if-env-changed=VCPKG_INSTALLED_DIR");
|
println!("cargo:rerun-if-env-changed=VCPKG_INSTALLED_DIR");
|
||||||
println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
|
println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
|
||||||
@@ -530,11 +354,9 @@ mod ffmpeg {
|
|||||||
}
|
}
|
||||||
// ARM (aarch64, arm): no X11 needed, uses RKMPP/V4L2
|
// ARM (aarch64, arm): no X11 needed, uses RKMPP/V4L2
|
||||||
v
|
v
|
||||||
} else if target_os == "android" {
|
|
||||||
Vec::new()
|
|
||||||
} else {
|
} else {
|
||||||
panic!(
|
panic!(
|
||||||
"Unsupported OS: {}. Only Windows, Linux, and Android are supported.",
|
"Unsupported OS: {}. Only Windows and Linux are supported.",
|
||||||
target_os
|
target_os
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -550,13 +372,7 @@ mod ffmpeg {
|
|||||||
let ffi_header_path = ffmpeg_ram_dir.join("ffmpeg_ffi.h");
|
let ffi_header_path = ffmpeg_ram_dir.join("ffmpeg_ffi.h");
|
||||||
println!("cargo:rerun-if-changed={}", ffi_header_path.display());
|
println!("cargo:rerun-if-changed={}", ffi_header_path.display());
|
||||||
let ffi_header = ffi_header_path.to_string_lossy().to_string();
|
let ffi_header = ffi_header_path.to_string_lossy().to_string();
|
||||||
let mut bindings = bindgen::builder()
|
let bindings = bindgen::builder().header(ffi_header).rustified_enum(".*");
|
||||||
.header(ffi_header)
|
|
||||||
.rustified_enum(".*");
|
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
|
|
||||||
print_android_bindgen_env();
|
|
||||||
bindings = bindings.clang_args(android_clang_args());
|
|
||||||
}
|
|
||||||
bindings
|
bindings
|
||||||
.generate()
|
.generate()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -571,13 +387,7 @@ mod ffmpeg {
|
|||||||
.join("ffmpeg_ram_ffi.h")
|
.join("ffmpeg_ram_ffi.h")
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.to_string();
|
.to_string();
|
||||||
let mut bindings = bindgen::builder()
|
let bindings = bindgen::builder().header(ffi_header).rustified_enum(".*");
|
||||||
.header(ffi_header)
|
|
||||||
.rustified_enum(".*");
|
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
|
|
||||||
print_android_bindgen_env();
|
|
||||||
bindings = bindings.clang_args(android_clang_args());
|
|
||||||
}
|
|
||||||
bindings
|
bindings
|
||||||
.generate()
|
.generate()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -589,12 +399,13 @@ mod ffmpeg {
|
|||||||
// RKMPP decode only exists on ARM builds where FFmpeg is compiled with RKMPP support.
|
// RKMPP decode only exists on ARM builds where FFmpeg is compiled with RKMPP support.
|
||||||
// Avoid compiling this file on x86/x64 where `AV_HWDEVICE_TYPE_RKMPP` doesn't exist.
|
// Avoid compiling this file on x86/x64 where `AV_HWDEVICE_TYPE_RKMPP` doesn't exist.
|
||||||
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
||||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
let enable_rkmpp = matches!(target_arch.as_str(), "aarch64" | "arm")
|
||||||
let enable_rkmpp = target_os != "android"
|
|
||||||
&& matches!(target_arch.as_str(), "aarch64" | "arm")
|
|
||||||
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
|
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
|
||||||
if enable_rkmpp {
|
if enable_rkmpp {
|
||||||
builder.file(ffmpeg_ram_dir.join("ffmpeg_ram_decode.cpp"));
|
builder.file(ffmpeg_ram_dir.join("ffmpeg_ram_decode.cpp"));
|
||||||
|
if enable_rkmpp {
|
||||||
|
builder.define("ONE_KVM_FFMPEG_RKMPP", None);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
println!(
|
println!(
|
||||||
"cargo:info=Skipping ffmpeg_ram_decode.cpp (RKMPP) for arch {}",
|
"cargo:info=Skipping ffmpeg_ram_decode.cpp (RKMPP) for arch {}",
|
||||||
@@ -647,9 +458,7 @@ mod ffmpeg {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
||||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
let enable_rkmpp = matches!(target_arch.as_str(), "aarch64" | "arm")
|
||||||
let enable_rkmpp = target_os != "android"
|
|
||||||
&& matches!(target_arch.as_str(), "aarch64" | "arm")
|
|
||||||
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
|
|| std::env::var_os("CARGO_FEATURE_RKMPP").is_some();
|
||||||
if enable_rkmpp {
|
if enable_rkmpp {
|
||||||
// Include RGA headers for NV16->NV12 conversion (RGA im2d API)
|
// Include RGA headers for NV16->NV12 conversion (RGA im2d API)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ bool is_software_h264(const std::string &name) {
|
|||||||
// Exclude all hardware encoders
|
// Exclude all hardware encoders
|
||||||
static const char* hw_suffixes[] = {
|
static const char* hw_suffixes[] = {
|
||||||
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
|
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
|
||||||
"v4l2m2m", "videotoolbox", "mediacodec", "_mf"
|
"v4l2m2m", "videotoolbox", "_mf"
|
||||||
};
|
};
|
||||||
for (const auto& suffix : hw_suffixes) {
|
for (const auto& suffix : hw_suffixes) {
|
||||||
if (name.find(suffix) != std::string::npos) return false;
|
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;
|
if (name != "hevc" && name != "libx265") return false;
|
||||||
static const char* hw_suffixes[] = {
|
static const char* hw_suffixes[] = {
|
||||||
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
|
"nvenc", "amf", "qsv", "vaapi", "rkmpp",
|
||||||
"v4l2m2m", "videotoolbox", "mediacodec", "_mf"
|
"v4l2m2m", "videotoolbox", "_mf"
|
||||||
};
|
};
|
||||||
for (const auto& suffix : hw_suffixes) {
|
for (const auto& suffix : hw_suffixes) {
|
||||||
if (name.find(suffix) != std::string::npos) return false;
|
if (name.find(suffix) != std::string::npos) return false;
|
||||||
@@ -100,13 +100,8 @@ void set_av_codec_ctx(AVCodecContext *c, const std::string &name, int kbs,
|
|||||||
c->color_primaries = AVCOL_PRI_SMPTE170M;
|
c->color_primaries = AVCOL_PRI_SMPTE170M;
|
||||||
c->color_trc = AVCOL_TRC_SMPTE170M;
|
c->color_trc = AVCOL_TRC_SMPTE170M;
|
||||||
|
|
||||||
// WebRTC SDP advertises constrained baseline. Keep most hardware and software
|
// WebRTC SDP advertises constrained baseline. Keep hardware and software
|
||||||
// encoders on the same browser-friendly H264 profile. Android MediaCodec is
|
// encoders on the same browser-friendly H264 profile.
|
||||||
// deliberately excluded because older vendor OMX encoders can reject explicit
|
|
||||||
// profile/level combinations during configure().
|
|
||||||
if (name.find("mediacodec") != std::string::npos) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (name.find("h264") != std::string::npos) {
|
if (name.find("h264") != std::string::npos) {
|
||||||
c->profile = AV_PROFILE_H264_CONSTRAINED_BASELINE;
|
c->profile = AV_PROFILE_H264_CONSTRAINED_BASELINE;
|
||||||
} else if (name.find("hevc") != std::string::npos) {
|
} else if (name.find("hevc") != std::string::npos) {
|
||||||
@@ -310,9 +305,6 @@ bool set_quality(void *priv_data, const std::string &name, int quality) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Do not force MediaCodec level here. Some Android TV vendor encoders,
|
|
||||||
// including older Amlogic OMX implementations, reject explicit level values
|
|
||||||
// even when they support the requested resolution and bitrate.
|
|
||||||
// libx264 software encoder presets
|
// libx264 software encoder presets
|
||||||
if (is_software_h264(name)) {
|
if (is_software_h264(name)) {
|
||||||
const char* preset = nullptr;
|
const char* preset = nullptr;
|
||||||
@@ -368,6 +360,25 @@ struct CodecOptions {
|
|||||||
|
|
||||||
bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
|
bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
|
||||||
int q) {
|
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) {
|
if (name.find("qsv") != std::string::npos) {
|
||||||
// https://github.com/LizardByte/Sunshine/blob/3e47cd3cc8fd37a7a88be82444ff4f3c0022856b/src/video.cpp#L1635
|
// https://github.com/LizardByte/Sunshine/blob/3e47cd3cc8fd37a7a88be82444ff4f3c0022856b/src/video.cpp#L1635
|
||||||
c->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
|
c->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
|
||||||
@@ -375,9 +386,6 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
|
|||||||
std::vector<CodecOptions> codecs = {
|
std::vector<CodecOptions> codecs = {
|
||||||
{"nvenc", "rc", {{RC_CBR, "cbr"}, {RC_VBR, "vbr"}}},
|
{"nvenc", "rc", {{RC_CBR, "cbr"}, {RC_VBR, "vbr"}}},
|
||||||
{"amf", "rc", {{RC_CBR, "cbr"}, {RC_VBR, "vbr_latency"}}},
|
{"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"}}},
|
// {"videotoolbox", "constant_bit_rate", {{RC_CBR, "1"}}},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -392,13 +400,6 @@ bool set_rate_control(AVCodecContext *c, const std::string &name, int rc,
|
|||||||
it->second + " failed, ret = " + av_err2str(ret));
|
it->second + " failed, ret = " + av_err2str(ret));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (name.find("mediacodec") != std::string::npos) {
|
|
||||||
if (rc == RC_CQ) {
|
|
||||||
if (q >= 0 && q <= 51) {
|
|
||||||
c->global_quality = q;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -448,13 +449,6 @@ bool set_others(void *priv_data, const std::string &name) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (name.find("mediacodec") != std::string::npos) {
|
|
||||||
if ((ret = av_opt_set_int(priv_data, "ndk_codec", 1, 0)) < 0) {
|
|
||||||
LOG_ERROR(std::string("mediacodec set ndk_codec failed, ret = ") +
|
|
||||||
av_err2str(ret));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// NOTE: Removed idr_interval = INT_MAX for VAAPI.
|
// NOTE: Removed idr_interval = INT_MAX for VAAPI.
|
||||||
// This was disabling automatic keyframe generation.
|
// This was disabling automatic keyframe generation.
|
||||||
// The encoder should respect c->gop_size for keyframe interval.
|
// The encoder should respect c->gop_size for keyframe interval.
|
||||||
|
|||||||
@@ -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" {
|
extern "C" {
|
||||||
#include <libavcodec/avcodec.h>
|
#include <libavcodec/avcodec.h>
|
||||||
@@ -54,9 +54,11 @@ public:
|
|||||||
thread_count_ = thread_count > 0 ? thread_count : 1;
|
thread_count_ = thread_count > 0 ? thread_count : 1;
|
||||||
callback_ = callback;
|
callback_ = callback;
|
||||||
|
|
||||||
|
#ifdef ONE_KVM_FFMPEG_RKMPP
|
||||||
if (name_.find("rkmpp") != std::string::npos) {
|
if (name_.find("rkmpp") != std::string::npos) {
|
||||||
hw_device_type_ = AV_HWDEVICE_TYPE_RKMPP;
|
hw_device_type_ = AV_HWDEVICE_TYPE_RKMPP;
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
~FFmpegRamDecoder() {}
|
~FFmpegRamDecoder() {}
|
||||||
@@ -137,13 +139,6 @@ public:
|
|||||||
av_buffer_unref(&frames_ref);
|
av_buffer_unref(&frames_ref);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name_.find("mediacodec") != std::string::npos && c_->priv_data) {
|
|
||||||
if ((ret = av_opt_set_int(c_->priv_data, "ndk_codec", 1, 0)) < 0) {
|
|
||||||
LOG_WARN(std::string("mediacodec decoder ndk_codec option failed, ret = ") +
|
|
||||||
av_err2str(ret));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((ret = avcodec_open2(c_, codec, NULL)) < 0) {
|
if ((ret = avcodec_open2(c_, codec, NULL)) < 0) {
|
||||||
set_last_error(std::string("avcodec_open2 failed, ret = ") + av_err2str(ret));
|
set_last_error(std::string("avcodec_open2 failed, ret = ") + av_err2str(ret));
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ extern "C" {
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
|
||||||
@@ -21,6 +22,13 @@ extern "C" {
|
|||||||
#include "win.h"
|
#include "win.h"
|
||||||
#endif
|
#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,
|
static int calculate_offset_length(int pix_fmt, int height, const int *linesize,
|
||||||
int *offset, int *length) {
|
int *offset, int *length) {
|
||||||
switch (pix_fmt) {
|
switch (pix_fmt) {
|
||||||
@@ -122,7 +130,6 @@ public:
|
|||||||
AVFrame *frame_ = NULL;
|
AVFrame *frame_ = NULL;
|
||||||
AVPacket *pkt_ = NULL;
|
AVPacket *pkt_ = NULL;
|
||||||
std::string name_;
|
std::string name_;
|
||||||
std::string mc_name_; // for mediacodec
|
|
||||||
|
|
||||||
int width_ = 0;
|
int width_ = 0;
|
||||||
int height_ = 0;
|
int height_ = 0;
|
||||||
@@ -145,14 +152,12 @@ public:
|
|||||||
AVPixelFormat hw_pixfmt_ = AV_PIX_FMT_NONE;
|
AVPixelFormat hw_pixfmt_ = AV_PIX_FMT_NONE;
|
||||||
AVBufferRef *hw_device_ctx_ = NULL;
|
AVBufferRef *hw_device_ctx_ = NULL;
|
||||||
AVFrame *hw_frame_ = NULL;
|
AVFrame *hw_frame_ = NULL;
|
||||||
AVFrame *borrowed_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 pixfmt, int align, int fps, int gop, int rc, int quality,
|
||||||
int kbs, int q, int thread_count, int gpu,
|
int kbs, int q, int thread_count, int gpu,
|
||||||
RamEncodeCallback callback) {
|
RamEncodeCallback callback) {
|
||||||
name_ = name;
|
name_ = name;
|
||||||
mc_name_ = mc_name ? mc_name : "";
|
|
||||||
width_ = width;
|
width_ = width;
|
||||||
height_ = height;
|
height_ = height;
|
||||||
pixfmt_ = (AVPixelFormat)pixfmt;
|
pixfmt_ = (AVPixelFormat)pixfmt;
|
||||||
@@ -184,12 +189,13 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool init(int *linesize, int *offset, int *length) {
|
bool init(int *linesize, int *offset, int *length) {
|
||||||
|
g_encoder_last_error.clear();
|
||||||
const AVCodec *codec = NULL;
|
const AVCodec *codec = NULL;
|
||||||
|
|
||||||
int ret;
|
int ret;
|
||||||
|
|
||||||
if (!(codec = avcodec_find_encoder_by_name(name_.c_str()))) {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,12 +258,6 @@ public:
|
|||||||
LOG_ERROR(std::string("Could not allocate video packet"));
|
LOG_ERROR(std::string("Could not allocate video packet"));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
borrowed_frame_ = av_frame_alloc();
|
|
||||||
if (!borrowed_frame_) {
|
|
||||||
LOG_ERROR(std::string("Could not allocate borrowed video frame"));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* resolution must be a multiple of two */
|
/* resolution must be a multiple of two */
|
||||||
c_->width = width_;
|
c_->width = width_;
|
||||||
c_->height = height_;
|
c_->height = height_;
|
||||||
@@ -273,23 +273,16 @@ public:
|
|||||||
LOG_ERROR(std::string("set_quality failed, name: ") + name_);
|
LOG_ERROR(std::string("set_quality failed, name: ") + name_);
|
||||||
return false;
|
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::set_gpu(c_->priv_data, name_, gpu_);
|
||||||
util_encode::force_hw(c_->priv_data, name_);
|
util_encode::force_hw(c_->priv_data, name_);
|
||||||
util_encode::set_others(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) {
|
if ((ret = avcodec_open2(c_, codec, NULL)) < 0) {
|
||||||
LOG_ERROR(std::string("avcodec_open2 failed, ret = ") + av_err2str(ret) +
|
set_encoder_last_error(std::string("avcodec_open2 failed, ret = ") +
|
||||||
", name: " + name_);
|
av_err2str(ret) + ", name: " + name_);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,14 +300,6 @@ public:
|
|||||||
int encode(const uint8_t *data, int length, const void *obj, uint64_t ms) {
|
int encode(const uint8_t *data, int length, const void *obj, uint64_t ms) {
|
||||||
int ret;
|
int ret;
|
||||||
|
|
||||||
if (can_borrow_input(length)) {
|
|
||||||
AVFrame *borrowed = wrap_borrowed_frame(data, length);
|
|
||||||
if (!borrowed) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return do_encode(borrowed, obj, ms);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((ret = av_frame_make_writable(frame_)) != 0) {
|
if ((ret = av_frame_make_writable(frame_)) != 0) {
|
||||||
LOG_ERROR(std::string("av_frame_make_writable failed, ret = ") + av_err2str(ret));
|
LOG_ERROR(std::string("av_frame_make_writable failed, ret = ") + av_err2str(ret));
|
||||||
return ret;
|
return ret;
|
||||||
@@ -350,8 +335,6 @@ public:
|
|||||||
av_frame_free(&frame_);
|
av_frame_free(&frame_);
|
||||||
if (hw_frame_)
|
if (hw_frame_)
|
||||||
av_frame_free(&hw_frame_);
|
av_frame_free(&hw_frame_);
|
||||||
if (borrowed_frame_)
|
|
||||||
av_frame_free(&borrowed_frame_);
|
|
||||||
if (hw_device_ctx_)
|
if (hw_device_ctx_)
|
||||||
av_buffer_unref(&hw_device_ctx_);
|
av_buffer_unref(&hw_device_ctx_);
|
||||||
if (c_)
|
if (c_)
|
||||||
@@ -610,65 +593,6 @@ private:
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool can_borrow_input(int data_length) const {
|
|
||||||
if (hw_device_type_ != AV_HWDEVICE_TYPE_NONE) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (name_.find("mediacodec") == std::string::npos) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
switch (pixfmt_) {
|
|
||||||
case AV_PIX_FMT_NV12:
|
|
||||||
case AV_PIX_FMT_NV21:
|
|
||||||
return data_length >= width_ * height_ * 3 / 2;
|
|
||||||
case AV_PIX_FMT_YUV420P:
|
|
||||||
return data_length >= width_ * height_ * 3 / 2;
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
AVFrame *wrap_borrowed_frame(const uint8_t *data, int data_length) {
|
|
||||||
if (!borrowed_frame_) {
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
av_frame_unref(borrowed_frame_);
|
|
||||||
borrowed_frame_->format = pixfmt_;
|
|
||||||
borrowed_frame_->width = width_;
|
|
||||||
borrowed_frame_->height = height_;
|
|
||||||
|
|
||||||
const int y_size = width_ * height_;
|
|
||||||
const int uv_size = y_size / 4;
|
|
||||||
switch (pixfmt_) {
|
|
||||||
case AV_PIX_FMT_NV12:
|
|
||||||
case AV_PIX_FMT_NV21:
|
|
||||||
if (data_length < y_size + y_size / 2) {
|
|
||||||
LOG_ERROR("wrap_borrowed_frame: NV12/NV21 data length error");
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
borrowed_frame_->data[0] = const_cast<uint8_t *>(data);
|
|
||||||
borrowed_frame_->data[1] = const_cast<uint8_t *>(data + y_size);
|
|
||||||
borrowed_frame_->linesize[0] = width_;
|
|
||||||
borrowed_frame_->linesize[1] = width_;
|
|
||||||
break;
|
|
||||||
case AV_PIX_FMT_YUV420P:
|
|
||||||
if (data_length < y_size + uv_size * 2) {
|
|
||||||
LOG_ERROR("wrap_borrowed_frame: YUV420P data length error");
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
borrowed_frame_->data[0] = const_cast<uint8_t *>(data);
|
|
||||||
borrowed_frame_->data[1] = const_cast<uint8_t *>(data + y_size);
|
|
||||||
borrowed_frame_->data[2] = const_cast<uint8_t *>(data + y_size + uv_size);
|
|
||||||
borrowed_frame_->linesize[0] = width_;
|
|
||||||
borrowed_frame_->linesize[1] = width_ / 2;
|
|
||||||
borrowed_frame_->linesize[2] = width_ / 2;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
return borrowed_frame_;
|
|
||||||
}
|
|
||||||
|
|
||||||
int bytes_per_pixel(int pix_fmt) {
|
int bytes_per_pixel(int pix_fmt) {
|
||||||
switch (pix_fmt) {
|
switch (pix_fmt) {
|
||||||
case AV_PIX_FMT_YUYV422:
|
case AV_PIX_FMT_YUYV422:
|
||||||
@@ -687,18 +611,45 @@ private:
|
|||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
extern "C" FFmpegRamEncoder *
|
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 height, int pixfmt, int align, int fps, int gop,
|
||||||
int rc, int quality, int kbs, int q, int thread_count,
|
int rc, int quality, int kbs, int q, int thread_count,
|
||||||
int gpu, int *linesize, int *offset, int *length,
|
int gpu, int *linesize, int *offset, int *length,
|
||||||
RamEncodeCallback callback) {
|
RamEncodeCallback callback) {
|
||||||
FFmpegRamEncoder *encoder = NULL;
|
FFmpegRamEncoder *encoder = NULL;
|
||||||
try {
|
try {
|
||||||
encoder = new FFmpegRamEncoder(name, mc_name, width, height, pixfmt, align,
|
auto try_create = [&](int attempt_rc, int attempt_kbs) {
|
||||||
fps, gop, rc, quality, kbs, q, thread_count,
|
FFmpegRamEncoder *candidate = new FFmpegRamEncoder(
|
||||||
gpu, callback);
|
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) {
|
||||||
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;
|
return encoder;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -772,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()));
|
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();
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ typedef void (*RamEncodePacketCallback)(void *packet, const uint8_t *data,
|
|||||||
typedef void (*RamDecodeCallback)(const uint8_t *data, int len, int width,
|
typedef void (*RamDecodeCallback)(const uint8_t *data, int len, int width,
|
||||||
int height, int pixfmt, const void *obj);
|
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 height, int pixfmt, int align, int fps,
|
||||||
int gop, int rc, int quality, int kbs, int q,
|
int gop, int rc, int quality, int kbs, int q,
|
||||||
int thread_count, int gpu, int *linesize,
|
int thread_count, int gpu, int *linesize,
|
||||||
@@ -31,6 +31,7 @@ int ffmpeg_ram_get_linesize_offset_length(int pix_fmt, int width, int height,
|
|||||||
int *length);
|
int *length);
|
||||||
int ffmpeg_ram_set_bitrate(void *encoder, int kbs);
|
int ffmpeg_ram_set_bitrate(void *encoder, int kbs);
|
||||||
void ffmpeg_ram_request_keyframe(void *encoder);
|
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,
|
void *ffmpeg_ram_new_decoder(const char *name, int width, int height,
|
||||||
int sw_pixfmt, int thread_count,
|
int sw_pixfmt, int thread_count,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ pub enum Driver {
|
|||||||
FFMPEG,
|
FFMPEG,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
|
#[cfg(any(windows, target_os = "linux"))]
|
||||||
pub(crate) fn supported_gpu(_encode: bool) -> (bool, bool, bool) {
|
pub(crate) fn supported_gpu(_encode: bool) -> (bool, bool, bool) {
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use std::ffi::c_int;
|
use std::ffi::c_int;
|
||||||
@@ -39,8 +39,6 @@ pub(crate) fn supported_gpu(_encode: bool) -> (bool, bool, bool) {
|
|||||||
linux_support_amd() == 0,
|
linux_support_amd() == 0,
|
||||||
linux_support_intel() == 0,
|
linux_support_intel() == 0,
|
||||||
);
|
);
|
||||||
#[cfg(target_os = "android")]
|
|
||||||
return (false, false, false);
|
|
||||||
#[allow(unreachable_code)]
|
#[allow(unreachable_code)]
|
||||||
(false, false, false)
|
(false, false, false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ impl Drop for Decoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn last_error_message() -> String {
|
pub fn last_error_message() -> String {
|
||||||
unsafe {
|
unsafe {
|
||||||
let ptr = ffmpeg_ram_last_error();
|
let ptr = ffmpeg_ram_last_error();
|
||||||
if ptr.is_null() {
|
if ptr.is_null() {
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
|
#[cfg(feature = "bytes")]
|
||||||
|
use crate::ffmpeg_ram::{ffmpeg_ram_encode_packet, ffmpeg_ram_free_packet};
|
||||||
use crate::{
|
use crate::{
|
||||||
common::DataFormat::{self, *},
|
common::DataFormat::{self, *},
|
||||||
ffmpeg::{init_av_log, AVPixelFormat},
|
ffmpeg::{init_av_log, AVPixelFormat},
|
||||||
ffmpeg_ram::{
|
ffmpeg_ram::{
|
||||||
ffmpeg_linesize_offset_length, ffmpeg_ram_encode, ffmpeg_ram_encode_packet,
|
ffmpeg_linesize_offset_length, ffmpeg_ram_encode, ffmpeg_ram_encoder_last_error,
|
||||||
ffmpeg_ram_free_encoder, ffmpeg_ram_free_packet, ffmpeg_ram_new_encoder,
|
ffmpeg_ram_free_encoder, ffmpeg_ram_new_encoder, ffmpeg_ram_request_keyframe,
|
||||||
ffmpeg_ram_request_keyframe, ffmpeg_ram_set_bitrate, CodecInfo, AV_NUM_DATA_POINTERS,
|
ffmpeg_ram_set_bitrate, CodecInfo, AV_NUM_DATA_POINTERS,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
#[cfg(feature = "bytes")]
|
#[cfg(feature = "bytes")]
|
||||||
@@ -17,7 +19,7 @@ use std::{
|
|||||||
slice,
|
slice,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
|
#[cfg(any(windows, target_os = "linux"))]
|
||||||
use crate::common::Driver;
|
use crate::common::Driver;
|
||||||
|
|
||||||
/// Timeout for encoder test in milliseconds
|
/// Timeout for encoder test in milliseconds
|
||||||
@@ -28,7 +30,6 @@ const PRIORITY_AMF: i32 = 2;
|
|||||||
const PRIORITY_RKMPP: i32 = 3;
|
const PRIORITY_RKMPP: i32 = 3;
|
||||||
const PRIORITY_VAAPI: i32 = 4;
|
const PRIORITY_VAAPI: i32 = 4;
|
||||||
const PRIORITY_V4L2M2M: i32 = 5;
|
const PRIORITY_V4L2M2M: i32 = 5;
|
||||||
const PRIORITY_MEDIACODEC: i32 = 2;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
struct CandidateCodecSpec {
|
struct CandidateCodecSpec {
|
||||||
@@ -95,32 +96,12 @@ fn linux_support_v4l2m2m() -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
|
#[cfg(any(windows, target_os = "linux"))]
|
||||||
fn enumerate_candidate_codecs(ctx: &EncodeContext) -> Vec<CodecInfo> {
|
fn enumerate_candidate_codecs(ctx: &EncodeContext) -> Vec<CodecInfo> {
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
let mut codecs = Vec::new();
|
let mut codecs = Vec::new();
|
||||||
|
|
||||||
if cfg!(target_os = "android") {
|
|
||||||
push_candidate(
|
|
||||||
&mut codecs,
|
|
||||||
CandidateCodecSpec {
|
|
||||||
name: "h264_mediacodec",
|
|
||||||
format: H264,
|
|
||||||
priority: PRIORITY_MEDIACODEC,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
push_candidate(
|
|
||||||
&mut codecs,
|
|
||||||
CandidateCodecSpec {
|
|
||||||
name: "hevc_mediacodec",
|
|
||||||
format: H265,
|
|
||||||
priority: PRIORITY_MEDIACODEC,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return codecs;
|
|
||||||
}
|
|
||||||
|
|
||||||
let contains = |_vendor: Driver, _format: DataFormat| {
|
let contains = |_vendor: Driver, _format: DataFormat| {
|
||||||
// Without VRAM feature, we can't check SDK availability.
|
// Without VRAM feature, we can't check SDK availability.
|
||||||
// Keep the prefilter coarse and let FFmpeg validation do the real check.
|
// Keep the prefilter coarse and let FFmpeg validation do the real check.
|
||||||
@@ -281,13 +262,7 @@ struct ProbePolicy {
|
|||||||
|
|
||||||
impl ProbePolicy {
|
impl ProbePolicy {
|
||||||
fn for_codec(codec_name: &str) -> Self {
|
fn for_codec(codec_name: &str) -> Self {
|
||||||
if codec_name.contains("mediacodec") {
|
if codec_name.contains("amf") {
|
||||||
Self {
|
|
||||||
max_attempts: 30,
|
|
||||||
request_keyframe: true,
|
|
||||||
accept_any_output: true,
|
|
||||||
}
|
|
||||||
} else if codec_name.contains("amf") {
|
|
||||||
Self {
|
Self {
|
||||||
max_attempts: 5,
|
max_attempts: 5,
|
||||||
request_keyframe: true,
|
request_keyframe: true,
|
||||||
@@ -340,7 +315,8 @@ fn log_failed_probe_attempt(
|
|||||||
if frames.is_empty() {
|
if frames.is_empty() {
|
||||||
trace!(
|
trace!(
|
||||||
"Encoder {} test produced no output on attempt {}",
|
"Encoder {} test produced no output on attempt {}",
|
||||||
codec_name, attempt
|
codec_name,
|
||||||
|
attempt
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
debug!(
|
debug!(
|
||||||
@@ -373,7 +349,6 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
|
|||||||
|
|
||||||
let test_ctx = EncodeContext {
|
let test_ctx = EncodeContext {
|
||||||
name: codec.name.clone(),
|
name: codec.name.clone(),
|
||||||
mc_name: codec.mc_name.clone(),
|
|
||||||
..ctx.clone()
|
..ctx.clone()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -418,13 +393,13 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
last_err = Some(err);
|
last_err = Some(err);
|
||||||
warn!(
|
warn!(
|
||||||
"Encoder {} test attempt {} returned error: {}",
|
"Encoder {} test attempt {} returned error: {}",
|
||||||
codec.name, attempt_no, err
|
codec.name, attempt_no, err
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -437,20 +412,16 @@ fn validate_candidate(codec: &CodecInfo, ctx: &EncodeContext, yuv: &[u8]) -> boo
|
|||||||
);
|
);
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
warn!("Failed to create encoder {}", codec.name);
|
warn!("Failed to create encoder {}", codec.name);
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_software_fallback(codecs: &mut Vec<CodecInfo>) {
|
fn add_software_fallback(codecs: &mut Vec<CodecInfo>) {
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
if cfg!(target_os = "android") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for fallback in CodecInfo::soft().into_vec() {
|
for fallback in CodecInfo::soft().into_vec() {
|
||||||
if !codecs.iter().any(|codec| codec.format == fallback.format) {
|
if !codecs.iter().any(|codec| codec.format == fallback.format) {
|
||||||
debug!(
|
debug!(
|
||||||
@@ -465,7 +436,6 @@ fn add_software_fallback(codecs: &mut Vec<CodecInfo>) {
|
|||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct EncodeContext {
|
pub struct EncodeContext {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub mc_name: Option<String>,
|
|
||||||
pub width: i32,
|
pub width: i32,
|
||||||
pub height: i32,
|
pub height: i32,
|
||||||
pub pixfmt: i32,
|
pub pixfmt: i32,
|
||||||
@@ -550,10 +520,8 @@ impl Encoder {
|
|||||||
.unwrap_or("-1".to_owned())
|
.unwrap_or("-1".to_owned())
|
||||||
.parse()
|
.parse()
|
||||||
.unwrap_or(-1);
|
.unwrap_or(-1);
|
||||||
let mc_name = ctx.mc_name.clone().unwrap_or_default();
|
|
||||||
let codec = ffmpeg_ram_new_encoder(
|
let codec = ffmpeg_ram_new_encoder(
|
||||||
CString::new(ctx.name.as_str()).map_err(|_| ())?.as_ptr(),
|
CString::new(ctx.name.as_str()).map_err(|_| ())?.as_ptr(),
|
||||||
CString::new(mc_name.as_str()).map_err(|_| ())?.as_ptr(),
|
|
||||||
ctx.width,
|
ctx.width,
|
||||||
ctx.height,
|
ctx.height,
|
||||||
ctx.pixfmt,
|
ctx.pixfmt,
|
||||||
@@ -573,6 +541,10 @@ impl Encoder {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if codec.is_null() {
|
if codec.is_null() {
|
||||||
|
let message = encoder_last_error_message();
|
||||||
|
if !message.is_empty() {
|
||||||
|
log::error!("ffmpeg_ram_new_encoder failed: {}", message);
|
||||||
|
}
|
||||||
return Err(());
|
return Err(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -698,11 +670,11 @@ impl Encoder {
|
|||||||
pub fn available_encoders(ctx: EncodeContext, _sdk: Option<String>) -> Vec<CodecInfo> {
|
pub fn available_encoders(ctx: EncodeContext, _sdk: Option<String>) -> Vec<CodecInfo> {
|
||||||
use log::debug;
|
use log::debug;
|
||||||
|
|
||||||
if !(cfg!(windows) || cfg!(target_os = "linux") || cfg!(target_os = "android")) {
|
if !(cfg!(windows) || cfg!(target_os = "linux")) {
|
||||||
return vec![];
|
return vec![];
|
||||||
}
|
}
|
||||||
let mut res = vec![];
|
let mut res = vec![];
|
||||||
#[cfg(any(windows, target_os = "linux", target_os = "android"))]
|
#[cfg(any(windows, target_os = "linux"))]
|
||||||
let codecs = enumerate_candidate_codecs(&ctx);
|
let codecs = enumerate_candidate_codecs(&ctx);
|
||||||
|
|
||||||
if let Ok(yuv) = Encoder::dummy_yuv(ctx.clone()) {
|
if let Ok(yuv) = Encoder::dummy_yuv(ctx.clone()) {
|
||||||
@@ -736,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 {
|
impl Drop for Encoder {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|||||||
@@ -9,18 +9,12 @@ use std::ffi::c_int;
|
|||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/ffmpeg_ram_ffi.rs"));
|
include!(concat!(env!("OUT_DIR"), "/ffmpeg_ram_ffi.rs"));
|
||||||
|
|
||||||
#[cfg(all(
|
#[cfg(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"))]
|
||||||
any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"),
|
|
||||||
not(target_os = "android")
|
|
||||||
))]
|
|
||||||
pub mod decode;
|
pub mod decode;
|
||||||
|
|
||||||
// Provide a small stub on non-ARM builds so dependents can still compile, but decoder
|
// Provide a small stub on non-ARM builds so dependents can still compile, but decoder
|
||||||
// construction will fail (since the C++ RKMPP decoder isn't built/linked).
|
// construction will fail (since the C++ RKMPP decoder isn't built/linked).
|
||||||
#[cfg(any(
|
#[cfg(not(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp")))]
|
||||||
not(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp")),
|
|
||||||
target_os = "android"
|
|
||||||
))]
|
|
||||||
pub mod decode {
|
pub mod decode {
|
||||||
use crate::ffmpeg::AVPixelFormat;
|
use crate::ffmpeg::AVPixelFormat;
|
||||||
|
|
||||||
@@ -69,8 +63,6 @@ pub enum Priority {
|
|||||||
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
|
||||||
pub struct CodecInfo {
|
pub struct CodecInfo {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
#[serde(skip)]
|
|
||||||
pub mc_name: Option<String>,
|
|
||||||
pub format: DataFormat,
|
pub format: DataFormat,
|
||||||
pub priority: i32,
|
pub priority: i32,
|
||||||
pub hwdevice: AVHWDeviceType,
|
pub hwdevice: AVHWDeviceType,
|
||||||
@@ -80,7 +72,6 @@ impl Default for CodecInfo {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
name: Default::default(),
|
name: Default::default(),
|
||||||
mc_name: Default::default(),
|
|
||||||
format: DataFormat::H264,
|
format: DataFormat::H264,
|
||||||
priority: Default::default(),
|
priority: Default::default(),
|
||||||
hwdevice: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
|
hwdevice: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
|
||||||
@@ -93,28 +84,24 @@ impl CodecInfo {
|
|||||||
match format {
|
match format {
|
||||||
H264 => Some(CodecInfo {
|
H264 => Some(CodecInfo {
|
||||||
name: "libx264".to_owned(),
|
name: "libx264".to_owned(),
|
||||||
mc_name: Default::default(),
|
|
||||||
format: H264,
|
format: H264,
|
||||||
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
||||||
priority: Priority::Soft as _,
|
priority: Priority::Soft as _,
|
||||||
}),
|
}),
|
||||||
H265 => Some(CodecInfo {
|
H265 => Some(CodecInfo {
|
||||||
name: "libx265".to_owned(),
|
name: "libx265".to_owned(),
|
||||||
mc_name: Default::default(),
|
|
||||||
format: H265,
|
format: H265,
|
||||||
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
||||||
priority: Priority::Soft as _,
|
priority: Priority::Soft as _,
|
||||||
}),
|
}),
|
||||||
VP8 => Some(CodecInfo {
|
VP8 => Some(CodecInfo {
|
||||||
name: "libvpx".to_owned(),
|
name: "libvpx".to_owned(),
|
||||||
mc_name: Default::default(),
|
|
||||||
format: VP8,
|
format: VP8,
|
||||||
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
||||||
priority: Priority::Soft as _,
|
priority: Priority::Soft as _,
|
||||||
}),
|
}),
|
||||||
VP9 => Some(CodecInfo {
|
VP9 => Some(CodecInfo {
|
||||||
name: "libvpx-vp9".to_owned(),
|
name: "libvpx-vp9".to_owned(),
|
||||||
mc_name: Default::default(),
|
|
||||||
format: VP9,
|
format: VP9,
|
||||||
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
hwdevice: AV_HWDEVICE_TYPE_NONE,
|
||||||
priority: Priority::Soft as _,
|
priority: Priority::Soft as _,
|
||||||
|
|||||||
@@ -2,10 +2,7 @@
|
|||||||
pub mod capture;
|
pub mod capture;
|
||||||
pub mod common;
|
pub mod common;
|
||||||
pub mod ffmpeg;
|
pub mod ffmpeg;
|
||||||
#[cfg(all(
|
#[cfg(any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"))]
|
||||||
any(target_arch = "aarch64", target_arch = "arm", feature = "rkmpp"),
|
|
||||||
not(target_os = "android")
|
|
||||||
))]
|
|
||||||
pub mod ffmpeg_hw;
|
pub mod ffmpeg_hw;
|
||||||
pub mod ffmpeg_ram;
|
pub mod ffmpeg_ram;
|
||||||
|
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
// This file is generated by cargo_embargo.
|
|
||||||
// Do not modify this file because the changes will be overridden on upgrade.
|
|
||||||
|
|
||||||
package {
|
|
||||||
default_applicable_licenses: ["external_rust_crates_v4l2r_license"],
|
|
||||||
}
|
|
||||||
|
|
||||||
rust_library {
|
|
||||||
name: "libv4l2r",
|
|
||||||
crate_name: "v4l2r",
|
|
||||||
cargo_env_compat: true,
|
|
||||||
cargo_pkg_version: "0.0.7",
|
|
||||||
crate_root: "src/lib.rs",
|
|
||||||
edition: "2021",
|
|
||||||
rustlibs: [
|
|
||||||
"libbitflags",
|
|
||||||
"liblog_rust",
|
|
||||||
"libnix",
|
|
||||||
"libthiserror",
|
|
||||||
],
|
|
||||||
proc_macros: ["libenumn"],
|
|
||||||
apex_available: [
|
|
||||||
"//apex_available:platform",
|
|
||||||
"//apex_available:anyapex",
|
|
||||||
],
|
|
||||||
product_available: true,
|
|
||||||
vendor_available: true,
|
|
||||||
// Bindgen-generated bindings of our local videodev2.h.
|
|
||||||
srcs: [":libv4l2r_bindgen"],
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
rust_test {
|
|
||||||
name: "v4l2r_test_src_lib",
|
|
||||||
crate_name: "v4l2r",
|
|
||||||
cargo_env_compat: true,
|
|
||||||
cargo_pkg_version: "0.0.7",
|
|
||||||
crate_root: "src/lib.rs",
|
|
||||||
test_suites: ["general-tests"],
|
|
||||||
auto_gen_config: true,
|
|
||||||
edition: "2021",
|
|
||||||
rustlibs: [
|
|
||||||
"libbitflags",
|
|
||||||
"liblog_rust",
|
|
||||||
"libnix",
|
|
||||||
"libthiserror",
|
|
||||||
],
|
|
||||||
proc_macros: ["libenumn"],
|
|
||||||
// Bindgen-generated bindings of our local videodev2.h.
|
|
||||||
srcs: [":libv4l2r_bindgen"],
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -49,7 +49,7 @@ version = "0.1.6"
|
|||||||
version = "0.4.14"
|
version = "0.4.14"
|
||||||
|
|
||||||
[dependencies.nix]
|
[dependencies.nix]
|
||||||
version = "0.28"
|
version = "0.31"
|
||||||
features = [
|
features = [
|
||||||
"ioctl",
|
"ioctl",
|
||||||
"mman",
|
"mman",
|
||||||
@@ -59,7 +59,7 @@ features = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[dependencies.thiserror]
|
[dependencies.thiserror]
|
||||||
version = "1.0"
|
version = "2"
|
||||||
|
|
||||||
[build-dependencies.bindgen]
|
[build-dependencies.bindgen]
|
||||||
version = "0.70.1"
|
version = "0.72"
|
||||||
|
|||||||
6
libs/v4l2r/Cargo.toml.orig
generated
6
libs/v4l2r/Cargo.toml.orig
generated
@@ -18,11 +18,11 @@ arch64 = []
|
|||||||
arch32 = []
|
arch32 = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
nix = { version = "0.28", features = ["ioctl", "mman", "poll", "fs", "event"] }
|
nix = { version = "0.31", features = ["ioctl", "mman", "poll", "fs", "event"] }
|
||||||
bitflags = "2.4"
|
bitflags = "2.4"
|
||||||
thiserror = "1.0"
|
thiserror = "2"
|
||||||
log = "0.4.14"
|
log = "0.4.14"
|
||||||
enumn = "0.1.6"
|
enumn = "0.1.6"
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
bindgen = "0.70.1"
|
bindgen = "0.72"
|
||||||
|
|||||||
@@ -17,7 +17,3 @@ parts are intentionally removed here so this dependency stays scoped to capture.
|
|||||||
|
|
||||||
`cargo build` generates V4L2 bindings from the vendored Linux UAPI headers in
|
`cargo build` generates V4L2 bindings from the vendored Linux UAPI headers in
|
||||||
`include/`.
|
`include/`.
|
||||||
|
|
||||||
For Android targets, the build script uses the Android NDK sysroot. Set one of
|
|
||||||
`ANDROID_NDK_HOME`, `ANDROID_NDK_ROOT`, `NDK_HOME`, `ANDROID_HOME`, or
|
|
||||||
`ANDROID_SDK_ROOT` if the NDK cannot be found automatically.
|
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
// This file defines the customizations to the bindgen builder used to generate the v4l2r
|
// This file defines the customizations to the bindgen builder used to generate the v4l2r
|
||||||
// bindings.
|
// bindings.
|
||||||
//
|
//
|
||||||
// It is meant to be included from `lib/build.rs` and `android/build.rs`.
|
// It is meant to be included from `build.rs`.
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
/// Workaround for https://github.com/rust-lang/rust-bindgen/issues/753.
|
/// Workaround for https://github.com/rust-lang/rust-bindgen/issues/753.
|
||||||
pub struct Fix753;
|
pub struct Fix753;
|
||||||
|
|
||||||
impl bindgen::callbacks::ParseCallbacks for Fix753 {
|
impl bindgen::callbacks::ParseCallbacks for Fix753 {
|
||||||
fn item_name(&self, original_item_name: &str) -> Option<String> {
|
fn item_name(&self, item_info: bindgen::callbacks::ItemInfo<'_>) -> Option<String> {
|
||||||
Some(original_item_name.trim_start_matches("Fix753_").to_owned())
|
Some(item_info.name.trim_start_matches("Fix753_").to_owned())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
include!("bindgen.rs");
|
include!("bindgen.rs");
|
||||||
|
|
||||||
/// Vendored Linux UAPI include root used for non-Android targets.
|
/// Vendored Linux UAPI include root.
|
||||||
const VENDORED_INCLUDE_DIR: &str = "include";
|
const VENDORED_INCLUDE_DIR: &str = "include";
|
||||||
|
|
||||||
/// Wrapper file to use as input of bindgen.
|
/// Wrapper file to use as input of bindgen.
|
||||||
@@ -13,28 +13,16 @@ const WRAPPER_H: &str = "v4l2r_wrapper.h";
|
|||||||
const FIX753_H: &str = "fix753.h";
|
const FIX753_H: &str = "fix753.h";
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let target = env::var("TARGET").unwrap_or_default();
|
let include_root =
|
||||||
let is_android = target.contains("android");
|
|
||||||
|
|
||||||
let include_root = if is_android {
|
|
||||||
android_sysroot().join("usr/include")
|
|
||||||
} else {
|
|
||||||
PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is not set"))
|
PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("`CARGO_MANIFEST_DIR` is not set"))
|
||||||
.join(VENDORED_INCLUDE_DIR)
|
.join(VENDORED_INCLUDE_DIR);
|
||||||
};
|
|
||||||
let videodev2_h = include_root.join("linux/videodev2.h");
|
let videodev2_h = include_root.join("linux/videodev2.h");
|
||||||
|
|
||||||
println!("cargo::rerun-if-env-changed=ANDROID_NDK_HOME");
|
|
||||||
println!("cargo::rerun-if-env-changed=ANDROID_NDK_ROOT");
|
|
||||||
println!("cargo::rerun-if-env-changed=NDK_HOME");
|
|
||||||
println!("cargo::rerun-if-env-changed=ANDROID_HOME");
|
|
||||||
println!("cargo::rerun-if-env-changed=ANDROID_SDK_ROOT");
|
|
||||||
println!("cargo::rerun-if-env-changed=CARGO_NDK_PLATFORM");
|
|
||||||
println!("cargo::rerun-if-changed={}", videodev2_h.display());
|
println!("cargo::rerun-if-changed={}", videodev2_h.display());
|
||||||
println!("cargo::rerun-if-changed={}", FIX753_H);
|
println!("cargo::rerun-if-changed={}", FIX753_H);
|
||||||
println!("cargo::rerun-if-changed={}", WRAPPER_H);
|
println!("cargo::rerun-if-changed={}", WRAPPER_H);
|
||||||
|
|
||||||
let mut clang_args = vec![
|
let clang_args = vec![
|
||||||
format!("-I{}", include_root.display()),
|
format!("-I{}", include_root.display()),
|
||||||
#[cfg(all(feature = "arch64", not(feature = "arch32")))]
|
#[cfg(all(feature = "arch64", not(feature = "arch32")))]
|
||||||
"--target=x86_64-linux-gnu".into(),
|
"--target=x86_64-linux-gnu".into(),
|
||||||
@@ -42,10 +30,6 @@ fn main() {
|
|||||||
"--target=i686-linux-gnu".into(),
|
"--target=i686-linux-gnu".into(),
|
||||||
];
|
];
|
||||||
|
|
||||||
if is_android {
|
|
||||||
clang_args.extend(android_clang_args(&target));
|
|
||||||
}
|
|
||||||
|
|
||||||
let bindings = v4l2r_bindgen_builder(bindgen::Builder::default())
|
let bindings = v4l2r_bindgen_builder(bindgen::Builder::default())
|
||||||
.header(WRAPPER_H)
|
.header(WRAPPER_H)
|
||||||
.clang_args(clang_args)
|
.clang_args(clang_args)
|
||||||
@@ -57,105 +41,3 @@ fn main() {
|
|||||||
.write_to_file(out_path.join("bindings.rs"))
|
.write_to_file(out_path.join("bindings.rs"))
|
||||||
.expect("Couldn't write bindings!");
|
.expect("Couldn't write bindings!");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn android_clang_args(target: &str) -> Vec<String> {
|
|
||||||
let ndk = android_ndk_home();
|
|
||||||
let toolchain = ndk.join("toolchains/llvm/prebuilt").join(host_tag());
|
|
||||||
let sysroot = toolchain.join("sysroot");
|
|
||||||
let clang_include = toolchain
|
|
||||||
.join("lib/clang")
|
|
||||||
.join(clang_version(&toolchain))
|
|
||||||
.join("include");
|
|
||||||
let api = env::var("CARGO_NDK_PLATFORM")
|
|
||||||
.ok()
|
|
||||||
.and_then(|value| value.parse::<u32>().ok())
|
|
||||||
.unwrap_or(21);
|
|
||||||
let clang_target = android_clang_target(target);
|
|
||||||
|
|
||||||
vec![
|
|
||||||
format!("--target={clang_target}"),
|
|
||||||
format!("--sysroot={}", sysroot.display()),
|
|
||||||
format!("-D__ANDROID_API__={api}"),
|
|
||||||
format!("-isystem{}", clang_include.display()),
|
|
||||||
format!("-isystem{}", sysroot.join("usr/include").display()),
|
|
||||||
format!(
|
|
||||||
"-isystem{}",
|
|
||||||
sysroot.join("usr/include").join(clang_target).display()
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_clang_target(target: &str) -> &'static str {
|
|
||||||
match target {
|
|
||||||
"aarch64-linux-android" => "aarch64-linux-android",
|
|
||||||
"armv7-linux-androideabi" => "armv7a-linux-androideabi",
|
|
||||||
"i686-linux-android" => "i686-linux-android",
|
|
||||||
"x86_64-linux-android" => "x86_64-linux-android",
|
|
||||||
other => panic!("unsupported Android target for v4l2r bindgen: {other}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_sysroot() -> PathBuf {
|
|
||||||
android_ndk_home()
|
|
||||||
.join("toolchains/llvm/prebuilt")
|
|
||||||
.join(host_tag())
|
|
||||||
.join("sysroot")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_ndk_home() -> PathBuf {
|
|
||||||
for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
return PathBuf::from(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
let ndk_dir = PathBuf::from(value).join("ndk");
|
|
||||||
if let Some(newest) = newest_child_dir(&ndk_dir) {
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!(
|
|
||||||
"v4l2r Android bindgen requires ANDROID_NDK_HOME, ANDROID_NDK_ROOT, NDK_HOME, \
|
|
||||||
or ANDROID_HOME/ANDROID_SDK_ROOT with an ndk directory"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn newest_child_dir(path: &PathBuf) -> Option<PathBuf> {
|
|
||||||
let mut entries = std::fs::read_dir(path)
|
|
||||||
.ok()?
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.filter(|path| path.is_dir())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries.pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn host_tag() -> &'static str {
|
|
||||||
if cfg!(target_os = "linux") {
|
|
||||||
"linux-x86_64"
|
|
||||||
} else if cfg!(target_os = "macos") {
|
|
||||||
"darwin-x86_64"
|
|
||||||
} else if cfg!(target_os = "windows") {
|
|
||||||
"windows-x86_64"
|
|
||||||
} else {
|
|
||||||
panic!("unsupported host OS for Android NDK");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clang_version(toolchain: &PathBuf) -> String {
|
|
||||||
let clang_dir = toolchain.join("lib/clang");
|
|
||||||
let mut entries = std::fs::read_dir(&clang_dir)
|
|
||||||
.unwrap_or_else(|err| panic!("failed to read {}: {err}", clang_dir.display()))
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries
|
|
||||||
.pop()
|
|
||||||
.unwrap_or_else(|| panic!("no clang resource directory in {}", clang_dir.display()))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use crate::ioctl::ioctl_and_convert;
|
|||||||
use crate::ioctl::IoctlConvertError;
|
use crate::ioctl::IoctlConvertError;
|
||||||
use crate::ioctl::IoctlConvertResult;
|
use crate::ioctl::IoctlConvertResult;
|
||||||
use crate::ioctl::UncheckedV4l2Buffer;
|
use crate::ioctl::UncheckedV4l2Buffer;
|
||||||
|
use crate::memory::MemoryType;
|
||||||
use crate::QueueType;
|
use crate::QueueType;
|
||||||
|
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
@@ -51,12 +52,13 @@ pub type DqBufError<CE> = IoctlConvertError<DqBufIoctlError, CE>;
|
|||||||
pub type DqBufResult<O, CE> = IoctlConvertResult<O, DqBufIoctlError, CE>;
|
pub type DqBufResult<O, CE> = IoctlConvertResult<O, DqBufIoctlError, CE>;
|
||||||
|
|
||||||
/// Safe wrapper around the `VIDIOC_DQBUF` ioctl.
|
/// Safe wrapper around the `VIDIOC_DQBUF` ioctl.
|
||||||
pub fn dqbuf<O>(fd: &impl AsRawFd, queue: QueueType) -> DqBufResult<O, O::Error>
|
pub fn dqbuf<O>(fd: &impl AsRawFd, queue: QueueType, memory: MemoryType) -> DqBufResult<O, O::Error>
|
||||||
where
|
where
|
||||||
O: TryFrom<UncheckedV4l2Buffer>,
|
O: TryFrom<UncheckedV4l2Buffer>,
|
||||||
O::Error: std::fmt::Debug,
|
O::Error: std::fmt::Debug,
|
||||||
{
|
{
|
||||||
let mut v4l2_buf = UncheckedV4l2Buffer::new_for_querybuf(queue, None);
|
let mut v4l2_buf = UncheckedV4l2Buffer::new_for_querybuf(queue, None);
|
||||||
|
v4l2_buf.0.memory = memory as u32;
|
||||||
|
|
||||||
ioctl_and_convert(
|
ioctl_and_convert(
|
||||||
unsafe { ioctl::vidioc_dqbuf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
|
unsafe { ioctl::vidioc_dqbuf(fd.as_raw_fd(), v4l2_buf.as_mut()) }
|
||||||
|
|||||||
@@ -1,9 +1,3 @@
|
|||||||
#ifdef __ANDROID__
|
|
||||||
#include <stddef.h>
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <sys/types.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#include <linux/videodev2.h>
|
#include <linux/videodev2.h>
|
||||||
|
|
||||||
#define MARK_FIX_753(name) const unsigned long int Fix753_##name = name;
|
#define MARK_FIX_753(name) const unsigned long int Fix753_##name = name;
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ license = "GPL-2.0"
|
|||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
|
||||||
# Error handling
|
# Error handling
|
||||||
thiserror = "1"
|
thiserror = "2"
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
|
|||||||
@@ -97,14 +97,14 @@ impl ExfatBootSector {
|
|||||||
let heap_sectors = volume_length as u32 - cluster_heap_offset;
|
let heap_sectors = volume_length as u32 - cluster_heap_offset;
|
||||||
let cluster_count = heap_sectors / sectors_per_cluster;
|
let cluster_count = heap_sectors / sectors_per_cluster;
|
||||||
|
|
||||||
// Calculate root directory cluster based on upcase table size
|
// Calculate root directory cluster based on bitmap and upcase table size.
|
||||||
// Cluster 2: Bitmap (1 cluster)
|
|
||||||
// Cluster 3...: Upcase table (128KB, may span multiple clusters)
|
|
||||||
// Next available: Root directory
|
|
||||||
const UPCASE_TABLE_SIZE: u64 = 128 * 1024;
|
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 =
|
let upcase_clusters =
|
||||||
((UPCASE_TABLE_SIZE + cluster_size as u64 - 1) / cluster_size as u64) as u32;
|
((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 {
|
Self {
|
||||||
jump_boot: [0xEB, 0x76, 0x90],
|
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_BITMAP: u8 = 0x81;
|
||||||
const ENTRY_TYPE_UPCASE: u8 = 0x82;
|
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
|
/// Create volume label directory entry
|
||||||
fn create_volume_label_entry(label: &str) -> [u8; 32] {
|
fn create_volume_label_entry(label: &str) -> [u8; 32] {
|
||||||
let mut entry = [0u8; 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;
|
let fat_offset = partition_offset + boot_sector.fat_offset as u64 * 512;
|
||||||
writer.seek(SeekFrom::Start(fat_offset))?;
|
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)
|
// Calculate how many clusters the upcase table needs (128KB)
|
||||||
const UPCASE_TABLE_SIZE: u64 = 128 * 1024;
|
const UPCASE_TABLE_SIZE: u64 = 128 * 1024;
|
||||||
let upcase_clusters =
|
let upcase_clusters =
|
||||||
((UPCASE_TABLE_SIZE + cluster_size as u64 - 1) / cluster_size as u64) as u32;
|
((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
|
// FAT entries: cluster 0 and 1 are reserved
|
||||||
// 0: Media type (0xFFFFFFF8)
|
// 0: Media type (0xFFFFFFF8)
|
||||||
// 1: Reserved (0xFFFFFFFF)
|
// 1: Reserved (0xFFFFFFFF)
|
||||||
// 2: Bitmap cluster (single cluster, end of chain)
|
// 2..2+bitmap_clusters-1: Bitmap cluster chain
|
||||||
// 3..3+upcase_clusters-1: Upcase table cluster chain
|
// upcase_start_cluster..upcase_start_cluster+upcase_clusters-1: Upcase table cluster chain
|
||||||
// 3+upcase_clusters: Root directory cluster (end of chain)
|
// root_cluster: Root directory cluster (end of chain)
|
||||||
let mut fat_entries = vec![
|
let mut fat_entries = vec![
|
||||||
0xFFFFFFF8, // Media type
|
0xFFFFFFF8, // Media type
|
||||||
0xFFFFFFFF, // Reserved
|
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
|
// Build upcase table cluster chain
|
||||||
for i in 0..upcase_clusters {
|
for i in 0..upcase_clusters {
|
||||||
let cluster_num = 3 + i;
|
let cluster_num = upcase_start_cluster + i;
|
||||||
if i == upcase_clusters - 1 {
|
if i == upcase_clusters - 1 {
|
||||||
// Last cluster in chain
|
// Last cluster in chain
|
||||||
fat_entries.push(0xFFFFFFFF);
|
fat_entries.push(0xFFFFFFFF);
|
||||||
@@ -345,38 +369,26 @@ pub fn format_exfat<W: Write + Seek>(
|
|||||||
// Calculate cluster heap offset
|
// Calculate cluster heap offset
|
||||||
let heap_offset = partition_offset + boot_sector.cluster_heap_offset as u64 * 512;
|
let heap_offset = partition_offset + boot_sector.cluster_heap_offset as u64 * 512;
|
||||||
|
|
||||||
// Cluster 2: Allocation Bitmap
|
// Allocation Bitmap
|
||||||
let bitmap_size = (boot_sector.cluster_count + 7) / 8;
|
let mut bitmap = vec![0u8; bitmap_clusters as usize * cluster_size as usize];
|
||||||
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];
|
|
||||||
|
|
||||||
// Mark clusters 2, 3..3+upcase_clusters-1, root_cluster as used
|
// Mark bitmap, upcase, and root directory clusters as used.
|
||||||
// Cluster 2: bitmap
|
// exFAT allocation bitmap bit 0 describes cluster 2.
|
||||||
bitmap[0] |= 0b00000100; // Bit 2
|
for i in 0..bitmap_clusters {
|
||||||
// Clusters 3..3+upcase_clusters-1: upcase table
|
set_cluster_allocated(&mut bitmap, bitmap_start_cluster + i);
|
||||||
|
}
|
||||||
for i in 0..upcase_clusters {
|
for i in 0..upcase_clusters {
|
||||||
let cluster = 3 + i;
|
set_cluster_allocated(&mut bitmap, upcase_start_cluster + 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, root_cluster);
|
||||||
|
|
||||||
writer.seek(SeekFrom::Start(heap_offset))?;
|
writer.seek(SeekFrom::Start(heap_offset))?;
|
||||||
writer.write_all(&bitmap)?;
|
writer.write_all(&bitmap)?;
|
||||||
|
|
||||||
// Cluster 3..3+upcase_clusters-1: Upcase table
|
// Upcase table
|
||||||
let upcase_data = generate_upcase_table();
|
let upcase_data = generate_upcase_table();
|
||||||
let upcase_checksum = calculate_upcase_checksum(&upcase_data);
|
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.seek(SeekFrom::Start(upcase_offset))?;
|
||||||
writer.write_all(&upcase_data)?;
|
writer.write_all(&upcase_data)?;
|
||||||
|
|
||||||
@@ -388,13 +400,18 @@ pub fn format_exfat<W: Write + Seek>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Root directory cluster
|
// 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))?;
|
writer.seek(SeekFrom::Start(root_offset))?;
|
||||||
|
|
||||||
// Write directory entries
|
// Write directory entries
|
||||||
let volume_label_entry = create_volume_label_entry(label);
|
let volume_label_entry = create_volume_label_entry(label);
|
||||||
let bitmap_entry = create_bitmap_entry(2, bitmap_size as u64);
|
let bitmap_entry = create_bitmap_entry(bitmap_start_cluster, bitmap_size as u64);
|
||||||
let upcase_entry = create_upcase_entry(3, upcase_data.len() as u64, upcase_checksum);
|
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(&volume_label_entry)?;
|
||||||
writer.write_all(&bitmap_entry)?;
|
writer.write_all(&bitmap_entry)?;
|
||||||
@@ -413,6 +430,9 @@ pub fn format_exfat<W: Write + Seek>(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::partition::PartitionLayout;
|
||||||
|
use std::io::Read;
|
||||||
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cluster_size() {
|
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(8 * 1024 * 1024 * 1024 / 512), 131072); // 8GB → 128KB
|
||||||
assert_eq!(get_cluster_size(16 * 1024 * 1024 * 1024 / 512), 131072); // 16GB → 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()
|
path.display()
|
||||||
);
|
);
|
||||||
|
|
||||||
// Create sparse file
|
// Build beside the destination so a failed create cannot leave a partial image.
|
||||||
let mut file = File::create(path)?;
|
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)?;
|
file.set_len(size)?;
|
||||||
|
|
||||||
// Write boot code
|
// Write boot code
|
||||||
@@ -64,6 +71,8 @@ impl VentoyImage {
|
|||||||
format_exfat(&mut file, layout.data_offset(), layout.data_size(), label)?;
|
format_exfat(&mut file, layout.data_offset(), layout.data_size(), label)?;
|
||||||
|
|
||||||
file.flush()?;
|
file.flush()?;
|
||||||
|
temp.persist(path)
|
||||||
|
.map_err(|error| VentoyError::Io(error.error))?;
|
||||||
|
|
||||||
println!("[INFO] Ventoy IMG created successfully!");
|
println!("[INFO] Ventoy IMG created successfully!");
|
||||||
|
|
||||||
@@ -274,3 +283,20 @@ impl VentoyImage {
|
|||||||
&self.path
|
&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]
|
[dependencies]
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
bindgen = "0.70.1"
|
bindgen = "0.72"
|
||||||
|
|||||||
@@ -19,17 +19,7 @@ fn main() {
|
|||||||
|
|
||||||
fn generate_bindings(cpp_dir: &Path) {
|
fn generate_bindings(cpp_dir: &Path) {
|
||||||
let ffi_header = cpp_dir.join("yuv_ffi.h");
|
let ffi_header = cpp_dir.join("yuv_ffi.h");
|
||||||
let mut builder = bindgen::builder().header(ffi_header.to_string_lossy().to_string());
|
let builder = bindgen::builder().header(ffi_header.to_string_lossy().to_string());
|
||||||
|
|
||||||
if env::var("CARGO_CFG_TARGET_OS").ok().as_deref() == Some("android") {
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_NDK_ROOT");
|
|
||||||
println!("cargo:rerun-if-env-changed=NDK_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_HOME");
|
|
||||||
println!("cargo:rerun-if-env-changed=ANDROID_SDK_ROOT");
|
|
||||||
println!("cargo:rerun-if-env-changed=CARGO_NDK_PLATFORM");
|
|
||||||
builder = builder.clang_args(android_clang_args());
|
|
||||||
}
|
|
||||||
|
|
||||||
builder
|
builder
|
||||||
// YUYV conversions
|
// YUYV conversions
|
||||||
@@ -96,28 +86,19 @@ fn generate_bindings(cpp_dir: &Path) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn link_libyuv() {
|
fn link_libyuv() {
|
||||||
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
println!("cargo:rerun-if-env-changed=ONE_KVM_LIBS_PATH");
|
||||||
|
println!("cargo:rerun-if-env-changed=LIBYUV_STATIC");
|
||||||
|
|
||||||
if target_os == "android" {
|
// An explicit library root must take precedence over host discovery.
|
||||||
if link_android_libyuv() {
|
if env::var("ONE_KVM_LIBS_PATH")
|
||||||
|
.ok()
|
||||||
|
.is_some_and(|path| !path.trim().is_empty())
|
||||||
|
{
|
||||||
|
if link_system() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if let Some(vcpkg_installed) = vcpkg_installed_root() {
|
|
||||||
if link_vcpkg(vcpkg_installed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!(
|
panic!("libyuv not found under ONE_KVM_LIBS_PATH");
|
||||||
"Android libyuv not found!\n\
|
|
||||||
\n\
|
|
||||||
Build it with scripts/build-android-libyuv.sh and set:\n\
|
|
||||||
export ONE_KVM_ANDROID_LIBYUV_ROOT=/path/to/android-libyuv\n\
|
|
||||||
\n\
|
|
||||||
Expected layout:\n\
|
|
||||||
$ONE_KVM_ANDROID_LIBYUV_ROOT/<abi>/include\n\
|
|
||||||
$ONE_KVM_ANDROID_LIBYUV_ROOT/<abi>/lib/libyuv.a"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try vcpkg first
|
// Try vcpkg first
|
||||||
@@ -148,217 +129,6 @@ fn link_libyuv() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn link_android_libyuv() -> bool {
|
|
||||||
println!("cargo:rerun-if-env-changed=ONE_KVM_ANDROID_LIBYUV_ROOT");
|
|
||||||
println!("cargo:rerun-if-env-changed=ONE_KVM_ANDROID_LIBYUV_STATIC");
|
|
||||||
|
|
||||||
let root = match env::var("ONE_KVM_ANDROID_LIBYUV_ROOT")
|
|
||||||
.ok()
|
|
||||||
.filter(|path| !path.trim().is_empty())
|
|
||||||
{
|
|
||||||
Some(path) => PathBuf::from(path),
|
|
||||||
None => return false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
|
||||||
let abi = android_abi(&target_arch);
|
|
||||||
let abi_root = root.join(abi);
|
|
||||||
let lib_dir = if abi_root.join("lib").exists() {
|
|
||||||
abi_root.join("lib")
|
|
||||||
} else {
|
|
||||||
root.join("lib")
|
|
||||||
};
|
|
||||||
let include_dir = if abi_root.join("include").exists() {
|
|
||||||
abi_root.join("include")
|
|
||||||
} else {
|
|
||||||
root.join("include")
|
|
||||||
};
|
|
||||||
|
|
||||||
let static_lib = lib_dir.join("libyuv.a");
|
|
||||||
let shared_lib = lib_dir.join("libyuv.so");
|
|
||||||
let use_static = env::var("ONE_KVM_ANDROID_LIBYUV_STATIC")
|
|
||||||
.or_else(|_| env::var("LIBYUV_STATIC"))
|
|
||||||
.map(|value| value != "0")
|
|
||||||
.unwrap_or(true);
|
|
||||||
|
|
||||||
if use_static && static_lib.exists() {
|
|
||||||
println!("cargo:rustc-link-search=native={}", lib_dir.display());
|
|
||||||
println!("cargo:rustc-link-lib=static=yuv");
|
|
||||||
link_android_libjpeg(&root, abi);
|
|
||||||
println!("cargo:rustc-link-lib=c++_shared");
|
|
||||||
println!(
|
|
||||||
"cargo:info=Using Android libyuv from {} (static linking)",
|
|
||||||
root.display()
|
|
||||||
);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if shared_lib.exists() {
|
|
||||||
println!("cargo:rustc-link-search=native={}", lib_dir.display());
|
|
||||||
println!("cargo:rustc-link-lib=yuv");
|
|
||||||
println!("cargo:rustc-link-lib=c++_shared");
|
|
||||||
println!(
|
|
||||||
"cargo:info=Using Android libyuv from {} (dynamic linking)",
|
|
||||||
root.display()
|
|
||||||
);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"cargo:warning=Android libyuv not found under {} for ABI {} (checked {}, {})",
|
|
||||||
root.display(),
|
|
||||||
abi,
|
|
||||||
static_lib.display(),
|
|
||||||
shared_lib.display()
|
|
||||||
);
|
|
||||||
if !include_dir.exists() {
|
|
||||||
println!(
|
|
||||||
"cargo:warning=Android libyuv include directory not found: {}",
|
|
||||||
include_dir.display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
fn link_android_libjpeg(libyuv_root: &Path, abi: &str) {
|
|
||||||
println!("cargo:rerun-if-env-changed=ONE_KVM_ANDROID_TURBOJPEG_ROOT");
|
|
||||||
|
|
||||||
let mut roots = Vec::new();
|
|
||||||
if let Ok(root) = env::var("ONE_KVM_ANDROID_TURBOJPEG_ROOT") {
|
|
||||||
if !root.trim().is_empty() {
|
|
||||||
roots.push(PathBuf::from(root));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
roots.push(libyuv_root.with_file_name("android-turbojpeg"));
|
|
||||||
|
|
||||||
for root in roots {
|
|
||||||
let abi_lib_dir = root.join(abi).join("lib");
|
|
||||||
let lib_dir = if abi_lib_dir.exists() {
|
|
||||||
abi_lib_dir
|
|
||||||
} else {
|
|
||||||
root.join("lib")
|
|
||||||
};
|
|
||||||
let jpeg_lib = lib_dir.join("libjpeg.a");
|
|
||||||
if jpeg_lib.exists() {
|
|
||||||
println!("cargo:rustc-link-search=native={}", lib_dir.display());
|
|
||||||
println!("cargo:rustc-link-lib=static=jpeg");
|
|
||||||
println!(
|
|
||||||
"cargo:info=Using Android libjpeg for libyuv MJPEG from {}",
|
|
||||||
root.display()
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
println!("cargo:warning=Android libjpeg.a not found; libyuv MJPEG symbols may fail to link");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_abi(target_arch: &str) -> &'static str {
|
|
||||||
match target_arch {
|
|
||||||
"aarch64" => "arm64-v8a",
|
|
||||||
"arm" => "armeabi-v7a",
|
|
||||||
"x86" => "x86",
|
|
||||||
"x86_64" => "x86_64",
|
|
||||||
_ => "unknown",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_clang_args() -> Vec<String> {
|
|
||||||
let ndk = android_ndk_home();
|
|
||||||
let target = env::var("TARGET").unwrap_or_default();
|
|
||||||
let toolchain = ndk.join("toolchains/llvm/prebuilt").join(host_tag());
|
|
||||||
let sysroot = toolchain.join("sysroot");
|
|
||||||
let clang_include = toolchain
|
|
||||||
.join("lib/clang")
|
|
||||||
.join(clang_version(&toolchain))
|
|
||||||
.join("include");
|
|
||||||
let api = env::var("CARGO_NDK_PLATFORM")
|
|
||||||
.ok()
|
|
||||||
.and_then(|value| value.parse::<u32>().ok())
|
|
||||||
.unwrap_or(21);
|
|
||||||
let clang_target = android_clang_target(&target);
|
|
||||||
|
|
||||||
vec![
|
|
||||||
format!("--target={clang_target}"),
|
|
||||||
format!("--sysroot={}", sysroot.display()),
|
|
||||||
format!("-D__ANDROID_API__={api}"),
|
|
||||||
format!("-isystem{}", clang_include.display()),
|
|
||||||
format!("-isystem{}", sysroot.join("usr/include").display()),
|
|
||||||
format!(
|
|
||||||
"-isystem{}",
|
|
||||||
sysroot.join("usr/include").join(clang_target).display()
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_clang_target(target: &str) -> &'static str {
|
|
||||||
match target {
|
|
||||||
"aarch64-linux-android" => "aarch64-linux-android",
|
|
||||||
"armv7-linux-androideabi" => "armv7a-linux-androideabi",
|
|
||||||
"i686-linux-android" => "i686-linux-android",
|
|
||||||
"x86_64-linux-android" => "x86_64-linux-android",
|
|
||||||
other => panic!("unsupported Android target for libyuv bindgen: {other}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn android_ndk_home() -> PathBuf {
|
|
||||||
for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
return PathBuf::from(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
|
|
||||||
if let Ok(value) = env::var(key) {
|
|
||||||
let ndk_dir = PathBuf::from(value).join("ndk");
|
|
||||||
if let Some(newest) = newest_child_dir(&ndk_dir) {
|
|
||||||
return newest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!(
|
|
||||||
"libyuv Android bindgen requires ANDROID_NDK_HOME, ANDROID_NDK_ROOT, NDK_HOME, \
|
|
||||||
or ANDROID_HOME/ANDROID_SDK_ROOT with an ndk directory"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn newest_child_dir(path: &Path) -> Option<PathBuf> {
|
|
||||||
let mut entries = std::fs::read_dir(path)
|
|
||||||
.ok()?
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.filter(|path| path.is_dir())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries.pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn host_tag() -> &'static str {
|
|
||||||
if cfg!(target_os = "linux") {
|
|
||||||
"linux-x86_64"
|
|
||||||
} else if cfg!(target_os = "macos") {
|
|
||||||
"darwin-x86_64"
|
|
||||||
} else if cfg!(target_os = "windows") {
|
|
||||||
"windows-x86_64"
|
|
||||||
} else {
|
|
||||||
panic!("unsupported host OS for Android NDK");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clang_version(toolchain: &Path) -> String {
|
|
||||||
let clang_dir = toolchain.join("lib/clang");
|
|
||||||
let mut entries = std::fs::read_dir(&clang_dir)
|
|
||||||
.unwrap_or_else(|_| panic!("missing NDK clang directory: {}", clang_dir.display()))
|
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
entries.sort();
|
|
||||||
entries
|
|
||||||
.pop()
|
|
||||||
.unwrap_or_else(|| panic!("no clang versions found under: {}", clang_dir.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn vcpkg_installed_root() -> Option<PathBuf> {
|
fn vcpkg_installed_root() -> Option<PathBuf> {
|
||||||
println!("cargo:rerun-if-env-changed=VCPKG_INSTALLED_DIR");
|
println!("cargo:rerun-if-env-changed=VCPKG_INSTALLED_DIR");
|
||||||
println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
|
println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
|
||||||
@@ -383,10 +153,6 @@ fn link_vcpkg(mut path: PathBuf) -> bool {
|
|||||||
("linux", "x86_64") => "x64-linux",
|
("linux", "x86_64") => "x64-linux",
|
||||||
("linux", "aarch64") => "arm64-linux",
|
("linux", "aarch64") => "arm64-linux",
|
||||||
("linux", "arm") => "arm-linux",
|
("linux", "arm") => "arm-linux",
|
||||||
("android", "x86_64") => "x64-android",
|
|
||||||
("android", "x86") => "x86-android",
|
|
||||||
("android", "aarch64") => "arm64-android",
|
|
||||||
("android", "arm") => "arm-neon-android",
|
|
||||||
("windows", "x86_64") => "x64-windows-static",
|
("windows", "x86_64") => "x64-windows-static",
|
||||||
("windows", "x86") => "x86-windows-static",
|
("windows", "x86") => "x86-windows-static",
|
||||||
("macos", "x86_64") => "x64-osx",
|
("macos", "x86_64") => "x64-osx",
|
||||||
@@ -426,8 +192,6 @@ fn link_vcpkg(mut path: PathBuf) -> bool {
|
|||||||
link_libjpeg_for_static_libyuv(&[lib_path.clone()], &target_os);
|
link_libjpeg_for_static_libyuv(&[lib_path.clone()], &target_os);
|
||||||
if target_os == "linux" {
|
if target_os == "linux" {
|
||||||
println!("cargo:rustc-link-lib=stdc++");
|
println!("cargo:rustc-link-lib=stdc++");
|
||||||
} else if target_os == "android" {
|
|
||||||
println!("cargo:rustc-link-lib=c++_shared");
|
|
||||||
}
|
}
|
||||||
println!("cargo:info=Using libyuv from vcpkg (static linking)");
|
println!("cargo:info=Using libyuv from vcpkg (static linking)");
|
||||||
} else {
|
} else {
|
||||||
@@ -435,8 +199,6 @@ fn link_vcpkg(mut path: PathBuf) -> bool {
|
|||||||
println!("cargo:rustc-link-lib=yuv");
|
println!("cargo:rustc-link-lib=yuv");
|
||||||
if target_os == "linux" {
|
if target_os == "linux" {
|
||||||
println!("cargo:rustc-link-lib=stdc++");
|
println!("cargo:rustc-link-lib=stdc++");
|
||||||
} else if target_os == "android" {
|
|
||||||
println!("cargo:rustc-link-lib=c++_shared");
|
|
||||||
}
|
}
|
||||||
println!("cargo:info=Using libyuv from vcpkg (dynamic linking)");
|
println!("cargo:info=Using libyuv from vcpkg (dynamic linking)");
|
||||||
}
|
}
|
||||||
@@ -485,17 +247,21 @@ fn link_system() -> bool {
|
|||||||
// Build custom library paths based on target architecture:
|
// Build custom library paths based on target architecture:
|
||||||
// 1. Check ONE_KVM_LIBS_PATH environment variable (explicit override)
|
// 1. Check ONE_KVM_LIBS_PATH environment variable (explicit override)
|
||||||
// 2. Fall back to architecture-based detection
|
// 2. Fall back to architecture-based detection
|
||||||
let custom_lib_path = if let Ok(path) = env::var("ONE_KVM_LIBS_PATH") {
|
let explicit_lib_root = env::var("ONE_KVM_LIBS_PATH")
|
||||||
format!("{}/lib", path)
|
.ok()
|
||||||
} else {
|
.filter(|path| !path.trim().is_empty());
|
||||||
match target_arch.as_str() {
|
let custom_lib_path = explicit_lib_root
|
||||||
"x86_64" => "/usr/local/lib",
|
.as_ref()
|
||||||
"aarch64" => "/usr/aarch64-linux-gnu/lib",
|
.map(|path| format!("{}/lib", path))
|
||||||
"arm" => "/usr/arm-linux-gnueabihf/lib",
|
.unwrap_or_else(|| {
|
||||||
_ => "",
|
match target_arch.as_str() {
|
||||||
}
|
"x86_64" => "/usr/local/lib",
|
||||||
.to_string()
|
"aarch64" => "/usr/aarch64-linux-gnu/lib",
|
||||||
};
|
"arm" => "/usr/arm-linux-gnueabihf/lib",
|
||||||
|
_ => "",
|
||||||
|
}
|
||||||
|
.to_string()
|
||||||
|
});
|
||||||
|
|
||||||
// Try common system library paths (custom paths first)
|
// Try common system library paths (custom paths first)
|
||||||
let mut lib_paths: Vec<String> = Vec::new();
|
let mut lib_paths: Vec<String> = Vec::new();
|
||||||
@@ -505,20 +271,22 @@ fn link_system() -> bool {
|
|||||||
lib_paths.push(custom_lib_path);
|
lib_paths.push(custom_lib_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then standard paths
|
// An explicit root is strict: do not silently fall back to host libraries.
|
||||||
lib_paths.extend(
|
if explicit_lib_root.is_none() {
|
||||||
[
|
lib_paths.extend(
|
||||||
"/usr/local/lib", // Custom builds
|
[
|
||||||
"/usr/local/lib64",
|
"/usr/local/lib", // Custom builds
|
||||||
"/usr/lib",
|
"/usr/local/lib64",
|
||||||
"/usr/lib64",
|
"/usr/lib",
|
||||||
"/usr/lib/x86_64-linux-gnu", // Debian/Ubuntu x86_64
|
"/usr/lib64",
|
||||||
"/usr/lib/aarch64-linux-gnu", // Debian/Ubuntu ARM64
|
"/usr/lib/x86_64-linux-gnu", // Debian/Ubuntu x86_64
|
||||||
"/usr/lib/arm-linux-gnueabihf", // Debian/Ubuntu ARMv7
|
"/usr/lib/aarch64-linux-gnu", // Debian/Ubuntu ARM64
|
||||||
]
|
"/usr/lib/arm-linux-gnueabihf", // Debian/Ubuntu ARMv7
|
||||||
.iter()
|
]
|
||||||
.map(|s| s.to_string()),
|
.iter()
|
||||||
);
|
.map(|s| s.to_string()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
for path in &lib_paths {
|
for path in &lib_paths {
|
||||||
let lib_path = Path::new(path);
|
let lib_path = Path::new(path);
|
||||||
|
|||||||
@@ -1088,17 +1088,17 @@ pub fn bgr24_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Res
|
|||||||
|
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
{
|
{
|
||||||
let y_size = w * h;
|
let y_size = w * h;
|
||||||
call_yuv!(RGB24ToNV12(
|
call_yuv!(RGB24ToNV12(
|
||||||
src.as_ptr(),
|
src.as_ptr(),
|
||||||
width * 3,
|
width * 3,
|
||||||
dst.as_mut_ptr(),
|
dst.as_mut_ptr(),
|
||||||
width,
|
width,
|
||||||
dst[y_size..].as_mut_ptr(),
|
dst[y_size..].as_mut_ptr(),
|
||||||
width,
|
width,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1119,25 +1119,73 @@ pub fn mjpg_size(src: &[u8]) -> Result<(i32, i32)> {
|
|||||||
|
|
||||||
/// Decode MJPEG directly to NV12.
|
/// Decode MJPEG directly to NV12.
|
||||||
pub fn mjpg_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Result<()> {
|
pub fn mjpg_to_nv12(src: &[u8], dst: &mut [u8], width: i32, height: i32) -> Result<()> {
|
||||||
if width % 2 != 0 || height % 2 != 0 {
|
let (y_size, output_size) = mjpg_nv12_plane_sizes(width, height)?;
|
||||||
return Err(YuvError::InvalidDimensions);
|
if dst.len() < output_size {
|
||||||
}
|
|
||||||
|
|
||||||
let w = width as usize;
|
|
||||||
let h = height as usize;
|
|
||||||
if dst.len() < nv12_size(w, h) {
|
|
||||||
return Err(YuvError::BufferTooSmall);
|
return Err(YuvError::BufferTooSmall);
|
||||||
}
|
}
|
||||||
|
|
||||||
let y_size = w * h;
|
|
||||||
let (dst_y, dst_uv) = dst.split_at_mut(y_size);
|
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(
|
call_yuv!(MJPGToNV12(
|
||||||
src.as_ptr(),
|
src.as_ptr(),
|
||||||
usize_to_size_t(src.len()),
|
usize_to_size_t(src.len()),
|
||||||
dst_y.as_mut_ptr(),
|
dst_y,
|
||||||
width,
|
width,
|
||||||
dst_uv.as_mut_ptr(),
|
dst_uv,
|
||||||
width,
|
width,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
@@ -1391,4 +1439,15 @@ mod tests {
|
|||||||
assert_eq!(converter.dimensions(), (8, 8));
|
assert_eq!(converter.dimensions(), (8, 8));
|
||||||
assert_eq!(converter.nv12_buffer().len(), nv12_size(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]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,200 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
|
|
||||||
OUTPUT_DIR="${PROJECT_ROOT}/dist/android-alsa"
|
|
||||||
ANDROID_API="${ANDROID_API:-21}"
|
|
||||||
NDK_ROOT="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
|
|
||||||
BUILD_ABIS="arm64-v8a armeabi-v7a"
|
|
||||||
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
|
|
||||||
ALSA_VERSION="${ALSA_VERSION:-1.2.15}"
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage:
|
|
||||||
scripts/build-android-alsa.sh [options]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--output <dir> Output root. Default: dist/android-alsa
|
|
||||||
--ndk <dir> Android NDK root. Defaults to ANDROID_NDK_HOME or ANDROID_NDK_ROOT.
|
|
||||||
--api <level> Android API level. Default: 21.
|
|
||||||
--abis <list> Space/comma separated ABI list. Default: arm64-v8a armeabi-v7a.
|
|
||||||
-h, --help Show this help.
|
|
||||||
|
|
||||||
The output layout is compatible with ONE_KVM_ANDROID_ALSA_ROOT:
|
|
||||||
<output>/arm64-v8a/include/alsa/asoundlib.h
|
|
||||||
<output>/arm64-v8a/lib/libasound.so
|
|
||||||
<output>/arm64-v8a/lib/pkgconfig/alsa.pc
|
|
||||||
<output>/armeabi-v7a/include/alsa/asoundlib.h
|
|
||||||
<output>/armeabi-v7a/lib/libasound.so
|
|
||||||
<output>/armeabi-v7a/lib/pkgconfig/alsa.pc
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--output)
|
|
||||||
OUTPUT_DIR="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--ndk)
|
|
||||||
NDK_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--api)
|
|
||||||
ANDROID_API="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--abis)
|
|
||||||
BUILD_ABIS="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-h | --help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[[ -n "$NDK_ROOT" ]] || fail "--ndk or ANDROID_NDK_HOME/ANDROID_NDK_ROOT is required"
|
|
||||||
[[ -d "$NDK_ROOT/toolchains/llvm/prebuilt" ]] || fail "Invalid NDK root: $NDK_ROOT"
|
|
||||||
|
|
||||||
SOURCE_DIR="${PROJECT_ROOT}/.tmp/android-alsa-src"
|
|
||||||
rm -rf "$SOURCE_DIR"
|
|
||||||
mkdir -p "${PROJECT_ROOT}/.tmp"
|
|
||||||
archive="${PROJECT_ROOT}/.tmp/alsa-lib-${ALSA_VERSION}.tar.bz2"
|
|
||||||
url="https://www.alsa-project.org/files/pub/lib/alsa-lib-${ALSA_VERSION}.tar.bz2"
|
|
||||||
echo "Downloading ALSA ${ALSA_VERSION}: $url"
|
|
||||||
curl -fL "$url" -o "$archive"
|
|
||||||
tar -xjf "$archive" -C "${PROJECT_ROOT}/.tmp"
|
|
||||||
mv "${PROJECT_ROOT}/.tmp/alsa-lib-${ALSA_VERSION}" "$SOURCE_DIR"
|
|
||||||
|
|
||||||
SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd)"
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
|
|
||||||
|
|
||||||
HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
|
|
||||||
TOOLCHAIN="${NDK_ROOT}/toolchains/llvm/prebuilt/${HOST_TAG}"
|
|
||||||
|
|
||||||
normalize_abis() {
|
|
||||||
printf '%s\n' "$BUILD_ABIS" | tr ',' ' '
|
|
||||||
}
|
|
||||||
|
|
||||||
clean_generated_source_headers() {
|
|
||||||
rm -f \
|
|
||||||
"$SOURCE_DIR/include/asoundlib.h" \
|
|
||||||
"$SOURCE_DIR/include/version.h" \
|
|
||||||
"$SOURCE_DIR/include/stamp-vh" \
|
|
||||||
"$SOURCE_DIR/include/alsa"
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one() {
|
|
||||||
local abi="$1"
|
|
||||||
local prefix build_dir
|
|
||||||
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a | armeabi-v7a) ;;
|
|
||||||
*) fail "Unsupported ABI: $abi" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
prefix="${OUTPUT_DIR}/${abi}"
|
|
||||||
build_dir="${PROJECT_ROOT}/.tmp/alsa-android-build/${abi}"
|
|
||||||
|
|
||||||
rm -rf "$build_dir"
|
|
||||||
mkdir -p "$build_dir" "$prefix"
|
|
||||||
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a)
|
|
||||||
export CC="${TOOLCHAIN}/bin/aarch64-linux-android${ANDROID_API}-clang"
|
|
||||||
export CXX="${TOOLCHAIN}/bin/aarch64-linux-android${ANDROID_API}-clang++"
|
|
||||||
export HOST_TRIPLE="aarch64-linux-android"
|
|
||||||
;;
|
|
||||||
armeabi-v7a)
|
|
||||||
export CC="${TOOLCHAIN}/bin/armv7a-linux-androideabi${ANDROID_API}-clang"
|
|
||||||
export CXX="${TOOLCHAIN}/bin/armv7a-linux-androideabi${ANDROID_API}-clang++"
|
|
||||||
export HOST_TRIPLE="arm-linux-androideabi"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
export AR="${TOOLCHAIN}/bin/llvm-ar"
|
|
||||||
export RANLIB="${TOOLCHAIN}/bin/llvm-ranlib"
|
|
||||||
export STRIP="${TOOLCHAIN}/bin/llvm-strip"
|
|
||||||
export CFLAGS="-fPIC"
|
|
||||||
export CXXFLAGS="-fPIC"
|
|
||||||
|
|
||||||
clean_generated_source_headers
|
|
||||||
|
|
||||||
if [[ ! -x "$SOURCE_DIR/configure" ]]; then
|
|
||||||
(
|
|
||||||
cd "$SOURCE_DIR"
|
|
||||||
autoreconf -fi
|
|
||||||
)
|
|
||||||
fi
|
|
||||||
|
|
||||||
(
|
|
||||||
cd "$build_dir"
|
|
||||||
pcm_plugins="copy linear route mulaw alaw adpcm rate plug multi file null empty meter hooks lfloat ladspa asym iec958 softvol extplug ioplug mmap_emul"
|
|
||||||
ctl_plugins="remap ext"
|
|
||||||
ac_cv_header_sys_shm_h=no \
|
|
||||||
"$SOURCE_DIR/configure" \
|
|
||||||
--host="$HOST_TRIPLE" \
|
|
||||||
--prefix="$prefix" \
|
|
||||||
--enable-shared \
|
|
||||||
--disable-static \
|
|
||||||
--disable-python \
|
|
||||||
--with-pcm-plugins="$pcm_plugins" \
|
|
||||||
--with-ctl-plugins="$ctl_plugins" \
|
|
||||||
--disable-doc \
|
|
||||||
--disable-oss \
|
|
||||||
--disable-seq \
|
|
||||||
--disable-ucm \
|
|
||||||
--disable-topology \
|
|
||||||
--disable-rawmidi \
|
|
||||||
--disable-hwdep \
|
|
||||||
--disable-usb \
|
|
||||||
--disable-firewire \
|
|
||||||
--disable-instr \
|
|
||||||
--disable-alisp
|
|
||||||
make -j"$JOBS"
|
|
||||||
make install
|
|
||||||
)
|
|
||||||
|
|
||||||
mkdir -p "$prefix/lib/pkgconfig"
|
|
||||||
cat > "$prefix/lib/pkgconfig/alsa.pc" <<EOF
|
|
||||||
prefix=\${pcfiledir}/../..
|
|
||||||
exec_prefix=\${prefix}
|
|
||||||
libdir=\${exec_prefix}/lib
|
|
||||||
includedir=\${prefix}/include
|
|
||||||
|
|
||||||
Name: alsa
|
|
||||||
Description: ALSA sound library
|
|
||||||
Version: 1.2.15
|
|
||||||
Libs: -L\${libdir} -lasound
|
|
||||||
Cflags: -I\${includedir}
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "Built ALSA for ${abi}: ${prefix}"
|
|
||||||
}
|
|
||||||
|
|
||||||
for abi in $(normalize_abis); do
|
|
||||||
build_one "$abi"
|
|
||||||
done
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
Done.
|
|
||||||
|
|
||||||
Use this when building the Android APK:
|
|
||||||
export ONE_KVM_ANDROID_ALSA_ROOT="${OUTPUT_DIR}"
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
@@ -1,291 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
|
|
||||||
OUTPUT_DIR="${PROJECT_ROOT}/dist/android-ffmpeg-mediacodec"
|
|
||||||
ANDROID_API="${ANDROID_API:-21}"
|
|
||||||
NDK_ROOT="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
|
|
||||||
BUILD_ABIS="arm64-v8a armeabi-v7a"
|
|
||||||
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
|
|
||||||
FFMPEG_ROCKCHIP_REV="${FFMPEG_ROCKCHIP_REV:-40c412daccf08164493da0de990eb99a8948116b}"
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage:
|
|
||||||
scripts/build-android-ffmpeg-mediacodec.sh [options]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--output <dir> Output root. Default: dist/android-ffmpeg-mediacodec
|
|
||||||
--ndk <dir> Android NDK root. Defaults to ANDROID_NDK_HOME or ANDROID_NDK_ROOT.
|
|
||||||
--api <level> Android API level. Default: 21.
|
|
||||||
--abis <list> Space/comma separated ABI list. Default: arm64-v8a armeabi-v7a.
|
|
||||||
-h, --help Show this help.
|
|
||||||
|
|
||||||
The output layout is compatible with ONE_KVM_ANDROID_FFMPEG_ROOT:
|
|
||||||
<output>/arm64-v8a/include
|
|
||||||
<output>/arm64-v8a/lib
|
|
||||||
<output>/armeabi-v7a/include
|
|
||||||
<output>/armeabi-v7a/lib
|
|
||||||
|
|
||||||
Example:
|
|
||||||
scripts/build-android-ffmpeg-mediacodec.sh --output /opt/one-kvm/android-ffmpeg
|
|
||||||
|
|
||||||
export ONE_KVM_ANDROID_FFMPEG_ROOT=/opt/one-kvm/android-ffmpeg
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--output)
|
|
||||||
OUTPUT_DIR="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--ndk)
|
|
||||||
NDK_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--api)
|
|
||||||
ANDROID_API="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--abis)
|
|
||||||
BUILD_ABIS="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-h | --help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
SOURCE_DIR="${PROJECT_ROOT}/.tmp/android-ffmpeg-check/src/ffmpeg-rockchip"
|
|
||||||
rm -rf "$SOURCE_DIR"
|
|
||||||
mkdir -p "$(dirname "$SOURCE_DIR")"
|
|
||||||
repo_url="https://github.com/nyanmisaka/ffmpeg-rockchip.git"
|
|
||||||
if [[ "${CHINAMIRRO:-0}" == "1" ]]; then
|
|
||||||
repo_url="${GH_PROXY:-https://gh-proxy.com}"
|
|
||||||
repo_url="${repo_url%/}/https://github.com/nyanmisaka/ffmpeg-rockchip.git"
|
|
||||||
fi
|
|
||||||
echo "Cloning FFmpeg source: $repo_url"
|
|
||||||
git init "$SOURCE_DIR"
|
|
||||||
(
|
|
||||||
cd "$SOURCE_DIR"
|
|
||||||
git remote add origin "$repo_url"
|
|
||||||
git fetch --depth 1 origin "$FFMPEG_ROCKCHIP_REV"
|
|
||||||
git checkout --detach FETCH_HEAD
|
|
||||||
)
|
|
||||||
|
|
||||||
[[ -n "$NDK_ROOT" ]] || fail "--ndk or ANDROID_NDK_HOME/ANDROID_NDK_ROOT is required"
|
|
||||||
|
|
||||||
SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd)"
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
|
|
||||||
|
|
||||||
HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
|
|
||||||
TOOLCHAIN="${NDK_ROOT}/toolchains/llvm/prebuilt/${HOST_TAG}"
|
|
||||||
|
|
||||||
normalize_abis() {
|
|
||||||
printf '%s\n' "$BUILD_ABIS" | tr ',' ' '
|
|
||||||
}
|
|
||||||
|
|
||||||
patch_android_ffmpeg_mjpeg_mediacodec() {
|
|
||||||
local avcodec_dir="${SOURCE_DIR}/libavcodec"
|
|
||||||
local configure_file="${SOURCE_DIR}/configure"
|
|
||||||
local mediacodecdec="${avcodec_dir}/mediacodecdec.c"
|
|
||||||
local allcodecs="${avcodec_dir}/allcodecs.c"
|
|
||||||
local makefile="${avcodec_dir}/Makefile"
|
|
||||||
|
|
||||||
python3 - "$mediacodecdec" "$allcodecs" "$configure_file" "$makefile" <<'PY'
|
|
||||||
from pathlib import Path
|
|
||||||
import sys
|
|
||||||
|
|
||||||
mediacodecdec, allcodecs, configure_file, makefile = map(Path, sys.argv[1:])
|
|
||||||
|
|
||||||
def replace_once(path: Path, old: str, new: str) -> None:
|
|
||||||
text = path.read_text()
|
|
||||||
if new in text:
|
|
||||||
return
|
|
||||||
if old not in text:
|
|
||||||
raise SystemExit(f"patch anchor not found in {path}: {old!r}")
|
|
||||||
path.write_text(text.replace(old, new, 1))
|
|
||||||
|
|
||||||
replace_once(
|
|
||||||
mediacodecdec,
|
|
||||||
"CONFIG_MPEG2_MEDIACODEC_DECODER || \\\n",
|
|
||||||
"CONFIG_MJPEG_MEDIACODEC_DECODER || \\\n"
|
|
||||||
" CONFIG_MPEG2_MEDIACODEC_DECODER || \\\n",
|
|
||||||
)
|
|
||||||
replace_once(
|
|
||||||
mediacodecdec,
|
|
||||||
"#if CONFIG_MPEG2_MEDIACODEC_DECODER\n"
|
|
||||||
" case AV_CODEC_ID_MPEG2VIDEO:",
|
|
||||||
"#if CONFIG_MJPEG_MEDIACODEC_DECODER\n"
|
|
||||||
" case AV_CODEC_ID_MJPEG:\n"
|
|
||||||
" codec_mime = \"video/mjpeg\";\n\n"
|
|
||||||
" ret = common_set_extradata(avctx, format);\n"
|
|
||||||
" if (ret < 0)\n"
|
|
||||||
" goto done;\n"
|
|
||||||
" break;\n"
|
|
||||||
"#endif\n"
|
|
||||||
"#if CONFIG_MPEG2_MEDIACODEC_DECODER\n"
|
|
||||||
" case AV_CODEC_ID_MPEG2VIDEO:",
|
|
||||||
)
|
|
||||||
replace_once(
|
|
||||||
mediacodecdec,
|
|
||||||
"#if CONFIG_MPEG2_MEDIACODEC_DECODER\n"
|
|
||||||
"DECLARE_MEDIACODEC_VDEC(mpeg2, \"MPEG-2\", AV_CODEC_ID_MPEG2VIDEO, NULL)",
|
|
||||||
"#if CONFIG_MJPEG_MEDIACODEC_DECODER\n"
|
|
||||||
"DECLARE_MEDIACODEC_VDEC(mjpeg, \"MJPEG\", AV_CODEC_ID_MJPEG, NULL)\n"
|
|
||||||
"#endif\n\n"
|
|
||||||
"#if CONFIG_MPEG2_MEDIACODEC_DECODER\n"
|
|
||||||
"DECLARE_MEDIACODEC_VDEC(mpeg2, \"MPEG-2\", AV_CODEC_ID_MPEG2VIDEO, NULL)",
|
|
||||||
)
|
|
||||||
replace_once(
|
|
||||||
allcodecs,
|
|
||||||
"extern const FFCodec ff_mjpeg_cuvid_decoder;",
|
|
||||||
"extern const FFCodec ff_mjpeg_cuvid_decoder;\n"
|
|
||||||
"extern const FFCodec ff_mjpeg_mediacodec_decoder;",
|
|
||||||
)
|
|
||||||
replace_once(
|
|
||||||
configure_file,
|
|
||||||
'mjpeg_cuvid_decoder_deps="cuvid"',
|
|
||||||
'mjpeg_cuvid_decoder_deps="cuvid"\n'
|
|
||||||
'mjpeg_mediacodec_decoder_deps="mediacodec"',
|
|
||||||
)
|
|
||||||
replace_once(
|
|
||||||
makefile,
|
|
||||||
"OBJS-$(CONFIG_MJPEG_RKMPP_DECODER)",
|
|
||||||
"OBJS-$(CONFIG_MJPEG_MEDIACODEC_DECODER) += mediacodecdec.o\n"
|
|
||||||
"OBJS-$(CONFIG_MJPEG_RKMPP_DECODER)",
|
|
||||||
)
|
|
||||||
PY
|
|
||||||
}
|
|
||||||
|
|
||||||
abi_arch() {
|
|
||||||
case "$1" in
|
|
||||||
arm64-v8a) echo "aarch64" ;;
|
|
||||||
armeabi-v7a) echo "arm" ;;
|
|
||||||
*) fail "Unsupported ABI: $1" ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
abi_cpu() {
|
|
||||||
case "$1" in
|
|
||||||
arm64-v8a) echo "armv8-a" ;;
|
|
||||||
armeabi-v7a) echo "armv7-a" ;;
|
|
||||||
*) fail "Unsupported ABI: $1" ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
abi_target() {
|
|
||||||
case "$1" in
|
|
||||||
arm64-v8a) echo "aarch64-linux-android" ;;
|
|
||||||
armeabi-v7a) echo "armv7a-linux-androideabi" ;;
|
|
||||||
*) fail "Unsupported ABI: $1" ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one() {
|
|
||||||
local abi="$1"
|
|
||||||
local arch cpu target prefix build_dir cc cxx ar ranlib strip extra_cflags extra_ldflags
|
|
||||||
|
|
||||||
arch="$(abi_arch "$abi")"
|
|
||||||
cpu="$(abi_cpu "$abi")"
|
|
||||||
target="$(abi_target "$abi")"
|
|
||||||
prefix="${OUTPUT_DIR}/${abi}"
|
|
||||||
build_dir="${PROJECT_ROOT}/.tmp/ffmpeg-android-build/${abi}"
|
|
||||||
cc="${TOOLCHAIN}/bin/${target}${ANDROID_API}-clang"
|
|
||||||
cxx="${TOOLCHAIN}/bin/${target}${ANDROID_API}-clang++"
|
|
||||||
ar="${TOOLCHAIN}/bin/llvm-ar"
|
|
||||||
ranlib="${TOOLCHAIN}/bin/llvm-ranlib"
|
|
||||||
strip="${TOOLCHAIN}/bin/llvm-strip"
|
|
||||||
extra_cflags="-fPIC"
|
|
||||||
extra_ldflags=""
|
|
||||||
|
|
||||||
if [[ "$abi" == "armeabi-v7a" ]]; then
|
|
||||||
extra_cflags="${extra_cflags} -march=armv7-a -mfloat-abi=softfp -mfpu=neon"
|
|
||||||
extra_ldflags="${extra_ldflags} -Wl,--fix-cortex-a8"
|
|
||||||
fi
|
|
||||||
|
|
||||||
rm -rf "$build_dir"
|
|
||||||
mkdir -p "$build_dir" "$prefix"
|
|
||||||
|
|
||||||
(
|
|
||||||
cd "$build_dir"
|
|
||||||
"${SOURCE_DIR}/configure" \
|
|
||||||
--prefix="$prefix" \
|
|
||||||
--target-os=android \
|
|
||||||
--arch="$arch" \
|
|
||||||
--cpu="$cpu" \
|
|
||||||
--cc="$cc" \
|
|
||||||
--cxx="$cxx" \
|
|
||||||
--ar="$ar" \
|
|
||||||
--ranlib="$ranlib" \
|
|
||||||
--strip="$strip" \
|
|
||||||
--cross-prefix="${TOOLCHAIN}/bin/llvm-" \
|
|
||||||
--sysroot="${TOOLCHAIN}/sysroot" \
|
|
||||||
--enable-cross-compile \
|
|
||||||
--enable-static \
|
|
||||||
--disable-shared \
|
|
||||||
--disable-programs \
|
|
||||||
--disable-doc \
|
|
||||||
--disable-avdevice \
|
|
||||||
--disable-avformat \
|
|
||||||
--disable-avfilter \
|
|
||||||
--disable-swscale \
|
|
||||||
--disable-swresample \
|
|
||||||
--disable-postproc \
|
|
||||||
--disable-network \
|
|
||||||
--disable-everything \
|
|
||||||
--disable-hwaccels \
|
|
||||||
--disable-cuda-llvm \
|
|
||||||
--disable-v4l2-m2m \
|
|
||||||
--disable-vulkan \
|
|
||||||
--enable-pthreads \
|
|
||||||
--enable-jni \
|
|
||||||
--enable-mediacodec \
|
|
||||||
--enable-decoder=mjpeg_mediacodec \
|
|
||||||
--enable-decoder=mjpeg \
|
|
||||||
--enable-encoder=h264_mediacodec \
|
|
||||||
--enable-encoder=hevc_mediacodec \
|
|
||||||
--enable-parser=mjpeg \
|
|
||||||
--enable-bsf=h264_metadata \
|
|
||||||
--enable-bsf=hevc_metadata \
|
|
||||||
--enable-protocol=file \
|
|
||||||
--extra-cflags="$extra_cflags" \
|
|
||||||
--extra-ldflags="$extra_ldflags"
|
|
||||||
|
|
||||||
make -j"$JOBS"
|
|
||||||
make install
|
|
||||||
)
|
|
||||||
|
|
||||||
echo "Built FFmpeg MediaCodec for ${abi}: ${prefix}"
|
|
||||||
}
|
|
||||||
|
|
||||||
patch_android_ffmpeg_mjpeg_mediacodec
|
|
||||||
|
|
||||||
for abi in $(normalize_abis); do
|
|
||||||
build_one "$abi"
|
|
||||||
done
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
Done.
|
|
||||||
|
|
||||||
Use this when building the Android APK:
|
|
||||||
export ONE_KVM_ANDROID_FFMPEG_ROOT="${OUTPUT_DIR}"
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
|
|
||||||
OUTPUT_DIR="${PROJECT_ROOT}/dist/android-libyuv"
|
|
||||||
JPEG_ROOT="${ONE_KVM_ANDROID_TURBOJPEG_ROOT:-${PROJECT_ROOT}/dist/android-turbojpeg}"
|
|
||||||
ANDROID_API="${ANDROID_API:-21}"
|
|
||||||
NDK_ROOT="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
|
|
||||||
BUILD_ABIS="arm64-v8a armeabi-v7a"
|
|
||||||
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
|
|
||||||
LIBYUV_REV="${LIBYUV_REV:-957f295ea946cbbd13fcfc46e7066f2efa801233}"
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage:
|
|
||||||
scripts/build-android-libyuv.sh [options]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--output <dir> Output root. Default: dist/android-libyuv
|
|
||||||
--ndk <dir> Android NDK root. Defaults to ANDROID_NDK_HOME or ANDROID_NDK_ROOT.
|
|
||||||
--api <level> Android API level. Default: 21.
|
|
||||||
--abis <list> Space/comma separated ABI list. Default: arm64-v8a armeabi-v7a.
|
|
||||||
--jpeg-root <dir> Android libjpeg root. Defaults to ONE_KVM_ANDROID_TURBOJPEG_ROOT
|
|
||||||
or dist/android-turbojpeg when present. Enables libyuv HAVE_JPEG.
|
|
||||||
-h, --help Show this help.
|
|
||||||
|
|
||||||
The output layout is compatible with ONE_KVM_ANDROID_LIBYUV_ROOT:
|
|
||||||
<output>/arm64-v8a/include
|
|
||||||
<output>/arm64-v8a/lib/libyuv.a
|
|
||||||
<output>/armeabi-v7a/include
|
|
||||||
<output>/armeabi-v7a/lib/libyuv.a
|
|
||||||
|
|
||||||
Example:
|
|
||||||
scripts/build-android-libyuv.sh --output /opt/one-kvm/android-libyuv
|
|
||||||
|
|
||||||
export ONE_KVM_ANDROID_LIBYUV_ROOT=/opt/one-kvm/android-libyuv
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--output)
|
|
||||||
OUTPUT_DIR="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--ndk)
|
|
||||||
NDK_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--api)
|
|
||||||
ANDROID_API="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--abis)
|
|
||||||
BUILD_ABIS="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--jpeg-root)
|
|
||||||
JPEG_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-h | --help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[[ -n "$NDK_ROOT" ]] || fail "--ndk or ANDROID_NDK_HOME/ANDROID_NDK_ROOT is required"
|
|
||||||
[[ -d "$NDK_ROOT/toolchains/llvm/prebuilt" ]] || fail "Invalid NDK root: $NDK_ROOT"
|
|
||||||
|
|
||||||
SOURCE_DIR="${PROJECT_ROOT}/.tmp/android-libyuv-src"
|
|
||||||
rm -rf "$SOURCE_DIR"
|
|
||||||
repo_url="https://github.com/lemenkov/libyuv.git"
|
|
||||||
if [[ "${CHINAMIRRO:-0}" == "1" ]]; then
|
|
||||||
repo_url="${GH_PROXY:-https://gh-proxy.com}"
|
|
||||||
repo_url="${repo_url%/}/https://github.com/lemenkov/libyuv.git"
|
|
||||||
fi
|
|
||||||
echo "Cloning libyuv source: $repo_url"
|
|
||||||
git init "$SOURCE_DIR"
|
|
||||||
(
|
|
||||||
cd "$SOURCE_DIR"
|
|
||||||
git remote add origin "$repo_url"
|
|
||||||
git fetch --depth 1 origin "$LIBYUV_REV"
|
|
||||||
git checkout --detach FETCH_HEAD
|
|
||||||
)
|
|
||||||
|
|
||||||
SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd)"
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
|
|
||||||
|
|
||||||
HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
|
|
||||||
ANDROID_TOOLCHAIN_FILE="${NDK_ROOT}/build/cmake/android.toolchain.cmake"
|
|
||||||
[[ -f "$ANDROID_TOOLCHAIN_FILE" ]] || fail "NDK CMake toolchain not found: $ANDROID_TOOLCHAIN_FILE"
|
|
||||||
|
|
||||||
normalize_abis() {
|
|
||||||
printf '%s\n' "$BUILD_ABIS" | tr ',' ' '
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one() {
|
|
||||||
local abi="$1"
|
|
||||||
local prefix build_dir jpeg_include jpeg_library
|
|
||||||
local -a jpeg_args
|
|
||||||
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a | armeabi-v7a | x86 | x86_64) ;;
|
|
||||||
*) fail "Unsupported ABI: $abi" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
prefix="${OUTPUT_DIR}/${abi}"
|
|
||||||
build_dir="${PROJECT_ROOT}/.tmp/libyuv-android-build/${abi}"
|
|
||||||
|
|
||||||
rm -rf "$build_dir"
|
|
||||||
mkdir -p "$build_dir" "$prefix"
|
|
||||||
|
|
||||||
jpeg_include="$JPEG_ROOT/$abi/include"
|
|
||||||
jpeg_library="$JPEG_ROOT/$abi/lib/libjpeg.a"
|
|
||||||
jpeg_args=()
|
|
||||||
if [[ -f "$jpeg_library" && -f "$jpeg_include/jpeglib.h" ]]; then
|
|
||||||
jpeg_args=(
|
|
||||||
-DJPEG_FOUND=TRUE
|
|
||||||
-DJPEG_INCLUDE_DIR="$jpeg_include"
|
|
||||||
-DJPEG_LIBRARY="$jpeg_library"
|
|
||||||
-DCMAKE_C_FLAGS="-DHAVE_JPEG"
|
|
||||||
-DCMAKE_CXX_FLAGS="-DHAVE_JPEG"
|
|
||||||
)
|
|
||||||
else
|
|
||||||
echo "Warning: Android libjpeg not found for ${abi}; libyuv MJPEG APIs will be disabled." >&2
|
|
||||||
echo " Checked: $jpeg_library and $jpeg_include/jpeglib.h" >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
cmake -S "$SOURCE_DIR" -B "$build_dir" \
|
|
||||||
-DCMAKE_TOOLCHAIN_FILE="$ANDROID_TOOLCHAIN_FILE" \
|
|
||||||
-DANDROID_ABI="$abi" \
|
|
||||||
-DANDROID_PLATFORM="android-${ANDROID_API}" \
|
|
||||||
-DANDROID_STL=c++_shared \
|
|
||||||
-DCMAKE_BUILD_TYPE=Release \
|
|
||||||
-DCMAKE_INSTALL_PREFIX="$prefix" \
|
|
||||||
-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
|
|
||||||
-DBUILD_SHARED_LIBS=OFF \
|
|
||||||
-DUNIT_TEST=OFF \
|
|
||||||
-DTEST=OFF \
|
|
||||||
"${jpeg_args[@]}"
|
|
||||||
|
|
||||||
cmake --build "$build_dir" --target yuv --parallel "$JOBS"
|
|
||||||
|
|
||||||
mkdir -p "$prefix/lib" "$prefix/include"
|
|
||||||
if [[ -f "$build_dir/libyuv.a" ]]; then
|
|
||||||
cp "$build_dir/libyuv.a" "$prefix/lib/libyuv.a"
|
|
||||||
elif [[ -f "$build_dir/lib/libyuv.a" ]]; then
|
|
||||||
cp "$build_dir/lib/libyuv.a" "$prefix/lib/libyuv.a"
|
|
||||||
else
|
|
||||||
fail "Built libyuv.a was not found under: $build_dir"
|
|
||||||
fi
|
|
||||||
cp -R "$SOURCE_DIR/include/." "$prefix/include/"
|
|
||||||
|
|
||||||
echo "Built libyuv for ${abi}: ${prefix}"
|
|
||||||
}
|
|
||||||
|
|
||||||
for abi in $(normalize_abis); do
|
|
||||||
build_one "$abi"
|
|
||||||
done
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
Done.
|
|
||||||
|
|
||||||
Use this when building the Android APK:
|
|
||||||
export ONE_KVM_ANDROID_LIBYUV_ROOT="${OUTPUT_DIR}"
|
|
||||||
export ONE_KVM_ANDROID_TURBOJPEG_ROOT="${JPEG_ROOT}"
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
|
|
||||||
OUTPUT_DIR="${PROJECT_ROOT}/dist/android-opus"
|
|
||||||
ANDROID_API="${ANDROID_API:-21}"
|
|
||||||
NDK_ROOT="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
|
|
||||||
BUILD_ABIS="arm64-v8a armeabi-v7a"
|
|
||||||
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
|
|
||||||
OPUS_VERSION="${OPUS_VERSION:-1.5.2}"
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage:
|
|
||||||
scripts/build-android-opus.sh [options]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--output <dir> Output root. Default: dist/android-opus
|
|
||||||
--ndk <dir> Android NDK root. Defaults to ANDROID_NDK_HOME or ANDROID_NDK_ROOT.
|
|
||||||
--api <level> Android API level. Default: 21.
|
|
||||||
--abis <list> Space/comma separated ABI list. Default: arm64-v8a armeabi-v7a.
|
|
||||||
-h, --help Show this help.
|
|
||||||
|
|
||||||
The output layout is compatible with ONE_KVM_ANDROID_OPUS_ROOT:
|
|
||||||
<output>/arm64-v8a/include/opus/opus.h
|
|
||||||
<output>/arm64-v8a/lib/libopus.so
|
|
||||||
<output>/armeabi-v7a/include/opus/opus.h
|
|
||||||
<output>/armeabi-v7a/lib/libopus.so
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--output)
|
|
||||||
OUTPUT_DIR="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--ndk)
|
|
||||||
NDK_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--api)
|
|
||||||
ANDROID_API="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--abis)
|
|
||||||
BUILD_ABIS="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-h | --help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[[ -n "$NDK_ROOT" ]] || fail "--ndk or ANDROID_NDK_HOME/ANDROID_NDK_ROOT is required"
|
|
||||||
[[ -d "$NDK_ROOT/toolchains/llvm/prebuilt" ]] || fail "Invalid NDK root: $NDK_ROOT"
|
|
||||||
|
|
||||||
SOURCE_DIR="${PROJECT_ROOT}/.tmp/android-opus-src"
|
|
||||||
rm -rf "$SOURCE_DIR"
|
|
||||||
mkdir -p "$SOURCE_DIR"
|
|
||||||
tarball="${PROJECT_ROOT}/.tmp/opus-${OPUS_VERSION}.tar.gz"
|
|
||||||
url="https://downloads.xiph.org/releases/opus/opus-${OPUS_VERSION}.tar.gz"
|
|
||||||
curl -fsSL "$url" -o "$tarball"
|
|
||||||
tar -xzf "$tarball" -C "$SOURCE_DIR" --strip-components=1
|
|
||||||
|
|
||||||
SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd)"
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
|
|
||||||
|
|
||||||
HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
|
|
||||||
TOOLCHAIN="${NDK_ROOT}/toolchains/llvm/prebuilt/${HOST_TAG}"
|
|
||||||
|
|
||||||
normalize_abis() {
|
|
||||||
printf '%s\n' "$BUILD_ABIS" | tr ',' ' '
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one() {
|
|
||||||
local abi="$1"
|
|
||||||
local prefix build_dir
|
|
||||||
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a | armeabi-v7a) ;;
|
|
||||||
*) fail "Unsupported ABI: $abi" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
prefix="${OUTPUT_DIR}/${abi}"
|
|
||||||
build_dir="${PROJECT_ROOT}/.tmp/opus-android-build/${abi}"
|
|
||||||
|
|
||||||
rm -rf "$build_dir"
|
|
||||||
mkdir -p "$build_dir" "$prefix"
|
|
||||||
|
|
||||||
(
|
|
||||||
cd "$build_dir"
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a)
|
|
||||||
export CC="${TOOLCHAIN}/bin/aarch64-linux-android${ANDROID_API}-clang"
|
|
||||||
export CXX="${TOOLCHAIN}/bin/aarch64-linux-android${ANDROID_API}-clang++"
|
|
||||||
export HOST_TRIPLE="aarch64-linux-android"
|
|
||||||
;;
|
|
||||||
armeabi-v7a)
|
|
||||||
export CC="${TOOLCHAIN}/bin/armv7a-linux-androideabi${ANDROID_API}-clang"
|
|
||||||
export CXX="${TOOLCHAIN}/bin/armv7a-linux-androideabi${ANDROID_API}-clang++"
|
|
||||||
export HOST_TRIPLE="arm-linux-androideabi"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
export AR="${TOOLCHAIN}/bin/llvm-ar"
|
|
||||||
export RANLIB="${TOOLCHAIN}/bin/llvm-ranlib"
|
|
||||||
export STRIP="${TOOLCHAIN}/bin/llvm-strip"
|
|
||||||
export CFLAGS="-fPIC"
|
|
||||||
export CXXFLAGS="-fPIC"
|
|
||||||
export LDFLAGS=""
|
|
||||||
"$SOURCE_DIR/configure" \
|
|
||||||
--prefix="$prefix" \
|
|
||||||
--host="$HOST_TRIPLE" \
|
|
||||||
--disable-static \
|
|
||||||
--enable-shared \
|
|
||||||
--disable-doc \
|
|
||||||
--disable-extra-programs \
|
|
||||||
--with-pic
|
|
||||||
make -j"$JOBS"
|
|
||||||
make install
|
|
||||||
)
|
|
||||||
|
|
||||||
echo "Built Opus for ${abi}: ${prefix}"
|
|
||||||
}
|
|
||||||
|
|
||||||
for abi in $(normalize_abis); do
|
|
||||||
build_one "$abi"
|
|
||||||
done
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
Done.
|
|
||||||
|
|
||||||
Use this when building the Android APK:
|
|
||||||
export ONE_KVM_ANDROID_OPUS_ROOT="${OUTPUT_DIR}"
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
|
|
||||||
OUTPUT_DIR="${PROJECT_ROOT}/dist/android-turbojpeg"
|
|
||||||
ANDROID_API="${ANDROID_API:-21}"
|
|
||||||
NDK_ROOT="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
|
|
||||||
BUILD_ABIS="arm64-v8a armeabi-v7a"
|
|
||||||
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
|
|
||||||
LIBJPEG_TURBO_VERSION="${LIBJPEG_TURBO_VERSION:-3.1.4.1}"
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Usage:
|
|
||||||
scripts/build-android-turbojpeg.sh [options]
|
|
||||||
|
|
||||||
Options:
|
|
||||||
--output <dir> Output root. Default: dist/android-turbojpeg
|
|
||||||
--ndk <dir> Android NDK root. Defaults to ANDROID_NDK_HOME or ANDROID_NDK_ROOT.
|
|
||||||
--api <level> Android API level. Default: 21.
|
|
||||||
--abis <list> Space/comma separated ABI list. Default: arm64-v8a armeabi-v7a.
|
|
||||||
-h, --help Show this help.
|
|
||||||
|
|
||||||
The output layout is compatible with ONE_KVM_ANDROID_TURBOJPEG_ROOT:
|
|
||||||
<output>/arm64-v8a/include/turbojpeg.h
|
|
||||||
<output>/arm64-v8a/lib/libturbojpeg.a
|
|
||||||
<output>/arm64-v8a/include/jpeglib.h
|
|
||||||
<output>/arm64-v8a/lib/libjpeg.a
|
|
||||||
<output>/armeabi-v7a/include/turbojpeg.h
|
|
||||||
<output>/armeabi-v7a/lib/libturbojpeg.a
|
|
||||||
<output>/armeabi-v7a/include/jpeglib.h
|
|
||||||
<output>/armeabi-v7a/lib/libjpeg.a
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
fail() {
|
|
||||||
echo "Error: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--output)
|
|
||||||
OUTPUT_DIR="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--ndk)
|
|
||||||
NDK_ROOT="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--api)
|
|
||||||
ANDROID_API="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--abis)
|
|
||||||
BUILD_ABIS="${2:-}"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-h | --help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
fail "Unknown argument: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[[ -n "$NDK_ROOT" ]] || fail "--ndk or ANDROID_NDK_HOME/ANDROID_NDK_ROOT is required"
|
|
||||||
[[ -d "$NDK_ROOT/toolchains/llvm/prebuilt" ]] || fail "Invalid NDK root: $NDK_ROOT"
|
|
||||||
|
|
||||||
SOURCE_DIR="${PROJECT_ROOT}/.tmp/android-turbojpeg-src"
|
|
||||||
rm -rf "$SOURCE_DIR"
|
|
||||||
repo_url="https://github.com/libjpeg-turbo/libjpeg-turbo.git"
|
|
||||||
if [[ "${CHINAMIRRO:-0}" == "1" ]]; then
|
|
||||||
repo_url="${GH_PROXY:-https://gh-proxy.com}"
|
|
||||||
repo_url="${repo_url%/}/https://github.com/libjpeg-turbo/libjpeg-turbo.git"
|
|
||||||
fi
|
|
||||||
echo "Cloning libjpeg-turbo ${LIBJPEG_TURBO_VERSION}: $repo_url"
|
|
||||||
git init "$SOURCE_DIR"
|
|
||||||
(
|
|
||||||
cd "$SOURCE_DIR"
|
|
||||||
git remote add origin "$repo_url"
|
|
||||||
git fetch --depth 1 origin "refs/tags/$LIBJPEG_TURBO_VERSION"
|
|
||||||
git checkout --detach FETCH_HEAD
|
|
||||||
)
|
|
||||||
|
|
||||||
SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd)"
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
OUTPUT_DIR="$(cd "$OUTPUT_DIR" && pwd)"
|
|
||||||
|
|
||||||
HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
|
|
||||||
ANDROID_TOOLCHAIN_FILE="${NDK_ROOT}/build/cmake/android.toolchain.cmake"
|
|
||||||
[[ -f "$ANDROID_TOOLCHAIN_FILE" ]] || fail "NDK CMake toolchain not found: $ANDROID_TOOLCHAIN_FILE"
|
|
||||||
|
|
||||||
normalize_abis() {
|
|
||||||
printf '%s\n' "$BUILD_ABIS" | tr ',' ' '
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one() {
|
|
||||||
local abi="$1"
|
|
||||||
local prefix build_dir lib_path
|
|
||||||
|
|
||||||
case "$abi" in
|
|
||||||
arm64-v8a | armeabi-v7a | x86 | x86_64) ;;
|
|
||||||
*) fail "Unsupported ABI: $abi" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
prefix="${OUTPUT_DIR}/${abi}"
|
|
||||||
build_dir="${PROJECT_ROOT}/.tmp/turbojpeg-android-build/${abi}"
|
|
||||||
|
|
||||||
rm -rf "$build_dir"
|
|
||||||
mkdir -p "$build_dir" "$prefix"
|
|
||||||
|
|
||||||
cmake -S "$SOURCE_DIR" -B "$build_dir" \
|
|
||||||
-DCMAKE_TOOLCHAIN_FILE="$ANDROID_TOOLCHAIN_FILE" \
|
|
||||||
-DANDROID_ABI="$abi" \
|
|
||||||
-DANDROID_PLATFORM="android-${ANDROID_API}" \
|
|
||||||
-DANDROID_STL=c++_shared \
|
|
||||||
-DCMAKE_BUILD_TYPE=Release \
|
|
||||||
-DCMAKE_INSTALL_PREFIX="$prefix" \
|
|
||||||
-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
|
|
||||||
-DCMAKE_C_FLAGS="-DANDROID -Dstderr=__sF+2" \
|
|
||||||
-DCMAKE_CXX_FLAGS="-DANDROID -Dstderr=__sF+2" \
|
|
||||||
-DENABLE_SHARED=OFF \
|
|
||||||
-DENABLE_STATIC=ON \
|
|
||||||
-DWITH_TURBOJPEG=ON \
|
|
||||||
-DWITH_JAVA=OFF \
|
|
||||||
-DWITH_12BIT=OFF \
|
|
||||||
-DWITH_ARITH_DEC=ON \
|
|
||||||
-DWITH_ARITH_ENC=ON
|
|
||||||
|
|
||||||
cmake --build "$build_dir" --target turbojpeg-static jpeg-static --parallel "$JOBS"
|
|
||||||
|
|
||||||
mkdir -p "$prefix/lib" "$prefix/include"
|
|
||||||
lib_path="$build_dir/libturbojpeg.a"
|
|
||||||
if [[ ! -f "$lib_path" ]]; then
|
|
||||||
lib_path="$build_dir/lib/libturbojpeg.a"
|
|
||||||
fi
|
|
||||||
[[ -f "$lib_path" ]] || fail "Built libturbojpeg.a was not found under: $build_dir"
|
|
||||||
|
|
||||||
cp "$lib_path" "$prefix/lib/libturbojpeg.a"
|
|
||||||
lib_path="$build_dir/libjpeg.a"
|
|
||||||
if [[ ! -f "$lib_path" ]]; then
|
|
||||||
lib_path="$build_dir/lib/libjpeg.a"
|
|
||||||
fi
|
|
||||||
[[ -f "$lib_path" ]] || fail "Built libjpeg.a was not found under: $build_dir"
|
|
||||||
|
|
||||||
cp "$lib_path" "$prefix/lib/libjpeg.a"
|
|
||||||
cp "$SOURCE_DIR/src/turbojpeg.h" "$prefix/include/turbojpeg.h"
|
|
||||||
cp "$SOURCE_DIR/src/jerror.h" "$prefix/include/jerror.h"
|
|
||||||
cp "$SOURCE_DIR/src/jmorecfg.h" "$prefix/include/jmorecfg.h"
|
|
||||||
cp "$SOURCE_DIR/src/jpeglib.h" "$prefix/include/jpeglib.h"
|
|
||||||
cp "$build_dir/jconfig.h" "$prefix/include/jconfig.h"
|
|
||||||
|
|
||||||
echo "Built TurboJPEG for ${abi}: ${prefix}"
|
|
||||||
}
|
|
||||||
|
|
||||||
for abi in $(normalize_abis); do
|
|
||||||
build_one "$abi"
|
|
||||||
done
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
Done.
|
|
||||||
|
|
||||||
Use this when building the Android APK:
|
|
||||||
export ONE_KVM_ANDROID_TURBOJPEG_ROOT="${OUTPUT_DIR}"
|
|
||||||
cd android && ./gradlew :app:assembleDebug
|
|
||||||
EOF
|
|
||||||
@@ -20,6 +20,9 @@ typeshare "$PROJECT_ROOT/src" \
|
|||||||
--lang=typescript \
|
--lang=typescript \
|
||||||
--output-file="$OUTPUT_FILE"
|
--output-file="$OUTPUT_FILE"
|
||||||
|
|
||||||
|
# Keep generated output stable for git diff --check.
|
||||||
|
perl -0pi -e 's/\n+\z/\n/' "$OUTPUT_FILE"
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "TypeScript types generated successfully!"
|
echo "TypeScript types generated successfully!"
|
||||||
echo "Output: $OUTPUT_FILE"
|
echo "Output: $OUTPUT_FILE"
|
||||||
|
|||||||
@@ -8,15 +8,22 @@ use tracing::{debug, info, warn};
|
|||||||
|
|
||||||
use super::executor::{timing, AtxKeyExecutor};
|
use super::executor::{timing, AtxKeyExecutor};
|
||||||
use super::led::LedSensor;
|
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};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct AtxControllerConfig {
|
pub struct AtxControllerConfig {
|
||||||
pub enabled: bool,
|
pub enabled: bool,
|
||||||
pub power: AtxKeyConfig,
|
pub driver: AtxDriverType,
|
||||||
pub reset: AtxKeyConfig,
|
pub device: String,
|
||||||
pub led: AtxLedConfig,
|
pub baud_rate: u32,
|
||||||
|
pub power: AtxOutputBinding,
|
||||||
|
pub reset: AtxOutputBinding,
|
||||||
|
pub led: AtxInputBinding,
|
||||||
|
pub hdd: AtxInputBinding,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Grouped together to reduce lock acquisitions
|
/// Grouped together to reduce lock acquisitions
|
||||||
@@ -25,6 +32,7 @@ struct AtxInner {
|
|||||||
power_executor: Option<AtxKeyExecutor>,
|
power_executor: Option<AtxKeyExecutor>,
|
||||||
reset_executor: Option<AtxKeyExecutor>,
|
reset_executor: Option<AtxKeyExecutor>,
|
||||||
led_sensor: Option<LedSensor>,
|
led_sensor: Option<LedSensor>,
|
||||||
|
hdd_sensor: Option<LedSensor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Manages ATX power control through independent executors for each action.
|
/// Manages ATX power control through independent executors for each action.
|
||||||
@@ -34,14 +42,44 @@ pub struct AtxController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AtxController {
|
impl AtxController {
|
||||||
fn should_share_serial_device(power: &AtxKeyConfig, reset: &AtxKeyConfig) -> bool {
|
fn build_key_config(
|
||||||
power.is_configured()
|
config: &AtxControllerConfig,
|
||||||
&& reset.is_configured()
|
binding: &AtxOutputBinding,
|
||||||
&& power.driver == super::types::AtxDriverType::Serial
|
) -> Option<AtxKeyConfig> {
|
||||||
&& reset.driver == super::types::AtxDriverType::Serial
|
if !binding.is_configured_for(config.driver, &config.device) {
|
||||||
&& !power.device.is_empty()
|
return None;
|
||||||
&& power.device == reset.device
|
}
|
||||||
&& power.baud_rate == reset.baud_rate
|
|
||||||
|
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(
|
async fn init_key_executor(
|
||||||
@@ -63,75 +101,80 @@ impl AtxController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn init_components(inner: &mut AtxInner) {
|
async fn init_components(inner: &mut AtxInner) {
|
||||||
if Self::should_share_serial_device(&inner.config.power, &inner.config.reset) {
|
let (power_config, reset_config) = Self::runtime_key_configs(&inner.config);
|
||||||
match AtxKeyExecutor::open_shared_serial(
|
|
||||||
&inner.config.power.device,
|
if Self::should_share_serial_device(&inner.config) {
|
||||||
inner.config.power.baud_rate,
|
match AtxKeyExecutor::open_shared_serial(&inner.config.device, inner.config.baud_rate) {
|
||||||
) {
|
|
||||||
Ok(shared_serial) => {
|
Ok(shared_serial) => {
|
||||||
for (slot, warn_label, info_label, config, serial) in [
|
for (slot, warn_label, info_label, config, serial) in [
|
||||||
(
|
(
|
||||||
&mut inner.power_executor,
|
&mut inner.power_executor,
|
||||||
"power",
|
"power",
|
||||||
"Power",
|
"Power",
|
||||||
inner.config.power.clone(),
|
power_config.clone(),
|
||||||
shared_serial.clone(),
|
shared_serial.clone(),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
&mut inner.reset_executor,
|
&mut inner.reset_executor,
|
||||||
"reset",
|
"reset",
|
||||||
"Reset",
|
"Reset",
|
||||||
inner.config.reset.clone(),
|
reset_config.clone(),
|
||||||
shared_serial,
|
shared_serial,
|
||||||
),
|
),
|
||||||
] {
|
] {
|
||||||
let executor =
|
if let Some(config) = config {
|
||||||
AtxKeyExecutor::new_with_shared_serial(config.clone(), serial);
|
let executor =
|
||||||
*slot =
|
AtxKeyExecutor::new_with_shared_serial(config.clone(), serial);
|
||||||
Self::init_key_executor(warn_label, info_label, config, executor).await;
|
*slot =
|
||||||
|
Self::init_key_executor(warn_label, info_label, config, executor)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!(
|
warn!(
|
||||||
"Failed to open shared serial device {} for ATX power/reset: {}",
|
"Failed to open shared serial device {} for ATX power/reset: {}",
|
||||||
inner.config.power.device, e
|
inner.config.device, e
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (slot, warn_label, info_label, config) in [
|
for (slot, warn_label, info_label, config) in [
|
||||||
(
|
(&mut inner.power_executor, "power", "Power", power_config),
|
||||||
&mut inner.power_executor,
|
(&mut inner.reset_executor, "reset", "Reset", reset_config),
|
||||||
"power",
|
|
||||||
"Power",
|
|
||||||
inner.config.power.clone(),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
&mut inner.reset_executor,
|
|
||||||
"reset",
|
|
||||||
"Reset",
|
|
||||||
inner.config.reset.clone(),
|
|
||||||
),
|
|
||||||
] {
|
] {
|
||||||
if config.is_configured() {
|
if let Some(config) = config {
|
||||||
let executor = AtxKeyExecutor::new(config.clone());
|
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());
|
let mut sensor = LedSensor::new(inner.config.led.clone());
|
||||||
if let Err(e) = sensor.init().await {
|
if let Err(e) = sensor.init().await {
|
||||||
warn!("Failed to initialize LED sensor: {}", e);
|
warn!("Failed to initialize LED sensor: {}", e);
|
||||||
} else {
|
} else {
|
||||||
info!(
|
info!(
|
||||||
"LED sensor initialized on {} pin {}",
|
"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);
|
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) {
|
async fn shutdown_components(inner: &mut AtxInner) {
|
||||||
@@ -153,6 +196,13 @@ impl AtxController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
inner.led_sensor = None;
|
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 {
|
async fn read_power_status(sensor: Option<&LedSensor>) -> PowerStatus {
|
||||||
@@ -169,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 {
|
pub fn new(config: AtxControllerConfig) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: RwLock::new(AtxInner {
|
inner: RwLock::new(AtxInner {
|
||||||
@@ -176,6 +241,7 @@ impl AtxController {
|
|||||||
power_executor: None,
|
power_executor: None,
|
||||||
reset_executor: None,
|
reset_executor: None,
|
||||||
led_sensor: None,
|
led_sensor: None,
|
||||||
|
hdd_sensor: None,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -270,13 +336,21 @@ impl AtxController {
|
|||||||
let inner = self.inner.read().await;
|
let inner = self.inner.read().await;
|
||||||
|
|
||||||
let power_status = Self::read_power_status(inner.led_sensor.as_ref()).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 {
|
AtxState {
|
||||||
available: inner.config.enabled,
|
available: inner.config.enabled,
|
||||||
|
driver: if inner.config.enabled {
|
||||||
|
inner.config.driver
|
||||||
|
} else {
|
||||||
|
AtxDriverType::None
|
||||||
|
},
|
||||||
power_configured: inner.power_executor.is_some(),
|
power_configured: inner.power_executor.is_some(),
|
||||||
reset_configured: inner.reset_executor.is_some(),
|
reset_configured: inner.reset_executor.is_some(),
|
||||||
power_status,
|
power_status,
|
||||||
led_supported: inner.led_sensor.is_some(),
|
led_supported: inner.led_sensor.is_some(),
|
||||||
|
hdd_status,
|
||||||
|
hdd_supported: inner.hdd_sensor.is_some(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,45 +358,96 @@ impl AtxController {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::atx::AtxDriverType;
|
use crate::atx::{AtxDriverType, AtxOutputBinding};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_should_share_serial_device_true() {
|
fn test_should_share_serial_device_true() {
|
||||||
let power = AtxKeyConfig {
|
let config = AtxControllerConfig {
|
||||||
driver: AtxDriverType::Serial,
|
driver: AtxDriverType::Serial,
|
||||||
device: "/dev/ttyUSB0".to_string(),
|
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,
|
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]
|
#[test]
|
||||||
fn test_should_share_serial_device_false_on_different_baud() {
|
fn test_should_share_serial_device_false_when_reset_disabled() {
|
||||||
let power = AtxKeyConfig {
|
let config = AtxControllerConfig {
|
||||||
driver: AtxDriverType::Serial,
|
driver: AtxDriverType::Serial,
|
||||||
device: "/dev/ttyUSB0".to_string(),
|
device: "/dev/ttyUSB0".to_string(),
|
||||||
pin: 1,
|
|
||||||
active_level: super::super::types::ActiveLevel::High,
|
|
||||||
baud_rate: 9600,
|
baud_rate: 9600,
|
||||||
};
|
power: AtxOutputBinding {
|
||||||
let reset = AtxKeyConfig {
|
enabled: true,
|
||||||
driver: AtxDriverType::Serial,
|
pin: 1,
|
||||||
device: "/dev/ttyUSB0".to_string(),
|
..Default::default()
|
||||||
pin: 2,
|
},
|
||||||
active_level: super::super::types::ActiveLevel::High,
|
reset: AtxOutputBinding {
|
||||||
baud_rate: 115200,
|
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)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
use super::types::{AtxLedConfig, PowerStatus};
|
use super::types::{AtxInputBinding, PowerStatus};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
|
|
||||||
pub struct LedSensor {
|
pub struct LedSensor {
|
||||||
config: AtxLedConfig,
|
config: AtxInputBinding,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LedSensor {
|
impl LedSensor {
|
||||||
pub fn new(config: AtxLedConfig) -> Self {
|
pub fn new(config: AtxInputBinding) -> Self {
|
||||||
Self { config }
|
Self { config }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,6 +28,10 @@ impl LedSensor {
|
|||||||
Ok(PowerStatus::Unknown)
|
Ok(PowerStatus::Unknown)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn read_active(&self) -> Result<bool> {
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn shutdown(&mut self) -> Result<()> {
|
pub async fn shutdown(&mut self) -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use std::fs::{File, OpenOptions};
|
use std::fs::{File, OpenOptions};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::os::fd::AsRawFd;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -9,12 +8,10 @@ use tokio::time::sleep;
|
|||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
use super::traits::AtxKeyBackend;
|
use super::traits::AtxKeyBackend;
|
||||||
use super::types::AtxKeyConfig;
|
use super::types::{AtxKeyConfig, LCUS_RELAY_MAX_CHANNEL};
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
const USB_RELAY_MAX_CHANNEL: u8 = 8;
|
const LCUS_RELAY_COMMAND_LEN: usize = 4;
|
||||||
const USB_RELAY_REPORT_LEN: usize = 9;
|
|
||||||
const HIDIOCSFEATURE_9: libc::c_ulong = 0xC009_4806;
|
|
||||||
|
|
||||||
pub struct HidrawLinuxRelayBackend {
|
pub struct HidrawLinuxRelayBackend {
|
||||||
config: AtxKeyConfig,
|
config: AtxKeyConfig,
|
||||||
@@ -34,13 +31,13 @@ impl HidrawLinuxRelayBackend {
|
|||||||
fn validate_config(&self) -> Result<()> {
|
fn validate_config(&self) -> Result<()> {
|
||||||
if self.config.pin == 0 {
|
if self.config.pin == 0 {
|
||||||
return Err(AppError::Config(
|
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!(
|
return Err(AppError::Config(format!(
|
||||||
"USB HID relay channel must be <= {}",
|
"LCUS HID relay channel must be <= {}",
|
||||||
USB_RELAY_MAX_CHANNEL
|
LCUS_RELAY_MAX_CHANNEL
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -49,20 +46,19 @@ impl HidrawLinuxRelayBackend {
|
|||||||
fn send_command(&self, on: bool) -> Result<()> {
|
fn send_command(&self, on: bool) -> Result<()> {
|
||||||
let channel = u8::try_from(self.config.pin).map_err(|_| {
|
let channel = u8::try_from(self.config.pin).map_err(|_| {
|
||||||
AppError::Config(format!(
|
AppError::Config(format!(
|
||||||
"USB relay channel {} exceeds max {}",
|
"LCUS HID relay channel {} exceeds max {}",
|
||||||
self.config.pin,
|
self.config.pin, LCUS_RELAY_MAX_CHANNEL
|
||||||
u8::MAX
|
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
if channel == 0 {
|
if channel == 0 {
|
||||||
return Err(AppError::Config(
|
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!(
|
return Err(AppError::Config(format!(
|
||||||
"USB HID relay channel must be <= {}",
|
"LCUS HID relay channel must be <= {}",
|
||||||
USB_RELAY_MAX_CHANNEL
|
LCUS_RELAY_MAX_CHANNEL
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,44 +66,22 @@ impl HidrawLinuxRelayBackend {
|
|||||||
let mut guard = self.handle.lock().unwrap();
|
let mut guard = self.handle.lock().unwrap();
|
||||||
let device = guard
|
let device = guard
|
||||||
.as_mut()
|
.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) {
|
device
|
||||||
debug!(
|
.write_all(&cmd)
|
||||||
"USB relay feature report failed ({}), falling back to hidraw write",
|
.map_err(|e| AppError::Internal(format!("LCUS HID relay write failed: {}", e)))?;
|
||||||
feature_err
|
device
|
||||||
);
|
.flush()
|
||||||
device.write_all(&cmd).map_err(|write_err| {
|
.map_err(|e| AppError::Internal(format!("LCUS HID relay flush failed: {}", e)))?;
|
||||||
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)))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_command(channel: u8, on: bool) -> [u8; USB_RELAY_REPORT_LEN] {
|
pub fn build_command(channel: u8, on: bool) -> [u8; LCUS_RELAY_COMMAND_LEN] {
|
||||||
let mut cmd = [0x00; USB_RELAY_REPORT_LEN];
|
let state = if on { 1 } else { 0 };
|
||||||
cmd[1] = if on { 0xFF } else { 0xFD };
|
let checksum = 0xA0u8.wrapping_add(channel).wrapping_add(state);
|
||||||
cmd[2] = channel;
|
[0xA0, channel, state, checksum]
|
||||||
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 as _, report.as_ptr()) };
|
|
||||||
if rc < 0 {
|
|
||||||
Err(std::io::Error::last_os_error())
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +91,7 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
|
|||||||
self.validate_config()?;
|
self.validate_config()?;
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
"Initializing USB relay ATX backend on {} channel {}",
|
"Initializing LCUS HID relay ATX backend on {} channel {}",
|
||||||
self.config.device, self.config.pin
|
self.config.device, self.config.pin
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -125,14 +99,14 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
|
|||||||
.read(true)
|
.read(true)
|
||||||
.write(true)
|
.write(true)
|
||||||
.open(&self.config.device)
|
.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.handle.lock().unwrap() = Some(device);
|
||||||
self.send_command(false)?;
|
self.send_command(false)?;
|
||||||
self.initialized.store(true, Ordering::Relaxed);
|
self.initialized.store(true, Ordering::Relaxed);
|
||||||
|
|
||||||
debug!(
|
debug!(
|
||||||
"USB relay channel {} configured successfully",
|
"LCUS HID relay channel {} configured successfully",
|
||||||
self.config.pin
|
self.config.pin
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -140,7 +114,9 @@ impl AtxKeyBackend for HidrawLinuxRelayBackend {
|
|||||||
|
|
||||||
async fn pulse(&self, duration: Duration) -> Result<()> {
|
async fn pulse(&self, duration: Duration) -> Result<()> {
|
||||||
if !self.is_initialized() {
|
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)?;
|
self.send_command(true)?;
|
||||||
@@ -177,14 +153,14 @@ mod tests {
|
|||||||
use super::HidrawLinuxRelayBackend;
|
use super::HidrawLinuxRelayBackend;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn usb_relay_command_format() {
|
fn lcus_hid_relay_command_format() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
HidrawLinuxRelayBackend::build_command(1, true),
|
HidrawLinuxRelayBackend::build_command(1, true),
|
||||||
[0x00, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
|
[0xA0, 0x01, 0x01, 0xA2]
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
HidrawLinuxRelayBackend::build_command(1, false),
|
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 std::sync::Mutex;
|
||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
use super::types::{AtxLedConfig, PowerStatus};
|
use super::types::{ActiveLevel, AtxInputBinding, PowerStatus};
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
pub struct LedSensor {
|
pub struct LedSensor {
|
||||||
config: AtxLedConfig,
|
config: AtxInputBinding,
|
||||||
handle: Mutex<Option<LineHandle>>,
|
handle: Mutex<Option<LineHandle>>,
|
||||||
initialized: AtomicBool,
|
initialized: AtomicBool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LedSensor {
|
impl LedSensor {
|
||||||
pub fn new(config: AtxLedConfig) -> Self {
|
pub fn new(config: AtxInputBinding) -> Self {
|
||||||
Self {
|
Self {
|
||||||
config,
|
config,
|
||||||
handle: Mutex::new(None),
|
handle: Mutex::new(None),
|
||||||
@@ -33,17 +33,14 @@ impl LedSensor {
|
|||||||
|
|
||||||
info!(
|
info!(
|
||||||
"Initializing LED sensor on {} pin {}",
|
"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)))?;
|
.map_err(|e| AppError::Internal(format!("LED GPIO chip failed: {}", e)))?;
|
||||||
|
|
||||||
let line = chip.get_line(self.config.gpio_pin).map_err(|e| {
|
let line = chip.get_line(self.config.pin).map_err(|e| {
|
||||||
AppError::Internal(format!(
|
AppError::Internal(format!("LED GPIO line {} failed: {}", self.config.pin, e))
|
||||||
"LED GPIO line {} failed: {}",
|
|
||||||
self.config.gpio_pin, e
|
|
||||||
))
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let handle = line
|
let handle = line
|
||||||
@@ -57,9 +54,11 @@ impl LedSensor {
|
|||||||
Ok(())
|
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) {
|
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();
|
let guard = self.handle.lock().unwrap();
|
||||||
@@ -69,22 +68,31 @@ impl LedSensor {
|
|||||||
.get_value()
|
.get_value()
|
||||||
.map_err(|e| AppError::Internal(format!("LED read failed: {}", e)))?;
|
.map_err(|e| AppError::Internal(format!("LED read failed: {}", e)))?;
|
||||||
|
|
||||||
let is_on = if self.config.inverted {
|
let active = match self.config.active_level {
|
||||||
value == 0
|
ActiveLevel::High => value == 1,
|
||||||
} else {
|
ActiveLevel::Low => value == 0,
|
||||||
value == 1
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(if is_on {
|
Ok(active)
|
||||||
PowerStatus::On
|
|
||||||
} else {
|
|
||||||
PowerStatus::Off
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
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<()> {
|
pub async fn shutdown(&mut self) -> Result<()> {
|
||||||
*self.handle.lock().unwrap() = None;
|
*self.handle.lock().unwrap() = None;
|
||||||
self.initialized.store(false, Ordering::Relaxed);
|
self.initialized.store(false, Ordering::Relaxed);
|
||||||
@@ -105,7 +113,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_led_sensor_creation() {
|
fn test_led_sensor_creation() {
|
||||||
let config = AtxLedConfig::default();
|
let config = AtxInputBinding::default();
|
||||||
let sensor = LedSensor::new(config);
|
let sensor = LedSensor::new(config);
|
||||||
assert!(!sensor.config.is_configured());
|
assert!(!sensor.config.is_configured());
|
||||||
assert!(!sensor.initialized.load(Ordering::Relaxed));
|
assert!(!sensor.initialized.load(Ordering::Relaxed));
|
||||||
@@ -113,11 +121,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_led_sensor_with_config() {
|
fn test_led_sensor_with_config() {
|
||||||
let config = AtxLedConfig {
|
let config = AtxInputBinding {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
gpio_chip: "/dev/gpiochip0".to_string(),
|
device: "/dev/gpiochip0".to_string(),
|
||||||
gpio_pin: 7,
|
pin: 7,
|
||||||
inverted: false,
|
active_level: ActiveLevel::High,
|
||||||
};
|
};
|
||||||
let sensor = LedSensor::new(config);
|
let sensor = LedSensor::new(config);
|
||||||
assert!(sensor.config.is_configured());
|
assert!(sensor.config.is_configured());
|
||||||
@@ -126,13 +134,13 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_led_sensor_inverted_config() {
|
fn test_led_sensor_inverted_config() {
|
||||||
let config = AtxLedConfig {
|
let config = AtxInputBinding {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
gpio_chip: "/dev/gpiochip0".to_string(),
|
device: "/dev/gpiochip0".to_string(),
|
||||||
gpio_pin: 7,
|
pin: 7,
|
||||||
inverted: true,
|
active_level: ActiveLevel::Low,
|
||||||
};
|
};
|
||||||
let sensor = LedSensor::new(config);
|
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 controller::{AtxController, AtxControllerConfig};
|
||||||
pub use executor::timing;
|
pub use executor::timing;
|
||||||
pub use types::{
|
pub use types::{
|
||||||
ActiveLevel, AtxAction, AtxDevices, AtxDriverType, AtxKeyConfig, AtxLedConfig, AtxPowerRequest,
|
ActiveLevel, AtxAction, AtxDevices, AtxDriverType, AtxInputBinding, AtxKeyConfig,
|
||||||
AtxState, PowerStatus,
|
AtxOutputBinding, AtxPowerRequest, AtxState, HddStatus, PowerStatus, LCUS_RELAY_MAX_CHANNEL,
|
||||||
};
|
};
|
||||||
pub use wol::{list_wol_history, record_wol_history, send_wol};
|
pub use wol::{list_wol_history, record_wol_history, send_wol};
|
||||||
|
|
||||||
#[cfg(any(unix, test))]
|
#[cfg(any(unix, test))]
|
||||||
fn hidraw_uevent_is_usb_relay(uevent: &str) -> bool {
|
fn hidraw_uevent_is_usb_relay(uevent: &str) -> bool {
|
||||||
let upper = uevent.to_ascii_uppercase();
|
let upper = uevent.to_ascii_uppercase();
|
||||||
upper.contains("000016C0:000005DF")
|
upper.contains("00005131:00002007")
|
||||||
|| upper.contains("00005131:00002007")
|
|
||||||
|| upper.contains("16C0:05DF")
|
|
||||||
|| upper.contains("5131:2007")
|
|| upper.contains("5131:2007")
|
||||||
|| upper.contains("PRODUCT=16C0/5DF")
|
|
||||||
|| upper.contains("PRODUCT=5131/2007")
|
|| upper.contains("PRODUCT=5131/2007")
|
||||||
|| upper.contains("USBRELAY")
|
|
||||||
|| upper.contains("USB RELAY")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -94,14 +89,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hidraw_uevent_detects_usb_relay_id() {
|
fn test_hidraw_uevent_rejects_non_lcus_usb_relay_id() {
|
||||||
assert!(hidraw_uevent_is_usb_relay(
|
assert!(!hidraw_uevent_is_usb_relay(
|
||||||
"HID_ID=0003:000016C0:000005DF\nHID_NAME=www.dcttech.com USBRelay2\n"
|
"HID_ID=0003:000016C0:000005DF\nHID_NAME=www.dcttech.com USBRelay2\n"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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(
|
assert!(hidraw_uevent_is_usb_relay(
|
||||||
"HID_ID=0003:00005131:00002007\n"
|
"HID_ID=0003:00005131:00002007\n"
|
||||||
));
|
));
|
||||||
@@ -120,7 +115,8 @@ mod tests {
|
|||||||
let _: AtxDriverType = AtxDriverType::None;
|
let _: AtxDriverType = AtxDriverType::None;
|
||||||
let _: ActiveLevel = ActiveLevel::High;
|
let _: ActiveLevel = ActiveLevel::High;
|
||||||
let _: AtxKeyConfig = AtxKeyConfig::default();
|
let _: AtxKeyConfig = AtxKeyConfig::default();
|
||||||
let _: AtxLedConfig = AtxLedConfig::default();
|
let _: AtxInputBinding = AtxInputBinding::default();
|
||||||
|
let _: AtxOutputBinding = AtxOutputBinding::default();
|
||||||
let _: AtxState = AtxState::default();
|
let _: AtxState = AtxState::default();
|
||||||
let _: AtxDevices = AtxDevices::default();
|
let _: AtxDevices = AtxDevices::default();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use tokio::time::sleep;
|
|||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
use super::traits::{validate_serial_config, AtxKeyBackend, SharedSerialHandle};
|
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};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
pub struct SerialRelayBackend {
|
pub struct SerialRelayBackend {
|
||||||
@@ -44,15 +44,23 @@ impl SerialRelayBackend {
|
|||||||
fn send_command(&self, on: bool) -> Result<()> {
|
fn send_command(&self, on: bool) -> Result<()> {
|
||||||
let channel = u8::try_from(self.config.pin).map_err(|_| {
|
let channel = u8::try_from(self.config.pin).map_err(|_| {
|
||||||
AppError::Config(format!(
|
AppError::Config(format!(
|
||||||
"Serial relay channel {} exceeds max {}",
|
"LCUS serial relay channel {} exceeds max {}",
|
||||||
self.config.pin,
|
self.config.pin, LCUS_RELAY_MAX_CHANNEL
|
||||||
u8::MAX
|
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
|
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 cmd = Self::build_command(channel, on);
|
||||||
let checksum = 0xA0u8.wrapping_add(channel).wrapping_add(state);
|
|
||||||
let cmd = [0xA0, channel, state, checksum];
|
|
||||||
|
|
||||||
let serial_handle = self
|
let serial_handle = self
|
||||||
.serial_handle
|
.serial_handle
|
||||||
@@ -60,16 +68,22 @@ impl SerialRelayBackend {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.cloned()
|
.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();
|
let mut port = serial_handle.lock().unwrap();
|
||||||
|
|
||||||
port.write_all(&cmd)
|
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()
|
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(())
|
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]
|
#[async_trait]
|
||||||
@@ -78,7 +92,7 @@ impl AtxKeyBackend for SerialRelayBackend {
|
|||||||
validate_serial_config(&self.config)?;
|
validate_serial_config(&self.config)?;
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
"Initializing Serial relay ATX backend on {} channel {}",
|
"Initializing LCUS serial relay ATX backend on {} channel {}",
|
||||||
self.config.device, self.config.pin
|
self.config.device, self.config.pin
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -92,7 +106,7 @@ impl AtxKeyBackend for SerialRelayBackend {
|
|||||||
self.initialized.store(true, Ordering::Relaxed);
|
self.initialized.store(true, Ordering::Relaxed);
|
||||||
|
|
||||||
debug!(
|
debug!(
|
||||||
"Serial relay channel {} configured successfully",
|
"LCUS serial relay channel {} configured successfully",
|
||||||
self.config.pin
|
self.config.pin
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -101,12 +115,12 @@ impl AtxKeyBackend for SerialRelayBackend {
|
|||||||
async fn pulse(&self, duration: Duration) -> Result<()> {
|
async fn pulse(&self, duration: Duration) -> Result<()> {
|
||||||
if !self.is_initialized() {
|
if !self.is_initialized() {
|
||||||
return Err(AppError::Internal(
|
return Err(AppError::Internal(
|
||||||
"Serial relay not initialized".to_string(),
|
"LCUS serial relay not initialized".to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
"Pulse serial relay on {} pin {}",
|
"Pulse LCUS serial relay on {} channel {}",
|
||||||
self.config.device, self.config.pin
|
self.config.device, self.config.pin
|
||||||
);
|
);
|
||||||
self.send_command(true)?;
|
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 {
|
impl Drop for SerialRelayBackend {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.is_initialized() {
|
if self.is_initialized() {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use serialport::SerialPort;
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use super::types::AtxKeyConfig;
|
use super::types::{AtxKeyConfig, LCUS_RELAY_MAX_CHANNEL};
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
|
|
||||||
pub type SharedSerialHandle = Arc<Mutex<Box<dyn SerialPort>>>;
|
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(),
|
"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!(
|
return Err(crate::error::AppError::Config(format!(
|
||||||
"Serial ATX channel must be <= {}",
|
"LCUS serial relay channel must be <= {}",
|
||||||
u8::MAX
|
LCUS_RELAY_MAX_CHANNEL
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
if config.baud_rate == 0 {
|
if config.baud_rate == 0 {
|
||||||
|
|||||||
136
src/atx/types.rs
136
src/atx/types.rs
@@ -1,11 +1,12 @@
|
|||||||
//! ATX data types and structures
|
//! ATX data types and structures
|
||||||
//!
|
//!
|
||||||
//! Defines the configuration and state types for the flexible ATX power control system.
|
//! Defines the configuration and state types for the ATX power control system.
|
||||||
//! Each ATX action (power, reset) can be independently configured with different hardware.
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use typeshare::typeshare;
|
use typeshare::typeshare;
|
||||||
|
|
||||||
|
pub const LCUS_RELAY_MAX_CHANNEL: u8 = 8;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum PowerStatus {
|
pub enum PowerStatus {
|
||||||
@@ -15,6 +16,15 @@ pub enum PowerStatus {
|
|||||||
Unknown,
|
Unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum HddStatus {
|
||||||
|
Active,
|
||||||
|
Inactive,
|
||||||
|
#[default]
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
#[typeshare]
|
#[typeshare]
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
@@ -36,6 +46,56 @@ pub enum ActiveLevel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[typeshare]
|
#[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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct AtxKeyConfig {
|
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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
pub struct AtxState {
|
pub struct AtxState {
|
||||||
pub available: bool,
|
pub available: bool,
|
||||||
|
pub driver: AtxDriverType,
|
||||||
pub power_configured: bool,
|
pub power_configured: bool,
|
||||||
pub reset_configured: bool,
|
pub reset_configured: bool,
|
||||||
pub power_status: PowerStatus,
|
pub power_status: PowerStatus,
|
||||||
pub led_supported: bool,
|
pub led_supported: bool,
|
||||||
|
pub hdd_status: HddStatus,
|
||||||
|
pub hdd_supported: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
@@ -139,6 +186,29 @@ mod tests {
|
|||||||
assert_eq!(ActiveLevel::default(), ActiveLevel::High);
|
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]
|
#[test]
|
||||||
fn test_atx_key_config_default() {
|
fn test_atx_key_config_default() {
|
||||||
let config = AtxKeyConfig::default();
|
let config = AtxKeyConfig::default();
|
||||||
@@ -149,37 +219,22 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_atx_key_config_is_configured() {
|
fn test_atx_input_binding_default() {
|
||||||
let mut config = AtxKeyConfig::default();
|
let config = AtxInputBinding::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();
|
|
||||||
assert!(!config.enabled);
|
assert!(!config.enabled);
|
||||||
assert!(config.gpio_chip.is_empty());
|
assert!(config.device.is_empty());
|
||||||
assert!(!config.is_configured());
|
assert!(!config.is_configured());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_atx_led_config_is_configured() {
|
fn test_atx_input_binding_is_configured() {
|
||||||
let mut config = AtxLedConfig::default();
|
let mut config = AtxInputBinding::default();
|
||||||
assert!(!config.is_configured());
|
assert!(!config.is_configured());
|
||||||
|
|
||||||
config.enabled = true;
|
config.enabled = true;
|
||||||
assert!(!config.is_configured());
|
assert!(!config.is_configured());
|
||||||
|
|
||||||
config.gpio_chip = "/dev/gpiochip0".to_string();
|
config.device = "/dev/gpiochip0".to_string();
|
||||||
assert!(config.is_configured());
|
assert!(config.is_configured());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,9 +242,12 @@ mod tests {
|
|||||||
fn test_atx_state_default() {
|
fn test_atx_state_default() {
|
||||||
let state = AtxState::default();
|
let state = AtxState::default();
|
||||||
assert!(!state.available);
|
assert!(!state.available);
|
||||||
|
assert_eq!(state.driver, AtxDriverType::None);
|
||||||
assert!(!state.power_configured);
|
assert!(!state.power_configured);
|
||||||
assert!(!state.reset_configured);
|
assert!(!state.reset_configured);
|
||||||
assert_eq!(state.power_status, PowerStatus::Unknown);
|
assert_eq!(state.power_status, PowerStatus::Unknown);
|
||||||
assert!(!state.led_supported);
|
assert!(!state.led_supported);
|
||||||
|
assert_eq!(state.hdd_status, HddStatus::Unknown);
|
||||||
|
assert!(!state.hdd_supported);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,163 @@
|
|||||||
#[cfg(all(unix, not(feature = "android")))]
|
//! Platform-neutral capture lifecycle and PCM frame types.
|
||||||
#[path = "capture_linux.rs"]
|
|
||||||
mod imp;
|
|
||||||
|
|
||||||
#[cfg(feature = "android")]
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
#[path = "capture_android.rs"]
|
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;
|
mod imp;
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
#[path = "capture_windows.rs"]
|
#[path = "capture_windows.rs"]
|
||||||
mod imp;
|
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,292 +0,0 @@
|
|||||||
use alsa::pcm::{Access, Format, Frames, HwParams};
|
|
||||||
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 crate::audio::device::AudioDeviceInfo;
|
|
||||||
use crate::error::{AppError, Result};
|
|
||||||
use crate::utils::LogThrottler;
|
|
||||||
use crate::{error_throttled, 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,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AudioConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
device_name: String::new(),
|
|
||||||
sample_rate: 48_000,
|
|
||||||
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(
|
|
||||||
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| {
|
|
||||||
AppError::AudioError(format!(
|
|
||||||
"Failed to open audio device {}: {}",
|
|
||||||
config.device_name, e
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
{
|
|
||||||
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");
|
|
||||||
|
|
||||||
pcm.prepare()
|
|
||||||
.map_err(|e| AppError::AudioError(format!("Failed to prepare PCM: {}", e)))?;
|
|
||||||
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)
|
|
||||||
.max(256);
|
|
||||||
let buf_frames = period_frames.saturating_mul(4).max(2048);
|
|
||||||
let io = pcm
|
|
||||||
.io_i16()
|
|
||||||
.map_err(|e| AppError::AudioError(format!("Failed to get PCM IO: {}", e)))?;
|
|
||||||
|
|
||||||
let mut buffer = vec![0i16; buf_frames * 2];
|
|
||||||
let mut next_log = Instant::now();
|
|
||||||
|
|
||||||
while !stop_flag.load(Ordering::SeqCst) {
|
|
||||||
match io.readi(&mut buffer[..period_frames * 2]) {
|
|
||||||
Ok(frames_read) => {
|
|
||||||
if frames_read == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let samples = frames_read * 2;
|
|
||||||
let data = Bytes::copy_from_slice(bytemuck::cast_slice(&buffer[..samples]));
|
|
||||||
let seq = sequence.fetch_add(1, Ordering::SeqCst);
|
|
||||||
let frame = AudioFrame::new_interleaved(data, 2, 48_000, seq);
|
|
||||||
let _ = frame_tx.send(frame);
|
|
||||||
if next_log.elapsed().as_secs() >= 5 {
|
|
||||||
debug!("Captured audio frame {} ({} samples)", seq, samples / 2);
|
|
||||||
next_log = Instant::now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
warn_throttled!(
|
|
||||||
log_throttler,
|
|
||||||
"alsa_read",
|
|
||||||
"ALSA read error on {}: {}",
|
|
||||||
config.device_name,
|
|
||||||
err
|
|
||||||
);
|
|
||||||
let _ = pcm.try_recover(err, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = pcm.drain();
|
|
||||||
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::pcm::{Access, Format, Frames, HwParams, State, IO};
|
||||||
use alsa::{Direction, ValueOr, PCM};
|
use alsa::{Direction, ValueOr, PCM};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
use tokio::sync::{broadcast, watch};
|
||||||
use std::sync::Arc;
|
use tracing::debug;
|
||||||
use std::time::Instant;
|
|
||||||
use tokio::sync::{broadcast, watch, Mutex};
|
|
||||||
use tracing::{debug, info};
|
|
||||||
|
|
||||||
use crate::audio::device::AudioDeviceInfo;
|
use super::{AudioConfig, AudioFrame, CaptureState};
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
use crate::utils::LogThrottler;
|
use crate::utils::LogThrottler;
|
||||||
use crate::{error_throttled, warn_throttled};
|
use crate::warn_throttled;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
const RETRY_DELAY: Duration = Duration::from_millis(5);
|
||||||
pub struct AudioConfig {
|
const MAX_CONSECUTIVE_READ_ERRORS: u32 = 10;
|
||||||
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 {
|
pub(super) fn run_capture(
|
||||||
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(
|
|
||||||
config: &AudioConfig,
|
config: &AudioConfig,
|
||||||
state: &watch::Sender<CaptureState>,
|
state: &watch::Sender<CaptureState>,
|
||||||
frame_tx: &broadcast::Sender<AudioFrame>,
|
frame_tx: &broadcast::Sender<AudioFrame>,
|
||||||
stop_flag: &AtomicBool,
|
stop_flag: &AtomicBool,
|
||||||
sequence: &AtomicU64,
|
|
||||||
log_throttler: &LogThrottler,
|
log_throttler: &LogThrottler,
|
||||||
) -> Result<()> {
|
) -> 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!(
|
AppError::AudioError(format!(
|
||||||
"Failed to open audio device {}: {}",
|
"Failed to open audio device {}: {}",
|
||||||
config.device_name, e
|
config.device_name, error
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
{
|
configure_pcm(&pcm, config)?;
|
||||||
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");
|
|
||||||
|
|
||||||
pcm.prepare()
|
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 _ = state.send(CaptureState::Running);
|
||||||
|
|
||||||
let period_frames = pcm
|
let period_frames = pcm
|
||||||
.hw_params_current()
|
.hw_params_current()
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|h| h.get_period_size().ok())
|
.and_then(|params| params.get_period_size().ok())
|
||||||
.map(|f| f as usize)
|
.map(|frames| frames as usize)
|
||||||
.unwrap_or(1024)
|
.unwrap_or(config.period_frames as usize)
|
||||||
.max(256);
|
.max(256);
|
||||||
let buf_frames = period_frames.saturating_mul(4).max(2048);
|
let mut buffer = vec![0u8; period_frames * config.channels as usize * 2];
|
||||||
let bytes_per_frame = (config.channels as usize) * 2;
|
let io: IO<u8> = pcm.io_bytes();
|
||||||
let mut buffer = vec![0u8; buf_frames * bytes_per_frame];
|
let mut consecutive_errors = 0;
|
||||||
|
|
||||||
while !stop_flag.load(Ordering::Relaxed) {
|
while !stop_flag.load(Ordering::Acquire) {
|
||||||
match pcm.state() {
|
match pcm.state() {
|
||||||
State::XRun => {
|
State::XRun => {
|
||||||
warn_throttled!(log_throttler, "xrun", "Audio buffer overrun, recovering");
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
State::Suspended => {
|
State::Suspended => {
|
||||||
@@ -274,61 +63,95 @@ fn run_capture(
|
|||||||
"suspended",
|
"suspended",
|
||||||
"Audio device suspended, recovering"
|
"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;
|
continue;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// io_bytes: USB capture often lacks mmap (io_checked requires it).
|
|
||||||
let io: IO<u8> = pcm.io_bytes();
|
|
||||||
|
|
||||||
match io.readi(&mut buffer) {
|
match io.readi(&mut buffer) {
|
||||||
|
Ok(0) => thread::sleep(RETRY_DELAY),
|
||||||
Ok(frames_read) => {
|
Ok(frames_read) => {
|
||||||
if frames_read == 0 {
|
consecutive_errors = 0;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let byte_count = frames_read * config.channels as usize * 2;
|
let byte_count = frames_read * config.channels as usize * 2;
|
||||||
|
|
||||||
let seq = sequence.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let frame = AudioFrame::new_interleaved(
|
let frame = AudioFrame::new_interleaved(
|
||||||
Bytes::copy_from_slice(&buffer[..byte_count]),
|
Bytes::copy_from_slice(&buffer[..byte_count]),
|
||||||
config.channels,
|
config.channels,
|
||||||
48_000,
|
config.sample_rate,
|
||||||
seq,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if frame_tx.receiver_count() > 0 {
|
if frame_tx.receiver_count() > 0 {
|
||||||
if let Err(e) = frame_tx.send(frame) {
|
let _ = frame_tx.send(frame);
|
||||||
debug!("No audio receivers: {}", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(error) if error.errno() == libc::EAGAIN => thread::sleep(RETRY_DELAY),
|
||||||
let desc = e.to_string();
|
Err(error) if is_device_lost_errno(error.errno()) => {
|
||||||
if is_device_lost_error(&desc) {
|
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!(
|
return Err(AppError::AudioError(format!(
|
||||||
"Audio device lost while reading {}: {}",
|
"Audio capture failed {consecutive_errors} times consecutively: {error}"
|
||||||
config.device_name, e
|
|
||||||
)));
|
)));
|
||||||
} 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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_device_lost_error(desc: &str) -> bool {
|
fn configure_pcm(pcm: &PCM, config: &AudioConfig) -> Result<()> {
|
||||||
desc.contains("No such device")
|
let params = HwParams::any(pcm)
|
||||||
|| desc.contains("ENODEV")
|
.map_err(|error| AppError::AudioError(format!("Failed to get HwParams: {error}")))?;
|
||||||
|| desc.contains("ENXIO")
|
params
|
||||||
|| desc.contains("ESHUTDOWN")
|
.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 bytes::Bytes;
|
||||||
use cpal::traits::{DeviceTrait, StreamTrait};
|
use cpal::traits::{DeviceTrait, StreamTrait};
|
||||||
use cpal::{BufferSize, SampleFormat, StreamConfig};
|
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::mpsc;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::Duration;
|
||||||
use tokio::sync::{broadcast, watch, Mutex};
|
use tokio::sync::{broadcast, watch};
|
||||||
use tracing::{debug, info};
|
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::{AppError, Result};
|
||||||
use crate::error_throttled;
|
|
||||||
use crate::utils::LogThrottler;
|
use crate::utils::LogThrottler;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
pub(super) fn run_capture(
|
||||||
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(
|
|
||||||
config: &AudioConfig,
|
config: &AudioConfig,
|
||||||
state: &watch::Sender<CaptureState>,
|
state: &watch::Sender<CaptureState>,
|
||||||
frame_tx: &broadcast::Sender<AudioFrame>,
|
frame_tx: &broadcast::Sender<AudioFrame>,
|
||||||
stop_flag: &AtomicBool,
|
stop_flag: &AtomicBool,
|
||||||
sequence: &AtomicU64,
|
|
||||||
log_throttler: &LogThrottler,
|
log_throttler: &LogThrottler,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let device = find_wasapi_device(&config.device_name)?;
|
let device = find_wasapi_device(&config.device_name)?;
|
||||||
@@ -220,7 +45,7 @@ fn run_capture(
|
|||||||
let stream = match sample_format {
|
let stream = match sample_format {
|
||||||
SampleFormat::F32 => build_stream::<f32>(
|
SampleFormat::F32 => build_stream::<f32>(
|
||||||
&device,
|
&device,
|
||||||
&stream_config,
|
stream_config,
|
||||||
input_channels,
|
input_channels,
|
||||||
input_rate,
|
input_rate,
|
||||||
tx.clone(),
|
tx.clone(),
|
||||||
@@ -229,7 +54,7 @@ fn run_capture(
|
|||||||
),
|
),
|
||||||
SampleFormat::I16 => build_stream::<i16>(
|
SampleFormat::I16 => build_stream::<i16>(
|
||||||
&device,
|
&device,
|
||||||
&stream_config,
|
stream_config,
|
||||||
input_channels,
|
input_channels,
|
||||||
input_rate,
|
input_rate,
|
||||||
tx.clone(),
|
tx.clone(),
|
||||||
@@ -238,7 +63,7 @@ fn run_capture(
|
|||||||
),
|
),
|
||||||
SampleFormat::U16 => build_stream::<u16>(
|
SampleFormat::U16 => build_stream::<u16>(
|
||||||
&device,
|
&device,
|
||||||
&stream_config,
|
stream_config,
|
||||||
input_channels,
|
input_channels,
|
||||||
input_rate,
|
input_rate,
|
||||||
tx.clone(),
|
tx.clone(),
|
||||||
@@ -272,12 +97,10 @@ fn run_capture(
|
|||||||
if samples.is_empty() {
|
if samples.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let seq = sequence.fetch_add(1, Ordering::Relaxed);
|
|
||||||
let frame = AudioFrame::new_interleaved(
|
let frame = AudioFrame::new_interleaved(
|
||||||
Bytes::copy_from_slice(bytemuck::cast_slice(&samples)),
|
Bytes::copy_from_slice(bytemuck::cast_slice(&samples)),
|
||||||
2,
|
2,
|
||||||
48_000,
|
48_000,
|
||||||
seq,
|
|
||||||
);
|
);
|
||||||
if frame_tx.receiver_count() > 0 {
|
if frame_tx.receiver_count() > 0 {
|
||||||
if let Err(e) = frame_tx.send(frame) {
|
if let Err(e) = frame_tx.send(frame) {
|
||||||
@@ -361,7 +184,7 @@ fn select_input_config(
|
|||||||
|
|
||||||
fn build_stream<T>(
|
fn build_stream<T>(
|
||||||
device: &cpal::Device,
|
device: &cpal::Device,
|
||||||
config: &StreamConfig,
|
config: StreamConfig,
|
||||||
input_channels: u32,
|
input_channels: u32,
|
||||||
input_rate: u32,
|
input_rate: u32,
|
||||||
tx: mpsc::SyncSender<Vec<i16>>,
|
tx: mpsc::SyncSender<Vec<i16>>,
|
||||||
@@ -508,9 +331,5 @@ fn device_label(device: &cpal::Device) -> String {
|
|||||||
device
|
device
|
||||||
.description()
|
.description()
|
||||||
.map(|desc| desc.to_string())
|
.map(|desc| desc.to_string())
|
||||||
.or_else(|_| {
|
|
||||||
#[allow(deprecated)]
|
|
||||||
device.name()
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|_| "Unknown WASAPI capture device".to_string())
|
.unwrap_or_else(|_| "Unknown WASAPI capture device".to_string())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
//! Device selection, quality presets, streaming.
|
//! Device selection, quality presets, streaming.
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::{Mutex, RwLock};
|
||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
use super::capture::AudioConfig;
|
use super::capture::AudioConfig;
|
||||||
@@ -22,23 +21,37 @@ pub(super) type AudioRecoveredCallback = Arc<dyn Fn() + Send + Sync>;
|
|||||||
pub struct AudioController {
|
pub struct AudioController {
|
||||||
config: Arc<RwLock<AudioControllerConfig>>,
|
config: Arc<RwLock<AudioControllerConfig>>,
|
||||||
streamer: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
streamer: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
||||||
devices: Arc<RwLock<Vec<AudioDeviceInfo>>>,
|
|
||||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
||||||
monitor: Arc<AudioHealthMonitor>,
|
monitor: Arc<AudioHealthMonitor>,
|
||||||
recovery_in_progress: Arc<AtomicBool>,
|
recovery: recovery::AudioRecovery,
|
||||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
||||||
|
operation: Arc<Mutex<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioController {
|
impl AudioController {
|
||||||
pub fn new(config: AudioControllerConfig) -> Self {
|
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 {
|
Self {
|
||||||
config: Arc::new(RwLock::new(config)),
|
config,
|
||||||
streamer: Arc::new(RwLock::new(None)),
|
streamer,
|
||||||
devices: Arc::new(RwLock::new(Vec::new())),
|
event_bus,
|
||||||
event_bus: Arc::new(RwLock::new(None)),
|
monitor,
|
||||||
monitor: Arc::new(AudioHealthMonitor::new()),
|
recovery,
|
||||||
recovery_in_progress: Arc::new(AtomicBool::new(false)),
|
recovered_callback,
|
||||||
recovered_callback: Arc::new(RwLock::new(None)),
|
operation,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,31 +68,6 @@ impl AudioController {
|
|||||||
bus.mark_device_info_dirty();
|
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>> {
|
pub async fn list_devices(&self) -> Result<Vec<AudioDeviceInfo>> {
|
||||||
let current_device = if self.is_streaming().await {
|
let current_device = if self.is_streaming().await {
|
||||||
@@ -88,26 +76,19 @@ impl AudioController {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let devices = enumerate_audio_devices_with_current(current_device.as_deref())?;
|
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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn select_device(&self, device: &str) -> Result<()> {
|
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 devices = self.list_devices().await?;
|
||||||
let found = devices
|
let found = devices
|
||||||
.iter()
|
.iter()
|
||||||
.any(|d| d.name == device || d.description.contains(device));
|
.any(|d| d.name == device || d.description.contains(device));
|
||||||
|
|
||||||
if !found {
|
if !found {
|
||||||
return Err(AppError::AudioError(format!(
|
return Err(AppError::NotFound(format!("audio device {device}")));
|
||||||
"Audio device not found: {}",
|
|
||||||
device
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -118,14 +99,15 @@ impl AudioController {
|
|||||||
info!("Audio device selected: {}", device);
|
info!("Audio device selected: {}", device);
|
||||||
|
|
||||||
if self.is_streaming().await {
|
if self.is_streaming().await {
|
||||||
self.stop_streaming().await?;
|
self.stop_streaming_inner().await?;
|
||||||
self.start_streaming().await?;
|
self.start_streaming_inner().await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_quality(&self, quality: AudioQuality) -> Result<()> {
|
pub async fn set_quality(&self, quality: AudioQuality) -> Result<()> {
|
||||||
|
let _operation = self.operation.lock().await;
|
||||||
{
|
{
|
||||||
let mut config = self.config.write().await;
|
let mut config = self.config.write().await;
|
||||||
config.quality = quality;
|
config.quality = quality;
|
||||||
@@ -144,6 +126,12 @@ impl AudioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_streaming(&self) -> Result<()> {
|
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;
|
let config = self.config.read().await;
|
||||||
if !config.enabled {
|
if !config.enabled {
|
||||||
@@ -171,7 +159,7 @@ impl AudioController {
|
|||||||
|
|
||||||
if let Some(error_msg) = select_error {
|
if let Some(error_msg) = select_error {
|
||||||
self.monitor.report_error(&error_msg, "start_failed").await;
|
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;
|
self.mark_device_info_dirty().await;
|
||||||
return Err(AppError::AudioError(error_msg));
|
return Err(AppError::AudioError(error_msg));
|
||||||
}
|
}
|
||||||
@@ -194,7 +182,7 @@ impl AudioController {
|
|||||||
let error_msg = format!("Failed to start audio: {}", e);
|
let error_msg = format!("Failed to start audio: {}", e);
|
||||||
|
|
||||||
self.monitor.report_error(&error_msg, "start_failed").await;
|
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;
|
self.mark_device_info_dirty().await;
|
||||||
|
|
||||||
@@ -203,14 +191,13 @@ impl AudioController {
|
|||||||
|
|
||||||
let streamer_for_monitor = streamer.clone();
|
let streamer_for_monitor = streamer.clone();
|
||||||
*self.streamer.write().await = Some(streamer);
|
*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 {
|
if self.monitor.is_error().await {
|
||||||
self.monitor.report_recovered().await;
|
self.monitor.report_recovered().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.recovery_in_progress.store(false, Ordering::SeqCst);
|
|
||||||
|
|
||||||
self.mark_device_info_dirty().await;
|
self.mark_device_info_dirty().await;
|
||||||
|
|
||||||
info!("Audio streaming started");
|
info!("Audio streaming started");
|
||||||
@@ -218,7 +205,12 @@ impl AudioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn stop_streaming(&self) -> Result<()> {
|
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() {
|
if let Some(streamer) = self.streamer.write().await.take() {
|
||||||
streamer.stop().await?;
|
streamer.stop().await?;
|
||||||
@@ -249,7 +241,7 @@ impl AudioController {
|
|||||||
let (streaming, subscriber_count) = if let Some(ref streamer) = *self.streamer.read().await
|
let (streaming, subscriber_count) = if let Some(ref streamer) = *self.streamer.read().await
|
||||||
{
|
{
|
||||||
let streaming = streamer.is_running();
|
let streaming = streamer.is_running();
|
||||||
let subscriber_count = streamer.stats().subscriber_count;
|
let subscriber_count = streamer.subscriber_count();
|
||||||
(streaming, subscriber_count)
|
(streaming, subscriber_count)
|
||||||
} else {
|
} else {
|
||||||
(false, 0)
|
(false, 0)
|
||||||
@@ -278,13 +270,15 @@ impl AudioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_enabled(&self, enabled: bool) -> Result<()> {
|
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;
|
let mut config = self.config.write().await;
|
||||||
config.enabled = enabled;
|
config.enabled = enabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !enabled && self.is_streaming().await {
|
if !enabled && self.is_streaming().await {
|
||||||
self.stop_streaming().await?;
|
self.stop_streaming_inner().await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("Audio enabled: {}", enabled);
|
info!("Audio enabled: {}", enabled);
|
||||||
@@ -292,16 +286,18 @@ impl AudioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update_config(&self, new_config: AudioControllerConfig) -> Result<()> {
|
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;
|
let was_streaming = self.is_streaming().await;
|
||||||
|
|
||||||
if was_streaming {
|
if was_streaming {
|
||||||
self.stop_streaming().await?;
|
self.stop_streaming_inner().await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
*self.config.write().await = new_config.clone();
|
*self.config.write().await = new_config.clone();
|
||||||
|
|
||||||
if new_config.enabled {
|
if new_config.enabled {
|
||||||
self.start_streaming().await?;
|
self.start_streaming_inner().await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,13 +1,43 @@
|
|||||||
#[cfg(all(unix, not(feature = "android")))]
|
//! Shared device description with platform-specific enumeration backends.
|
||||||
#[path = "device_linux.rs"]
|
|
||||||
mod imp;
|
|
||||||
|
|
||||||
#[cfg(feature = "android")]
|
use serde::Serialize;
|
||||||
#[path = "device_android.rs"]
|
|
||||||
|
use crate::error::Result;
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[path = "device_linux.rs"]
|
||||||
mod imp;
|
mod imp;
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
#[path = "device_windows.rs"]
|
#[path = "device_windows.rs"]
|
||||||
mod imp;
|
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,185 +0,0 @@
|
|||||||
use alsa::pcm::HwParams;
|
|
||||||
use alsa::{Direction, PCM};
|
|
||||||
use serde::Serialize;
|
|
||||||
use tracing::{debug, info, warn};
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
let device_path = format!("/sys/class/sound/card{}/device", card_index);
|
|
||||||
let link_target = std::fs::read_link(&device_path).ok()?;
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn enumerate_audio_devices() -> Result<Vec<AudioDeviceInfo>> {
|
|
||||||
enumerate_audio_devices_with_current(None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn enumerate_audio_devices_with_current(
|
|
||||||
current_device: Option<&str>,
|
|
||||||
) -> Result<Vec<AudioDeviceInfo>> {
|
|
||||||
let mut devices = Vec::new();
|
|
||||||
|
|
||||||
for card_result in alsa::card::Iter::new() {
|
|
||||||
let card = match card_result {
|
|
||||||
Ok(card) => card,
|
|
||||||
Err(err) => {
|
|
||||||
debug!("Error iterating card: {}", err);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let card_index = card.get_index();
|
|
||||||
let card_name = card.get_name().unwrap_or_else(|_| "Unknown".to_string());
|
|
||||||
let card_longname = card.get_longname().unwrap_or_else(|_| card_name.clone());
|
|
||||||
|
|
||||||
debug!("Found audio card {}: {}", card_index, card_longname);
|
|
||||||
|
|
||||||
let long_lower = card_longname.to_lowercase();
|
|
||||||
let is_hdmi = long_lower.contains("hdmi")
|
|
||||||
|| long_lower.contains("capture")
|
|
||||||
|| long_lower.contains("usb");
|
|
||||||
let usb_bus = get_usb_bus_info(card_index);
|
|
||||||
|
|
||||||
for device_index in 0..8 {
|
|
||||||
let device_name = format!("hw:{},{}", card_index, device_index);
|
|
||||||
let is_current_device = current_device == Some(device_name.as_str());
|
|
||||||
|
|
||||||
let mut push_info =
|
|
||||||
|sample_rates: Vec<u32>, channels: Vec<u32>, description: String| {
|
|
||||||
devices.push(AudioDeviceInfo {
|
|
||||||
name: device_name.clone(),
|
|
||||||
description,
|
|
||||||
card_index,
|
|
||||||
device_index,
|
|
||||||
sample_rates,
|
|
||||||
channels,
|
|
||||||
is_capture: true,
|
|
||||||
is_hdmi,
|
|
||||||
usb_bus: usb_bus.clone(),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
match PCM::new(&device_name, Direction::Capture, false) {
|
|
||||||
Ok(pcm) => {
|
|
||||||
let (sample_rates, channels) = query_device_caps(&pcm);
|
|
||||||
if !sample_rates.is_empty() && !channels.is_empty() {
|
|
||||||
push_info(
|
|
||||||
sample_rates,
|
|
||||||
channels,
|
|
||||||
format!("{} - Device {}", card_longname, device_index),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) if is_current_device => {
|
|
||||||
debug!(
|
|
||||||
"Device {} is busy (in use by us), adding with default caps",
|
|
||||||
device_name
|
|
||||||
);
|
|
||||||
push_info(
|
|
||||||
vec![44_100, 48_000],
|
|
||||||
vec![2],
|
|
||||||
format!("{} - Device {} (in use)", card_longname, device_index),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Found {} audio capture devices", devices.len());
|
|
||||||
Ok(devices)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn query_device_caps(pcm: &PCM) -> (Vec<u32>, Vec<u32>) {
|
|
||||||
let hwp = match HwParams::any(pcm) {
|
|
||||||
Ok(h) => h,
|
|
||||||
Err(_) => return (vec![], vec![]),
|
|
||||||
};
|
|
||||||
|
|
||||||
let common_rates = [8000, 16000, 22050, 44100, 48000, 96000];
|
|
||||||
let mut supported_rates = Vec::new();
|
|
||||||
|
|
||||||
for rate in &common_rates {
|
|
||||||
if hwp.test_rate(*rate).is_ok() {
|
|
||||||
supported_rates.push(*rate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut supported_channels = Vec::new();
|
|
||||||
for ch in 1..=8 {
|
|
||||||
if hwp.test_channels(ch).is_ok() {
|
|
||||||
supported_channels.push(ch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(supported_rates, supported_channels)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
|
||||||
let devices = enumerate_audio_devices()?;
|
|
||||||
|
|
||||||
if devices.is_empty() {
|
|
||||||
return Err(AppError::AudioError(
|
|
||||||
"No audio capture devices found".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut first_48k_stereo: Option<&AudioDeviceInfo> = None;
|
|
||||||
for device in &devices {
|
|
||||||
if !device.sample_rates.contains(&48_000) || !device.channels.contains(&2) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if device.is_hdmi {
|
|
||||||
info!("Selected HDMI audio device: {}", device.description);
|
|
||||||
return Ok(device.clone());
|
|
||||||
}
|
|
||||||
if first_48k_stereo.is_none() {
|
|
||||||
first_48k_stereo = Some(device);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(device) = first_48k_stereo {
|
|
||||||
info!("Selected audio device: {}", device.description);
|
|
||||||
return Ok(device.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
let device = devices.into_iter().next().unwrap();
|
|
||||||
warn!(
|
|
||||||
"Using fallback audio device: {} (may not support optimal settings)",
|
|
||||||
device.description
|
|
||||||
);
|
|
||||||
Ok(device)
|
|
||||||
}
|
|
||||||
@@ -1,23 +1,10 @@
|
|||||||
use alsa::pcm::HwParams;
|
use alsa::pcm::HwParams;
|
||||||
use alsa::{Direction, PCM};
|
use alsa::{Direction, PCM};
|
||||||
use serde::Serialize;
|
|
||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
|
use super::AudioDeviceInfo;
|
||||||
use crate::error::{AppError, Result};
|
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> {
|
fn get_usb_bus_info(card_index: i32) -> Option<String> {
|
||||||
if card_index < 0 {
|
if card_index < 0 {
|
||||||
return None;
|
return None;
|
||||||
@@ -28,26 +15,18 @@ fn get_usb_bus_info(card_index: i32) -> Option<String> {
|
|||||||
let link_str = link_target.to_string_lossy();
|
let link_str = link_target.to_string_lossy();
|
||||||
|
|
||||||
for component in link_str.split('/') {
|
for component in link_str.split('/') {
|
||||||
if component.contains('-') && !component.contains(':') {
|
if component.contains('-')
|
||||||
if component
|
&& !component.contains(':')
|
||||||
.chars()
|
&& component.chars().next().is_some_and(|c| c.is_ascii_digit())
|
||||||
.next()
|
{
|
||||||
.map(|c| c.is_ascii_digit())
|
return Some(component.to_string());
|
||||||
.unwrap_or(false)
|
|
||||||
{
|
|
||||||
return Some(component.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enumerate_audio_devices() -> Result<Vec<AudioDeviceInfo>> {
|
pub(super) fn enumerate_audio_devices_with_current(
|
||||||
enumerate_audio_devices_with_current(None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn enumerate_audio_devices_with_current(
|
|
||||||
current_device: Option<&str>,
|
current_device: Option<&str>,
|
||||||
) -> Result<Vec<AudioDeviceInfo>> {
|
) -> Result<Vec<AudioDeviceInfo>> {
|
||||||
let mut devices = Vec::new();
|
let mut devices = Vec::new();
|
||||||
@@ -153,8 +132,8 @@ fn query_device_caps(pcm: &PCM) -> (Vec<u32>, Vec<u32>) {
|
|||||||
(supported_rates, supported_channels)
|
(supported_rates, supported_channels)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
pub(super) fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||||
let devices = enumerate_audio_devices()?;
|
let devices = enumerate_audio_devices_with_current(None)?;
|
||||||
|
|
||||||
if devices.is_empty() {
|
if devices.is_empty() {
|
||||||
return Err(AppError::AudioError(
|
return Err(AppError::AudioError(
|
||||||
@@ -194,7 +173,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_enumerate_devices() {
|
fn test_enumerate_devices() {
|
||||||
let result = enumerate_audio_devices();
|
let result = enumerate_audio_devices_with_current(None);
|
||||||
println!("Audio devices: {:?}", result);
|
println!("Audio devices: {:?}", result);
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,12 @@
|
|||||||
use cpal::traits::{DeviceTrait, HostTrait};
|
use cpal::traits::{DeviceTrait, HostTrait};
|
||||||
use cpal::DeviceId;
|
use cpal::DeviceId;
|
||||||
use serde::Serialize;
|
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
|
use super::AudioDeviceInfo;
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
pub(super) fn enumerate_audio_devices_with_current(
|
||||||
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(
|
|
||||||
current_device: Option<&str>,
|
current_device: Option<&str>,
|
||||||
) -> Result<Vec<AudioDeviceInfo>> {
|
) -> Result<Vec<AudioDeviceInfo>> {
|
||||||
let host = cpal::default_host();
|
let host = cpal::default_host();
|
||||||
@@ -130,11 +113,11 @@ fn device_labels(device: &cpal::Device) -> DeviceLabels {
|
|||||||
let formatted = desc.to_string();
|
let formatted = desc.to_string();
|
||||||
let display = desc
|
let display = desc
|
||||||
.extended()
|
.extended()
|
||||||
.first()
|
.next()
|
||||||
.cloned()
|
.map(str::to_owned)
|
||||||
.unwrap_or_else(|| formatted.clone());
|
.unwrap_or_else(|| formatted.clone());
|
||||||
let mut parts = vec![formatted, desc.name().to_string(), display.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 {
|
DeviceLabels {
|
||||||
display,
|
display,
|
||||||
@@ -142,10 +125,7 @@ fn device_labels(device: &cpal::Device) -> DeviceLabels {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
#[allow(deprecated)]
|
let display = "Unknown WASAPI capture device".to_string();
|
||||||
let display = device
|
|
||||||
.name()
|
|
||||||
.unwrap_or_else(|_| "Unknown WASAPI capture device".to_string());
|
|
||||||
DeviceLabels {
|
DeviceLabels {
|
||||||
display: display.clone(),
|
display: display.clone(),
|
||||||
search_text: display,
|
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> {
|
pub(super) fn find_best_audio_device() -> Result<AudioDeviceInfo> {
|
||||||
let devices = enumerate_audio_devices()?;
|
let devices = enumerate_audio_devices_with_current(None)?;
|
||||||
|
|
||||||
if devices.is_empty() {
|
if devices.is_empty() {
|
||||||
return Err(AppError::AudioError(
|
return Err(AppError::AudioError(
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use audiopus::{coder::Encoder, Application, Bitrate, Channels, SampleRate};
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
|
|
||||||
use super::capture::AudioFrame;
|
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[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 {
|
pub fn config(&self) -> &OpusConfig {
|
||||||
&self.config
|
&self.config
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
//! Platform audio capture, Opus encode, device enumeration, streaming, controller, health monitor.
|
//! Platform audio capture, Opus encode, device enumeration, streaming, controller, health monitor.
|
||||||
|
|
||||||
#[cfg(any(unix, windows))]
|
#[cfg(any(unix, windows))]
|
||||||
pub mod capture;
|
mod capture;
|
||||||
pub mod controller;
|
mod controller;
|
||||||
#[cfg(any(unix, windows))]
|
#[cfg(any(unix, windows))]
|
||||||
pub mod device;
|
mod device;
|
||||||
#[cfg(any(unix, windows))]
|
#[cfg(any(unix, windows))]
|
||||||
pub mod encoder;
|
mod encoder;
|
||||||
pub mod monitor;
|
mod monitor;
|
||||||
pub mod recovery;
|
mod recovery;
|
||||||
pub mod streamer;
|
mod streamer;
|
||||||
pub mod types;
|
mod types;
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub mod uac;
|
||||||
|
|
||||||
pub use capture::{AudioCapturer, AudioConfig, AudioFrame};
|
pub use capture::{AudioCapturer, AudioConfig, AudioFrame};
|
||||||
pub use controller::AudioController;
|
pub use controller::AudioController;
|
||||||
|
|||||||
@@ -71,14 +71,14 @@ impl AudioHealthMonitor {
|
|||||||
|
|
||||||
pub async fn report_recovered(&self) {
|
pub async fn report_recovered(&self) {
|
||||||
let prev_status = self.status.read().await.clone();
|
let prev_status = self.status.read().await.clone();
|
||||||
|
self.suppress_display.store(false, Ordering::Relaxed);
|
||||||
|
|
||||||
if prev_status != AudioHealthStatus::Healthy {
|
if prev_status != AudioHealthStatus::Healthy {
|
||||||
let retry_count = self.retry_count.load(Ordering::Relaxed);
|
let retry_count = self.retry_count.load(Ordering::Relaxed);
|
||||||
info!("Audio recovered after {} retries", retry_count);
|
info!("Audio recovered after {} retries", retry_count);
|
||||||
|
|
||||||
self.suppress_display.store(false, Ordering::Relaxed);
|
|
||||||
self.retry_count.store(0, Ordering::Relaxed);
|
self.retry_count.store(0, Ordering::Relaxed);
|
||||||
self.throttler.clear("audio_");
|
self.throttler.clear_all();
|
||||||
*self.last_error_code.write().await = None;
|
*self.last_error_code.write().await = None;
|
||||||
*self.status.write().await = AudioHealthStatus::Healthy;
|
*self.status.write().await = AudioHealthStatus::Healthy;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
//! Audio device-loss monitoring and serialized recovery.
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::RwLock;
|
|
||||||
|
use tokio::sync::{Mutex, RwLock};
|
||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
use super::capture::AudioConfig;
|
use super::capture::AudioConfig;
|
||||||
@@ -9,312 +12,395 @@ use super::device::{enumerate_audio_devices, AudioDeviceInfo};
|
|||||||
use super::monitor::AudioHealthMonitor;
|
use super::monitor::AudioHealthMonitor;
|
||||||
use super::streamer::{AudioStreamState, AudioStreamer, AudioStreamerConfig};
|
use super::streamer::{AudioStreamState, AudioStreamer, AudioStreamerConfig};
|
||||||
use super::types::AudioControllerConfig;
|
use super::types::AudioControllerConfig;
|
||||||
use crate::events::{EventBus, StreamDeviceLostKind, SystemEvent};
|
use crate::events::{EventBus, StreamKind, SystemEvent};
|
||||||
|
|
||||||
const AUDIO_RECOVERY_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
|
const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
|
||||||
|
|
||||||
|
struct RecoveryControl {
|
||||||
|
/// Even values are idle; the following odd value is that recovery's token.
|
||||||
|
/// A single compare-exchange therefore owns both activity and generation.
|
||||||
|
state: AtomicU64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecoveryControl {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
state: AtomicU64::new(0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin(&self) -> Option<u64> {
|
||||||
|
let idle = self.state.load(Ordering::Acquire);
|
||||||
|
if !idle.is_multiple_of(2) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let token = idle.wrapping_add(1);
|
||||||
|
self.state
|
||||||
|
.compare_exchange(idle, token, Ordering::AcqRel, Ordering::Acquire)
|
||||||
|
.ok()
|
||||||
|
.map(|_| token)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_current(&self, token: u64) -> bool {
|
||||||
|
self.state.load(Ordering::Acquire) == token
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish(&self, token: u64) {
|
||||||
|
let _ = self.state.compare_exchange(
|
||||||
|
token,
|
||||||
|
token.wrapping_add(1),
|
||||||
|
Ordering::AcqRel,
|
||||||
|
Ordering::Acquire,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cancel(&self) {
|
||||||
|
let token = self.state.load(Ordering::Acquire);
|
||||||
|
if !token.is_multiple_of(2) {
|
||||||
|
let _ = self.state.compare_exchange(
|
||||||
|
token,
|
||||||
|
token.wrapping_add(1),
|
||||||
|
Ordering::AcqRel,
|
||||||
|
Ordering::Acquire,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RecoveryLease {
|
||||||
|
control: Arc<RecoveryControl>,
|
||||||
|
generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for RecoveryLease {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.control.finish(self.generation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RecoveryInner {
|
||||||
|
config: Arc<RwLock<AudioControllerConfig>>,
|
||||||
|
streamer: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
||||||
|
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
||||||
|
monitor: Arc<AudioHealthMonitor>,
|
||||||
|
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
||||||
|
operation: Arc<Mutex<()>>,
|
||||||
|
control: Arc<RecoveryControl>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(super) struct AudioRecovery {
|
||||||
|
inner: Arc<RecoveryInner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioRecovery {
|
||||||
|
pub(super) fn new(
|
||||||
|
config: Arc<RwLock<AudioControllerConfig>>,
|
||||||
|
streamer: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
||||||
|
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
||||||
|
monitor: Arc<AudioHealthMonitor>,
|
||||||
|
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
||||||
|
operation: Arc<Mutex<()>>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Arc::new(RecoveryInner {
|
||||||
|
config,
|
||||||
|
streamer,
|
||||||
|
event_bus,
|
||||||
|
monitor,
|
||||||
|
recovered_callback,
|
||||||
|
operation,
|
||||||
|
control: Arc::new(RecoveryControl::new()),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn cancel(&self) {
|
||||||
|
self.inner.control.cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn monitor(&self, streamer: Arc<AudioStreamer>, device: String) {
|
||||||
|
let recovery = self.clone();
|
||||||
|
let mut state = streamer.state_watch();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let current_state = *state.borrow();
|
||||||
|
match current_state {
|
||||||
|
AudioStreamState::Error => {}
|
||||||
|
AudioStreamState::Stopped => return,
|
||||||
|
AudioStreamState::Starting | AudioStreamState::Running => {
|
||||||
|
if state.changed().await.is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize the ownership check with user-driven start/stop
|
||||||
|
// operations. If a stop already owns the operation lock, it
|
||||||
|
// removes the streamer before this monitor may start recovery.
|
||||||
|
let _operation = recovery.inner.operation.lock().await;
|
||||||
|
let is_current = recovery
|
||||||
|
.inner
|
||||||
|
.streamer
|
||||||
|
.read()
|
||||||
|
.await
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|current| Arc::ptr_eq(current, &streamer));
|
||||||
|
if !is_current {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let reason = format!("Audio device lost: {device}");
|
||||||
|
recovery
|
||||||
|
.inner
|
||||||
|
.monitor
|
||||||
|
.report_error(&reason, "device_lost")
|
||||||
|
.await;
|
||||||
|
recovery.start(device, reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn start(&self, lost_device: String, reason: String) {
|
||||||
|
let Some(generation) = self.inner.control.begin() else {
|
||||||
|
debug!("Audio recovery already in progress");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let recovery = self.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _lease = RecoveryLease {
|
||||||
|
control: recovery.inner.control.clone(),
|
||||||
|
generation,
|
||||||
|
};
|
||||||
|
recovery.run(generation, lost_device, reason).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(&self, generation: u64, lost_device: String, reason: String) {
|
||||||
|
warn!("Audio recovery started for {lost_device}: {reason}");
|
||||||
|
self.publish_device_lost(&lost_device, &reason).await;
|
||||||
|
self.publish_state(
|
||||||
|
"device_lost",
|
||||||
|
Some(lost_device.clone()),
|
||||||
|
Some("audio_device_lost"),
|
||||||
|
Some(RETRY_DELAY.as_millis() as u64),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let mut attempt = 0u32;
|
||||||
|
while self.inner.control.is_current(generation) {
|
||||||
|
let config = self.inner.config.read().await.clone();
|
||||||
|
if !config.enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.inner
|
||||||
|
.streamer
|
||||||
|
.read()
|
||||||
|
.await
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|streamer| streamer.is_running())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
attempt = attempt.saturating_add(1);
|
||||||
|
self.publish_reconnecting(&lost_device, attempt).await;
|
||||||
|
self.publish_state(
|
||||||
|
"device_lost",
|
||||||
|
Some(lost_device.clone()),
|
||||||
|
Some("audio_reconnecting"),
|
||||||
|
Some(RETRY_DELAY.as_millis() as u64),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
tokio::time::sleep(RETRY_DELAY).await;
|
||||||
|
if !self.inner.control.is_current(generation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let devices = match enumerate_audio_devices() {
|
||||||
|
Ok(devices) => devices,
|
||||||
|
Err(error) => {
|
||||||
|
debug!("Audio recovery enumeration attempt {attempt} failed: {error}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let Some(device) = select_recovery_device(&devices, &config.device) else {
|
||||||
|
debug!("No audio device found on recovery attempt {attempt}");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let streamer = Arc::new(AudioStreamer::with_config(AudioStreamerConfig {
|
||||||
|
capture: AudioConfig {
|
||||||
|
device_name: device.name.clone(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
opus: config.quality.to_opus_config(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
if let Err(error) = streamer.start().await {
|
||||||
|
debug!(
|
||||||
|
"Audio recovery attempt {attempt} failed with {}: {error}",
|
||||||
|
device.name
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit a recovered streamer under the same operation lock used by
|
||||||
|
// user-driven start/stop/config updates. Cancellation is rechecked
|
||||||
|
// after acquiring the lock so an old task cannot resurrect itself.
|
||||||
|
let _operation = self.inner.operation.lock().await;
|
||||||
|
if !self.inner.control.is_current(generation) || !self.inner.config.read().await.enabled
|
||||||
|
{
|
||||||
|
let _ = streamer.stop().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.inner.config.write().await.device = device.name.clone();
|
||||||
|
*self.inner.streamer.write().await = Some(streamer.clone());
|
||||||
|
self.inner.monitor.report_recovered().await;
|
||||||
|
self.publish_recovered(&device.name).await;
|
||||||
|
if let Some(callback) = self.inner.recovered_callback.read().await.clone() {
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
self.publish_state("streaming", Some(device.name.clone()), None, None)
|
||||||
|
.await;
|
||||||
|
info!(
|
||||||
|
"Audio recovered with {} after {} attempts",
|
||||||
|
device.name, attempt
|
||||||
|
);
|
||||||
|
self.inner.control.finish(generation);
|
||||||
|
self.monitor(streamer, device.name);
|
||||||
|
drop(_operation);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_state(
|
||||||
|
&self,
|
||||||
|
state: &str,
|
||||||
|
device: Option<String>,
|
||||||
|
reason: Option<&str>,
|
||||||
|
next_retry_ms: Option<u64>,
|
||||||
|
) {
|
||||||
|
if let Some(bus) = self.inner.event_bus.read().await.as_ref() {
|
||||||
|
bus.publish(SystemEvent::StreamStateChanged {
|
||||||
|
kind: StreamKind::Audio,
|
||||||
|
state: state.to_string(),
|
||||||
|
device,
|
||||||
|
reason: reason.map(str::to_string),
|
||||||
|
next_retry_ms,
|
||||||
|
});
|
||||||
|
bus.mark_device_info_dirty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_device_lost(&self, device: &str, reason: &str) {
|
||||||
|
if let Some(bus) = self.inner.event_bus.read().await.as_ref() {
|
||||||
|
bus.publish(SystemEvent::StreamDeviceLost {
|
||||||
|
kind: StreamKind::Audio,
|
||||||
|
device: device.to_string(),
|
||||||
|
reason: reason.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_reconnecting(&self, device: &str, attempt: u32) {
|
||||||
|
if let Some(bus) = self.inner.event_bus.read().await.as_ref() {
|
||||||
|
bus.publish(SystemEvent::StreamReconnecting {
|
||||||
|
device: device.to_string(),
|
||||||
|
attempt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_recovered(&self, device: &str) {
|
||||||
|
if let Some(bus) = self.inner.event_bus.read().await.as_ref() {
|
||||||
|
bus.publish(SystemEvent::StreamRecovered {
|
||||||
|
device: device.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn select_recovery_device(
|
pub(super) fn select_recovery_device(
|
||||||
devices: &[AudioDeviceInfo],
|
devices: &[AudioDeviceInfo],
|
||||||
preferred: &str,
|
preferred: &str,
|
||||||
) -> Option<AudioDeviceInfo> {
|
) -> Option<AudioDeviceInfo> {
|
||||||
if let Some(device) = devices
|
|
||||||
.iter()
|
|
||||||
.find(|d| !preferred.trim().is_empty() && d.name == preferred)
|
|
||||||
{
|
|
||||||
return Some(device.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
devices
|
devices
|
||||||
.iter()
|
.iter()
|
||||||
.find(|d| d.is_hdmi && d.sample_rates.contains(&48_000) && d.channels.contains(&2))
|
.find(|device| !preferred.trim().is_empty() && device.name == preferred)
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
devices
|
devices.iter().find(|device| {
|
||||||
.iter()
|
device.is_hdmi
|
||||||
.find(|d| d.sample_rates.contains(&48_000) && d.channels.contains(&2))
|
&& device.sample_rates.contains(&48_000)
|
||||||
|
&& device.channels.contains(&2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.or_else(|| {
|
||||||
|
devices.iter().find(|device| {
|
||||||
|
device.sample_rates.contains(&48_000) && device.channels.contains(&2)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.or_else(|| devices.first())
|
.or_else(|| devices.first())
|
||||||
.cloned()
|
.cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn publish_state(
|
#[cfg(test)]
|
||||||
event_bus: &Arc<RwLock<Option<Arc<EventBus>>>>,
|
mod tests {
|
||||||
state: &str,
|
use super::*;
|
||||||
device: Option<String>,
|
|
||||||
reason: Option<&str>,
|
|
||||||
next_retry_ms: Option<u64>,
|
|
||||||
) {
|
|
||||||
if let Some(bus) = event_bus.read().await.as_ref() {
|
|
||||||
bus.publish(SystemEvent::StreamStateChanged {
|
|
||||||
state: state.to_string(),
|
|
||||||
device,
|
|
||||||
reason: reason.map(str::to_string),
|
|
||||||
next_retry_ms,
|
|
||||||
});
|
|
||||||
bus.mark_device_info_dirty();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn publish_device_lost(
|
fn device(name: &str, compatible: bool, hdmi: bool) -> AudioDeviceInfo {
|
||||||
event_bus: &Arc<RwLock<Option<Arc<EventBus>>>>,
|
AudioDeviceInfo {
|
||||||
device: &str,
|
name: name.to_string(),
|
||||||
reason: &str,
|
description: name.to_string(),
|
||||||
) {
|
card_index: 0,
|
||||||
if let Some(bus) = event_bus.read().await.as_ref() {
|
device_index: 0,
|
||||||
bus.publish(SystemEvent::StreamDeviceLost {
|
sample_rates: if compatible {
|
||||||
kind: StreamDeviceLostKind::Audio,
|
vec![48_000]
|
||||||
device: device.to_string(),
|
} else {
|
||||||
reason: reason.to_string(),
|
vec![44_100]
|
||||||
});
|
},
|
||||||
}
|
channels: vec![2],
|
||||||
}
|
is_capture: true,
|
||||||
|
is_hdmi: hdmi,
|
||||||
async fn publish_reconnecting(
|
usb_bus: None,
|
||||||
event_bus: &Arc<RwLock<Option<Arc<EventBus>>>>,
|
|
||||||
device: &str,
|
|
||||||
attempt: u32,
|
|
||||||
) {
|
|
||||||
if let Some(bus) = event_bus.read().await.as_ref() {
|
|
||||||
bus.publish(SystemEvent::StreamReconnecting {
|
|
||||||
device: device.to_string(),
|
|
||||||
attempt,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn publish_recovered(event_bus: &Arc<RwLock<Option<Arc<EventBus>>>>, device: &str) {
|
|
||||||
if let Some(bus) = event_bus.read().await.as_ref() {
|
|
||||||
bus.publish(SystemEvent::StreamRecovered {
|
|
||||||
device: device.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spawn_stream_monitor_from_parts(
|
|
||||||
config: Arc<RwLock<AudioControllerConfig>>,
|
|
||||||
streamer_slot: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
|
||||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
|
||||||
monitor: Arc<AudioHealthMonitor>,
|
|
||||||
recovery_in_progress: Arc<AtomicBool>,
|
|
||||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
|
||||||
streamer: Arc<AudioStreamer>,
|
|
||||||
device: String,
|
|
||||||
) {
|
|
||||||
let mut state_rx = streamer.state_watch();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
if state_rx.changed().await.is_err() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if *state_rx.borrow() != AudioStreamState::Error {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
let current = streamer_slot.read().await;
|
|
||||||
if !current
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|current| Arc::ptr_eq(current, &streamer))
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let reason = format!("Audio device lost: {}", device);
|
|
||||||
monitor.report_error(&reason, "device_lost").await;
|
|
||||||
spawn_recovery_task_from_parts(
|
|
||||||
config,
|
|
||||||
streamer_slot,
|
|
||||||
event_bus,
|
|
||||||
monitor,
|
|
||||||
recovery_in_progress,
|
|
||||||
recovered_callback,
|
|
||||||
device,
|
|
||||||
reason,
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spawn_recovery_task_from_parts(
|
|
||||||
config: Arc<RwLock<AudioControllerConfig>>,
|
|
||||||
streamer_slot: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
|
||||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
|
||||||
monitor: Arc<AudioHealthMonitor>,
|
|
||||||
recovery_in_progress: Arc<AtomicBool>,
|
|
||||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
|
||||||
lost_device: String,
|
|
||||||
reason: String,
|
|
||||||
) {
|
|
||||||
if recovery_in_progress.swap(true, Ordering::SeqCst) {
|
|
||||||
debug!("Audio recovery already in progress");
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tokio::spawn(async move {
|
#[test]
|
||||||
warn!("Audio recovery started for {}: {}", lost_device, reason);
|
fn stale_recovery_cannot_finish_a_new_generation() {
|
||||||
publish_device_lost(&event_bus, &lost_device, &reason).await;
|
let control = RecoveryControl::new();
|
||||||
publish_state(
|
let stale = control.begin().unwrap();
|
||||||
&event_bus,
|
control.cancel();
|
||||||
"device_lost",
|
let current = control.begin().unwrap();
|
||||||
Some(lost_device.clone()),
|
|
||||||
Some("audio_device_lost"),
|
|
||||||
Some(AUDIO_RECOVERY_RETRY_DELAY.as_millis() as u64),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let mut attempt = 0u32;
|
control.finish(stale);
|
||||||
|
assert!(control.is_current(current));
|
||||||
|
}
|
||||||
|
|
||||||
loop {
|
#[test]
|
||||||
if !recovery_in_progress.load(Ordering::SeqCst) {
|
fn completed_recovery_cannot_finish_the_next_recovery() {
|
||||||
debug!("Audio recovery canceled");
|
let control = RecoveryControl::new();
|
||||||
return;
|
let completed = control.begin().unwrap();
|
||||||
}
|
control.finish(completed);
|
||||||
|
let current = control.begin().unwrap();
|
||||||
|
|
||||||
if streamer_slot
|
control.finish(completed);
|
||||||
.read()
|
assert!(control.is_current(current));
|
||||||
.await
|
}
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|s| s.is_running())
|
|
||||||
{
|
|
||||||
recovery_in_progress.store(false, Ordering::SeqCst);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let cfg: AudioControllerConfig = config.read().await.clone();
|
#[test]
|
||||||
if !cfg.enabled {
|
fn recovery_prefers_requested_then_compatible_hdmi() {
|
||||||
recovery_in_progress.store(false, Ordering::SeqCst);
|
let devices = vec![device("fallback", true, false), device("hdmi", true, true)];
|
||||||
return;
|
assert_eq!(
|
||||||
}
|
select_recovery_device(&devices, "fallback").unwrap().name,
|
||||||
|
"fallback"
|
||||||
attempt = attempt.saturating_add(1);
|
);
|
||||||
publish_reconnecting(&event_bus, &lost_device, attempt).await;
|
assert_eq!(
|
||||||
publish_state(
|
select_recovery_device(&devices, "missing").unwrap().name,
|
||||||
&event_bus,
|
"hdmi"
|
||||||
"device_lost",
|
);
|
||||||
Some(lost_device.clone()),
|
}
|
||||||
Some("audio_reconnecting"),
|
|
||||||
Some(AUDIO_RECOVERY_RETRY_DELAY.as_millis() as u64),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
tokio::time::sleep(AUDIO_RECOVERY_RETRY_DELAY).await;
|
|
||||||
|
|
||||||
let devices = match enumerate_audio_devices() {
|
|
||||||
Ok(devices) => devices,
|
|
||||||
Err(e) => {
|
|
||||||
debug!(
|
|
||||||
"Audio recovery enumerate failed (attempt {}): {}",
|
|
||||||
attempt, e
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(device) = select_recovery_device(&devices, &cfg.device) else {
|
|
||||||
debug!("No audio devices found during recovery attempt {}", attempt);
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let streamer_config = AudioStreamerConfig {
|
|
||||||
capture: AudioConfig {
|
|
||||||
device_name: device.name.clone(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
opus: cfg.quality.to_opus_config(),
|
|
||||||
};
|
|
||||||
let new_streamer = Arc::new(AudioStreamer::with_config(streamer_config));
|
|
||||||
|
|
||||||
match new_streamer.start().await {
|
|
||||||
Ok(()) => {
|
|
||||||
{
|
|
||||||
let mut cfg = config.write().await;
|
|
||||||
cfg.device = device.name.clone();
|
|
||||||
}
|
|
||||||
*streamer_slot.write().await = Some(new_streamer.clone());
|
|
||||||
monitor.report_recovered().await;
|
|
||||||
publish_recovered(&event_bus, &device.name).await;
|
|
||||||
if let Some(callback) = recovered_callback.read().await.clone() {
|
|
||||||
callback();
|
|
||||||
}
|
|
||||||
publish_state(
|
|
||||||
&event_bus,
|
|
||||||
"streaming",
|
|
||||||
Some(device.name.clone()),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
recovery_in_progress.store(false, Ordering::SeqCst);
|
|
||||||
info!(
|
|
||||||
"Audio device recovered with {} after {} attempts",
|
|
||||||
device.name, attempt
|
|
||||||
);
|
|
||||||
spawn_stream_monitor_from_parts(
|
|
||||||
config,
|
|
||||||
streamer_slot,
|
|
||||||
event_bus,
|
|
||||||
monitor,
|
|
||||||
recovery_in_progress,
|
|
||||||
recovered_callback,
|
|
||||||
new_streamer,
|
|
||||||
device.name,
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!(
|
|
||||||
"Audio recovery start failed with {} (attempt {}): {}",
|
|
||||||
device.name, attempt, e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn spawn_stream_monitor(
|
|
||||||
config: Arc<RwLock<AudioControllerConfig>>,
|
|
||||||
streamer_slot: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
|
||||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
|
||||||
monitor: Arc<AudioHealthMonitor>,
|
|
||||||
recovery_in_progress: Arc<AtomicBool>,
|
|
||||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
|
||||||
streamer: Arc<AudioStreamer>,
|
|
||||||
device: String,
|
|
||||||
) {
|
|
||||||
spawn_stream_monitor_from_parts(
|
|
||||||
config,
|
|
||||||
streamer_slot,
|
|
||||||
event_bus,
|
|
||||||
monitor,
|
|
||||||
recovery_in_progress,
|
|
||||||
recovered_callback,
|
|
||||||
streamer,
|
|
||||||
device,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn spawn_recovery_task(
|
|
||||||
config: Arc<RwLock<AudioControllerConfig>>,
|
|
||||||
streamer_slot: Arc<RwLock<Option<Arc<AudioStreamer>>>>,
|
|
||||||
event_bus: Arc<RwLock<Option<Arc<EventBus>>>>,
|
|
||||||
monitor: Arc<AudioHealthMonitor>,
|
|
||||||
recovery_in_progress: Arc<AtomicBool>,
|
|
||||||
recovered_callback: Arc<RwLock<Option<AudioRecoveredCallback>>>,
|
|
||||||
lost_device: String,
|
|
||||||
reason: String,
|
|
||||||
) {
|
|
||||||
spawn_recovery_task_from_parts(
|
|
||||||
config,
|
|
||||||
streamer_slot,
|
|
||||||
event_bus,
|
|
||||||
monitor,
|
|
||||||
recovery_in_progress,
|
|
||||||
recovered_callback,
|
|
||||||
lost_device,
|
|
||||||
reason,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use tokio::sync::{broadcast, mpsc, watch, Mutex as AsyncMutex, RwLock};
|
use tokio::sync::{broadcast, mpsc, watch, Mutex as AsyncMutex, RwLock};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
use tracing::{debug, error, info, warn};
|
use tracing::{debug, error, info, warn};
|
||||||
|
|
||||||
use super::capture::{AudioCapturer, AudioConfig, AudioFrame, CaptureState};
|
use super::capture::{AudioCapturer, AudioConfig, CaptureState};
|
||||||
use super::encoder::{OpusConfig, OpusEncoder, OpusFrame};
|
use super::encoder::{OpusConfig, OpusEncoder, OpusFrame};
|
||||||
use crate::error::{AppError, Result};
|
use crate::error::{AppError, Result};
|
||||||
use bytemuck;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// 48 kHz stereo: 20 ms = 960 × 2 samples (S16LE).
|
/// 48 kHz stereo: 20 ms = 960 × 2 samples (S16LE).
|
||||||
const OPUS_STEREO_SAMPLES: usize = 960 * 2;
|
const OPUS_STEREO_SAMPLES: usize = 960 * 2;
|
||||||
@@ -40,16 +40,6 @@ impl AudioStreamerConfig {
|
|||||||
opus: OpusConfig::default(),
|
opus: OpusConfig::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_bitrate(mut self, bitrate: u32) -> Self {
|
|
||||||
self.opus.bitrate = bitrate;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct AudioStreamStats {
|
|
||||||
pub subscriber_count: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AudioStreamer {
|
pub struct AudioStreamer {
|
||||||
@@ -60,6 +50,9 @@ pub struct AudioStreamer {
|
|||||||
encoder: Arc<AsyncMutex<Option<OpusEncoder>>>,
|
encoder: Arc<AsyncMutex<Option<OpusEncoder>>>,
|
||||||
opus_subscribers: Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
opus_subscribers: Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
||||||
stop_flag: Arc<AtomicBool>,
|
stop_flag: Arc<AtomicBool>,
|
||||||
|
shutdown_generation: watch::Sender<u64>,
|
||||||
|
lifecycle: AsyncMutex<()>,
|
||||||
|
stream_task: AsyncMutex<Option<JoinHandle<()>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioStreamer {
|
impl AudioStreamer {
|
||||||
@@ -69,6 +62,7 @@ impl AudioStreamer {
|
|||||||
|
|
||||||
pub fn with_config(config: AudioStreamerConfig) -> Self {
|
pub fn with_config(config: AudioStreamerConfig) -> Self {
|
||||||
let (state_tx, state_rx) = watch::channel(AudioStreamState::Stopped);
|
let (state_tx, state_rx) = watch::channel(AudioStreamState::Stopped);
|
||||||
|
let (shutdown_generation, _) = watch::channel(0);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
config: RwLock::new(config),
|
config: RwLock::new(config),
|
||||||
@@ -78,6 +72,9 @@ impl AudioStreamer {
|
|||||||
encoder: Arc::new(AsyncMutex::new(None)),
|
encoder: Arc::new(AsyncMutex::new(None)),
|
||||||
opus_subscribers: Arc::new(Mutex::new(Vec::new())),
|
opus_subscribers: Arc::new(Mutex::new(Vec::new())),
|
||||||
stop_flag: Arc::new(AtomicBool::new(false)),
|
stop_flag: Arc::new(AtomicBool::new(false)),
|
||||||
|
shutdown_generation,
|
||||||
|
lifecycle: AsyncMutex::new(()),
|
||||||
|
stream_task: AsyncMutex::new(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +87,9 @@ impl AudioStreamer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn subscribe_opus(&self) -> mpsc::Receiver<Arc<OpusFrame>> {
|
pub fn subscribe_opus(&self) -> mpsc::Receiver<Arc<OpusFrame>> {
|
||||||
let (tx, rx) = mpsc::channel::<Arc<OpusFrame>>(128);
|
// Keep latency bounded for real-time consumers. Slow receivers lose
|
||||||
|
// new frames instead of accumulating seconds of stale audio.
|
||||||
|
let (tx, rx) = mpsc::channel::<Arc<OpusFrame>>(4);
|
||||||
self.opus_subscribers.lock().unwrap().push(tx);
|
self.opus_subscribers.lock().unwrap().push(tx);
|
||||||
rx
|
rx
|
||||||
}
|
}
|
||||||
@@ -104,22 +103,6 @@ impl AudioStreamer {
|
|||||||
.count()
|
.count()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn stats(&self) -> AudioStreamStats {
|
|
||||||
AudioStreamStats {
|
|
||||||
subscriber_count: self.subscriber_count(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_config(&self, config: AudioStreamerConfig) -> Result<()> {
|
|
||||||
if self.state() != AudioStreamState::Stopped {
|
|
||||||
return Err(AppError::AudioError(
|
|
||||||
"Cannot change config while streaming".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
*self.config.write().await = config;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_bitrate(&self, bitrate: u32) -> Result<()> {
|
pub async fn set_bitrate(&self, bitrate: u32) -> Result<()> {
|
||||||
self.config.write().await.opus.bitrate = bitrate;
|
self.config.write().await.opus.bitrate = bitrate;
|
||||||
|
|
||||||
@@ -132,10 +115,25 @@ impl AudioStreamer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start(&self) -> Result<()> {
|
pub async fn start(&self) -> Result<()> {
|
||||||
if self.state() == AudioStreamState::Running {
|
let _lifecycle = self.lifecycle.lock().await;
|
||||||
|
if matches!(
|
||||||
|
self.state(),
|
||||||
|
AudioStreamState::Starting | AudioStreamState::Running
|
||||||
|
) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error and stopped states may still own completed task handles. Reap
|
||||||
|
// them before installing a new capture pipeline so restart is a clean
|
||||||
|
// lifecycle transition rather than an overwrite of old resources.
|
||||||
|
if let Some(capturer) = self.capturer.write().await.take() {
|
||||||
|
let _ = capturer.stop().await;
|
||||||
|
}
|
||||||
|
if let Some(task) = self.stream_task.lock().await.take() {
|
||||||
|
let _ = task.await;
|
||||||
|
}
|
||||||
|
*self.encoder.lock().await = None;
|
||||||
|
|
||||||
let _ = self.state.send(AudioStreamState::Starting);
|
let _ = self.state.send(AudioStreamState::Starting);
|
||||||
self.stop_flag.store(false, Ordering::SeqCst);
|
self.stop_flag.store(false, Ordering::SeqCst);
|
||||||
|
|
||||||
@@ -149,13 +147,21 @@ impl AudioStreamer {
|
|||||||
config.opus.bitrate
|
config.opus.bitrate
|
||||||
);
|
);
|
||||||
|
|
||||||
let capturer = Arc::new(AudioCapturer::new(config.capture.clone()));
|
let encoder = match OpusEncoder::new(config.opus.clone()) {
|
||||||
*self.capturer.write().await = Some(capturer.clone());
|
Ok(encoder) => encoder,
|
||||||
|
Err(error) => {
|
||||||
let encoder = OpusEncoder::new(config.opus.clone())?;
|
let _ = self.state.send(AudioStreamState::Error);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
*self.encoder.lock().await = Some(encoder);
|
*self.encoder.lock().await = Some(encoder);
|
||||||
|
|
||||||
capturer.start().await?;
|
let capturer = Arc::new(AudioCapturer::new(config.capture.clone()));
|
||||||
|
*self.capturer.write().await = Some(capturer.clone());
|
||||||
|
if let Err(error) = capturer.start().await {
|
||||||
|
self.cleanup_failed_start(&capturer).await;
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
|
||||||
let mut capture_state = capturer.state_watch();
|
let mut capture_state = capturer.state_watch();
|
||||||
let startup_result = tokio::time::timeout(Duration::from_secs(2), async {
|
let startup_result = tokio::time::timeout(Duration::from_secs(2), async {
|
||||||
@@ -168,7 +174,7 @@ impl AudioStreamer {
|
|||||||
"Audio capture failed to start".to_string(),
|
"Audio capture failed to start".to_string(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
CaptureState::Stopped => {
|
CaptureState::Stopped | CaptureState::Starting => {
|
||||||
if capture_state.changed().await.is_err() {
|
if capture_state.changed().await.is_err() {
|
||||||
return Err(AppError::AudioError(
|
return Err(AppError::AudioError(
|
||||||
"Audio capture stopped during startup".to_string(),
|
"Audio capture stopped during startup".to_string(),
|
||||||
@@ -183,17 +189,11 @@ impl AudioStreamer {
|
|||||||
match startup_result {
|
match startup_result {
|
||||||
Ok(Ok(())) => {}
|
Ok(Ok(())) => {}
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
let _ = capturer.stop().await;
|
self.cleanup_failed_start(&capturer).await;
|
||||||
*self.capturer.write().await = None;
|
|
||||||
*self.encoder.lock().await = None;
|
|
||||||
let _ = self.state.send(AudioStreamState::Error);
|
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
let _ = capturer.stop().await;
|
self.cleanup_failed_start(&capturer).await;
|
||||||
*self.capturer.write().await = None;
|
|
||||||
*self.encoder.lock().await = None;
|
|
||||||
let _ = self.state.send(AudioStreamState::Error);
|
|
||||||
return Err(AppError::AudioError(
|
return Err(AppError::AudioError(
|
||||||
"Timed out waiting for audio capture to start".to_string(),
|
"Timed out waiting for audio capture to start".to_string(),
|
||||||
));
|
));
|
||||||
@@ -205,22 +205,27 @@ impl AudioStreamer {
|
|||||||
let opus_subscribers = self.opus_subscribers.clone();
|
let opus_subscribers = self.opus_subscribers.clone();
|
||||||
let state = self.state.clone();
|
let state = self.state.clone();
|
||||||
let stop_flag = self.stop_flag.clone();
|
let stop_flag = self.stop_flag.clone();
|
||||||
|
let shutdown_rx = self.shutdown_generation.subscribe();
|
||||||
|
let _ = self.state.send(AudioStreamState::Running);
|
||||||
|
|
||||||
tokio::spawn(async move {
|
let task = tokio::spawn(async move {
|
||||||
Self::stream_task(
|
Self::stream_task(
|
||||||
capturer_for_task,
|
capturer_for_task,
|
||||||
encoder,
|
encoder,
|
||||||
opus_subscribers,
|
opus_subscribers,
|
||||||
state,
|
state,
|
||||||
stop_flag,
|
stop_flag,
|
||||||
|
shutdown_rx,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
});
|
});
|
||||||
|
*self.stream_task.lock().await = Some(task);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn stop(&self) -> Result<()> {
|
pub async fn stop(&self) -> Result<()> {
|
||||||
|
let _lifecycle = self.lifecycle.lock().await;
|
||||||
if self.state() == AudioStreamState::Stopped {
|
if self.state() == AudioStreamState::Stopped {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -228,10 +233,16 @@ impl AudioStreamer {
|
|||||||
info!("Stopping audio stream");
|
info!("Stopping audio stream");
|
||||||
|
|
||||||
self.stop_flag.store(true, Ordering::SeqCst);
|
self.stop_flag.store(true, Ordering::SeqCst);
|
||||||
|
self.shutdown_generation.send_modify(|generation| {
|
||||||
|
*generation = generation.wrapping_add(1);
|
||||||
|
});
|
||||||
|
|
||||||
if let Some(ref capturer) = *self.capturer.read().await {
|
if let Some(ref capturer) = *self.capturer.read().await {
|
||||||
capturer.stop().await?;
|
capturer.stop().await?;
|
||||||
}
|
}
|
||||||
|
if let Some(task) = self.stream_task.lock().await.take() {
|
||||||
|
let _ = task.await;
|
||||||
|
}
|
||||||
|
|
||||||
*self.capturer.write().await = None;
|
*self.capturer.write().await = None;
|
||||||
*self.encoder.lock().await = None;
|
*self.encoder.lock().await = None;
|
||||||
@@ -242,28 +253,26 @@ impl AudioStreamer {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn cleanup_failed_start(&self, capturer: &AudioCapturer) {
|
||||||
|
let _ = capturer.stop().await;
|
||||||
|
*self.capturer.write().await = None;
|
||||||
|
*self.encoder.lock().await = None;
|
||||||
|
let _ = self.state.send(AudioStreamState::Error);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_running(&self) -> bool {
|
pub fn is_running(&self) -> bool {
|
||||||
self.state() == AudioStreamState::Running
|
self.state() == AudioStreamState::Running
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fanout_opus(
|
fn fanout_opus(
|
||||||
subscribers: &Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
subscribers: &Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
||||||
frame: Arc<OpusFrame>,
|
frame: Arc<OpusFrame>,
|
||||||
) {
|
) {
|
||||||
let txs: Vec<_> = {
|
let mut subscribers = subscribers.lock().unwrap();
|
||||||
let g = subscribers.lock().unwrap();
|
subscribers.retain(|subscriber| match subscriber.try_send(frame.clone()) {
|
||||||
if g.is_empty() {
|
Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => true,
|
||||||
return;
|
Err(mpsc::error::TrySendError::Closed(_)) => false,
|
||||||
}
|
});
|
||||||
g.clone()
|
|
||||||
};
|
|
||||||
for tx in &txs {
|
|
||||||
let _ = tx.send(frame.clone()).await;
|
|
||||||
}
|
|
||||||
if txs.iter().any(|tx| tx.is_closed()) {
|
|
||||||
let mut g = subscribers.lock().unwrap();
|
|
||||||
g.retain(|tx| !tx.is_closed());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn stream_task(
|
async fn stream_task(
|
||||||
@@ -272,9 +281,9 @@ impl AudioStreamer {
|
|||||||
opus_subscribers: Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
opus_subscribers: Arc<Mutex<Vec<mpsc::Sender<Arc<OpusFrame>>>>>,
|
||||||
state: watch::Sender<AudioStreamState>,
|
state: watch::Sender<AudioStreamState>,
|
||||||
stop_flag: Arc<AtomicBool>,
|
stop_flag: Arc<AtomicBool>,
|
||||||
|
mut shutdown_rx: watch::Receiver<u64>,
|
||||||
) {
|
) {
|
||||||
let mut pcm_rx = capturer.subscribe();
|
let mut pcm_rx = capturer.subscribe();
|
||||||
let _ = state.send(AudioStreamState::Running);
|
|
||||||
|
|
||||||
debug!("Audio stream task started (48 kHz stereo → Opus, mpsc fan-out)");
|
debug!("Audio stream task started (48 kHz stereo → Opus, mpsc fan-out)");
|
||||||
|
|
||||||
@@ -291,8 +300,19 @@ impl AudioStreamer {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let recv_result =
|
let recv_result = tokio::select! {
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(2), pcm_rx.recv()).await;
|
biased;
|
||||||
|
changed = shutdown_rx.changed() => {
|
||||||
|
if changed.is_ok() || stop_flag.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result = tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(2),
|
||||||
|
pcm_rx.recv(),
|
||||||
|
) => result,
|
||||||
|
};
|
||||||
|
|
||||||
match recv_result {
|
match recv_result {
|
||||||
Ok(Ok(audio_frame)) => {
|
Ok(Ok(audio_frame)) => {
|
||||||
@@ -316,23 +336,17 @@ impl AudioStreamer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
while pending.len() >= OPUS_STEREO_SAMPLES {
|
while pending.len() >= OPUS_STEREO_SAMPLES {
|
||||||
let pcm_20ms = Bytes::copy_from_slice(bytemuck::cast_slice(
|
|
||||||
&pending[..OPUS_STEREO_SAMPLES],
|
|
||||||
));
|
|
||||||
pending.drain(..OPUS_STEREO_SAMPLES);
|
|
||||||
|
|
||||||
let frame_48k = AudioFrame::new_interleaved(pcm_20ms, 2, 48_000, 0);
|
|
||||||
|
|
||||||
let opus_result = {
|
let opus_result = {
|
||||||
let mut enc_guard = encoder.lock().await;
|
let mut enc_guard = encoder.lock().await;
|
||||||
(*enc_guard)
|
(*enc_guard)
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.map(|enc| enc.encode_frame(&frame_48k))
|
.map(|enc| enc.encode(&pending[..OPUS_STEREO_SAMPLES]))
|
||||||
};
|
};
|
||||||
|
pending.drain(..OPUS_STEREO_SAMPLES);
|
||||||
|
|
||||||
match opus_result {
|
match opus_result {
|
||||||
Some(Ok(opus_frame)) => {
|
Some(Ok(opus_frame)) => {
|
||||||
Self::fanout_opus(&opus_subscribers, Arc::new(opus_frame)).await;
|
Self::fanout_opus(&opus_subscribers, Arc::new(opus_frame));
|
||||||
}
|
}
|
||||||
Some(Err(e)) => {
|
Some(Err(e)) => {
|
||||||
error!("Opus encode error: {}", e);
|
error!("Opus encode error: {}", e);
|
||||||
@@ -365,6 +379,7 @@ impl AudioStreamer {
|
|||||||
let _ = state.send(AudioStreamState::Stopped);
|
let _ = state.send(AudioStreamState::Stopped);
|
||||||
} else {
|
} else {
|
||||||
opus_subscribers.lock().unwrap().clear();
|
opus_subscribers.lock().unwrap().clear();
|
||||||
|
let _ = capturer.stop().await;
|
||||||
}
|
}
|
||||||
info!("Audio stream task ended");
|
info!("Audio stream task ended");
|
||||||
}
|
}
|
||||||
@@ -379,6 +394,7 @@ impl Default for AudioStreamer {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_streamer_config_default() {
|
fn test_streamer_config_default() {
|
||||||
@@ -398,4 +414,42 @@ mod tests {
|
|||||||
let streamer = AudioStreamer::new();
|
let streamer = AudioStreamer::new();
|
||||||
assert_eq!(streamer.state(), AudioStreamState::Stopped);
|
assert_eq!(streamer.state(), AudioStreamState::Stopped);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn slow_subscriber_does_not_block_or_grow_unbounded() {
|
||||||
|
let streamer = AudioStreamer::new();
|
||||||
|
let mut receiver = streamer.subscribe_opus();
|
||||||
|
for sequence in 0..20 {
|
||||||
|
AudioStreamer::fanout_opus(
|
||||||
|
&streamer.opus_subscribers,
|
||||||
|
Arc::new(OpusFrame {
|
||||||
|
data: Bytes::from_static(&[1]),
|
||||||
|
duration_ms: 20,
|
||||||
|
sequence,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut received = 0;
|
||||||
|
while receiver.try_recv().is_ok() {
|
||||||
|
received += 1;
|
||||||
|
}
|
||||||
|
assert_eq!(received, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_subscriber_is_pruned() {
|
||||||
|
let streamer = AudioStreamer::new();
|
||||||
|
let receiver = streamer.subscribe_opus();
|
||||||
|
drop(receiver);
|
||||||
|
AudioStreamer::fanout_opus(
|
||||||
|
&streamer.opus_subscribers,
|
||||||
|
Arc::new(OpusFrame {
|
||||||
|
data: Bytes::from_static(&[1]),
|
||||||
|
duration_ms: 20,
|
||||||
|
sequence: 0,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert_eq!(streamer.subscriber_count(), 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
59
src/audio/uac/decoder.rs
Normal file
59
src/audio/uac/decoder.rs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
use audiopus::coder::Decoder;
|
||||||
|
use audiopus::{Channels, SampleRate};
|
||||||
|
|
||||||
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
|
const CHANNELS: usize = 2;
|
||||||
|
const MAX_PACKET_BYTES: usize = 1275;
|
||||||
|
const MAX_SAMPLES_PER_CHANNEL: usize = 5760;
|
||||||
|
|
||||||
|
pub struct UacOpusDecoder {
|
||||||
|
decoder: Decoder,
|
||||||
|
buffer: Vec<i16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UacOpusDecoder {
|
||||||
|
pub fn new() -> Result<Self> {
|
||||||
|
let decoder = Decoder::new(SampleRate::Hz48000, Channels::Stereo)
|
||||||
|
.map_err(|error| AppError::AudioError(format!("Opus decoder init failed: {error}")))?;
|
||||||
|
Ok(Self {
|
||||||
|
decoder,
|
||||||
|
buffer: vec![0; MAX_SAMPLES_PER_CHANNEL * CHANNELS],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decode(&mut self, packet: &[u8]) -> Result<&[i16]> {
|
||||||
|
if packet.is_empty() || packet.len() > MAX_PACKET_BYTES {
|
||||||
|
return Err(AppError::BadRequest(format!(
|
||||||
|
"invalid Opus packet length {}",
|
||||||
|
packet.len()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let frames = self
|
||||||
|
.decoder
|
||||||
|
.decode(Some(packet), &mut self.buffer, false)
|
||||||
|
.map_err(|error| AppError::AudioError(format!("Opus decode failed: {error}")))?;
|
||||||
|
Ok(&self.buffer[..frames * CHANNELS])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use audiopus::coder::Encoder;
|
||||||
|
use audiopus::Application;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn decode_preserves_all_stereo_samples() {
|
||||||
|
let encoder =
|
||||||
|
Encoder::new(SampleRate::Hz48000, Channels::Stereo, Application::Audio).unwrap();
|
||||||
|
let pcm = vec![0i16; 960 * CHANNELS];
|
||||||
|
let mut packet = vec![0u8; MAX_PACKET_BYTES];
|
||||||
|
let packet_len = encoder.encode(&pcm, &mut packet).unwrap();
|
||||||
|
|
||||||
|
let mut decoder = UacOpusDecoder::new().unwrap();
|
||||||
|
let decoded = decoder.decode(&packet[..packet_len]).unwrap();
|
||||||
|
assert_eq!(decoded.len(), pcm.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/audio/uac/mod.rs
Normal file
9
src/audio/uac/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
//! Browser-to-USB microphone audio pipeline.
|
||||||
|
|
||||||
|
mod decoder;
|
||||||
|
mod playback;
|
||||||
|
mod protocol;
|
||||||
|
|
||||||
|
pub use decoder::UacOpusDecoder;
|
||||||
|
pub use playback::{UacPlayback, UacPlaybackConfig, UacPlaybackState, UacSession};
|
||||||
|
pub use protocol::{parse_audio_packet, UacAudioPacket};
|
||||||
509
src/audio/uac/playback.rs
Normal file
509
src/audio/uac/playback.rs
Normal file
@@ -0,0 +1,509 @@
|
|||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use alsa::pcm::{Access, Format, Frames, HwParams, State};
|
||||||
|
use alsa::{Direction, ValueOr, PCM};
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
|
const RETRY_BACKOFF: Duration = Duration::from_secs(1);
|
||||||
|
const PERIOD_FRAMES: Frames = 960;
|
||||||
|
const BUFFER_FRAMES: Frames = 4_800;
|
||||||
|
const START_THRESHOLD_PERIODS: Frames = 4;
|
||||||
|
const SINK_STALL_TIMEOUT: Duration = Duration::from_millis(200);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum UacPlaybackState {
|
||||||
|
Idle,
|
||||||
|
Waiting,
|
||||||
|
Active,
|
||||||
|
Stalled,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UacPlaybackState {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Idle => "idle",
|
||||||
|
Self::Waiting => "waiting",
|
||||||
|
Self::Active => "active",
|
||||||
|
Self::Stalled => "stalled",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct UacPlaybackConfig {
|
||||||
|
pub device_name: String,
|
||||||
|
pub sample_rate: u32,
|
||||||
|
pub channels: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for UacPlaybackConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
device_name: crate::otg::uac::find_uac_pcm_device()
|
||||||
|
.unwrap_or_else(crate::otg::uac::uac_pcm_device),
|
||||||
|
sample_rate: 48_000,
|
||||||
|
channels: 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PlaybackInner {
|
||||||
|
config: UacPlaybackConfig,
|
||||||
|
stopped: AtomicBool,
|
||||||
|
active_session: Mutex<Option<Arc<Mutex<SessionRuntime>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SessionSink {
|
||||||
|
Closed { retry_at: Option<Instant> },
|
||||||
|
Probing { pcm: PCM, stalled: bool },
|
||||||
|
Active { pcm: PCM, last_progress: Instant },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SessionSink {
|
||||||
|
fn state(&self) -> UacPlaybackState {
|
||||||
|
match self {
|
||||||
|
Self::Closed { retry_at: None } => UacPlaybackState::Waiting,
|
||||||
|
Self::Closed { retry_at: Some(_) } => UacPlaybackState::Stalled,
|
||||||
|
Self::Probing { stalled: false, .. } => UacPlaybackState::Waiting,
|
||||||
|
Self::Probing { stalled: true, .. } => UacPlaybackState::Stalled,
|
||||||
|
Self::Active { .. } => UacPlaybackState::Active,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SessionRuntime {
|
||||||
|
sink: SessionSink,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SessionRuntime {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
sink: SessionSink::Closed { retry_at: None },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state(&self) -> UacPlaybackState {
|
||||||
|
self.sink.state()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self) {
|
||||||
|
self.sink = SessionSink::Closed { retry_at: None };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Advance playback only when a WebSocket frame arrives. All ALSA handles
|
||||||
|
/// are non-blocking, so a slow or absent USB host drops the current frame
|
||||||
|
/// instead of occupying a worker thread or accumulating stale speech.
|
||||||
|
fn write(&mut self, config: &UacPlaybackConfig, samples: &[i16]) -> bool {
|
||||||
|
let sink = std::mem::replace(&mut self.sink, SessionSink::Closed { retry_at: None });
|
||||||
|
let (next_sink, accepted) = drive_sink(sink, config, samples);
|
||||||
|
self.sink = next_sink;
|
||||||
|
accepted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct UacPlayback {
|
||||||
|
inner: Arc<PlaybackInner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UacSession {
|
||||||
|
playback: UacPlayback,
|
||||||
|
runtime: Arc<Mutex<SessionRuntime>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UacPlayback {
|
||||||
|
pub fn start(config: UacPlaybackConfig) -> Result<Self> {
|
||||||
|
if config.sample_rate != 48_000 || config.channels != 2 {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"UAC playback supports only 48000 Hz stereo".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
inner: Arc::new(PlaybackInner {
|
||||||
|
config,
|
||||||
|
stopped: AtomicBool::new(false),
|
||||||
|
active_session: Mutex::new(None),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquire_session(&self) -> Result<UacSession> {
|
||||||
|
let mut active = self.inner.active_session.lock().unwrap();
|
||||||
|
if self.inner.stopped.load(Ordering::Acquire) {
|
||||||
|
return Err(AppError::ServiceUnavailable(
|
||||||
|
"UAC playback is stopping".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if active.is_some() {
|
||||||
|
return Err(AppError::ServiceUnavailable(
|
||||||
|
"another UAC microphone session is already active".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let runtime = Arc::new(Mutex::new(SessionRuntime::new()));
|
||||||
|
*active = Some(Arc::clone(&runtime));
|
||||||
|
Ok(UacSession {
|
||||||
|
playback: self.clone(),
|
||||||
|
runtime,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop accepting frames and synchronously close an active ALSA handle.
|
||||||
|
/// This guarantees configfs may rebuild the UAC function after this call.
|
||||||
|
pub fn stop(&self) {
|
||||||
|
if self.inner.stopped.swap(true, Ordering::AcqRel) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let runtime = self.inner.active_session.lock().unwrap().take();
|
||||||
|
if let Some(runtime) = runtime {
|
||||||
|
runtime.lock().unwrap().close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UacSession {
|
||||||
|
pub fn state(&self) -> UacPlaybackState {
|
||||||
|
self.runtime.lock().unwrap().state()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns whether the frame was accepted and the resulting target state.
|
||||||
|
pub fn try_write(&self, pcm: &[i16]) -> Result<(bool, UacPlaybackState)> {
|
||||||
|
let channels = self.playback.inner.config.channels as usize;
|
||||||
|
if pcm.is_empty() || !pcm.len().is_multiple_of(channels) {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"UAC PCM must contain complete stereo frames".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.playback.inner.stopped.load(Ordering::Acquire) {
|
||||||
|
return Err(AppError::ServiceUnavailable(
|
||||||
|
"UAC playback has stopped".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut runtime = self.runtime.lock().unwrap();
|
||||||
|
if self.playback.inner.stopped.load(Ordering::Acquire) {
|
||||||
|
runtime.close();
|
||||||
|
return Err(AppError::ServiceUnavailable(
|
||||||
|
"UAC playback has stopped".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let accepted = runtime.write(&self.playback.inner.config, pcm);
|
||||||
|
Ok((accepted, runtime.state()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for UacSession {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let mut active = self.playback.inner.active_session.lock().unwrap();
|
||||||
|
if active
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|session| Arc::ptr_eq(session, &self.runtime))
|
||||||
|
{
|
||||||
|
*active = None;
|
||||||
|
}
|
||||||
|
drop(active);
|
||||||
|
self.runtime.lock().unwrap().close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drive_sink(
|
||||||
|
sink: SessionSink,
|
||||||
|
config: &UacPlaybackConfig,
|
||||||
|
samples: &[i16],
|
||||||
|
) -> (SessionSink, bool) {
|
||||||
|
match sink {
|
||||||
|
SessionSink::Closed { retry_at } => {
|
||||||
|
if retry_at.is_some_and(|deadline| Instant::now() < deadline) {
|
||||||
|
return (SessionSink::Closed { retry_at }, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
match open_pcm(config).and_then(|pcm| {
|
||||||
|
prime_pcm_with_silence(&pcm, config.channels as usize)?;
|
||||||
|
Ok(pcm)
|
||||||
|
}) {
|
||||||
|
Ok(pcm) => drive_probe(pcm, false, config, samples),
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Failed to open UAC playback device; retrying later: {error}");
|
||||||
|
(
|
||||||
|
SessionSink::Closed {
|
||||||
|
retry_at: Some(Instant::now() + RETRY_BACKOFF),
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SessionSink::Probing { pcm, stalled } => drive_probe(pcm, stalled, config, samples),
|
||||||
|
SessionSink::Active { pcm, last_progress } => {
|
||||||
|
drive_active(pcm, last_progress, config, samples)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drive_probe(
|
||||||
|
pcm: PCM,
|
||||||
|
stalled: bool,
|
||||||
|
config: &UacPlaybackConfig,
|
||||||
|
samples: &[i16],
|
||||||
|
) -> (SessionSink, bool) {
|
||||||
|
match sink_is_consuming(&pcm) {
|
||||||
|
Ok(false) => (SessionSink::Probing { pcm, stalled }, false),
|
||||||
|
Ok(true) => {
|
||||||
|
if let Err(error) = reset_pcm_buffer(&pcm) {
|
||||||
|
warn!("Failed to activate UAC playback; retrying later: {error}");
|
||||||
|
return retry_later();
|
||||||
|
}
|
||||||
|
info!("UAC target started consuming microphone audio");
|
||||||
|
drive_active(pcm, Instant::now(), config, samples)
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Failed to probe UAC playback; retrying later: {error}");
|
||||||
|
retry_later()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drive_active(
|
||||||
|
pcm: PCM,
|
||||||
|
last_progress: Instant,
|
||||||
|
config: &UacPlaybackConfig,
|
||||||
|
samples: &[i16],
|
||||||
|
) -> (SessionSink, bool) {
|
||||||
|
match write_pcm_nonblocking(&pcm, samples, config.channels as usize) {
|
||||||
|
Ok(WriteOutcome::Progress) => (
|
||||||
|
SessionSink::Active {
|
||||||
|
pcm,
|
||||||
|
last_progress: Instant::now(),
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
Ok(WriteOutcome::Recovered) => (
|
||||||
|
SessionSink::Active {
|
||||||
|
pcm,
|
||||||
|
last_progress: Instant::now(),
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
Ok(WriteOutcome::Blocked) if last_progress.elapsed() < SINK_STALL_TIMEOUT => {
|
||||||
|
(SessionSink::Active { pcm, last_progress }, false)
|
||||||
|
}
|
||||||
|
Ok(WriteOutcome::Blocked) => {
|
||||||
|
if let Err(error) = reset_pcm_buffer(&pcm)
|
||||||
|
.and_then(|_| prime_pcm_with_silence(&pcm, config.channels as usize))
|
||||||
|
{
|
||||||
|
warn!("Failed to reset stalled UAC playback: {error}");
|
||||||
|
return retry_later();
|
||||||
|
}
|
||||||
|
info!("UAC target stopped consuming audio; waiting for playback activity");
|
||||||
|
(SessionSink::Probing { pcm, stalled: true }, false)
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("UAC playback write failed; retrying later: {error}");
|
||||||
|
retry_later()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn retry_later() -> (SessionSink, bool) {
|
||||||
|
(
|
||||||
|
SessionSink::Closed {
|
||||||
|
retry_at: Some(Instant::now() + RETRY_BACKOFF),
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_pcm(config: &UacPlaybackConfig) -> Result<PCM> {
|
||||||
|
let pcm = PCM::new(&config.device_name, Direction::Playback, true).map_err(|error| {
|
||||||
|
AppError::AudioError(format!(
|
||||||
|
"Failed to open UAC device {}: {error}",
|
||||||
|
config.device_name
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
{
|
||||||
|
let params = HwParams::any(&pcm)
|
||||||
|
.map_err(|error| AppError::AudioError(format!("UAC HwParams failed: {error}")))?;
|
||||||
|
params
|
||||||
|
.set_channels(config.channels as u32)
|
||||||
|
.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_period_size_near(PERIOD_FRAMES, ValueOr::Nearest))
|
||||||
|
.and_then(|_| params.set_buffer_size_near(BUFFER_FRAMES))
|
||||||
|
.and_then(|_| pcm.hw_params(¶ms))
|
||||||
|
.map_err(|error| {
|
||||||
|
AppError::AudioError(format!("Failed to configure UAC playback: {error}"))
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (buffer_frames, period_frames) = pcm.get_params().map_err(|error| {
|
||||||
|
AppError::AudioError(format!("Failed to read UAC PCM parameters: {error}"))
|
||||||
|
})?;
|
||||||
|
{
|
||||||
|
let params = pcm.sw_params_current().map_err(|error| {
|
||||||
|
AppError::AudioError(format!("Failed to read UAC SwParams: {error}"))
|
||||||
|
})?;
|
||||||
|
let start_threshold =
|
||||||
|
(period_frames as Frames * START_THRESHOLD_PERIODS).min(buffer_frames as Frames);
|
||||||
|
params
|
||||||
|
.set_start_threshold(start_threshold)
|
||||||
|
.and_then(|_| params.set_avail_min(period_frames as Frames))
|
||||||
|
.and_then(|_| pcm.sw_params(¶ms))
|
||||||
|
.map_err(|error| {
|
||||||
|
AppError::AudioError(format!("Failed to configure UAC SwParams: {error}"))
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
pcm.prepare().map_err(|error| {
|
||||||
|
AppError::AudioError(format!("Failed to prepare UAC playback: {error}"))
|
||||||
|
})?;
|
||||||
|
info!(
|
||||||
|
"UAC playback opened on {} (buffer={} frames, period={} frames)",
|
||||||
|
config.device_name, buffer_frames, period_frames
|
||||||
|
);
|
||||||
|
Ok(pcm)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum WriteOutcome {
|
||||||
|
Progress,
|
||||||
|
Blocked,
|
||||||
|
Recovered,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_pcm_nonblocking(pcm: &PCM, samples: &[i16], channels: usize) -> Result<WriteOutcome> {
|
||||||
|
let total_frames = samples.len() / channels;
|
||||||
|
match pcm.avail() {
|
||||||
|
Ok(available) if available < total_frames as Frames => return Ok(WriteOutcome::Blocked),
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) => {
|
||||||
|
recover_pcm(pcm, error)?;
|
||||||
|
return Ok(WriteOutcome::Recovered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let io = pcm
|
||||||
|
.io_i16()
|
||||||
|
.map_err(|error| AppError::AudioError(format!("UAC PCM I/O failed: {error}")))?;
|
||||||
|
match io.writei(samples) {
|
||||||
|
Ok(0) => Ok(WriteOutcome::Blocked),
|
||||||
|
Ok(_) => Ok(WriteOutcome::Progress),
|
||||||
|
Err(error) if error.errno() == libc::EAGAIN => Ok(WriteOutcome::Blocked),
|
||||||
|
Err(error) => {
|
||||||
|
recover_pcm(pcm, error)?;
|
||||||
|
Ok(WriteOutcome::Recovered)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Once a full playback buffer gains at least one period of free space, the
|
||||||
|
/// USB host has enabled the UAC streaming interface and is consuming samples.
|
||||||
|
fn sink_is_consuming(pcm: &PCM) -> Result<bool> {
|
||||||
|
if pcm.state() == State::XRun {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
match pcm.avail() {
|
||||||
|
Ok(available) => Ok(available >= PERIOD_FRAMES),
|
||||||
|
Err(error) if error.errno() == libc::EPIPE => Ok(true),
|
||||||
|
Err(error) => Err(AppError::AudioError(format!(
|
||||||
|
"Failed to query UAC playback availability: {error}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recover_pcm(pcm: &PCM, error: alsa::Error) -> Result<()> {
|
||||||
|
let errno = error.errno();
|
||||||
|
pcm.try_recover(error, true).map_err(|recover_error| {
|
||||||
|
AppError::AudioError(format!("Failed to recover UAC playback: {recover_error}"))
|
||||||
|
})?;
|
||||||
|
if matches!(errno, libc::EPIPE | libc::ESTRPIPE) {
|
||||||
|
warn!("Recovered UAC playback after ALSA error {errno}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_pcm_buffer(pcm: &PCM) -> Result<()> {
|
||||||
|
pcm.drop()
|
||||||
|
.and_then(|_| pcm.prepare())
|
||||||
|
.map_err(|error| AppError::AudioError(format!("Failed to reset UAC PCM: {error}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prime the non-blocking ALSA buffer with silence. Subsequent WebSocket
|
||||||
|
/// frames inspect buffer progress to detect when the USB host starts reading.
|
||||||
|
fn prime_pcm_with_silence(pcm: &PCM, channels: usize) -> Result<()> {
|
||||||
|
let silence = vec![0i16; BUFFER_FRAMES as usize * channels];
|
||||||
|
let io = pcm
|
||||||
|
.io_i16()
|
||||||
|
.map_err(|error| AppError::AudioError(format!("UAC PCM I/O failed: {error}")))?;
|
||||||
|
let mut frame_offset = 0usize;
|
||||||
|
while frame_offset < BUFFER_FRAMES as usize {
|
||||||
|
match io.writei(&silence[frame_offset * channels..]) {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(written) => frame_offset += written,
|
||||||
|
Err(error) if error.errno() == libc::EAGAIN => break,
|
||||||
|
Err(error) => {
|
||||||
|
return Err(AppError::AudioError(format!(
|
||||||
|
"Failed to prime UAC PCM with silence: {error}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn permits_only_one_microphone_session() {
|
||||||
|
let playback = UacPlayback::start(UacPlaybackConfig::default()).unwrap();
|
||||||
|
let first = playback.acquire_session().unwrap();
|
||||||
|
assert_eq!(first.state(), UacPlaybackState::Waiting);
|
||||||
|
assert!(playback.acquire_session().is_err());
|
||||||
|
|
||||||
|
drop(first);
|
||||||
|
assert!(playback.acquire_session().is_ok());
|
||||||
|
playback.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stop_rejects_new_and_existing_session_writes() {
|
||||||
|
let playback = UacPlayback::start(UacPlaybackConfig::default()).unwrap();
|
||||||
|
let session = playback.acquire_session().unwrap();
|
||||||
|
|
||||||
|
playback.stop();
|
||||||
|
|
||||||
|
assert!(session.try_write(&[0, 0]).is_err());
|
||||||
|
assert!(playback.acquire_session().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_incomplete_stereo_frames_before_opening_alsa() {
|
||||||
|
let playback = UacPlayback::start(UacPlaybackConfig::default()).unwrap();
|
||||||
|
let session = playback.acquire_session().unwrap();
|
||||||
|
|
||||||
|
assert!(session.try_write(&[0]).is_err());
|
||||||
|
assert_eq!(session.state(), UacPlaybackState::Waiting);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_sink_state_reflects_retry_backoff() {
|
||||||
|
assert_eq!(
|
||||||
|
SessionSink::Closed { retry_at: None }.state(),
|
||||||
|
UacPlaybackState::Waiting
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
SessionSink::Closed {
|
||||||
|
retry_at: Some(Instant::now())
|
||||||
|
}
|
||||||
|
.state(),
|
||||||
|
UacPlaybackState::Stalled
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
98
src/audio/uac/protocol.rs
Normal file
98
src/audio/uac/protocol.rs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
use crate::error::{AppError, Result};
|
||||||
|
|
||||||
|
const HEADER_SIZE: usize = 15;
|
||||||
|
const OPUS_MESSAGE: u8 = 0x03;
|
||||||
|
const PCM_MESSAGE: u8 = 0x04;
|
||||||
|
const CHANNELS: usize = 2;
|
||||||
|
const MAX_PCM_SAMPLES: usize = 5760 * CHANNELS;
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum UacAudioPacket<'a> {
|
||||||
|
Opus(&'a [u8]),
|
||||||
|
Pcm(&'a [u8]),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UacAudioPacket<'_> {
|
||||||
|
pub fn pcm_samples(&self) -> Result<Vec<i16>> {
|
||||||
|
let Self::Pcm(bytes) = self else {
|
||||||
|
return Err(AppError::BadRequest("packet is not raw PCM".to_string()));
|
||||||
|
};
|
||||||
|
if bytes.is_empty() || bytes.len() % (CHANNELS * 2) != 0 {
|
||||||
|
return Err(AppError::BadRequest(format!(
|
||||||
|
"invalid stereo PCM byte length {}",
|
||||||
|
bytes.len()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if bytes.len() / 2 > MAX_PCM_SAMPLES {
|
||||||
|
return Err(AppError::BadRequest("PCM frame exceeds 120 ms".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(bytes
|
||||||
|
.chunks_exact(2)
|
||||||
|
.map(|sample| i16::from_le_bytes([sample[0], sample[1]]))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_audio_packet(data: &[u8]) -> Result<UacAudioPacket<'_>> {
|
||||||
|
if data.len() < HEADER_SIZE {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"UAC frame is shorter than its header".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload_len = u32::from_le_bytes([data[11], data[12], data[13], data[14]]) as usize;
|
||||||
|
let expected_len = HEADER_SIZE
|
||||||
|
.checked_add(payload_len)
|
||||||
|
.ok_or_else(|| AppError::BadRequest("UAC payload length overflow".to_string()))?;
|
||||||
|
if data.len() != expected_len {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"UAC payload length does not match its header".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload = &data[HEADER_SIZE..];
|
||||||
|
match data[0] {
|
||||||
|
OPUS_MESSAGE => Ok(UacAudioPacket::Opus(payload)),
|
||||||
|
PCM_MESSAGE => Ok(UacAudioPacket::Pcm(payload)),
|
||||||
|
message_type => Err(AppError::BadRequest(format!(
|
||||||
|
"unsupported UAC message type 0x{message_type:02x}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn message(message_type: u8, payload: &[u8]) -> Vec<u8> {
|
||||||
|
let mut data = vec![0; HEADER_SIZE + payload.len()];
|
||||||
|
data[0] = message_type;
|
||||||
|
data[11..15].copy_from_slice(&(payload.len() as u32).to_le_bytes());
|
||||||
|
data[HEADER_SIZE..].copy_from_slice(payload);
|
||||||
|
data
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requires_exact_payload_length() {
|
||||||
|
let valid = message(OPUS_MESSAGE, &[1, 2, 3]);
|
||||||
|
assert_eq!(
|
||||||
|
parse_audio_packet(&valid).unwrap(),
|
||||||
|
UacAudioPacket::Opus(&[1, 2, 3])
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut trailing = valid.clone();
|
||||||
|
trailing.push(4);
|
||||||
|
assert!(parse_audio_packet(&trailing).is_err());
|
||||||
|
assert!(parse_audio_packet(&valid[..valid.len() - 1]).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn converts_little_endian_stereo_pcm() {
|
||||||
|
let data = message(PCM_MESSAGE, &[1, 0, 255, 255]);
|
||||||
|
assert_eq!(
|
||||||
|
parse_audio_packet(&data).unwrap().pcm_samples().unwrap(),
|
||||||
|
vec![1, -1]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,6 +71,7 @@ pub async fn auth_middleware(
|
|||||||
fn unauthorized_response(message: &str) -> Response {
|
fn unauthorized_response(message: &str) -> Response {
|
||||||
let body = ErrorResponse {
|
let body = ErrorResponse {
|
||||||
success: false,
|
success: false,
|
||||||
|
code: None,
|
||||||
message: message.to_string(),
|
message: message.to_string(),
|
||||||
};
|
};
|
||||||
(StatusCode::UNAUTHORIZED, Json(body)).into_response()
|
(StatusCode::UNAUTHORIZED, Json(body)).into_response()
|
||||||
@@ -79,7 +80,7 @@ fn unauthorized_response(message: &str) -> Response {
|
|||||||
fn is_public_endpoint(path: &str) -> bool {
|
fn is_public_endpoint(path: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
path,
|
path,
|
||||||
"/" | "/auth/login" | "/health" | "/setup" | "/setup/init"
|
"/" | "/auth/login" | "/auth/login/totp" | "/health" | "/setup" | "/setup/init"
|
||||||
) || path.starts_with("/assets/")
|
) || path.starts_with("/assets/")
|
||||||
|| path.starts_with("/static/")
|
|| path.starts_with("/static/")
|
||||||
|| path.ends_with(".js")
|
|| path.ends_with(".js")
|
||||||
@@ -92,6 +93,11 @@ fn is_public_endpoint(path: &str) -> bool {
|
|||||||
fn is_setup_public_endpoint(path: &str) -> bool {
|
fn is_setup_public_endpoint(path: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
path,
|
path,
|
||||||
"/setup" | "/setup/init" | "/devices" | "/stream/codecs"
|
"/setup"
|
||||||
|
| "/setup/init"
|
||||||
|
| "/devices"
|
||||||
|
| "/video/input-status"
|
||||||
|
| "/stream/codecs"
|
||||||
|
| "/video/codecs"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
pub mod middleware;
|
pub mod middleware;
|
||||||
mod password;
|
mod password;
|
||||||
mod session;
|
mod session;
|
||||||
|
mod two_factor;
|
||||||
mod user;
|
mod user;
|
||||||
|
|
||||||
pub use middleware::{auth_middleware, SESSION_COOKIE};
|
pub use middleware::{auth_middleware, SESSION_COOKIE};
|
||||||
pub use password::{hash_password, verify_password};
|
pub use password::{hash_password, verify_password};
|
||||||
pub use session::{Session, SessionStore};
|
pub use session::{Session, SessionStore};
|
||||||
|
pub use two_factor::{server_time_unix_ms, ChallengeInfo, EnrollmentInfo, TwoFactorService};
|
||||||
pub use user::{User, UserStore};
|
pub use user::{User, UserStore};
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user