Compare commits

..

No commits in common. "main" and "v0.2.17" have entirely different histories.

40 changed files with 4402 additions and 4895 deletions

View file

@ -1,113 +0,0 @@
name: CI
on:
push:
branches:
- main
pull_request:
workflow_dispatch:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: "1"
jobs:
build-linux:
name: Linux (check, test, build)
runs-on: ubuntu-24.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install System Dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
pkg-config clang libva-dev \
libavcodec-dev libavformat-dev libavutil-dev \
libswresample-dev libswscale-dev libavfilter-dev libavdevice-dev \
libpipewire-0.3-dev libxcb1-dev libxcb-shm0-dev libxcb-xfixes0-dev \
libasound2-dev
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Cache cargo registry and target
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: linux-${{ hashFiles('Cargo.lock') }}
restore-keys: linux-
- name: Format check (advisory)
continue-on-error: true
run: cargo fmt --check
- name: Type check
run: cargo check --locked --all-targets
- name: Unit tests
run: cargo test --locked
- name: Clippy
run: cargo clippy --locked --all-targets -- -D warnings
- name: Build release
run: cargo build --locked --release
- name: Verify binary
run: |
./target/release/scythe --help | head -3
test -x target/release/scythe
ls -la target/release/scythe
- name: Upload binary
uses: actions/upload-artifact@v4
with:
name: scythe-linux-x86_64
path: target/release/scythe
if-no-files-found: error
build-windows:
name: Windows (cross build)
runs-on: windows-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
path-type: minimal
install: >-
mingw-w64-x86_64-toolchain
mingw-w64-x86_64-rust
mingw-w64-x86_64-ffmpeg
mingw-w64-x86_64-pkg-config
mingw-w64-x86_64-clang
- name: Build release
shell: msys2 {0}
env:
LIBCLANG_PATH: /mingw64/bin
BINDGEN_EXTRA_CLANG_ARGS: "--target=x86_64-w64-windows-gnu"
run: |
cargo build --release
ls -la target/release/scythe.exe
- name: Upload binary
uses: actions/upload-artifact@v4
with:
name: scythe-windows-x86_64
path: target/release/scythe.exe
if-no-files-found: error

View file

@ -33,15 +33,14 @@ jobs:
- name: Build Release Binaries
run: cargo build --release
- name: Package Linux Tarball (Unified Binary)
- name: Package Linux Tarball (Generic Binaries)
run: |
mkdir -p dist/scythe-linux-x86_64
cp target/release/scythe dist/scythe-linux-x86_64/
ln -sf scythe dist/scythe-linux-x86_64/scythe-daemon
ln -sf scythe dist/scythe-linux-x86_64/scythe-ui
ln -sf scythe dist/scythe-linux-x86_64/vrec-daemon
ln -sf scythe dist/scythe-linux-x86_64/vrec-ui
ln -sf scythe dist/scythe-linux-x86_64/vrec
cp target/release/scythe-daemon target/release/scythe-ui dist/scythe-linux-x86_64/
ln -sf scythe-daemon dist/scythe-linux-x86_64/vrec-daemon
ln -sf scythe-ui dist/scythe-linux-x86_64/vrec-ui
ln -sf scythe-ui dist/scythe-linux-x86_64/scythe
ln -sf scythe-ui dist/scythe-linux-x86_64/vrec
cp packaging/scythe.desktop dist/scythe-linux-x86_64/
tar -czvf dist/scythe-linux-x86_64.tar.gz -C dist scythe-linux-x86_64
@ -64,12 +63,12 @@ jobs:
Description: High-performance GPU hardware screen recorder and instant replay overlay
Depends: libgtk-3-0, libgtk-layer-shell0, libpipewire-0.3-0, libva2, libasound2
EOF
cp target/release/scythe "deb/scythe_${VERSION}/usr/bin/scythe"
ln -sf scythe "deb/scythe_${VERSION}/usr/bin/scythe-daemon"
ln -sf scythe "deb/scythe_${VERSION}/usr/bin/scythe-ui"
ln -sf scythe "deb/scythe_${VERSION}/usr/bin/vrec-daemon"
ln -sf scythe "deb/scythe_${VERSION}/usr/bin/vrec-ui"
ln -sf scythe "deb/scythe_${VERSION}/usr/bin/vrec"
cp target/release/scythe-daemon "deb/scythe_${VERSION}/usr/bin/"
cp target/release/scythe-ui "deb/scythe_${VERSION}/usr/bin/"
ln -sf scythe-daemon "deb/scythe_${VERSION}/usr/bin/vrec-daemon"
ln -sf scythe-ui "deb/scythe_${VERSION}/usr/bin/vrec-ui"
ln -sf scythe-ui "deb/scythe_${VERSION}/usr/bin/scythe"
ln -sf scythe-ui "deb/scythe_${VERSION}/usr/bin/vrec"
cp packaging/scythe.desktop "deb/scythe_${VERSION}/usr/share/applications/"
dpkg-deb --build "deb/scythe_${VERSION}" "dist/scythe_${VERSION}_amd64.deb"
@ -82,18 +81,17 @@ jobs:
- name: Package Standalone AppImage
run: |
mkdir -p AppDir/usr/bin AppDir/usr/share/applications AppDir/usr/share/icons/hicolor/scalable/apps
cp target/release/scythe AppDir/usr/bin/
ln -sf scythe AppDir/usr/bin/scythe-ui
ln -sf scythe AppDir/usr/bin/scythe-daemon
ln -sf scythe AppDir/usr/bin/vrec-ui
ln -sf scythe AppDir/usr/bin/vrec-daemon
ln -sf scythe AppDir/usr/bin/vrec
cp target/release/scythe-ui AppDir/usr/bin/
cp target/release/scythe-daemon AppDir/usr/bin/
ln -sf scythe-ui AppDir/usr/bin/scythe
ln -sf scythe-ui AppDir/usr/bin/vrec-ui
ln -sf scythe-daemon AppDir/usr/bin/vrec-daemon
cp packaging/scythe.desktop AppDir/usr/share/applications/
cat > AppDir/AppRun << 'EOF'
#!/bin/sh
HERE="$(dirname "$(readlink -f "${0}")")"
exec "${HERE}/usr/bin/scythe" "$@"
exec "${HERE}/usr/bin/scythe-ui" "$@"
EOF
chmod +x AppDir/AppRun
@ -142,7 +140,8 @@ jobs:
run: |
cargo build --release
mkdir -p dist/bundle
cp target/release/scythe.exe dist/bundle/
cp target/release/scythe-daemon.exe dist/bundle/
cp target/release/scythe-ui.exe dist/bundle/
python3 packaging/windows/bundle_deps.py dist/bundle
strip dist/bundle/*.exe || true
strip --strip-unneeded dist/bundle/*.dll || true

View file

@ -1,105 +0,0 @@
stages:
- check
- build
- package
variables:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: "1"
# Cache the target dir — Rust builds are slow, everything after the first is fast.
cache:
key:
files:
- Cargo.lock
prefix: cargo
paths:
- target/
# ---------- check ----------
# The codebase is not rustfmt-clean yet; this job reports drift without blocking
# builds. Run `cargo fmt` in a dedicated commit before promoting it to a hard gate.
fmt:
stage: check
image: rust:latest
script:
- rustup component add rustfmt
- cargo fmt --check
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
allow_failure: true
clippy:
stage: check
image: rust:latest
before_script:
- apt-get update && apt-get install -y pkg-config libssl-dev
- rustup component add clippy
script:
- cargo clippy --all-targets -- --deny warnings
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
allow_failure: true
test:
stage: check
image: rust:latest
before_script:
- apt-get update && apt-get install -y pkg-config libssl-dev
script:
- cargo test --locked
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
# ---------- build ----------
build-linux:
stage: build
image: rust:latest
before_script:
- apt-get update && apt-get install -y
pkg-config libssl-dev
libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev
libavdevice-dev libswscale-dev libswresample-dev
libxcb1-dev libxcb-shm0-dev libxcb-xfixes0-dev
libxkbcommon-dev libgtk-3-dev
script:
- cargo build --release --locked
artifacts:
name: "scythe-linux-x86_64"
paths:
- target/release/scythe
expire_in: 30 days
build-windows:
stage: build
image: rust:latest
before_script:
- apt-get update && apt-get install -y
mingw-w64
pkg-config libssl-dev
gcc-mingw-w64-x86-64
script:
- rustup target add x86_64-pc-windows-gnu
- cargo build --release --locked --target x86_64-pc-windows-gnu --bin scythe
artifacts:
name: "scythe-windows-x86_64"
paths:
- target/x86_64-pc-windows-gnu/release/scythe.exe
expire_in: 30 days
# ---------- package ----------
# Real releases only on tags, so a main-branch push doesn't burn CI minutes.
release:
stage: package
image: rust:latest
needs: [build-linux]
rules:
- if: $CI_COMMIT_TAG
script:
- echo "Release build for $CI_COMMIT_TAG"
- cargo build --release --locked
artifacts:
name: "scythe-$CI_COMMIT_TAG"
paths:
- target/release/scythe
expire_in: 90 days

617
Cargo.lock generated
View file

@ -414,6 +414,29 @@ dependencies = [
"syn 3.0.4",
]
[[package]]
name = "atk"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
dependencies = [
"atk-sys",
"glib 0.18.5",
"libc",
]
[[package]]
name = "atk-sys"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
@ -649,6 +672,31 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cairo-rs"
version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
dependencies = [
"bitflags 2.13.1",
"cairo-sys-rs",
"glib 0.18.5",
"libc",
"once_cell",
"thiserror 1.0.69",
]
[[package]]
name = "cairo-sys-rs"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
dependencies = [
"glib-sys 0.18.1",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "calloop"
version = "0.13.0"
@ -721,6 +769,16 @@ dependencies = [
"nom 7.1.3",
]
[[package]]
name = "cfg-expr"
version = "0.15.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
dependencies = [
"smallvec",
"target-lexicon 0.12.16",
]
[[package]]
name = "cfg-expr"
version = "0.20.9"
@ -728,7 +786,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"
dependencies = [
"smallvec",
"target-lexicon",
"target-lexicon 0.13.5",
]
[[package]]
@ -1314,6 +1372,16 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "field-offset"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
dependencies = [
"memoffset",
"rustc_version",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.11"
@ -1373,12 +1441,32 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-executor"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.34"
@ -1437,6 +1525,64 @@ dependencies = [
"slab",
]
[[package]]
name = "gdk"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"
dependencies = [
"cairo-rs",
"gdk-pixbuf",
"gdk-sys",
"gio",
"glib 0.18.5",
"libc",
"pango",
]
[[package]]
name = "gdk-pixbuf"
version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
dependencies = [
"gdk-pixbuf-sys",
"gio",
"glib 0.18.5",
"libc",
"once_cell",
]
[[package]]
name = "gdk-pixbuf-sys"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
dependencies = [
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "gdk-sys"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"pango-sys",
"pkg-config",
"system-deps 6.2.2",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@ -1491,6 +1637,51 @@ dependencies = [
"r-efi 6.0.0",
]
[[package]]
name = "gio"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"gio-sys 0.18.1",
"glib 0.18.5",
"libc",
"once_cell",
"pin-project-lite",
"smallvec",
"thiserror 1.0.69",
]
[[package]]
name = "gio-sys"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
"winapi",
]
[[package]]
name = "gio-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
dependencies = [
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.0",
"windows-sys 0.61.2",
]
[[package]]
name = "gl_generator"
version = "0.14.0"
@ -1502,6 +1693,96 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glib"
version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
dependencies = [
"bitflags 2.13.1",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys 0.18.1",
"glib-macros 0.18.5",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"memchr",
"once_cell",
"smallvec",
"thiserror 1.0.69",
]
[[package]]
name = "glib"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18b9b8d350db41f690ec1b87109f202782748bbd8ab2f2ede17cb40d29e2838c"
dependencies = [
"bitflags 2.13.1",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys 0.22.9",
"glib-macros 0.22.9",
"glib-sys 0.22.9",
"gobject-sys 0.22.9",
"libc",
"memchr",
"smallvec",
]
[[package]]
name = "glib-macros"
version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
dependencies = [
"heck 0.4.1",
"proc-macro-crate 2.0.2",
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "glib-macros"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 3.0.4",
]
[[package]]
name = "glib-sys"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"
dependencies = [
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "glib-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
dependencies = [
"libc",
"system-deps 9.0.0",
]
[[package]]
name = "glob"
version = "0.3.4"
@ -1603,6 +1884,28 @@ dependencies = [
"gl_generator",
]
[[package]]
name = "gobject-sys"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
dependencies = [
"glib-sys 0.18.1",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "gobject-sys"
version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys 0.22.9",
"libc",
"system-deps 9.0.0",
]
[[package]]
name = "gpu-alloc"
version = "0.6.2"
@ -1642,6 +1945,86 @@ dependencies = [
"bitflags 2.13.1",
]
[[package]]
name = "gtk"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"
dependencies = [
"atk",
"cairo-rs",
"field-offset",
"futures-channel",
"gdk",
"gdk-pixbuf",
"gio",
"glib 0.18.5",
"gtk-sys",
"gtk3-macros",
"libc",
"pango",
"pkg-config",
]
[[package]]
name = "gtk-layer-shell"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc759b3184830a547b31549ab40c4b54450ab702bba79ba23f049bc1d1e3ca98"
dependencies = [
"bitflags 2.13.1",
"gdk",
"glib 0.18.5",
"glib-sys 0.18.1",
"gtk",
"gtk-layer-shell-sys",
"libc",
]
[[package]]
name = "gtk-layer-shell-sys"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4eee067e022416d53a70de69d3d3929d8a6e687f3278b8934faa671750fa6eb"
dependencies = [
"gdk-sys",
"glib-sys 0.18.1",
"gtk-sys",
"libc",
"system-deps 7.0.8",
]
[[package]]
name = "gtk-sys"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"
dependencies = [
"atk-sys",
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gdk-sys",
"gio-sys 0.18.1",
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"pango-sys",
"system-deps 6.2.2",
]
[[package]]
name = "gtk3-macros"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"
dependencies = [
"proc-macro-crate 1.3.1",
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "half"
version = "2.7.1"
@ -1668,6 +2051,12 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "heck"
version = "0.5.0"
@ -1992,7 +2381,7 @@ dependencies = [
"libspa-sys",
"nom 8.0.0",
"rustix 1.1.4",
"system-deps",
"system-deps 7.0.8",
]
[[package]]
@ -2003,7 +2392,7 @@ checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"
dependencies = [
"bindgen",
"cc",
"system-deps",
"system-deps 7.0.8",
]
[[package]]
@ -2345,7 +2734,7 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
dependencies = [
"proc-macro-crate",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 2.0.119",
@ -2734,6 +3123,31 @@ dependencies = [
"ttf-parser",
]
[[package]]
name = "pango"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
dependencies = [
"gio",
"glib 0.18.5",
"libc",
"once_cell",
"pango-sys",
]
[[package]]
name = "pango-sys"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
dependencies = [
"glib-sys 0.18.1",
"gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
[[package]]
name = "parking"
version = "2.2.1"
@ -2834,7 +3248,7 @@ checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"
dependencies = [
"bindgen",
"libspa-sys",
"system-deps",
"system-deps 7.0.8",
]
[[package]]
@ -2918,13 +3332,57 @@ dependencies = [
"num-integer",
]
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"
dependencies = [
"once_cell",
"toml_edit 0.19.15",
]
[[package]]
name = "proc-macro-crate"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
dependencies = [
"toml_datetime 0.6.3",
"toml_edit 0.20.2",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
"toml_edit 0.25.13+spec-1.1.0",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn 1.0.109",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
@ -3242,7 +3700,7 @@ dependencies = [
[[package]]
name = "scythe"
version = "0.2.18"
version = "0.2.17"
dependencies = [
"ashpd",
"cpal",
@ -3252,7 +3710,11 @@ dependencies = [
"egui",
"ffmpeg-next",
"ffmpeg-sys-next",
"gdk",
"glib 0.22.9",
"global-hotkey",
"gtk",
"gtk-layer-shell",
"image",
"libc",
"memmap2",
@ -3327,6 +3789,15 @@ dependencies = [
"syn 3.0.4",
]
[[package]]
name = "serde_spanned"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
]
[[package]]
name = "serde_spanned"
version = "1.1.1"
@ -3542,13 +4013,23 @@ version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck",
"heck 0.5.0",
"proc-macro2",
"quote",
"rustversion",
"syn 2.0.119",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.119"
@ -3582,19 +4063,51 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "system-deps"
version = "6.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
dependencies = [
"cfg-expr 0.15.8",
"heck 0.5.0",
"pkg-config",
"toml 0.8.2",
"version-compare",
]
[[package]]
name = "system-deps"
version = "7.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"
dependencies = [
"cfg-expr",
"heck",
"cfg-expr 0.20.9",
"heck 0.5.0",
"pkg-config",
"toml",
"toml 1.1.4+spec-1.1.0",
"version-compare",
]
[[package]]
name = "system-deps"
version = "9.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a0dae2cbca1f0ff93795713cfe0a4c02f760e3c0b8ae2ab4ec4045808ff429f"
dependencies = [
"cfg-expr 0.20.9",
"heck 0.5.0",
"pkg-config",
"toml 1.1.4+spec-1.1.0",
"version-compare",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "target-lexicon"
version = "0.13.5"
@ -3740,6 +4253,18 @@ dependencies = [
"syn 3.0.4",
]
[[package]]
name = "toml"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"
dependencies = [
"serde",
"serde_spanned 0.6.9",
"toml_datetime 0.6.3",
"toml_edit 0.20.2",
]
[[package]]
name = "toml"
version = "1.1.4+spec-1.1.0"
@ -3748,11 +4273,20 @@ checksum = "3aace63f4bbcdfc2c965b059de67119c89c4017a70d633be6c104910f67056f5"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"serde_spanned 1.1.1",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow",
"winnow 1.0.4",
]
[[package]]
name = "toml_datetime"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
dependencies = [
"serde",
]
[[package]]
@ -3764,6 +4298,30 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.19.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
dependencies = [
"indexmap",
"toml_datetime 0.6.3",
"winnow 0.5.40",
]
[[package]]
name = "toml_edit"
version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
dependencies = [
"indexmap",
"serde",
"serde_spanned 0.6.9",
"toml_datetime 0.6.3",
"winnow 0.5.40",
]
[[package]]
name = "toml_edit"
version = "0.25.13+spec-1.1.0"
@ -3771,9 +4329,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
dependencies = [
"indexmap",
"toml_datetime",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"winnow",
"winnow 1.0.4",
]
[[package]]
@ -3782,7 +4340,7 @@ version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
dependencies = [
"winnow",
"winnow 1.0.4",
]
[[package]]
@ -4670,6 +5228,15 @@ dependencies = [
"xkbcommon-dl",
]
[[package]]
name = "winnow"
version = "0.5.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"
dependencies = [
"memchr",
]
[[package]]
name = "winnow"
version = "1.0.4"
@ -4860,7 +5427,7 @@ dependencies = [
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"winnow 1.0.4",
"zbus_macros 5.19.0",
"zbus_names 4.3.4",
"zvariant 5.15.0",
@ -4896,7 +5463,7 @@ version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"
dependencies = [
"proc-macro-crate",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 2.0.119",
@ -4909,7 +5476,7 @@ version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
dependencies = [
"proc-macro-crate",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.4",
@ -4936,7 +5503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
dependencies = [
"serde",
"winnow",
"winnow 1.0.4",
"zvariant 5.15.0",
]
@ -5085,7 +5652,7 @@ dependencies = [
"endi",
"enumflags2",
"serde",
"winnow",
"winnow 1.0.4",
"zcheapstr",
"zvariant_derive 5.15.0",
"zvariant_utils 4.2.0",
@ -5097,7 +5664,7 @@ version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"
dependencies = [
"proc-macro-crate",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 2.0.119",
@ -5110,7 +5677,7 @@ version = "5.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"
dependencies = [
"proc-macro-crate",
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.4",
@ -5138,5 +5705,5 @@ dependencies = [
"quote",
"serde",
"syn 3.0.4",
"winnow",
"winnow 1.0.4",
]

View file

@ -1,17 +1,24 @@
[package]
name = "scythe"
version = "0.2.18"
version = "0.2.17"
edition = "2024"
[[bin]]
name = "scythe"
path = "src/main.rs"
name = "scythe-daemon"
path = "src/bin/scythe-daemon.rs"
[[bin]]
name = "scythe-ui"
path = "src/bin/scythe-ui.rs"
[dependencies]
crossbeam-channel = "0.5.16"
ffmpeg-next = "9.0.0"
ffmpeg-sys-next = "9.0.0"
gdk = "0.18.2"
glib = "0.22.9"
global-hotkey = "0.8.0"
gtk = { version = "0.18.2", package = "gtk" }
libc = "0.2.189"
mp4 = "0.14.0"
ringbuf = "0.5.1"
@ -27,17 +34,11 @@ image = { version = "0.25", default-features = false, features = ["png"] }
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.13.13", features = ["screencast"] }
gtk-layer-shell = { version = "0.8.2", features = ["v0_5"] }
pipewire = "0.10.1"
xcb = { version = "1.7.1", features = ["shm", "xfixes"] }
memmap2 = "0.9.11"
[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 4
panic = "abort"
strip = true
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58.0", features = [
"Win32_Foundation",
@ -54,6 +55,5 @@ windows = { version = "0.58.0", features = [
"Win32_System_Threading",
"Win32_System_LibraryLoader",
"Win32_System_Console",
"Win32_System_Power",
"Win32_UI_Shell",
] }

View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 katR (oiupoyt)
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
http://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.

View file

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

View file

@ -1,431 +0,0 @@
# Scythe: Comprehensive Project & Architecture Guide
This document is the definitive technical reference for developers and AI agents working on the Scythe codebase. It outlines the project's design philosophy, unified binary architecture, hardware encoding pathways, audio subsystem, power management, HUD overlay, and development standards.
---
## 1. Project Overview & Current Status
**Current Version:** `v0.2.18`
**License:** Dual MIT / Apache 2.0
### Repository Topology
| Remote | URL | Role | Status |
|---|---|---|---|
| `forgejo` | `https://git.oiupoyt.space/oiupoyt/scythe.git` | Self-hosted primary; source of truth, release assets | Active |
| `origin` | `https://spearzificial@github.com/spearzificial/scythe.git` | **GitHub development mirror** (currently maintained account) | Active |
| `gitlab` | `https://gitlab.com/oiupoyt.cat/scythe.git` | Optional mirror | Optional |
**GitHub account policy:** GitHub pushes go to the `spearzificial` account, and `origin` points at that account's repository. The `oiupoyt` GitHub OAuth token is expired, so the old `oiupoyt` repository is not a push target. Always name the account in the remote URL (`https://spearzificial@github.com/...`) so Git selects the correct stored credential when multiple GitHub accounts exist in the credential store.
### Dual-Push Rule
Every push must reach both active remotes:
```bash
git push origin main
git push forgejo main
```
Scythe is a cross-platform, ultra-low-overhead desktop screen recorder, instant replay buffer, and livestreamer written in Rust. It delivers functionality comparable to NVIDIA ShadowPlay and GPU Screen Recorder with minimal CPU and GPU overhead.
### Core Capabilities:
1. **Unified Multicall Binary Architecture**: UI overlay, CLI client, and headless daemon engine are consolidated into a single executable ([`src/main.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs)) with subcommands (`scythe daemon`, `scythe record`, `scythe save`, etc.) and backward-compatible symlinks (`scythe-daemon`, `scythe-ui`).
2. **Zero-Copy Hardware Video Encoding**:
- **Linux**: FFmpeg VA-API (`h264_vaapi`, `hevc_vaapi`, `av1_vaapi`) with direct DRM DMA-BUF import for Intel and AMD GPUs. Automatic low-power hardware fallback handles drivers lacking `VAEntrypointEncSliceLP`.
- **Windows**: Native NVENC, AMD AMF, Intel QuickSync (QSV), and multithreaded software fallbacks via DirectX Graphics Infrastructure (DXGI) desktop duplication.
3. **High-Fidelity Audio Engine**:
- Multi-source routing: System Audio, Microphone, Both, or Muted.
- Dual codec support: Native Opus (`AV_CODEC_ID_OPUS`, 48 kHz stereo, 160 kbps, `AV_SAMPLE_FMT_FLT`) as recommended default, with native AAC (`AV_CODEC_ID_AAC`, 48 kHz stereo, 192 kbps, `AV_SAMPLE_FMT_FLTP`) as universal fallback.
- Interactive sound verification suite with live dB / percentage VU meters and test tone playback.
4. **Lock-Free Circular RAM Replay Buffer**:
- Continuous lock-free packet ring buffer in system RAM (configurable from 5 seconds to 30 minutes).
- Keyframe-aware draining ensures saved MP4 clips begin cleanly on IDR boundaries with zero decoder corruption.
5. **Smart Power Management**:
- AC power connectivity monitoring via Linux `/sys/class/power_supply` and Windows Win32 `GetSystemPowerStatus`.
- Dedicated 1-second background power poller thread.
- "Power-only" replay mode automatically drains and pauses the replay buffer on battery power to conserve battery life, and seamlessly resumes with keyframe forced resync upon AC connection.
6. **KAT Square Minimalist Interface**:
- Strictly conforms to `DESIGN.md` guidelines: `border-radius: 0 !important;` across all windows, inputs, buttons, and badges.
- Obsidian dark palette (`#0b0b0b` / `#111111`) with hairline `#222222` framing and restrained functional accents.
- Borderless, shadowless terminal-style notification toasts.
- Monospace typography option with integrated `Adwaita Mono` font.
7. **Screenshot Resolution Presets**:
- Intuitive presets: `Native (Source)`, `1080p (FHD)`, `1440p (QHD)`, `2160p (4K UHD)`, `720p (HD)` with hardware-accelerated Lanczos scaling via FFmpeg.
8. **In-App Auto-Updater**:
- Synchronizes against Forgejo releases API (`https://git.oiupoyt.space/api/v1/repos/oiupoyt/scythe/releases/latest`) with automated binary replacement.
---
## 2. High-Level Architecture & Process Model
Scythe uses a unified multicall binary dispatch model:
```
+-----------------------------------+
| scythe binary |
+-----------------+-----------------+
|
Inspects argv[0] and first CLI argument
|
+---------------------------------+---------------------------------+
| |
v v
"scythe daemon" "scythe [command]"
or argv[0] == "scythe-daemon" or argv[0] == "scythe-ui"
| |
+--------v-------------------------+ +---------v-----------------------+
| Headless Daemon Engine | | Client CLI & Overlay |
| (src/daemon.rs) | <--- Unix Domain Socket / --- | (src/overlay_egui.rs) |
| - Screen Capture (PipeWire/DXGI) | Local TCP IPC Loop | - egui HUD Overlay (Alt+Z) |
| - Hardware Video Encoder | | - Audio Diagnostics & VU Meters |
| - Native Opus/AAC Audio Encoder | | - Clip Trimmer & Gallery |
| - Lock-Free Circular Ring Buffer | | - Terminal Notification Toasts |
| - AC Power Watcher Thread | | - Global Hotkey Listener Pump |
| - MP4 Muxer & RTMP Streamer | +---------------------------------+
+----------------------------------+
```
### Multicall Dispatching:
- **Daemon Mode**: Invoked when `args[1] == "daemon"`, `args[1] == "--mock"`, or when executed via symlink `scythe-daemon` / `vrec-daemon`. Runs the headless capture and recording engine ([`src/daemon.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/daemon.rs)).
- **Dispatch uses argv[0], not `current_exe()`**: `current_exe()` reads `/proc/self/exe`, which resolves symlinks to the real file. Every installed alias would therefore report `scythe` and dispatch to the client, so `scythe-daemon` would open the HUD instead of starting the engine. `invoked_stem()` reads argv[0] and falls back to `current_exe()` only when argv[0] has no usable stem.
- **Client / UI Mode**: Invoked when executed as `scythe`, `scythe-ui`, or with client arguments (`save`, `record`, `screenshot`, `status`, `menu`, etc.). Runs [`src/main.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs) and launches [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs).
---
## 3. Inter-Process Communication (IPC)
The protocol is implemented in [`src/ipc.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/ipc.rs).
### Transport Layer:
- **Linux**: Unix Domain Socket at `$XDG_RUNTIME_DIR/scythe.sock` (with legacy fallback to `/run/user/<UID>/vrec.sock`).
- **Windows**: Local TCP socket on `127.0.0.1` binding to candidate ports `42069`–`42072` and persisting the active port in `%TEMP%\scythe-ipc.port`.
### Message Payload:
Packets are framed with a 4-byte little-endian length prefix followed by JSON-serialized structs:
- **Command (`Command`)**:
- `SaveReplay`: Drains the circular buffer and muxes an MP4 replay.
- `StartRecording` / `StopRecording` / `ToggleRecording`: Controls manual recording.
- `StartStreaming` / `StopStreaming` / `ToggleStreaming`: Controls RTMP broadcasting.
- `ToggleAudio`: Toggles microphone/system audio mute state.
- `CycleAudioMode`: Cycles through System -> Mic -> Both -> Muted.
- `ToggleCursor`: Inverts cursor visibility state and triggers capture synchronization.
- `ShowOverlay`: Opens the HUD overlay via the daemon if it is not already running (`scythe --show-overlay`). Distinct from `--menu`, which toggles an already-open overlay closed.
- `ReloadConfig`: Live-reloads configuration changes without restarting the daemon unless video parameters change.
- `PowerStateChanged(bool)`: Internal notification dispatched by the power poller when AC state transitions.
- `GetStatus`: Requests the current `DaemonStatus`.
- `StopDaemon`: Triggers clean daemon shutdown.
- **DaemonStatus (`DaemonStatus`)**:
- `is_recording`: bool
- `recording_duration_sec`: u64
- `is_replay_active`: bool
- `audio_muted`: bool
- `audio_mode`: String ("system", "mic", "both", "muted")
- `show_cursor`: bool
- `mic_volume` / `system_volume`: f32
- `mic_level_peak` / `system_level_peak`: f32 (0.0 to 1.0 real-time peak values)
- `is_streaming`: bool
- `streaming_duration_sec`: u64
---
## 4. Video Capture Subsystem
Capture sources implement the [`FrameSource`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/mod.rs#L21) trait located in [`src/capture/mod.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/mod.rs).
### Frame Representation:
```rust
pub enum Frame {
Raw {
width: u32,
height: u32,
stride: u32,
data: Arc<Vec<u8>>,
},
DmaBuf {
fd: std::os::fd::RawFd,
width: u32,
height: u32,
stride: u32,
format: u32,
modifier: u64,
offset: u32,
},
D3D11Texture {
handle: usize,
width: u32,
height: u32,
},
}
```
### Platform Implementations:
1. **Wayland ([`src/capture/wayland.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/wayland.rs) & [`src/capture/wayland_stream.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/wayland_stream.rs))**:
- Uses `xdg-desktop-portal` and PipeWire screencast stream.
- Negotiates DMA-BUF memory buffers (`SPA_DATA_DmaBuf`) for zero-copy GPU video encoding.
- Falls back to shared memory buffers (`SPA_DATA_MemPtr`) when DMA-BUF is unavailable.
2. **X11 ([`src/capture/x11.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/x11.rs))**:
- Uses MIT-SHM (`xcb::shm`) for direct shared-memory frame transfer from the X server.
3. **Windows ([`src/capture/windows.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/windows.rs))**:
- Uses the DirectX Graphics Infrastructure (DXGI) Desktop Duplication API (`IDXGIOutputDuplication`).
- Iterates through all display adapters and outputs to probe and select the active desktop.
- Uses a single Direct3D 11 staging texture (`D3D11_USAGE_STAGING`) with `D3D11_CPU_ACCESS_READ` for low-latency GPU readback.
- Tightly packs rows into BGRA format if GPU pitch padding is detected.
- Ensures fallback / idle frames generate opaque black (`[0, 0, 0, 255]`) to prevent uninitialized green chroma artifacts.
4. **Mock Capture ([`src/capture/mock.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/mock.rs))**:
- Generates simulated 1080p frames for headless unit tests and CI runners where no display server is attached.
---
## 5. Video Encoding Pipeline
The video encoder module is located in [`src/encoder.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs).
### Linux Encoder (`VaapiEncoder`):
- Uses FFmpeg libavcodec with VA-API hardware acceleration (`h264_vaapi`, `hevc_vaapi`, `av1_vaapi`).
- Direct DRM DMA-BUF Import: Zero-copy surface creation via `vaCreateSurfacesFromProperties` for Intel and AMD GPUs.
- Color Standards: ITU-R BT.709 color primaries (`AVCOL_PRI_BT709`), transfer characteristics (`AVCOL_TRC_BT709`), and MPEG limited range (`AVCOL_RANGE_MPEG`).
- SIMD Color Space Conversion: When software fallback is required, `sws_scale` operates with `SWS_FAST_BILINEAR` and explicit ITU-709 coefficient mapping.
### Windows Encoder (`WindowsHwEncoder`):
- Hardware Probing Priority:
- H.264: `h264_nvenc` -> `h264_amf` -> `h264_qsv` -> `libx264`
- HEVC: `hevc_nvenc` -> `hevc_amf` -> `hevc_qsv` -> `libx265`
- AV1: `av1_nvenc` -> `av1_amf` -> `av1_qsv` -> `libsvtav1`
- Standardized Pixel Format: NV12 (`AV_PIX_FMT_NV12`) across hardware encoders, with YUV420P fallback.
- Color Conversion: Converts captured BGRA to NV12 using `sws_scale` configured with ITU-R BT.709 matrix and full-range to limited-range mapping (`sws_setColorspaceDetails`), eliminating washed-out colors and green screen bugs.
- Low Latency Settings: Rate control VBR with burst ceiling, zero B-frames (`max_b_frames = 0`), ultrafast tuning, and 1-second GOP size (`gop_size = fps`).
---
## 6. Audio Subsystem
Audio capture and conversion is implemented in [`src/capture/audio.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/audio.rs) and [`src/encoder.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs).
### Pipeline:
1. **Capture**:
- **Linux**: Uses PulseAudio/PipeWire `parec` targeting `@DEFAULT_MONITOR@` (for system audio loopback) and `@DEFAULT_SOURCE@` (for microphone input) with a 20ms low-latency buffer.
- **Windows**: Direct WASAPI loopback capture using the `cpal` crate.
2. **Channel Downmixing & Resampling**:
- Downmixes 5.1 and 7.1 surround sound to stereo using center and surround coefficients:
```
L = FL + 0.707 * C + 0.707 * SL + 0.5 * LFE
R = FR + 0.707 * C + 0.707 * SR + 0.5 * LFE
```
- Resamples arbitrary input sample rates to 48,000 Hz using linear interpolation and soft-clipping limiting (`tanh` curve).
3. **Encoding (`AudioEncoder`)**:
- **Opus (`AV_CODEC_ID_OPUS`)**: Native Opus stereo at 160 kbps, 48 kHz with float sample format (`AV_SAMPLE_FMT_FLT`). Primary recommended standard.
- **AAC (`AV_CODEC_ID_AAC`)**: Native AAC stereo at 192 kbps, 48 kHz with planar float format (`AV_SAMPLE_FMT_FLTP`). Universal fallback standard.
- Microsecond-accurate PTS rebasing aligns audio packets against video IDR keyframes.
4. **Interactive Verification & Live VU Meters**:
- The UI includes live decibel / percentage VU meters for both system sound and microphone.
- Integrated test suite (`test mic` and `test sys` with automated chime playback) allows users to immediately verify sound capture without running external applications.
---
## 7. Lock-Free RAM Ring Buffer & Power Management
Implemented in [`src/ring.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/ring.rs), [`src/daemon.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/daemon.rs), and [`src/config.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs).
### Buffer Mechanics:
- Keeps encoded video and audio packets in RAM without writing to disk during active buffer mode.
- Fixed Capacity: Capacity is calculated dynamically from duration (seconds) * target framerate * safety factor. On low-power hardware, capacity is tightly bounded to conserve memory.
- **Keyframe-Aware Pruning**:
- Replay clips must always begin with an IDR keyframe to prevent visual corruption.
- When the circular buffer reaches maximum capacity, packets are dropped starting from the oldest non-keyframe sequence up to the next IDR keyframe boundary.
- Drain Operation: When `Command::SaveReplay` is received, the buffer packets are cloned into an asynchronous channel without blocking the capture and encoding threads.
### AC Power Management:
- **Connectivity Detection**: `ScytheConfig::is_ac_power_connected()` inspects `/sys/class/power_supply/*/online` on Linux and calls `GetSystemPowerStatus` on Windows.
- **Poller Thread**: A dedicated 1-second background thread continuously monitors AC power changes.
- **Automatic Buffer Gating**: When `autostart_power_only` is enabled:
- On battery power loss: The replay buffer is automatically paused, drained of existing frames, and a toast notification (`power lost, replay paused`) is dispatched.
- On AC connection restore: Replay buffering automatically resumes, forces an encoder keyframe, and dispatches a notification (`power restored, replay resumed`).
---
## 8. Muxer & Livestreaming
Implemented in [`src/muxer.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/muxer.rs).
### MP4 Container Muxing (`Muxer`):
- Wraps FFmpeg libavformat to produce universal MP4 files (`.mp4`) containing H.264/HEVC/AV1 video and Opus/AAC audio.
- Emits faststart headers (`+faststart`) to place the `moov` atom at the beginning of the file for instant streaming and playback.
- Rebases PTS and DTS timestamps to zero for both video and audio streams at file initialization.
- Automatic Collision Handling: Formats filenames as `Replay-HH-MM-SS_DD-MM-YYYY.mp4` or `Recording-HH-MM-SS_DD-MM-YYYY.mp4` and resolves conflicts via incremental suffixes (`_1`, `_2`).
### RTMP Livestreaming (`spawn_stream_worker`):
- Connects to RTMP endpoints (Twitch, YouTube, Kick, Custom RTMP).
- Encapsulates video and audio NAL units into FLV/RTMP transport on a dedicated worker thread with non-blocking channel dispatch.
---
## 9. In-Game HUD Overlay & Notifications
Implemented in [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs).
### Design System: KAT Square Minimalist:
- Strictly adheres to `DESIGN.md`:
- **`border-radius: 0 !important;`**: Zero rounded corners or pill badges anywhere in the interface.
- **Obsidian Dark Palette**: `#0b0b0b` root background, `#111111` surface panels, `#222222` hairline borders.
- **Restrained Accents**: Functional emerald (`#10b981`), red (`#ef4444`), cyan (`#38bdf8`), and vendor themes (AMD, NVIDIA, Intel).
- **Monospace Typography**: Full support for `Adwaita Mono` / `JetBrains Mono` with an interface toggle.
### Views:
- **Main HUD**:
- Rolldown / swipe animated dropdown menus (`ui.ctx().animate_bool(...)` over 180ms) for Replay, Record, and Broadcast.
- Quick actions with drop shadow framing.
- **Settings View**:
- File Information: Output directory with native folder pickers.
- Video Parameters: Resolution scaling, FPS (15 to 360), bitrate (5 to 150 Mbps), codec (H.264, HEVC, AV1), color range (Full vs Limited), low-power recording mode.
- Audio: Mode routing, volume sliders (0-150%), Opus/AAC codec choice, and live verification test suite.
- Screenshot: Resolution presets (`Native`, `1080p`, `1440p`, `2160p`, `720p`), format (`PNG` vs `JPEG`), and cursor capture toggle.
- General: Theme accents, 8 global keybinds with interactive recording listener, compact `Reset Hotkeys` button, and typography toggle.
- **Notification Toasts (`ShadowPlayToastApp`)**:
- Borderless, shadowless terminal-style card.
- Obsidian `#111111` fill with 2px vertical accent rule and 6px status dot.
- Uppercase monospace title, lowercase metadata subtitle, and 2px hairline progress countdown line.
---
## 10. Global Hotkeys & Window Hooks
Implemented in [`src/hotkey.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/hotkey.rs) and [`src/hyprland_binds.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/hyprland_binds.rs).
### Keybind Registry:
1. Menu Overlay: `Alt+Z`
2. Save Instant Replay: `Ctrl+Shift+R`
3. Start / Stop Recording: `Ctrl+Shift+F9`
4. Pause / Resume Recording: `Ctrl+Shift+F8`
5. Take Screenshot: `Ctrl+Shift+S`
6. Toggle Mouse Cursor: `Ctrl+Shift+F10`
7. Mute / Unmute Microphone: `Ctrl+Shift+M`
8. Mute / Unmute System Audio: `Ctrl+Shift+N`
### Dispatch Strategies:
1. **Hyprland Direct IPC**: Registers binds dynamically using `hyprctl keyword bind` to bypass Wayland global hotkey restrictions. Watches `hyprland.conf` modifications and auto-reapplies.
2. **Universal Desktop**: Uses the `global-hotkey` crate for standard Windows and X11 hotkey registration.
---
## 11. Configuration Management
Implemented in [`src/config.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs).
### File Locations:
- Linux: `~/.config/scythe/config.json`
- Windows: `%APPDATA%\scythe\config.json`
### Autostart Integration:
`ScytheConfig::apply_autostart_system(enable_replay, enable_overlay)` manages:
1. Systemd user service: `systemctl --user enable/disable scythe-daemon.service`.
2. Standard XDG autostart desktop entries in `~/.config/autostart/scythe-daemon.desktop` and `scythe-overlay.desktop`.
Linux only. The Windows path is a no-op: there is no registry `Run` key write in either the overlay toggle or the NSIS installer, so the autostart switch in the UI currently has no effect on Windows.
### Retired Settings (v0.2.18 cleanup):
These keys were accepted by the settings UI and persisted to disk, but nothing in the capture, encoder, or daemon paths ever read them. They were removed from `ScytheConfig` and the corresponding UI controls were deleted, so the overlay no longer presents options that do nothing:
| Retired key | Why it was removed |
|---|---|
| `capture_source` | Capture always selected the focused monitor; window/region modes were never implemented |
| `replay_storage` | Replay buffer is always RAM-backed; the disk path was never built |
| `change_resolution`, `resolution_w`, `resolution_h` | Encoder always used native capture dimensions |
| `container_format` | Muxer always writes MP4 |
| `show_scroll_lock_led` | No LED driver integration existed |
| `autostart_on_game` | No game-detection layer existed |
| `save_folder_by_game`, `name_by_game` | No game detection; filenames are timestamp-based |
| `language`, `ui_color_theme` | No translation layer or theme engine; `accent_color` drives the real palette |
| `record_enabled` | Dead field superseded by runtime `is_recording` state |
Unknown keys in an existing `config.json` are ignored by serde, so upgrading does not break saved configurations. `scythe` rewrites the file without these keys on the next save.
---
## 12. In-App Auto-Updater
Implemented in [`src/updater.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/updater.rs).
### Workflow:
1. Queries the self-hosted Forgejo release API:
`GET https://git.oiupoyt.space/api/v1/repos/oiupoyt/scythe/releases/latest`
(Falls back to GitHub API if Forgejo is unreachable).
2. Parses SemVer strings and checks if `is_newer(latest, CURRENT_VERSION)`.
3. Downloads the singular platform package:
- Linux: `scythe-v<version>-linux-x86_64.tar.gz`
- Windows: `scythe-v<version>-windows-x86_64.zip` (includes standalone portable FFmpeg DLLs).
4. Atomically swaps the executable in `~/.local/bin/scythe` or `%USERPROFILE%\.local\bin\scythe.exe`.
---
## 13. Verification, Testing & Cross-Compilation
### Local Linux Commands:
```bash
# Type check all targets
cargo check --all-targets
# Run the complete unit test suite (27 tests)
cargo test
# Strict clippy lint verification
cargo clippy --all-targets -- -D warnings
# Build optimized Linux release binary
cargo build --release
# Install release binary and symlinks to ~/.local/bin
bash install.sh
# Run end-to-end integration test suite
bash tests/e2e_test.sh
```
`tests/e2e_test.sh` treats a running daemon as a resource it borrows rather than deletes. Unix sockets cannot be re-linked: removing the path entry of a live daemon leaves the kernel socket bound but unreachable, and the session stays broken until that process dies.
The script therefore:
1. probes liveness by connecting to the socket directly (`scythe --status` cannot be used for this, because it calls `ensure_daemon_running()` and would spawn a daemon while probing);
2. records the running daemon's command line and working directory;
3. sends `StopDaemon` and waits for the socket to disappear, aborting without unlinking if it will not stop;
4. restores that daemon on exit, so a developer's recorder survives a test run.
### Windows Cross-Compilation (from Linux Host):
```bash
FFMPEG_DIR="$HOME/.local/share/ffmpeg-win64/ffmpeg-n9.0-latest-win64-gpl-shared-9.0" \
PKG_CONFIG_PATH="$HOME/.local/share/ffmpeg-win64/ffmpeg-n9.0-latest-win64-gpl-shared-9.0/lib/pkgconfig" \
PKG_CONFIG_ALLOW_CROSS=1 \
cargo build --release --target x86_64-pc-windows-gnu
```
### GitHub Actions:
| Workflow | Trigger | Purpose |
|---|---|---|
| [`ci.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.github/workflows/ci.yml) | push to `main`, pull request, manual | Compiles and tests both targets on every push. Linux job: `cargo check --all-targets`, `cargo test`, `cargo clippy -D warnings`, `cargo build --release`, then runs `scythe --help` to prove the binary starts. Windows job: MSYS2 MINGW64 `cargo build --release`. Both binaries upload as artifacts. |
| [`release.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.github/workflows/release.yml) | push of a `v*` tag | Packages `.tar.gz`, `.deb`, `.rpm`, `.AppImage` and the NSIS Windows installer, then publishes a GitHub Release. |
The CI workflow is the only thing that compiles the Windows target on a routine basis, and it exists because the Windows build had already rotted: `src/config.rs` calls `GetSystemPowerStatus` but the `windows` crate feature list never enabled `Win32_System_Power`, so `cargo build --target x86_64-pc-windows-gnu` failed with `E0432`. Tag pushes were the only previous trigger, so nothing caught it before a release was attempted.
The `cargo fmt --check` step is advisory (`continue-on-error: true`). The tree has formatting drift that is intentionally not mass-fixed, because reformatting every file would bury the real changes in a diff.
Tests that need real hardware (a live audio server) are opt-in:
```bash
SCYTHE_HW_TESTS=1 cargo test
```
---
## 14. Behavioral Rules & Coding Standards
1. **ABSOLUTELY ZERO EMOJIS**: Under no circumstances should emojis be added to code, comments, log outputs, commit messages, or communication.
2. **File & Symbol Links**: Every file path or code symbol mentioned in communication must be formatted as a clickable markdown link using the `file://` scheme (e.g., [`src/encoder.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs)).
3. **KAT Square Minimalist**: Strict `border-radius: 0 !important;` on all visual elements.
4. **Dual-Push Rule**: When pushing commits or tags, always push to both active remotes (`origin` for GitHub and `forgejo` for self-hosted):
```bash
git push origin <branch>
git push forgejo <branch>
```
5. **Memory Safety & Process Isolation**: Avoid blocking the audio or video capture loops. Use unbounded or high-capacity crossbeam channels for frame dispatch.

View file

@ -2,7 +2,7 @@
> High-performance, zero-copy GPU hardware screen recorder and instant replay overlay for Linux (Wayland & X11) and Windows.
[![Release](https://img.shields.io/github/v/release/spearzificial/scythe?style=flat-square)](https://github.com/spearzificial/scythe/releases)
[![Release](https://img.shields.io/github/v/release/oiupoyt/scythe?style=flat-square)](https://github.com/oiupoyt/scythe/releases)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue?style=flat-square)](LICENSE)
Scythe is a native, ultra-lightweight alternative to NVIDIA ShadowPlay and GPU Screen Recorder. It records gameplay and desktop screens with near-zero CPU and GPU overhead by leveraging hardware video acceleration and zero-copy direct memory pipelines.
@ -35,11 +35,10 @@ Scythe is a native, ultra-lightweight alternative to NVIDIA ShadowPlay and GPU S
| Action | Shortcut | CLI Command |
|---|---|---|
| Open / Close HUD Overlay | `Alt + Z` | `scythe --menu` |
| Save Instant Replay | `Ctrl + Shift + R` | `scythe --save` |
| Toggle Normal Recording | `Ctrl + Shift + F9` | `scythe --record` |
| Toggle Mouse Cursor | `Ctrl + Shift + F10` | `scythe --cursor` |
| Take Screenshot | `Ctrl + Shift + S` | `scythe --screenshot` |
| Open / Close HUD Overlay | `Alt + Z` | `scythe-ui --menu` |
| Save Instant Replay | `Ctrl + Shift + R` | `scythe-ui --save` |
| Toggle Normal Recording | `Ctrl + Shift + F9` | `scythe-ui --record` |
| Toggle Mouse Cursor | `Ctrl + Shift + F10` | `scythe-ui --cursor` |
---
@ -55,7 +54,7 @@ makepkg -si
### Pre-Built Packages (Releases)
Download the latest packages directly from [GitHub Releases](https://github.com/spearzificial/scythe/releases) or [Forgejo Releases](https://git.oiupoyt.space/oiupoyt/scythe/releases):
Download the latest packages directly from [GitHub Releases](https://github.com/oiupoyt/scythe/releases):
- **Windows Setup**: `scythe-setup.exe` (Official installer with Start Menu & Desktop shortcuts)
- **Windows Portable**: `scythe.exe` (Standalone self-contained executable) & `scythe-windows-x86_64.zip`
@ -76,7 +75,7 @@ Download the latest packages directly from [GitHub Releases](https://github.com/
#### Compile & Install
```bash
git clone https://github.com/spearzificial/scythe.git
git clone https://github.com/oiupoyt/scythe.git
cd scythe
bash install.sh
```
@ -86,13 +85,13 @@ bash install.sh
## CLI Usage
```bash
scythe --menu # Open the interactive overlay UI menu
scythe --status # Query background daemon state and metrics
scythe --save # Save instant replay clip to disk
scythe --record # Toggle normal recording on/off
scythe --cursor # Toggle mouse cursor capture
scythe --reload # Reload daemon settings
scythe --quit # Stop background recording daemon
scythe-ui --menu # Open the interactive overlay UI menu
scythe-ui --status # Query background daemon state and metrics
scythe-ui --save # Save instant replay clip to disk
scythe-ui --record # Toggle normal recording on/off
scythe-ui --cursor # Toggle mouse cursor capture
scythe-ui --reload # Reload daemon settings
scythe-ui --quit # Stop background recording daemon
```
---
@ -107,7 +106,7 @@ Settings are saved in JSON format at `~/.config/scythe/config.json`:
"record_bitrate_kbps": 18000,
"replay_duration_sec": 60,
"video_codec": "h264",
"output_directory": "~/Videos",
"output_directory": "~/Videos/Scythe",
"show_cursor": true,
"audio_mode": "system",
"mic_volume": 0.6,

View file

@ -1,345 +0,0 @@
# Scythe: Maintainer Todo & Audit Checklist
This checklist tracks known bugs, UI refinements, optimizations, and technical debt items across the Scythe codebase.
> **Historical note:** entries recorded before v0.2.18 reference `src/bin/scythe-daemon.rs` and `src/bin/scythe-ui.rs`. Those files were merged into [`src/main.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs) and [`src/daemon.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/daemon.rs) by the multicall consolidation; the paths are kept as an accurate record of where the work happened at the time.
---
## 1. UI Refinements & Imperfections
- [x] **Singular Multicall Binary Architecture (`scythe`)**:
- **Issue**: Distributing separate `scythe-daemon` and `scythe-ui` binaries required cross-process path discovery in `$PATH`, complicated Windows bundling with multiple executables, and prevented atomic single-file updates.
- **Resolution**:
- Consolidated daemon engine and UI overlay/CLI into a single binary (`scythe`) in [src/main.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs) and [src/daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/daemon.rs).
- Implemented multicall dispatch: inspects `argv[0]` and subcommands (`scythe daemon`, `scythe [options]`, or symlinks `scythe-daemon` / `scythe-ui`).
- Configured [install.sh](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/install.sh) with backward-compatible symlinks.
- Updated release packages: both Linux and Windows distributions now ship a single executable.
- [x] **Screenshot Resolution Presets (Native, 1080p, 1440p, 2160p, 720p) & Lanczos Downscaling**:
- **Issue**: Vague compression percentages and presets confused users instead of providing clear resolution controls.
- **Resolution**: Replaced vague compression sliders with clean resolution presets (`Native (Source)`, `1080p (FHD)`, `1440p (QHD)`, `2160p (4K UHD)`, `720p (HD)`) in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs). When a target resolution is selected, [src/bin/scythe-ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-ui.rs) executes pristine Lanczos hardware-accelerated scaling via FFmpeg.
- [x] **Removed Obsolete Game Folder Option**:
- **Issue**: The "Save video in a folder based on the game's name" toggle in Instant Replay settings was redundant.
- **Resolution**: Removed the toggle from the Replay settings panel in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs).
- [x] **Low-End Hardware Memory and Pipeline Optimizations**:
- **Issue**: Budget systems and laptops with iGPUs or low RAM suffered high memory pressure and command-queue stalls during replay buffering.
- **Resolution**:
- Reduced `async_depth` from 4 to 2 and enabled low-power compression preset in [src/encoder.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs) when `record_low_power` is enabled.
- Reduced circular packet ring buffer capacity allocation in [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs), saving ~30% buffer RAM on low-end hardware.
- [x] **Dropdown Rolldown Animation & Frosted Blur Styling**:
- **Issue**: Dropdowns previously appeared abruptly without animation, and background shadow/framing lacked smooth transition.
- **Resolution**: Implemented smooth cubic ease-out rolldown animation (`ui.ctx().animate_bool(...)` over 180ms) in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs). Content smoothly slides into position while clipped to the expanding frame, with multi-layered drop shadows (`draw_window_shadow`) and softened frosted background blur (`#10141a` at 96% opacity).
- [x] **Instant Replay Sound Capture Parity & Autostart Layout Fix**:
- **Issue**: Instant replay settings were missing sound capture options, and the Autostart section overflowed beyond the panel width.
- **Resolution**:
- Added full audio capture controls to Instant Replay settings (audio mode selection, volume sliders, live VU peak meters, and Opus/AAC codec choice).
- Refactored the Autostart section in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs) into a vertical button list matching the available container width.
- [x] **Functional Audio Settings Integration**:
- **Issue**: Audio settings in normal recording previously contained non-functional mockup buttons.
- **Resolution**: Replaced placeholder elements with fully functional controls for source routing (`System Audio`, `Microphone`, `Both`, `Muted`), live volume adjustment (0-150%), audio codec selection (`Opus` vs `AAC`), and live stereo peak meters.
- [x] **Screenshot Quality, Compression Preset & Keybind Integration**:
- **Issue**: Screenshot settings lacked quality/compression tuning and keybind rebinding in the general settings view.
- **Resolution**: Added compression quality slider (10% to 100%), compression preset selector (`Fast`, `Balanced`, `Maximum Compression`), and integrated screenshot keybind (`Ctrl+Shift+S`) into the general settings hotkey rebinding list.
- [x] **Comprehensive QoL Quick Keybinds & Compact Reset Button**:
- **Issue**: Hotkey settings lacked common shortcuts (such as pause recording, muting microphone, muting system audio), and the reset button in general settings took up too much width.
- **Resolution**:
- Added interactive rebinding for Pause Recording (`Ctrl+Shift+F8`), Mute Microphone (`Ctrl+Shift+M`), and Mute System Audio (`Ctrl+Shift+N`) in [src/config.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs), [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), and [src/bin/scythe-ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-ui.rs).
- Compacted the "Reset to Defaults" button in the hotkeys card to a compact `Reset Hotkeys` button (`96px x 24px`).
- [x] **Monospace Interface Font Support (Adwaita Mono)**:
- **Issue**: Interface typography was limited to proportional font without monospace option.
- **Resolution**: Integrated `AdwaitaMono-Regular.ttf` into [assets/fonts/](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/assets/fonts) and added a working toggle in General Settings allowing instant switching between Proportional and Monospace typography.
- [x] **Square Buttons, Zero-Roundness Dropdown Frames & Persistent Options**:
- **Issue**: The dropdown menu still had rounded styling and top accent bars, plus/minus buttons in numeric input boxes had rounded corners (`CornerRadius::same(3)`), and several options (such as changing resolution, scroll lock LED status, container format selection, and game naming rules) were dummy placeholders that didn't persist to configuration.
- **Resolution**:
- Completely stripped all roundness (`CornerRadius::ZERO`) from dropdown frames, dropdown items, keycap badges, and plus/minus stepper buttons in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs).
- Removed all top horizontal accent bars from dropdown frames and added realistic drop shadows (`draw_window_shadow`).
- Wired every single setting (`container_format`, `change_resolution`, `resolution_w`, `resolution_h`, `save_folder_by_game`, `name_by_game`, `restart_replay_on_save`, `show_scroll_lock_led`, `autostart_on_game`, `autostart_power_only`, `capture_source`, `video_quality_mode`, `color_range`, `audio_codec`, `replay_storage`, `record_low_power`, `show_replay_notifications`) to persist cleanly into [src/config.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs) and `~/.config/scythe/config.json`.
- Added automated unit test `test_overlay_app_options_synchronization` (27/27 passing) verifying save, apply, and reset for every single option.
- Fixed low-power hardware encoder fallback in [src/encoder.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs) on drivers without `VAEntrypointEncSliceLP`.
- [x] **Sharp Dark Slate Window Architecture with Drop Shadows (Matching GSR Screenshots)**:
- **Issue**: The UI previously had curved/rounded edges and embedded horizontal accent bars that felt uncharacteristic of native GPU screen recorder overlays.
- **Resolution**: Redesigned all overlay windows in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs) to match the visual language of the provided GPU Screen Recorder screenshots:
- Deep charcoal slate background (`#15191E`), crisp `#1D2228` section cards, and `#14181E` inset boxes.
- Zero roundness (`CornerRadius::ZERO`) across all windows, buttons, segmented pills, toggle switches, and inputs.
- Added multi-layered deep drop shadow effects (`draw_window_shadow`) behind the floating settings window and dropdown menus.
- Removed all top horizontal accent bars from the settings modal and card dropdowns.
- [x] **Dedicated Screenshot Feature & Settings Panel**:
- **Issue**: Screenshot functionality lacked a dedicated settings panel and CLI access.
- **Resolution**:
- Added a dedicated **Screenshot Settings** menu (`SettingsTab::Screenshot`) with destination folder configuration (Browse & Open), format selection (`PNG (Lossless)` vs `JPEG`), cursor capture toggle, hotkey display, CLI command reference (`scythe-ui --screenshot`), and instant capture trigger.
- Added `scythe-ui --screenshot` CLI command and registered global hotkey (`Ctrl+Shift+S`) across Hyprland and Windows/X11.
- [x] **Comprehensive Customizability & Options Expansion**:
- **Issue**: Settings lacked granular capture and audio controls shown in GPU Screen Recorder.
- **Resolution**: Expanded settings across all 5 menus:
- **Instant Replay**: Replay duration (sec/formatted time), RAM vs Disk storage selection, low-power mode toggle, game-based naming, replay notification toggles, autostart rules (on startup, on game launch, power supply condition), and video bitrate in Kbps/Mbps.
- **Normal Recording**: Capture source selection (`Focused monitor`, `Monitor eDP-1`, `Window`, `Region`), resolution change toggle, audio track management with output/input/application audio routing, audio codecs (`Opus` vs `AAC`), volume sliders with live meters, and color range (`Full` vs `Limited`).
- **Broadcast LIVE**: Streaming services (`Twitch`, `YouTube`, `Kick`, `Custom RTMP`), URL, masked stream key with eye toggle, and streaming quality parameters.
- **General Settings**: Interface accent palette chips, global keyboard shortcuts rebinding, and autostart toggles.
- [x] **Four Dedicated Independent Settings Menus**:
- **Issue**: Settings options were previously mixed across different tabs rather than dedicated to the specific feature chosen.
- **Resolution**: Refactored `SettingsTab` into 4 dedicated menus:
1. **Instant Replay**: Buffer Duration (numeric box + RAM footprint badge), Replay FPS, Replay Bitrate, Codec, Cursor toggle, Save Directory, Audio Source.
2. **Normal Recording**: Record FPS, Record Bitrate, Codec, Cursor toggle, Save Directory, Audio Source & Volume sliders with live VU meters.
3. **Broadcast LIVE**: Service selector, Server URL, Stream Key (masked with unmask toggle), Stream FPS, Stream Bitrate, Audio Source.
4. **General Settings**: Accent Color Theme chips, Keyboard Shortcuts (interactive listener cards), Startup integration, Software Updates.
- [x] **Floating Frosted Glass Dropdowns on HUD Cards**:
- **Issue**: Dropdowns beneath HUD cards were harsh black rectangles flush against the cards.
- **Resolution**: Rebuilt dropdowns with floating glass containers (`CornerRadius::same(10)`, `#10141A` at 97% opacity, 1px soft stroke, 2.5px top accent line). Dropdown items feature smooth `CornerRadius::same(6)` hover pills, clean typography, right-aligned hotkey badges, and direct links to each feature's dedicated settings menu.
- [x] **Silky Ease-In and Smooth Haste Exit Notification Animations**:
- **Issue**: Notifications felt sluggish on exit and lacked snappy responsiveness.
- **Resolution**: Implemented silky cubic ease-out entrance (`1.0 - (1.0 - t).powi(3)`) over 280ms, a legible hold, and a swift smooth-haste exit slide over 200ms with smoothstep acceleration (`t * t * (3.0 - 2.0 * t)`). Styled notification cards with `CornerRadius::same(10)` and curved top accent bar.
- [x] **NVIDIA ShadowPlay Settings Modal Complete Ground-Up Rewrite**:
- **Issue**: The previous settings page used an unwieldy 3-column freestanding layout that was visually fragmented, cluttered, and confusing to navigate across different categories.
- **Resolution**: Rebuilt the entire settings view in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs) as a centered, obsidian-glass ShadowPlay split modal with a dedicated left category navigation sidebar (`Video`, `Audio`, `Shortcuts`, `Replay & Storage`, `Livestream`, `Themes & System`). Replaced cluttered pill grids and sliders with direct, smooth numeric input fields with unit tags and stepper controls.
- [x] **In-Overlay Notification Animation Engine Overhaul**:
- **Issue**: Spawning separate OS processes for each toast notification created startup delays and visual popping.
- **Resolution**: Implemented in-process `InOverlayToast` rendering directly inside egui with cubic ease-out slide-in, accent progress indicator line, and smooth alpha fade-out, running at 0ms latency with zero process spawn overhead.
- [x] **Settings Page Reset to Defaults Button Over-sizing**:
- **Issue**: In [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), the "Defaults" button in the right-hand action stack was allocated the same massive primary button height (`btn_h` = 52.0px to 64.0px, width `side_w` = 160.0px to 192.0px) as the primary "Back" and "Save" buttons. This took up excessive vertical space in the sidebar, competing with primary actions.
- **Resolution**: Resized `def_rect` height from `btn_h` down to a compact secondary button height (`def_btn_h = (btn_h * 0.58).clamp(32.0, 36.0)`). Applied a dedicated subtle border and secondary font sizing with a clear "Reset to Defaults" label.
- **Resolution (Hotkeys Card)**: Streamlined the "Reset Hotkeys to Defaults" button in the keyboard hotkeys card from 180.0px down to 130.0px width for visual balance.
- [x] **Adaptive Content Box Scaling on Compact Displays**:
- **Issue**: On sub-1080p viewports (720p, 768p, 800p handhelds such as Steam Deck or ROG Ally), content box padding and card spacing previously caused unwanted vertical scrollbars.
- **Resolution**: Implemented dynamic scaling in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs) in both `render_section_card` and `render_settings_view`. On displays with height under 850px, inner padding adjusts from 16px to 12px horizontal and 12px to 8px vertical, section gaps compress, and `max_content_h` expands to 78% of viewport height.
- [x] **HUD Toast Notification Smooth Handoff & Queuing**:
- **Issue**: Rapid sequential toast alerts previously killed the prior toast process abruptly via `SIGKILL` / `TerminateProcess`, clipping the entry animation.
- **Resolution**: Implemented smooth handoff in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs). On Windows, dispatches `WM_CLOSE` to the prior toast window before terminating; on Linux, issues `SIGTERM` with a 50ms graceful settling delay.
- [x] **Windows Event-Driven Hotkey Message Pump (`MsgWaitForMultipleObjectsEx`)**:
- **Issue**: In [src/bin/scythe-ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-ui.rs), the hotkey loop previously polled `PeekMessageW` with a 20ms sleep, burning CPU cycles in an idle polling loop and introducing up to 20ms of shortcut response latency.
- **Resolution**: Replaced with `MsgWaitForMultipleObjectsEx(None, 200, QS_ALLINPUT, MWMO_INPUTAVAILABLE)`. The listener thread sleeps with 0% CPU consumption until a Win32 hotkey message arrives, immediately waking with sub-millisecond response latency.
- [x] **Windows DXGI Display Output Dynamic Re-enumeration**:
- **Issue**: When displays are hot-plugged or resolution changes occur, capture can lose sync.
- **Resolution**: In [src/capture/windows.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/windows.rs), added `AttachedToDesktop` checks and filtering for software rasterizers (`DXGI_ADAPTER_FLAG_SOFTWARE`), ensuring the active physical display is dynamically prioritized and re-enumerated.
- [x] **Linux PipeWire Portal Stream Reconnect on Compositor Crash**:
- **Issue**: If Hyprland, Sway, or `xdg-desktop-portal` restarts, the existing PipeWire stream FD disconnects, causing capture to stall.
- **Resolution**: In [src/capture/wayland.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/wayland.rs), implemented `try_reconnect()` with backoff. When the PipeWire stream disconnects, it re-negotiates portal sessions and resumes live frames without taking down the recording daemon.
---
## 2. Compiler & Linter Warnings
- [x] **Clippy `chunks_exact_to_as_chunks` Lints**:
- **Issue**: Newer Rust toolchains (Rust 1.88+) flag `chunks_exact` and `chunks_exact_mut` on constant chunk sizes (4 in mock capture, 2/3/4 in audio processing, 4 in Windows DXGI texture mapping).
- **Resolution**: Added `#![allow(clippy::chunks_exact_to_as_chunks)]` at crate roots in [src/lib.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/lib.rs), [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs), and [src/bin/scythe-ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-ui.rs) to ensure strict zero-warning builds (`cargo clippy --all-targets -- -D warnings`) across all Rust compiler versions (1.80 through current).
---
## 3. Reliability & Bug Fixes
- [x] **Gray Screen Recording & Mock Fallback Startup Race Condition**:
- **Issue**: At system boot or when logging into the session, `scythe-daemon` started before `xdg-desktop-portal` finished registering on D-Bus. After failing to acquire portals within 3 seconds, the daemon silently fell back to `MockCapture` (hardcoded to emit flat gray `RGB(64, 64, 64)` frames), permanently capturing a blank gray screen on subsequent recordings and replays.
- **Resolution**:
- Updated [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs) so that the daemon never silently traps the user into `MockCapture` unless the explicit `--mock` CLI flag is passed for automated testing.
- Added systemd service dependencies (`After=graphical-session.target xdg-desktop-portal.service xdg-desktop-portal-hyprland.service` and `Wants=xdg-desktop-portal.service`) with `Restart=always` and `RestartSec=2` backoff in [install.sh](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/install.sh).
- [x] **GTK3 Retirement, Compile-Time Optimization & Windows Cross-Compilation**:
- **Issue**: Legacy GTK3 C-bindings (`gtk`, `gdk`, `glib`, `gtk-layer-shell`) inflated compile times to over 1 minute, consumed heavy build memory, and completely blocked cross-compiling for Windows due to missing MinGW GTK headers.
- **Resolution**:
- Removed `gtk`, `gdk`, `glib`, `gtk-layer-shell`, and retired [src/settings_ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/settings_ui.rs) and the legacy GTK overlay code. Moved `ToastIcon` directly into [src/ipc.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/ipc.rs).
- Reduced release compile time by over 60% and unlocked Windows release cross-compilation (`x86_64-pc-windows-gnu`).
- Added optimized release profile with thin LTO and symbol stripping in [Cargo.toml](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/Cargo.toml).
- [x] **Forgejo Releases Integration & Auto-Updater Synchronization**:
- **Issue**: The auto-updater was hardcoded to GitHub API endpoints, and release binaries were not packaged for both Windows and Linux on the self-hosted Forgejo instance.
- **Resolution**:
- Updated [src/updater.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/updater.rs) to prioritize Forgejo API releases (`https://git.oiupoyt.space/api/v1/repos/oiupoyt/scythe/releases/latest`) with GitHub fallback.
- Cross-compiled release binaries for both Linux (`scythe-v0.2.18-linux-x86_64.tar.gz`) and Windows (`scythe-v0.2.18-windows-x86_64.zip` including full standalone portable FFmpeg DLLs).
- Published Release `v0.2.18` directly to Forgejo with assets uploaded.
- [x] **Opus Audio Encoder Implementation & AAC Fallback**:
- **Issue**: Previously, only AAC audio encoding was supported, despite Opus being the industry standard for low-latency streaming and high-fidelity game recording.
- **Resolution**: Implemented native `Opus` audio encoding in [src/encoder.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs) (`AudioEncoder::new_with_codec`) using `AV_SAMPLE_FMT_FLT` at 160 kbps with automatic fallback to AAC when unavailable. Dynamically wired into [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs) based on `config.audio_codec`. Verified 60 FPS recording with native Opus audio streams in MP4 containers.
- [x] **Hardware Video Encoder Quality Mode (CBR/VBR), Color Range & Low Power Mode**:
- **Issue**: Hardware video encoders previously hardcoded VBR rate control, MPEG limited color range, and default GPU performance profiles regardless of user settings.
- **Resolution**: Updated `VaapiEncoder` and `WindowsHwEncoder` in [src/encoder.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs) (`new_with_options`):
- Configured explicit `rc_mode` (CBR with strict bitrate caps vs VBR with 2x burst headroom).
- Configured color range (`AVCOL_RANGE_JPEG` full range 0-255 vs `AVCOL_RANGE_MPEG` limited range 16-235) in both codec contexts and `sws_setColorspaceDetails`.
- Implemented hardware low-power mode (`low_power` on VAAPI and `p1` energy-efficient preset on NVENC) to conserve battery during background replay buffering.
- [x] **Video Timestamp Pacing Judder (Lag & Micro-Stutter Fix)**:
- **Issue**: In [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs), video packet presentation timestamps (PTS) were calculated using wall-clock floating point math with small timing jitter. When a frame was processed a few milliseconds early or late, PTS deltas jumped between 0, 16ms, and 33ms, creating perceptible visual micro-stutter (judder) and making smooth 60 FPS video look choppy in video players.
- **Resolution**: Implemented smooth constant framerate (CFR) pacing. Each consecutive encoded video frame now receives an exact, uniform PTS step (`last_video_pts + 1`), providing an exact 16.666ms delta (verified with `ffprobe`). Video players and web browsers now play back smoothly without frame pacing judder.
- [x] **Hardware Video Encoder Rate Control & Quality Bottleneck**:
- **Issue**: In [src/encoder.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/encoder.rs), `rc_buffer_size` was restricted to `rate / 2` (only 0.5 seconds), `rc_mode` was unconfigured, and quantizer was capped with `qmin = 16`. On fast-motion or complex gaming scenes, the VAAPI and NVENC rate control buffers choked within 10 frames, forcing aggressive compression (macroblocking, muddy text, and visual blur).
- **Resolution**: Sized `rc_buffer_size` and `rc_max_rate` to `rate * 2` (2 full seconds of headroom), unlocked `qmin = 1` for crystal-clear fine details, set explicit `rc_mode = VBR`, and enabled `async_depth = 4` for hardware pipelining. Matches GPU Screen Recorder quality standards.
- [x] **Daemon Config Reload Process Deadlock**:
- **Issue**: In [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs), when video settings changed, the daemon spawned a replacement process and called `exit(0)`. Because the old daemon was still holding `flock` on `scythe.lock`, the child process failed with "Another instance is already running" and aborted, while systemd saw `exit(0)` and marked the service dead, leaving no daemon running.
- **Resolution**: Added up to 1.2s retries on lock acquisition for reloaded processes, removed `replay_enabled` and bitrates from restart triggers (they are now dynamically resized in RAM), and delegated service restarts to systemd (`systemctl --user restart`) when running under systemd.
- [x] **Manual Recording Start Error Propagation**:
- **Issue**: In [src/bin/scythe-daemon.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-daemon.rs), `Muxer::new` for manual recording previously discarded errors with `.ok()`. If opening the file failed (e.g., read-only filesystem or invalid path), the daemon remained in `is_recording = true` state while silently dropping video frames.
- **Resolution**: Replaced `.ok()` with explicit pattern matching. On failure, logs the exact error, marks recording inactive, and resets start timestamps cleanly.
- [x] **Windows Multi-Monitor Detection for Overlay and Notifications**:
- **Issue**: In [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), `run_egui_overlay()` and `run_egui_toast()` previously hardcoded `(0.0, 0.0)` with `SM_CXSCREEN`/`SM_CYSCREEN`. On multi-monitor setups, the overlay and notification toasts always appeared on the primary monitor even if the active game or foreground window was on monitor 2 or 3.
- **Resolution**: Implemented Windows `query_focused_monitor_rect()` using `GetForegroundWindow()` -> `MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)` -> `GetMonitorInfoW()`. Seamlessly falls back to `MonitorFromPoint` via cursor coordinates and primary metrics. Both overlay and toast now target the active monitor.
- [x] **Windows DXGI Desktop Duplication Buffer Pool Memory Churn**:
- **Issue**: In [src/capture/windows.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/windows.rs), `buffer_pool` checked `Arc::strong_count(buf) == 1` and took entries with `slot.take()`, but never pushed reused entries back once `len == 4`. Within 4 frames of launch, the pool was permanently emptied, causing fresh 8.3 MB `Arc::new(vec![0u8; total_bytes])` allocations every frame (~500 MB/s allocation thrashing at 1080p60).
- **Resolution**: Refactored `buffer_pool` to a true reusable `Vec<Arc<Vec<u8>>>` with capacity 8. Entries are borrowed when `strong_count == 1`, mutated in place, cloned for dispatch, and maintained in the pool. Allocation churn drops to zero after startup.
- [x] **Windows DXGI Invalid `ReleaseFrame` on Error Codes**:
- **Issue**: In [src/capture/windows.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/windows.rs), `ReleaseFrame()` was called on error paths (`ACCESS_LOST`, `ACCESS_DENIED`, etc.). Per Microsoft DXGI specification, calling `ReleaseFrame` when `AcquireNextFrame` failed returns `DXGI_ERROR_INVALID_CALL` and corrupts state.
- **Resolution**: Removed invalid `ReleaseFrame()` invocations from error branches.
- [x] **Windows Overlay Ungraceful Process Hard-Kill**:
- **Issue**: In [src/bin/scythe-ui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/bin/scythe-ui.rs), toggling the overlay closed previously invoked `TerminateProcess(h, 0)` immediately, bypassing all Rust destructors, Direct3D context teardown, and configuration saving.
- **Resolution**: Replaced with graceful `WM_CLOSE` message dispatch via `EnumWindows` and `PostMessageW`, using a 150ms timeout before falling back to `TerminateProcess` only if frozen.
- [x] **Windows Native Folder Picker Latency**:
- **Issue**: In [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), clicking "Change" directory previously spawned `powershell.exe` with a 2-4 second cold-start delay.
- **Resolution**: Replaced with native Windows COM `IFileOpenDialog` (`FOS_PICKFOLDERS`), opening in under 5 milliseconds with PowerShell retained as fallback.
- [x] **Windows WASAPI / CPAL Audio Format Expansion**:
- **Issue**: In [src/capture/audio.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/audio.rs), CPAL only handled `F32` and `I16` sample formats. Systems with DACs or audio drivers defaulting to `I32` (32-bit signed integer) failed with "Unsupported audio format", resulting in no audio.
- **Resolution**: Added normalization handlers for `cpal::SampleFormat::I32` and `cpal::SampleFormat::U16`.
- [x] **Windows In-App Auto-Updater Missing DLL Synchronization**:
- **Issue**: In [src/updater.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/updater.rs), portable zip extraction only copied `scythe-ui.exe` and `scythe-daemon.exe`, leaving updated FFmpeg/MinGW DLLs uncopied and causing potential version mismatches.
- **Resolution**: Expanded extraction to scan all `.exe` and `.dll` binaries recursively and swap them atomically using the `.old` staging pattern.
- [x] **Windows IPC Candidate Port Deduplication**:
- **Issue**: In [src/ipc.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/ipc.rs), candidate ports array repeated `active_port`, causing redundant connection timeout delays when probing daemon status.
- **Resolution**: Deduplicated candidate ports in `get_candidate_ipc_ports()`.
---
## 4. Performance & Memory Optimizations
- [x] **Repository Cleanup & Scratch Code Removal**:
- **Issue**: Obsolete exploratory files in `scythe/scratch/` (`test_shm.rs`, `test_x11_shm.rs`) and ad-hoc python scripts in the project root (`test_ipc.py`, `test_record.py`, `test_reload.py`, `test_stop.py`, `send_ipc.py`) cluttered the workspace.
- **Resolution**: Removed `scratch/` directory and relocated testing utilities into [tests/manual_ipc/](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/tests/manual_ipc).
- [x] **Dynamic PipeWire DRM Format Negotiation (Zero-Copy Pipeline)**:
- **Issue**: In [src/capture/wayland_stream.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/wayland_stream.rs), the DRM format code was hardcoded to `0x34325241` (`DRM_FORMAT_ARGB8888`), causing driver mismatches when compositors negotiated `XRGB8888`, `XBGR8888`, or `NV12`.
- **Resolution**: Dynamically mapped `user_data.format.format()` to its matching DRM fourcc (`DRM_FORMAT_XRGB8888`, `DRM_FORMAT_XBGR8888`, `DRM_FORMAT_NV12`). When `NV12` buffers arrive, they are passed directly into VAAPI without CPU color conversion.
- [x] **Audio Resampling Fast Path for 48,000 Hz Sources**:
- **Status**: Implemented in `convert_to_stereo_48k` via early return passthrough, avoiding interpolation when input matches 48 kHz.
- [x] **Windows Desktop Duplication Buffer Pool Recycling**:
- **Status**: Implemented in [src/capture/windows.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/capture/windows.rs) with 8-slot reusable buffer pool, eliminating heap allocations in the 60 FPS capture loop.
---
## 4a. Binary Dispatch
- [x] **Symlink Aliases Dispatched to the UI Instead of the Daemon**:
- **Issue**: [`src/main.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs) decided daemon mode from `std::env::current_exe()`, which reads `/proc/self/exe` and resolves symlinks. Because every installed alias points at the real `scythe` file, all of them reported the stem `scythe`, so `scythe-daemon` and `vrec-daemon` fell through to client mode and opened the HUD instead of starting the recording engine. The aliases shipped by [`install.sh`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/install.sh), the `.deb`/`.rpm`/Flatpak packages, and the Hyprland `exec_cmd("scythe-daemon")` autostart line were all affected. A stale pre-consolidation `target/release/scythe-daemon` from an older build masked the bug during local testing.
- **Resolution**: Added `invoked_stem()`, which reads argv[0] and only falls back to `current_exe()` when argv[0] has no usable stem. Verified against a packaged tarball: `scythe-daemon` and `vrec-daemon` now report the running-instance guard, while `scythe`, `scythe-ui`, `vrec` and `vrec-ui` open the client.
---
## 4b. Release Pipeline & Packaging Consolidation
- [x] **CI/CD Referenced Binaries That No Longer Build**:
- **Issue**: The multicall consolidation removed `scythe-daemon` and `scythe-ui` crate targets, but the release pipeline still copied `target/release/scythe-daemon` and `target/release/scythe-ui`. A tag push would fail at the very first packaging step, so no release could be produced. The same stale paths existed in the GitLab CI artifacts, RPM spec, Flatpak manifest, and both NSIS installers.
- **Resolution**:
- [`.github/workflows/release.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.github/workflows/release.yml): tarball, `.deb`, and AppImage now ship the single `scythe` binary plus `scythe-daemon` / `scythe-ui` / `vrec-*` symlinks. The AppImage `AppRun` and the Windows bundle copy only `scythe` / `scythe.exe`.
- [`.gitlab-ci.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.gitlab-ci.yml): artifacts publish `target/release/scythe`; the Windows job builds `--bin scythe`.
- [`packaging/rpm/scythe.spec`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/packaging/rpm/scythe.spec), [`packaging/flatpak/com.scythe.Scythe.yaml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/packaging/flatpak/com.scythe.Scythe.yaml): install one binary, link the aliases; Flatpak `command` is now `scythe`.
- [`packaging/windows/scythe-installer.nsi`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/packaging/windows/scythe-installer.nsi), [`packaging/windows/scythe-standalone.nsi`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/packaging/windows/scythe-standalone.nsi): shortcuts, finish-page runner, `DisplayIcon`, and forwarded arguments all target `scythe.exe`. Legacy process names remain in the `taskkill` upgrade path so old installs shut down cleanly.
- [x] **GitLab `fmt` Job Blocked Every Build**:
- **Issue**: `cargo fmt --check` reports drift across 20 files, and `build-linux` declared `needs: [fmt]`, so a formatting mismatch prevented any build from running.
- **Resolution**: Marked the `fmt` job `allow_failure: true` and dropped the hard `needs` edge, matching how `clippy` is already treated. A whole-tree reformat belongs in its own commit rather than being mixed into functional changes.
- [x] **GitHub Push Target & Credentials**:
- **Issue**: GitHub pushes targeted `oiupoyt/scythe`, but that account's OAuth token is expired, so the mirror had fallen 31 commits behind and pushes failed.
- **Resolution**: Added the `spearzificial` remote and pinned the username in the URL (`https://spearzificial@github.com/spearzificial/scythe.git`) so Git selects the correct entry from the multi-account credential store. Repository topology and the dual-push rule are documented in [`PROJECT_GUIDE.md`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/PROJECT_GUIDE.md).
---
## 4c. Dead Configuration Removal
- [x] **Settings That Persisted But Did Nothing**:
- **Issue**: Fourteen `ScytheConfig` keys were exposed in the settings UI and written to `config.json`, but no capture, encoder, muxer, or daemon path ever read them. Users could change them with no observable effect.
- **Resolution**: Removed the keys from [`src/config.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs), deleted their overlay state fields and controls in [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), and pruned the assertions in both test suites. The retired list and rationale live in [`PROJECT_GUIDE.md`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/PROJECT_GUIDE.md). Unknown JSON keys are ignored by serde, so existing configs still load.
- [x] **`Command::ShowOverlay` Was Declared But Ignored**:
- **Issue**: The IPC enum defined `ShowOverlay`, but the daemon's dispatcher had no arm for it and it fell through to `_ => {}`. Nothing could open the HUD once closed except the `--menu` toggle path.
- **Resolution**: Added `show_overlay_once()` in [`src/daemon.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/daemon.rs) — it checks the overlay pid file for a live process and spawns `scythe --menu` only when none is running, so repeated requests cannot stack overlays. Exposed as `scythe --show-overlay`, with a direct-launch fallback when the daemon is unreachable.
- [x] **E2E Test Unlinked a Live Daemon's Socket**:
- **Issue**: [`tests/e2e_test.sh`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/tests/e2e_test.sh) ran `rm -f "$SOCKET_PATH"` unconditionally and only stopped the systemd unit. A daemon started any other way (Hyprland `execs.lua`, manual launch) kept the flock; the test removed its socket path entry, leaving the kernel socket bound but unreachable. The session stayed broken until the process was killed.
- **Resolution**: The script now probes liveness with a direct Unix-socket connect (not `--status`, which calls `ensure_daemon_running()` and spawns a daemon while probing), records the running daemon's command line and working directory, sends `StopDaemon`, waits for the socket to disappear, aborts without unlinking if it will not stop, and restores the original daemon on exit.
---
## 4d. Build & CI
- [x] **No CI Ran on Routine Commits**:
- **Issue**: GitHub Actions only triggered on `v*` tag pushes. Nothing compiled the project between releases, so breakage accumulated unnoticed and every release was the first real build in weeks.
- **Resolution**: Added [`ci.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.github/workflows/ci.yml), which runs on every push to `main`, on pull requests, and manually. The Linux job type-checks, tests, lints with `-D warnings`, builds the release binary, runs `scythe --help` to prove the binary starts, and uploads it as an artifact. The Windows job builds through MSYS2 MINGW64 and uploads `scythe.exe`. Both binaries are downloadable from the run.
- [x] **The Windows Target Did Not Compile**:
- **Issue**: [`src/config.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/config.rs) reads AC line status through `GetSystemPowerStatus`, but the `windows` crate feature list in [`Cargo.toml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/Cargo.toml) never enabled `Win32_System_Power`. `cargo build --target x86_64-pc-windows-gnu` failed with `E0432: unresolved import windows::Win32::System::Power`. The build had been broken since the power-monitoring feature landed, and only tag pushes could have revealed it.
- **Resolution**: Added the `Win32_System_Power` feature. The Windows job now builds green on every push.
- [x] **Unknown CLI Arguments Became a Background Hotkey Daemon**:
- **Issue**: The dispatch match in [`src/main.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/main.rs) ended in `_ => {}`, so an unrecognised flag fell through into the global hotkey loop. `scythe --version` registered the Hyprland binds and then blocked forever instead of reporting the bad flag.
- **Resolution**: The catch-all arm now prints the offending argument with a pointer to `--help` and exits with status 2.
- [x] **The Audio Test Needed Hardware CI Could Not Provide**:
- **Issue**: `test_audio_probe` asserts that a system audio device opens and emits samples. A headless runner has no audio server, so the unit suite could never pass in CI.
- **Resolution**: The test is opt-in through `SCYTHE_HW_TESTS=1` and still runs on a real desktop session. The remaining 27 tests run everywhere.
- [x] **Windows Autostart Does Nothing**:
- **Issue**: `apply_autostart_system` has only a Linux body (systemd user unit plus XDG autostart entries). On Windows the call is a no-op, and the NSIS installer writes no registry `Run` key either, so the autostart switch in the overlay has no effect there.
- **Resolution**: Parameters marked intentionally unused off Linux so the Windows build is warning-free, and the gap is recorded in [`PROJECT_GUIDE.md`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/PROJECT_GUIDE.md). Implementing the registry entry is still open.
---
Run these commands before any commit or release to verify project health:
```bash
# Type check all platform targets
cargo check --all-targets
# Run the complete unit test suite (27 tests)
cargo test
# Strict zero-warning clippy verification
cargo clippy --all-targets -- -D warnings
# Build the unified release binary
cargo build --release
# Run the automated end-to-end pipeline test (mock capture, ffprobe validation)
bash tests/e2e_test.sh
# Hardware-dependent tests (needs a live audio server)
SCYTHE_HW_TESTS=1 cargo test
```
GitHub Actions runs the same checks on every push to `main`, for both the Linux and the Windows target. See [`ci.yml`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/.github/workflows/ci.yml).
Formatting is currently advisory: `cargo fmt --check` still reports drift across the tree. Run `cargo fmt` as an isolated commit before turning it into a release gate.

Binary file not shown.

View file

@ -1,292 +0,0 @@
# Settings UI and Notification Engine Redesign Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Rebuild the Scythe settings UI into a clean, centered NVIDIA ShadowPlay-style split-panel modal with smooth direct numeric input fields and implement a zero-latency in-overlay toast animation system with graceful standalone toast handoff.
**Architecture:** Replace the legacy 3-column freestanding page stack in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs) with a unified `ShadowPlayView::Settings(SettingsTab)` modal. Implement numeric inputs with bounds clamping and inline stepper buttons. Replace external toast process killing with in-overlay egui animation banners and graceful window messaging.
**Tech Stack:** Rust 2024 edition, egui / eframe 0.31, Win32 DWM / Windows COM, Wayland layer-shell.
**Spec:** [`docs/superpowers/specs/2026-10-04-settings-ui-and-notifications-redesign.md`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/docs/superpowers/specs/2026-10-04-settings-ui-and-notifications-redesign.md)
## Global Constraints
- Absolutely zero emojis across code, comments, logs, test outputs, and commits.
- Clickable markdown links formatted with the `file://` scheme.
- Complete conditional compilation safety across Linux and Windows.
- No blocking operations on UI rendering loops.
## Review Focus
1. Sub-1080p display clipping: Modal must adaptively scale below 850px viewport heights without overflowing the screen.
2. Direct numeric string parsing: Typing non-numeric characters in FPS, Bitrate, or Duration fields must not crash or corrupt settings state.
3. Rapid hotkey keycap binding: Entering key listener mode must capture multi-modifier shortcuts (`Ctrl+Shift+R`, `Alt+Z`) cleanly and allow cancellation with `Escape`.
4. Simultaneous in-overlay notifications: Multiple sequential alerts must reset duration or smoothly update without graphical popping.
5. Multi-monitor Windows geometry: Standalone toasts and modals must respect active monitor bounds when `monitor_x` is negative or non-zero.
---
### Task 1: Data Structures, Enums, and Numeric Input Component
**Files:**
- Modify: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
- Test: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
**Interfaces:**
- Produces:
- `pub enum SettingsTab { Video, Audio, Shortcuts, ReplayAndStorage, Livestream, AppearanceAndSystem }`
- `pub enum ShadowPlayView { MainHud, Settings(SettingsTab), Gallery }`
- `pub fn numeric_input_box(ui: &mut egui::Ui, value_str: &mut String, val: &mut u32, min: u32, max: u32, step: u32, unit: &str, accent: Color32) -> bool`
- `pub struct InOverlayToast { pub title: String, pub subtitle: String, pub icon: ToastIcon, pub created_at: Instant, pub duration: Duration }`
- [ ] **Step 1: Write unit tests for numeric input bounds and Tab enums**
In `src/overlay_egui.rs` tests module:
```rust
#[test]
fn test_numeric_input_clamping_and_validation() {
let mut val = 60u32;
let mut text = "60".to_string();
assert!((15..=360).contains(&val));
// Test text update
text = "144".to_string();
if let Ok(parsed) = text.trim().parse::<u32>() {
val = parsed.clamp(15, 360);
}
assert_eq!(val, 144);
// Test out of bounds clamping
text = "999".to_string();
if let Ok(parsed) = text.trim().parse::<u32>() {
val = parsed.clamp(15, 360);
}
assert_eq!(val, 360);
}
```
- [ ] **Step 2: Run test to verify it passes or fails**
Run: `cargo test --lib test_numeric_input_clamping_and_validation`
- [ ] **Step 3: Define `SettingsTab` and `numeric_input_box` in `src/overlay_egui.rs`**
Implement:
- `SettingsTab` enum with `Video`, `Audio`, `Shortcuts`, `ReplayAndStorage`, `Livestream`, `AppearanceAndSystem`.
- `numeric_input_box` rendering a dark input box with `[-]` and `[+]` stepper buttons and unit label.
- Add `active_tab: SettingsTab` and `in_overlay_toast: Option<InOverlayToast>` to `ScytheOverlayApp`.
- [ ] **Step 4: Verify compilation**
Run: `cargo check --all-targets`
- [ ] **Step 5: Commit**
```bash
git add src/overlay_egui.rs
git commit -m "feat(ui): add SettingsTab enum, InOverlayToast struct, and numeric input component"
```
---
### Task 2: Unified Centered ShadowPlay Settings Modal Layout
**Files:**
- Modify: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
- Test: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
**Interfaces:**
- Consumes: `SettingsTab`, `ScytheOverlayApp`, `accent_color()`.
- Produces: `render_settings_modal(&mut self, ctx: &egui::Context, ui: &mut egui::Ui)`.
- [ ] **Step 1: Write layout geometry test for settings modal**
In `src/overlay_egui.rs` tests module:
```rust
#[test]
fn test_settings_modal_geometry_bounds() {
for (screen_w, screen_h) in [(1280.0, 720.0), (1920.0, 1080.0), (2560.0, 1440.0), (3840.0, 2160.0)] {
let is_compact_h = screen_h < 850.0;
let modal_w = if screen_w < 1400.0 { 680.0 } else { 760.0 };
let modal_h = if is_compact_h { 450.0 } else { 520.0 };
let pos_x = (screen_w - modal_w) * 0.5;
let pos_y = (screen_h - modal_h) * 0.5;
assert!(pos_x >= 0.0);
assert!(pos_y >= 0.0);
assert!(pos_x + modal_w <= screen_w);
assert!(pos_y + modal_h <= screen_h);
}
}
```
- [ ] **Step 2: Run test to verify it passes**
Run: `cargo test --lib test_settings_modal_geometry_bounds`
- [ ] **Step 3: Implement `render_settings_modal`**
- Centered modal container (`modal_w x modal_h`) with obsidian glass fill `#101418` and top accent line.
- Left sidebar (`190px` width) with vertical tab buttons for `Video`, `Audio`, `Shortcuts`, `Replay & Storage`, `Livestream`, `Appearance & System`.
- Active tab highlight with accent pill border and crisp text.
- Compact "Reset to Defaults" button and version tag at sidebar footer.
- Close button (`X`) and "Done" button at top-right.
- Clicking outside or pressing Escape returns to `ShadowPlayView::MainHud`.
- [ ] **Step 4: Run compiler check**
Run: `cargo check --all-targets`
- [ ] **Step 5: Commit**
```bash
git add src/overlay_egui.rs
git commit -m "feat(ui): implement centered ShadowPlay settings modal with tab navigation"
```
---
### Task 3: Category Settings Panels Implementation
**Files:**
- Modify: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
**Interfaces:**
- Produces:
- `render_tab_video`
- `render_tab_audio`
- `render_tab_shortcuts`
- `render_tab_replay_storage`
- `render_tab_livestream`
- `render_tab_appearance_system`
- [ ] **Step 1: Implement `render_tab_video`**
- Numeric input box for Target Framerate (`15` to `360` FPS) with `[-]` and `[+]` steppers.
- Numeric input box for Recording Bitrate (`5` to `150` Mbps).
- Codec selector (`H.264`, `HEVC`, `AV1`).
- Toggle switch for "Record mouse cursor".
- [ ] **Step 2: Implement `render_tab_audio`**
- Source selector (`System Audio`, `Microphone`, `Both`, `Muted`).
- Sliders for System Volume (0-100%) and Mic Volume (0-100%).
- Live stereo VU meters with soft-limit indicators.
- [ ] **Step 3: Implement `render_tab_shortcuts`**
- Interactive cards for `Menu Overlay`, `Save Replay`, `Start/Stop Record`, `Toggle Cursor`.
- Click to listen for key combinations, with instant rebind and Esc to cancel.
- [ ] **Step 4: Implement `render_tab_replay_storage`**
- Numeric input box for Replay Buffer Duration (`5` to `1800` seconds).
- Calculated RAM footprint badge.
- Path input with "Browse" button (invoking native Windows COM `IFileOpenDialog` / Linux portal) and "Open Folder".
- [ ] **Step 5: Implement `render_tab_livestream` and `render_tab_appearance_system`**
- Service dropdown (`Twitch`, `YouTube`, `Kick`, `Custom RTMP`), URL, and masked stream key field.
- 8 accent color chips with instant preview.
- Startup toggles ("Start replay on login", "Open overlay on login").
- In-app version checker with "Check for Updates" button.
- [ ] **Step 6: Run verification and tests**
Run: `cargo check --all-targets && cargo test`
- [ ] **Step 7: Commit**
```bash
git add src/overlay_egui.rs
git commit -m "feat(ui): implement clean settings tab panels with numeric input boxes"
```
---
### Task 4: In-Overlay Notification Animation Engine & Standalone Toast Overhaul
**Files:**
- Modify: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
- Test: [`src/overlay_egui.rs`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs)
**Interfaces:**
- Produces:
- `ScytheOverlayApp::show_hud_notification` (queues in-process `InOverlayToast`)
- `render_in_overlay_toast(&mut self, ctx: &egui::Context, ui: &mut egui::Ui)`
- Overhauled `run_egui_toast` with cubic ease-out animation
- [ ] **Step 1: Write test for cubic ease-out calculation**
```rust
#[test]
fn test_cubic_ease_out_progress() {
let ease_out = |t: f32| -> f32 {
let inv = 1.0 - t.clamp(0.0, 1.0);
1.0 - inv * inv * inv
};
assert_eq!(ease_out(0.0), 0.0);
assert_eq!(ease_out(1.0), 1.0);
assert!(ease_out(0.5) > 0.5); // Fast start, gentle deceleration
}
```
- [ ] **Step 2: Run test to verify it passes**
Run: `cargo test --lib test_cubic_ease_out_progress`
- [ ] **Step 3: Implement `render_in_overlay_toast`**
- Paints floating notification banner in top-right corner of overlay.
- `0.0s – 0.22s`: Slide in from right viewport margin using cubic ease-out.
- `0.22s – 2.4s`: Fully visible with icon, bold title, subtitle, and discharging accent progress line.
- `2.4s – 2.7s`: Smooth alpha fade-out to zero.
- Renders directly in the egui viewport with zero process spawning overhead.
- [ ] **Step 4: Refactor `run_egui_toast` standalone window**
- Uses the same cubic ease-out curve and ShadowPlay aesthetic card.
- Positioned at `(active_mon_x + active_mon_w - 364, active_mon_y + 24)`.
- Clean automatic exit after 2.7s duration.
- [ ] **Step 5: Verify compiler and tests**
Run: `cargo check --all-targets && cargo test`
- [ ] **Step 6: Commit**
```bash
git add src/overlay_egui.rs
git commit -m "feat(ui): implement in-overlay toast animation engine and overhaul standalone toasts"
```
---
### Task 5: Integration, End-to-End Verification, and Build Deployment
**Files:**
- Modify: [`TODO_CHECKLIST.md`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/TODO_CHECKLIST.md)
- Test: [`tests/e2e_test.sh`](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/tests/e2e_test.sh)
- [ ] **Step 1: Run clippy and check across all targets**
Run: `cargo clippy --all-targets -- -D warnings`
Expected: 0 warnings, 0 errors.
- [ ] **Step 2: Run full unit test suite**
Run: `cargo test`
Expected: All tests pass.
- [ ] **Step 3: Run end-to-end integration test**
Run: `bash tests/e2e_test.sh`
Expected: Recording and replay succeed without corruption.
- [ ] **Step 4: Compile release binaries and install locally**
Run: `cargo build --release && bash install.sh`
Expected: Fresh binaries deployed to `~/.local/bin/` and daemon restarted.
- [ ] **Step 5: Commit final changes**
```bash
git add TODO_CHECKLIST.md
git commit -m "chore: update maintainer checklist with settings modal and notification overhaul"
```

View file

@ -1,156 +0,0 @@
# Design Specification: Scythe Settings UI and Notification Engine Redesign
## 1. Overview & Objective
This specification details the comprehensive redesign of the Settings User Interface and Notification Engine in [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs). The objective is to replace the legacy 3-column freestanding settings pages and fragmented external toast process spawning with:
1. **A Unified NVIDIA ShadowPlay-Inspired Settings Modal**:
- Centered, frosted-glass modal (`780px x 520px`) with split-panel layout.
- Left-hand category sidebar (`Video`, `Audio`, `Shortcuts`, `Replay & Storage`, `Livestream`, `Appearance & System`).
- Clean, direct numeric input boxes for Bitrate, Framerate, and Replay Duration (with inline unit tags, instant validation, and increment/decrement steppers), replacing cluttered pill grids and sliders.
- Live calculated buffer metrics and instant folder browser buttons.
2. **Fluid, Multi-Tier Notification Engine**:
- In-Overlay Notification Banner: Rendered in-process by egui with zero process spawn latency and cubic ease-out animations.
- Standalone Toast Window: Clean, single-window presentation on active monitors across Linux and Windows with graceful lifecycle teardown.
3. **Cross-Platform Zero-Defect Architecture**:
- Full parity and bug-free execution across Linux (Wayland layer-shell, X11) and Windows 10/11 (DWM per-pixel glass transparency, multi-monitor geometry detection).
---
## 2. Architecture & Component Decomposition
### 2.1 UI State Machine & Views
In [src/overlay_egui.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/overlay_egui.rs), replace the disjointed view variants (`ReplaySettings`, `RecordSettings`, `StreamSettings`, `GlobalSettings`, `ScreenshotSettings`) with a cohesive modal state:
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShadowPlayView {
MainHud,
Settings(SettingsTab),
Gallery,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingsTab {
Video,
Audio,
Shortcuts,
ReplayAndStorage,
Livestream,
AppearanceAndSystem,
}
```
### 2.2 Modal Window Geometry & Styling
- **Modal Dimensions**: Width `780.0px`, Height `520.0px` (adaptively scaled on viewports with height `< 850.0px` to `680.0px x 450.0px`).
- **Dimmed Backdrop**: Dimming scrim covering the screen (`rgba(0, 0, 0, 0.70)` on Linux, transparent backbuffer on Windows with DWM glass). Clicking outside the modal or pressing `Escape` saves settings and returns cleanly to `MainHud`.
- **Card Framing**:
- Fill: Obsidian Glass `Color32::from_rgb(16, 20, 24)`.
- Border: 1px subtle stroke `Color32::from_rgba_unmultiplied(255, 255, 255, 18)`.
- Accent Line: Top 3px highlight band colored by user's active theme accent.
### 2.3 Left-Hand Sidebar Navigation (Width `200.0px`)
Displays a vertical stack of category buttons:
- Tab item height: `38.0px`, rounded corners (`CornerRadius::same(4)`).
- Active tab styling: Accent-tinted background (`rgba(accent, 0.20)`), 1.5px accent left border pill, and bold white text.
- Inactive tab styling: Transparent background with `#94A3B8` text, shifting to `#CBD5E1` on hover.
- Footer controls: Compact secondary button: "Reset to Defaults" (`height: 30.0px`) and version identifier ("Scythe v0.2.17").
### 2.4 Right-Hand Content Panel (Width `540.0px`)
Displays the content for the currently active `SettingsTab`:
#### Tab 1: Video Settings
- **Target Framerate (FPS)**:
- Numeric input box with unit `FPS`. Range `15` to `360`. Stepper buttons `[-]` and `[+]` by 5/10 steps.
- **Recording Video Bitrate**:
- Numeric input box with unit `Mbps`. Range `5` to `150`.
- **Video Codec**:
- Clean horizontal segment pills `[ H.264 ]`, `[ HEVC (H.265) ]`, `[ AV1 ]`.
- **Mouse Cursor Recording**:
- Sleek toggle switch: "Record mouse cursor".
#### Tab 2: Audio Settings
- **Audio Capture Source**:
- Segment pills `[ System Audio ]`, `[ Microphone ]`, `[ Both ]`, `[ Muted ]`.
- **Microphone Selection**:
- Dropdown populated from system input devices.
- **Volume Inputs & Controls**:
- System Volume (`0% – 100%`) and Microphone Volume (`0% – 100%`) with numeric fields and live visual VU meters.
#### Tab 3: Shortcuts Settings
- **Hotkeys Cards**:
- Menu Overlay (Default: `Alt+Z`)
- Save Instant Replay (Default: `Ctrl+Shift+R`)
- Start/Stop Recording (Default: `Ctrl+Shift+F9`)
- Toggle Mouse Cursor (Default: `Ctrl+Shift+F10`)
- **Key Listening Mode**:
- Displays interactive keycap badge. When clicked, enters listening state; pressing any key combination captures and re-binds instantly. Pressing `Escape` cancels without modifying.
#### Tab 4: Replay & Storage Settings
- **Replay Buffer Duration**:
- Numeric input box with unit `seconds`. Range `5` to `1800` (up to 30 minutes).
- Displays human-readable label: e.g. `60 sec (1 min 00 sec)`.
- **Estimated RAM Footprint**:
- Calculated dynamically: `(seconds * bitrate_mbps * 1000) / 8192 MB`.
- **Save Location**:
- Path text field with "Browse" button (invokes Windows COM `IFileOpenDialog` or Linux portal) and "Open" folder button.
#### Tab 5: Livestream Settings
- **Streaming Service**: Dropdown for `Twitch`, `YouTube`, `Kick`, `Custom RTMP`.
- **Server URL & Stream Key**:
- Stream URL text input.
- Stream Key masked input with eye toggle to unmask.
#### Tab 6: Appearance & System Settings
- **Accent Color Theme**:
- 8 palette chips (AMD Red, NVIDIA Green, Intel Blue, Charming Blue, Emerald Green, Solar Yellow, Royal Purple, Neon Pink).
- **Startup Integration**:
- Toggles for "Launch background replay engine on login" and "Launch HUD overlay on login".
- **Application Updater**:
- Status display and "Check for Updates" trigger invoking [src/updater.rs](file:///home/oiupoyt/my%20stuff%20yea/projects/scythe/src/updater.rs).
---
## 3. Notification Animation & Rendering Architecture
### 3.1 In-Overlay Notification System (Overlay Open)
- Stored as an optional field in `ScytheOverlayApp`:
```rust
pub struct InOverlayToast {
pub title: String,
pub subtitle: String,
pub icon: ToastIcon,
pub created_at: Instant,
pub duration: Duration,
}
```
- **Lifecycle & Easing**:
- `0.0s – 0.22s`: Slide in from right viewport edge (`x` offset interpolated with `cubic_ease_out`).
- `0.22s – 2.4s`: Fully visible top-right card with accent progress bar discharging to 0.
- `2.4s – 2.7s`: Alpha fade out to `0.0`.
- Handled directly in egui frame drawing with zero additional OS windows or process spawns.
### 3.2 Standalone Floating Toast System (Overlay Closed)
- Invoked via `scythe-ui --toast <title> <subtitle> <icon>`.
- Displays a dedicated single-purpose viewport card (`340px x 56px`):
- Borderless, per-pixel transparent background, positioned at `(active_mon_x + active_mon_w - 364, active_mon_y + 24)`.
- Icon on left, bold title, message, and subtle accent bottom border.
- Smooth 2.6-second duration with auto-shutdown.
- Replaces process hard-kills with clean window messages (`WM_CLOSE` on Windows, graceful `SIGTERM` settling on Linux).
---
## 4. Verification & Testing Plan
1. **Unit Tests**:
- Numeric input bounds validation (FPS 15-360, Bitrate 5-150, Replay 5-1800).
- Layout geometry assertions ensuring modal cards fit across 720p, 1080p, 1440p, and 4K displays.
- Color palette mapping and theme serialization.
2. **Integration Verification**:
- Verify settings persistence to `~/.config/scythe/config.json`.
- Verify daemon dynamic reload on parameter changes.
- Verify in-overlay notification display and standalone toast execution.
3. **Compiler Checks**:
- `cargo check --all-targets` with zero errors.
- `cargo clippy --all-targets -- -D warnings` with zero warnings.
- `cargo test` with all tests passing.

View file

@ -15,38 +15,17 @@ APP_DIR="$HOME/.local/share/applications"
mkdir -p "$BIN_DIR"
mkdir -p "$APP_DIR"
echo "[2/4] Installing singular binary to $BIN_DIR..."
install -m 755 target/release/scythe "$BIN_DIR/scythe"
echo "[2/4] Installing binaries to $BIN_DIR..."
install -m 755 target/release/scythe-daemon "$BIN_DIR/scythe-daemon"
install -m 755 target/release/scythe-ui "$BIN_DIR/scythe-ui"
ln -sf "$BIN_DIR/scythe-ui" "$BIN_DIR/scythe"
# Backward-compatible multicall symlinks
ln -sf "$BIN_DIR/scythe" "$BIN_DIR/scythe-daemon"
ln -sf "$BIN_DIR/scythe" "$BIN_DIR/scythe-ui"
ln -sf "$BIN_DIR/scythe" "$BIN_DIR/vrec-daemon"
ln -sf "$BIN_DIR/scythe" "$BIN_DIR/vrec-ui"
ln -sf "$BIN_DIR/scythe" "$BIN_DIR/vrec"
# Backward-compatible symlinks
ln -sf "$BIN_DIR/scythe-daemon" "$BIN_DIR/vrec-daemon"
ln -sf "$BIN_DIR/scythe-ui" "$BIN_DIR/vrec-ui"
ln -sf "$BIN_DIR/scythe-ui" "$BIN_DIR/vrec"
SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
mkdir -p "$SYSTEMD_USER_DIR"
cat > "$SYSTEMD_USER_DIR/scythe-daemon.service" << EOF
[Unit]
Description=Scythe Screen Recorder Background Engine
After=graphical-session.target xdg-desktop-portal.service xdg-desktop-portal-hyprland.service
Wants=xdg-desktop-portal.service
[Service]
Type=simple
ExecStart=$BIN_DIR/scythe daemon
Restart=always
RestartSec=2
Environment="XDG_RUNTIME_DIR=/run/user/1000"
Environment="XDG_CURRENT_DESKTOP=Hyprland"
Environment="XDG_SESSION_TYPE=wayland"
[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload 2>/dev/null || true
if [ -f "$SYSTEMD_USER_DIR/vrec-daemon.service" ] || systemctl --user is-active --quiet vrec-daemon.service 2>/dev/null; then
echo "Migrating legacy vrec-daemon systemd service to scythe-daemon.service..."
systemctl --user stop vrec-daemon.service 2>/dev/null || true

View file

@ -4,7 +4,7 @@ runtime-version: '46'
sdk: org.gnome.Sdk
sdk-extensions:
- org.freedesktop.Sdk.Extension.rust-stable
command: scythe
command: scythe-ui
finish-args:
- --share=ipc
- --socket=fallback-x11
@ -26,11 +26,11 @@ modules:
buildsystem: simple
build-commands:
- cargo build --release --verbose
- install -Dm755 target/release/scythe-daemon /app/bin/scythe-daemon
- install -Dm755 target/release/scythe-ui /app/bin/scythe-ui
- install -Dm755 target/release/scythe /app/bin/scythe
- ln -sf /app/bin/scythe /app/bin/scythe-daemon
- ln -sf /app/bin/scythe /app/bin/scythe-ui
- ln -sf /app/bin/scythe /app/bin/vrec-daemon
- ln -sf /app/bin/scythe /app/bin/vrec-ui
- ln -sf /app/bin/scythe-daemon /app/bin/vrec-daemon
- ln -sf /app/bin/scythe-ui /app/bin/vrec-ui
- ln -sf /app/bin/scythe /app/bin/vrec
- install -Dm644 packaging/scythe.desktop /app/share/applications/com.scythe.Scythe.desktop
sources:

View file

@ -32,19 +32,19 @@ cargo build --release
%install
rm -rf $RPM_BUILD_ROOT
install -D -m 0755 target/release/scythe-daemon %{buildroot}%{_bindir}/scythe-daemon
install -D -m 0755 target/release/scythe-ui %{buildroot}%{_bindir}/scythe-ui
install -D -m 0755 target/release/scythe %{buildroot}%{_bindir}/scythe
ln -sf %{_bindir}/scythe %{buildroot}%{_bindir}/scythe-daemon
ln -sf %{_bindir}/scythe %{buildroot}%{_bindir}/scythe-ui
ln -sf %{_bindir}/scythe %{buildroot}%{_bindir}/vrec-daemon
ln -sf %{_bindir}/scythe %{buildroot}%{_bindir}/vrec-ui
ln -sf %{_bindir}/scythe-daemon %{buildroot}%{_bindir}/vrec-daemon
ln -sf %{_bindir}/scythe-ui %{buildroot}%{_bindir}/vrec-ui
ln -sf %{_bindir}/scythe %{buildroot}%{_bindir}/vrec
install -D -m 0644 packaging/scythe.desktop %{buildroot}%{_datadir}/applications/scythe.desktop
ln -sf %{_datadir}/applications/scythe.desktop %{buildroot}%{_datadir}/applications/vrec.desktop
%files
%{_bindir}/scythe
%{_bindir}/scythe-daemon
%{_bindir}/scythe-ui
%{_bindir}/scythe
%{_bindir}/vrec-daemon
%{_bindir}/vrec-ui
%{_bindir}/vrec

View file

@ -15,7 +15,7 @@ RequestExecutionLevel user
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!define MUI_FINISHPAGE_RUN "$INSTDIR\scythe.exe"
!define MUI_FINISHPAGE_RUN "$INSTDIR\scythe-ui.exe"
!define MUI_FINISHPAGE_RUN_PARAMETERS "--menu"
!define MUI_FINISHPAGE_RUN_TEXT "Launch Scythe"
!insertmacro MUI_PAGE_FINISH
@ -27,12 +27,11 @@ RequestExecutionLevel user
Section "Scythe" SecMain
; Terminate any running instances so locked executables and DLLs can be updated cleanly
nsExec::Exec 'taskkill /F /IM scythe.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-ui.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-daemon.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-ui.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-daemon.exe /T'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe, scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
Sleep 1500
SetOverwrite try
@ -41,24 +40,23 @@ Section "Scythe" SecMain
; Create Start Menu and Desktop shortcuts
CreateDirectory "$SMPROGRAMS\scythe"
CreateShortcut "$SMPROGRAMS\scythe\scythe.lnk" "$INSTDIR\scythe.exe" "--menu"
CreateShortcut "$DESKTOP\scythe.lnk" "$INSTDIR\scythe.exe" "--menu"
CreateShortcut "$SMPROGRAMS\scythe\scythe.lnk" "$INSTDIR\scythe-ui.exe" "--menu"
CreateShortcut "$DESKTOP\scythe.lnk" "$INSTDIR\scythe-ui.exe" "--menu"
; Register uninstaller with Windows Control Panel / Settings
WriteUninstaller "$INSTDIR\uninstall.exe"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\scythe" "DisplayName" "Scythe Screen Recorder"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\scythe" "UninstallString" '"$INSTDIR\uninstall.exe"'
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\scythe" "DisplayIcon" "$INSTDIR\scythe.exe"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\scythe" "DisplayIcon" "$INSTDIR\scythe-ui.exe"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\scythe" "Publisher" "oiupoyt"
SectionEnd
Section "Uninstall"
nsExec::Exec 'taskkill /F /IM scythe.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-ui.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-daemon.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-ui.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-daemon.exe /T'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe, scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
Sleep 1500
Delete "$DESKTOP\scythe.lnk"

View file

@ -9,12 +9,11 @@ RequestExecutionLevel user
Section
; Terminate any running instances so locked executables and DLLs can be updated cleanly
nsExec::Exec 'taskkill /F /IM scythe.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-ui.exe /T'
nsExec::Exec 'taskkill /F /IM scythe-daemon.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-ui.exe /T'
nsExec::Exec 'taskkill /F /IM vrec-daemon.exe /T'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe, scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
nsExec::Exec 'powershell -NoProfile -NonInteractive -WindowStyle Hidden -Command "Get-Process -Name scythe-ui, scythe-daemon, vrec-ui, vrec-daemon -ErrorAction SilentlyContinue | Stop-Process -Force"'
Sleep 1500
SetOverwrite try
@ -22,11 +21,11 @@ Section
SetOutPath "$LOCALAPPDATA\scythe"
File /r "..\..\dist\bundle\*.*"
; Execute scythe with any forwarded command-line arguments, or default to overlay menu
; Execute scythe-ui with any forwarded command-line arguments, or default to overlay menu
${GetParameters} $R0
${If} $R0 == ""
Exec '"$LOCALAPPDATA\scythe\scythe.exe" --menu'
Exec '"$LOCALAPPDATA\scythe\scythe-ui.exe" --menu'
${Else}
Exec '"$LOCALAPPDATA\scythe\scythe.exe" $R0'
Exec '"$LOCALAPPDATA\scythe\scythe-ui.exe" $R0'
${EndIf}
SectionEnd

View file

@ -1,9 +1,10 @@
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
use crate::capture::{Frame, FrameSource};
use crate::encoder::VideoEncoder;
use crate::ring::Packet;
use crate::muxer::Muxer;
use crate::ipc::{Command, DaemonStatus};
use scythe::capture::{Frame, FrameSource};
use scythe::encoder::VideoEncoder;
use scythe::ring::Packet;
use scythe::muxer::Muxer;
use scythe::ipc::{Command, DaemonStatus};
use ringbuf::HeapRb;
use ringbuf::traits::{RingBuffer, Consumer, Observer};
use crossbeam_channel::bounded;
@ -13,67 +14,6 @@ use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
/// Returns true when the overlay process recorded in the pid file is still alive.
fn overlay_alive() -> bool {
let pid_path = crate::ipc::get_overlay_pid_path();
let Ok(content) = std::fs::read_to_string(&pid_path) else {
return false;
};
let Ok(pid) = content.trim().parse::<i32>() else {
return false;
};
if pid <= 0 {
return false;
}
#[cfg(unix)]
{
unsafe { libc::kill(pid, 0) == 0 }
}
#[cfg(windows)]
{
use windows::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
use windows::Win32::System::Threading::{
GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
};
unsafe {
let Ok(handle) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid as u32) else {
return false;
};
let mut code = 0u32;
let alive = GetExitCodeProcess(handle, &mut code).is_ok() && code == STILL_ACTIVE.0 as u32;
let _ = CloseHandle(handle);
alive
}
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
/// Opens the HUD overlay without toggling an already-visible one closed.
fn spawn_overlay_once() {
if overlay_alive() {
return;
}
let exe = std::env::current_exe()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "scythe".to_string());
let mut cmd = std::process::Command::new(exe);
cmd.arg("--menu")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000);
}
let _ = cmd.spawn();
}
fn mask_stream_url(url: &str) -> String {
if let Some((base, key)) = url.rsplit_once('/')
&& key.len() > 4 {
@ -138,18 +78,12 @@ fn spawn_stream_worker(
}
fn ensure_wayland_env() {
crate::overlay::ensure_wayland_env();
}
pub fn run_daemon() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?
.block_on(run_daemon_async())
scythe::overlay::ensure_wayland_env();
}
#[tokio::main]
#[allow(unused_assignments)]
async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg(target_os = "windows")]
unsafe {
use windows::Win32::System::Console::FreeConsole;
@ -171,14 +105,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
{
Ok(file) => {
use std::os::unix::io::AsRawFd;
let mut res = -1;
for _ in 0..15 {
res = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if res == 0 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(80));
}
let res = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if res != 0 {
eprintln!("Another instance of scythe-daemon is already running. Exiting.");
return Ok(());
@ -188,16 +115,11 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
Err(_) => None,
}
};
let mut initial_config = crate::config::ScytheConfig::load();
if initial_config.autostart_power_only
&& !crate::config::ScytheConfig::is_ac_power_connected() {
eprintln!("Power-only replay armed but no AC supply detected; replay buffer paused until power returns.");
initial_config.replay_enabled = false;
}
let initial_config = scythe::config::ScytheConfig::load();
// Automatically register dynamic keybindings on Hyprland if active (no config edits needed)
crate::hyprland_binds::register_hyprland_binds(&initial_config);
crate::hyprland_binds::spawn_hyprland_reload_watcher();
scythe::hyprland_binds::register_hyprland_binds(&initial_config);
scythe::hyprland_binds::spawn_hyprland_reload_watcher();
let (frame_tx, frame_rx) = bounded::<Frame>(2);
let (cmd_tx, cmd_rx) = bounded::<Command>(32);
@ -210,11 +132,11 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
let stream_start_state = Arc::new(AtomicU64::new(0));
let replay_enabled_state = Arc::new(AtomicBool::new(initial_config.replay_enabled));
let audio_muted_state = Arc::new(AtomicBool::new(false));
let audio_levels = Arc::new(crate::capture::audio::AudioLevels::new());
let audio_levels = Arc::new(scythe::capture::audio::AudioLevels::new());
#[cfg(unix)]
let listener = {
let socket_path = crate::ipc::get_socket_path();
let socket_path = scythe::ipc::get_socket_path();
let _ = std::fs::remove_file(&socket_path);
let l = std::os::unix::net::UnixListener::bind(&socket_path)?;
println!("Daemon listening on IPC socket: {}", socket_path);
@ -232,7 +154,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
break;
}
Err(_) => {
if crate::ipc::query_status_port(port).is_ok() {
if scythe::ipc::query_status_port(port).is_ok() {
println!("Another instance of scythe-daemon is already running on port {}. Exiting cleanly.", port);
return Ok(());
}
@ -242,7 +164,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
match bound {
Some((l, p)) => {
println!("Daemon listening on TCP IPC: 127.0.0.1:{}", p);
let _ = std::fs::write(crate::ipc::get_ipc_port_path(), p.to_string());
let _ = std::fs::write(scythe::ipc::get_ipc_port_path(), p.to_string());
let _ = std::fs::write(std::env::temp_dir().join("vrec-ipc.port"), p.to_string());
l
}
@ -300,7 +222,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
} else {
0
};
let cfg = crate::config::ScytheConfig::load();
let cfg = scythe::config::ScytheConfig::load();
let status = DaemonStatus {
is_recording: rec,
recording_duration_sec: duration,
@ -322,13 +244,30 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
}
},
Command::ToggleCursor => {
let mut cfg = crate::config::ScytheConfig::load();
let mut cfg = scythe::config::ScytheConfig::load();
cfg.show_cursor = !cfg.show_cursor;
let _ = cfg.save();
#[cfg(target_os = "linux")]
{
let session_type = env::var("XDG_SESSION_TYPE").unwrap_or_default();
if session_type.to_lowercase() == "wayland" {
println!("Cursor display toggled to: {}. Restarting Wayland session...", cfg.show_cursor);
let _ = cmd_tx_ipc.send(Command::StopRecording);
if let Ok(exe) = std::env::current_exe() {
let _ = std::process::Command::new(exe)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
}
std::thread::sleep(std::time::Duration::from_millis(150));
std::process::exit(0);
}
}
println!("Cursor display toggled to: {}", cfg.show_cursor);
},
Command::CycleAudioMode => {
let mut cfg = crate::config::ScytheConfig::load();
let mut cfg = scythe::config::ScytheConfig::load();
cfg.audio_mode = match cfg.audio_mode.as_str() {
"system" => "mic",
"mic" => "both",
@ -339,13 +278,9 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
println!("Audio mode cycled to: {}", cfg.audio_mode);
let _ = cmd_tx_ipc.try_send(Command::ReloadConfig);
},
Command::ShowOverlay => {
println!("ShowOverlay requested: opening HUD overlay.");
std::thread::spawn(spawn_overlay_once);
},
Command::StopDaemon => {
println!("StopDaemon requested: Finalizing active recordings...");
crate::hyprland_binds::unregister_hyprland_binds(&crate::config::ScytheConfig::load());
scythe::hyprland_binds::unregister_hyprland_binds(&scythe::config::ScytheConfig::load());
let _ = cmd_tx_ipc.send(Command::StopRecording);
std::thread::sleep(std::time::Duration::from_millis(350));
std::process::exit(0);
@ -371,7 +306,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
println!("\nReceived shutdown signal. Finalizing recordings...");
let _ = cmd_tx_sig.send(Command::StopRecording);
tokio::time::sleep(std::time::Duration::from_millis(350)).await;
crate::hyprland_binds::unregister_hyprland_binds(&crate::config::ScytheConfig::load());
scythe::hyprland_binds::unregister_hyprland_binds(&scythe::config::ScytheConfig::load());
std::process::exit(0);
}
});
@ -379,7 +314,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
let session_type = env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| "x11".to_string());
println!("Detected session type: {}", session_type);
let audio_capture_initial = crate::capture::audio::AudioCapture::new_with_device_mode_volumes_and_levels(
let audio_capture_initial = scythe::capture::audio::AudioCapture::new_with_device_mode_volumes_and_levels(
audio_tx.clone(),
Some(&initial_config.audio_device),
&initial_config.audio_mode,
@ -392,12 +327,12 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
if std::env::args().any(|a| a == "--mock") {
println!("Initializing MOCK capture...");
source_opt = Some(Box::new(crate::capture::mock::MockCapture::new()));
source_opt = Some(Box::new(scythe::capture::mock::MockCapture::new()));
} else if cfg!(target_os = "windows") {
#[cfg(target_os = "windows")]
{
println!("Initializing Windows DXGI capture...");
if let Ok(c) = crate::capture::windows::WindowsCapture::new() {
if let Ok(c) = scythe::capture::windows::WindowsCapture::new() {
source_opt = Some(Box::new(c));
}
}
@ -411,7 +346,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
.args(["--user", "start", "xdg-desktop-portal-hyprland"])
.status();
match crate::capture::wayland::WaylandCapture::new_with_cursor(initial_config.show_cursor).await {
match scythe::capture::wayland::WaylandCapture::new_with_cursor(initial_config.show_cursor).await {
Ok(cap) => {
source_opt = Some(Box::new(cap));
break;
@ -432,23 +367,17 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
#[cfg(target_os = "linux")]
{
println!("Initializing X11 capture...");
if let Ok(c) = crate::capture::x11::X11Capture::new() {
if let Ok(c) = scythe::capture::x11::X11Capture::new() {
source_opt = Some(Box::new(c));
}
}
}
let is_mock_cli = std::env::args().any(|a| a == "--mock");
let mut source: Box<dyn FrameSource> = match source_opt {
Some(s) => s,
None => {
if is_mock_cli {
eprintln!("Warning: Mock capture mode active via --mock flag.");
Box::new(crate::capture::mock::MockCapture::new())
} else {
eprintln!("Error: Hardware capture failed to initialize on {} session. Exiting for restart.", session_type);
std::process::exit(1);
}
eprintln!("Warning: Hardware capture unavailable; falling back to mock capture to preserve daemon IPC.");
Box::new(scythe::capture::mock::MockCapture::new())
}
};
@ -511,68 +440,24 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
#[allow(unused_variables, unused_assignments)]
let mut audio_capture = audio_capture_initial.map(|(c, _, _)| c);
fn effective_replay_active(cfg: &crate::config::ScytheConfig) -> bool {
if !cfg.replay_enabled {
return false;
}
if cfg.autostart_power_only && !crate::config::ScytheConfig::is_ac_power_connected() {
return false;
}
true
}
let cmd_tx_power = cmd_tx.clone();
std::thread::spawn(move || {
let mut last_ac = crate::config::ScytheConfig::is_ac_power_connected();
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let now_ac = crate::config::ScytheConfig::is_ac_power_connected();
if now_ac != last_ac {
last_ac = now_ac;
let _ = cmd_tx_power.send(Command::PowerStateChanged(now_ac));
}
}
});
fn spawn_power_toast(title: &str, subtitle: &str, icon: &str) {
let exe = std::env::current_exe()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "scythe".to_string());
let _ = std::process::Command::new(exe)
.args(["--toast", title, subtitle, icon])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
}
let recorder_handle = thread::spawn(move || {
let mut config = crate::config::ScytheConfig::load();
let mut replay_effective = effective_replay_active(&config);
replay_state_clone.store(replay_effective, Ordering::SeqCst);
let mut config = scythe::config::ScytheConfig::load();
replay_state_clone.store(config.replay_enabled, Ordering::SeqCst);
let active_bitrate = if config.replay_enabled {
config.replay_bitrate_kbps
} else {
config.record_bitrate_kbps
};
let mut encoder = VideoEncoder::new_with_options(
width,
height,
active_bitrate,
config.fps,
&config.video_codec,
&config.video_quality_mode,
&config.color_range,
config.record_low_power,
).expect("Failed to init encoder");
let mut encoder = VideoEncoder::new_with_params(width, height, active_bitrate, config.fps, &config.video_codec)
.expect("Failed to init encoder");
let codec_ctx_ptr = encoder.codec_ctx() as usize;
println!("Background recorder engine active and ready ({} fps, replay: {}).", config.fps, config.replay_enabled);
let mut audio_encoder = if let Some((sr, ch)) = audio_info {
crate::encoder::AudioEncoder::new_with_codec(sr as i32, ch as i32, &config.audio_codec).ok()
scythe::encoder::AudioEncoder::new(sr as i32, ch as i32).ok()
} else {
crate::encoder::AudioEncoder::new_with_codec(48000, 2, &config.audio_codec).ok()
scythe::encoder::AudioEncoder::new(48000, 2).ok()
};
let audio_codec_ctx_ptr = audio_encoder.as_ref().map(|e| e.codec_ctx() as usize);
@ -580,11 +465,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
let audio_time_base = audio_codec_ctx_ptr.map(|p| unsafe { (*(p as *mut ffmpeg_next::ffi::AVCodecContext)).time_base });
let ring_capacity = if config.replay_enabled {
if config.record_low_power {
(config.replay_duration_sec as usize) * (config.fps as usize + 15) + 30
} else {
(config.replay_duration_sec as usize) * (config.fps as usize + 50) + 60
}
(config.replay_duration_sec as usize) * (config.fps as usize + 50) + 60
} else {
1
};
@ -604,8 +485,8 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
thread::spawn(move || {
while let Ok(drain) = mux_rx.recv() {
let filename = crate::config::ScytheConfig::format_video_filename("Replay", "mp4");
let full_path = crate::config::ScytheConfig::load().resolve_save_path(&filename);
let filename = scythe::config::ScytheConfig::format_video_filename("Replay", "mp4");
let full_path = scythe::config::ScytheConfig::load().resolve_save_path(&filename);
println!("Saving replay to {}...", full_path);
// Find the first video IDR keyframe (ignore audio packets which always have keyframe flag set)
@ -732,21 +613,11 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
rec_base_video_pts = pkt.pts();
rec_base_audio_pts = -1;
let codec_ctx = codec_ctx_ptr as *mut ffmpeg_next::ffi::AVCodecContext;
let filename = crate::config::ScytheConfig::format_video_filename("Recording", "mp4");
let filename = scythe::config::ScytheConfig::format_video_filename("Recording", "mp4");
let full_path = config.resolve_save_path(&filename);
let audio_codec_ctx = audio_codec_ctx_ptr.map(|p| p as *mut ffmpeg_next::ffi::AVCodecContext);
match unsafe { Muxer::new(&full_path, codec_ctx, audio_codec_ctx) } {
Ok(m) => {
normal_muxer = Some(m);
println!("Started normal recording to {}", full_path);
}
Err(e) => {
eprintln!("Failed to start normal recording to {}: {}", full_path, e);
normal_recording = false;
rec_state_clone.store(false, Ordering::SeqCst);
rec_start_clone.store(0, Ordering::SeqCst);
}
}
normal_muxer = unsafe { Muxer::new(&full_path, codec_ctx, audio_codec_ctx).ok() };
println!("Started normal recording to {}", full_path);
} else if normal_waiting_keyframe {
normal_keyframe_timeout += 1;
}
@ -771,7 +642,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
}
}
if replay_effective {
if config.replay_enabled {
ring.push_overwrite(pkt);
}
}
@ -789,34 +660,20 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
if let Ok(cmd) = cmd_res {
match cmd {
Command::ReloadConfig => {
let new_config = crate::config::ScytheConfig::load();
let new_config = scythe::config::ScytheConfig::load();
let video_changed = new_config.show_cursor != config.show_cursor
|| new_config.fps != config.fps
|| new_config.video_codec != config.video_codec
|| new_config.color_range != config.color_range
|| new_config.video_quality_mode != config.video_quality_mode
|| new_config.audio_codec != config.audio_codec
|| new_config.record_low_power != config.record_low_power;
|| new_config.record_bitrate_kbps != config.record_bitrate_kbps
|| new_config.replay_bitrate_kbps != config.replay_bitrate_kbps
|| new_config.replay_enabled != config.replay_enabled;
if video_changed {
println!("Core video settings changed (fps/codec/cursor). Restarting daemon for new capture session...");
println!("Core video settings changed (fps/codec/bitrate/cursor/replay). Restarting daemon for new capture session...");
if let Some(mut m) = normal_muxer.take() {
let _ = m.finalize();
}
let _ = stream_sender.take();
#[cfg(unix)]
{
if let Ok(status) = std::process::Command::new("systemctl")
.args(["--user", "is-active", "--quiet", "scythe-daemon.service"])
.status()
&& status.success() {
let _ = std::process::Command::new("systemctl")
.args(["--user", "restart", "scythe-daemon.service"])
.spawn();
std::thread::sleep(std::time::Duration::from_millis(100));
std::process::exit(0);
}
}
if let Ok(exe) = std::env::current_exe() {
let mut cmd = std::process::Command::new(exe);
cmd.stdin(std::process::Stdio::null())
@ -833,14 +690,9 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
std::process::exit(0);
}
config = new_config;
replay_effective = effective_replay_active(&config);
replay_state_clone.store(replay_effective, Ordering::SeqCst);
if !replay_effective && config.replay_enabled {
while ring.try_pop().is_some() {}
eprintln!("Replay paused: power-only armed and running on battery.");
}
replay_state_clone.store(config.replay_enabled, Ordering::SeqCst);
audio_muted_clone.store(config.audio_mode == "muted", Ordering::SeqCst);
println!("Daemon config reloaded! Audio mode: {} replay_effective: {}", config.audio_mode, replay_effective);
println!("Daemon config reloaded! Audio mode: {}", config.audio_mode);
let new_capacity = if config.replay_enabled {
(config.replay_duration_sec as usize) * (config.fps as usize + 50) + 60
} else {
@ -852,8 +704,8 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
#[cfg(target_os = "linux")]
unsafe { libc::malloc_trim(0); }
}
crate::hyprland_binds::register_hyprland_binds(&config);
audio_capture = match crate::capture::audio::AudioCapture::new_with_device_mode_volumes_and_levels(
scythe::hyprland_binds::register_hyprland_binds(&config);
audio_capture = match scythe::capture::audio::AudioCapture::new_with_device_mode_volumes_and_levels(
audio_tx_clone.clone(),
Some(&config.audio_device),
&config.audio_mode,
@ -872,27 +724,8 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
};
ticker = crossbeam_channel::tick(std::time::Duration::from_nanos(1_000_000_000 / config.fps.max(1) as u64));
},
Command::PowerStateChanged(on_ac) => {
let was_effective = replay_effective;
replay_effective = effective_replay_active(&config);
replay_state_clone.store(replay_effective, Ordering::SeqCst);
if !replay_effective && (was_effective || !on_ac) {
while ring.try_pop().is_some() {}
eprintln!("Power lost: replay buffer paused and drained.");
if config.autostart_power_only && config.show_replay_notifications {
spawn_power_toast("POWER", "power lost, replay paused", "error");
}
} else if replay_effective && !was_effective {
encoder.force_keyframe();
has_new_frame = true;
println!("Power restored: replay buffer resumed.");
if config.show_replay_notifications {
spawn_power_toast("POWER", "power restored, replay resumed", "replay");
}
}
},
Command::SaveReplay => {
if replay_effective {
if config.replay_enabled {
let now = std::time::Instant::now();
if now.duration_since(last_replay_save) > std::time::Duration::from_millis(800) {
last_replay_save = now;
@ -915,7 +748,6 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
normal_recording = true;
normal_waiting_keyframe = true;
normal_keyframe_timeout = 0;
has_new_frame = true;
encoder.force_keyframe();
rec_state_clone.store(true, Ordering::SeqCst);
rec_base_audio_pts = -1;
@ -958,7 +790,6 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
normal_recording = true;
normal_waiting_keyframe = true;
normal_keyframe_timeout = 0;
has_new_frame = true;
encoder.force_keyframe();
rec_state_clone.store(true, Ordering::SeqCst);
rec_base_audio_pts = -1;
@ -973,7 +804,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
println!("Audio mute toggled: {}", !cur);
},
Command::StartStreaming => {
let cfg = crate::config::ScytheConfig::load();
let cfg = scythe::config::ScytheConfig::load();
let key = cfg.stream_key.trim();
if key.is_empty() {
eprintln!("Cannot start livestream: stream key is empty in config.");
@ -1020,7 +851,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
stream_start_clone.store(0, Ordering::SeqCst);
println!("ToggleStreaming: Livestream stopped.");
} else {
let cfg = crate::config::ScytheConfig::load();
let cfg = scythe::config::ScytheConfig::load();
let key = cfg.stream_key.trim();
if key.is_empty() {
eprintln!("Cannot start livestream: stream key is empty in config.");
@ -1117,7 +948,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
let _ = tx.try_send(rebased);
}
}
if replay_effective {
if config.replay_enabled {
ring.push_overwrite(pkt);
}
}
@ -1135,7 +966,7 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
}
let is_streaming = stream_sender.is_some();
if !normal_recording && !replay_effective && !is_streaming {
if !normal_recording && !config.replay_enabled && !is_streaming {
has_new_frame = false;
continue;
}
@ -1145,9 +976,9 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
if now + jitter_margin >= next_frame_time {
let elapsed = now.duration_since(stream_start);
let raw_pts = (elapsed.as_secs_f64() * config.fps as f64).round() as i64;
let pts = if last_video_pts < 0 {
0
} else if raw_pts > last_video_pts + 4 {
let pts = if (raw_pts - last_video_pts).abs() <= 1 {
last_video_pts + 1
} else if raw_pts > last_video_pts {
raw_pts
} else {
last_video_pts + 1
@ -1220,9 +1051,9 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
if now.duration_since(last_frame_encoded_time) >= target_frame_duration.saturating_sub(jitter_margin) {
let elapsed = now.duration_since(stream_start);
let raw_pts = (elapsed.as_secs_f64() * config.fps as f64).round() as i64;
let pts = if last_video_pts < 0 {
0
} else if raw_pts > last_video_pts + 4 {
let pts = if (raw_pts - last_video_pts).abs() <= 1 {
last_video_pts + 1
} else if raw_pts > last_video_pts {
raw_pts
} else {
last_video_pts + 1
@ -1279,6 +1110,6 @@ async fn run_daemon_async() -> Result<(), Box<dyn std::error::Error + Send + Syn
let _ = recorder_handle.join();
#[cfg(windows)]
let _ = std::fs::remove_file(crate::ipc::get_ipc_port_path());
let _ = std::fs::remove_file(scythe::ipc::get_ipc_port_path());
Ok(())
}

View file

@ -1,5 +1,4 @@
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
#![allow(clippy::chunks_exact_to_as_chunks)]
use scythe::ipc::{Command, send_command, query_status};
use scythe::overlay::{show_shadowplay_toast, ToastIcon};
@ -12,14 +11,44 @@ fn ensure_wayland_env() {
fn get_daemon_cmd() -> std::process::Command {
#[allow(unused_mut)]
let mut cmd = if let Ok(self_exe) = std::env::current_exe() {
let mut c = std::process::Command::new(self_exe);
c.arg("daemon");
c
let mut cmd = if let Ok(mut path) = std::env::current_exe() {
path.pop();
#[cfg(target_os = "windows")]
let primary = path.join("scythe-daemon.exe");
#[cfg(target_os = "windows")]
let fallback = path.join("vrec-daemon.exe");
#[cfg(not(target_os = "windows"))]
let primary = path.join("scythe-daemon");
#[cfg(not(target_os = "windows"))]
let fallback = path.join("vrec-daemon");
if primary.exists() {
let mut c = std::process::Command::new(primary);
c.current_dir(&path);
c
} else if fallback.exists() {
let mut c = std::process::Command::new(fallback);
c.current_dir(&path);
c
} else {
#[cfg(target_os = "windows")]
{
std::process::Command::new("scythe-daemon.exe")
}
#[cfg(not(target_os = "windows"))]
{
std::process::Command::new("scythe-daemon")
}
}
} else {
let mut c = std::process::Command::new("scythe");
c.arg("daemon");
c
#[cfg(target_os = "windows")]
{
std::process::Command::new("scythe-daemon.exe")
}
#[cfg(not(target_os = "windows"))]
{
std::process::Command::new("scythe-daemon")
}
};
#[cfg(target_os = "windows")]
@ -90,42 +119,19 @@ fn check_and_toggle_overlay() -> bool {
}
}
#[cfg(windows)]
if let Ok(pid) = content.trim().parse::<u32>()
&& pid != std::process::id() {
if let Ok(pid) = content.trim().parse::<u32>() {
if pid != std::process::id() {
unsafe {
use windows::Win32::UI::WindowsAndMessaging::{
EnumWindows, GetWindowThreadProcessId, PostMessageW, WM_CLOSE,
};
use windows::Win32::Foundation::{BOOL, HWND, LPARAM, CloseHandle};
use windows::Win32::System::Threading::{
OpenProcess, TerminateProcess, PROCESS_TERMINATE, PROCESS_SYNCHRONIZE, WaitForSingleObject,
};
unsafe extern "system" fn close_proc(hwnd: HWND, lparam: LPARAM) -> BOOL {
unsafe {
let target = lparam.0 as u32;
let mut pid = 0u32;
GetWindowThreadProcessId(hwnd, Some(&mut pid));
if pid == target {
let _ = PostMessageW(hwnd, WM_CLOSE, None, None);
}
BOOL(1)
}
}
let _ = EnumWindows(Some(close_proc), LPARAM(pid as isize));
// Wait up to 150ms for graceful shutdown before fallback termination
if let Ok(h) = OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_TERMINATE, false, pid) {
let wait_res = WaitForSingleObject(h, 150);
if wait_res.0 != 0 {
let _ = TerminateProcess(h, 0);
}
use windows::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
use windows::Win32::Foundation::CloseHandle;
if let Ok(h) = OpenProcess(PROCESS_TERMINATE, false, pid) {
let _ = TerminateProcess(h, 0);
let _ = CloseHandle(h);
let _ = std::fs::remove_file(&pid_path);
return true;
}
let _ = std::fs::remove_file(&pid_path);
return true;
}
}
}
}
let _ = std::fs::remove_file(&pid_path);
@ -245,12 +251,10 @@ fn handle_toggle_recording() -> Result<(), Box<dyn std::error::Error + Send + Sy
fn handle_toggle_cursor() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
ensure_daemon_running();
let current_cursor = query_status().ok().map(|s| s.show_cursor).unwrap_or(true);
let next_cursor = !current_cursor;
match send_command(Command::ToggleCursor) {
Ok(()) => {
std::thread::sleep(std::time::Duration::from_millis(120));
let next_cursor = query_status().ok().map(|s| s.show_cursor).unwrap_or_else(|| {
scythe::config::ScytheConfig::load().show_cursor
});
if next_cursor {
show_shadowplay_toast("MOUSE CURSOR", "Visible in recording", ToastIcon::Cursor);
} else {
@ -275,90 +279,6 @@ fn handle_save_replay() -> Result<(), Box<dyn std::error::Error + Send + Sync>>
send_with_notification(Command::SaveReplay, "INSTANT REPLAY", "Saved to Videos", ToastIcon::Replay)
}
fn handle_screenshot() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let cfg = scythe::config::ScytheConfig::load();
let dir = scythe::config::ScytheConfig::expand_tilde(&cfg.screenshot_directory);
let _ = std::fs::create_dir_all(&dir);
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();
let ext = if cfg.screenshot_format.to_lowercase() == "jpg" || cfg.screenshot_format.to_lowercase() == "jpeg" { "jpg" } else { "png" };
let filename = format!("Screenshot_{}.{}", now, ext);
let out_path = dir.join(&filename);
#[cfg(target_os = "linux")]
{
let mut grim = std::process::Command::new("grim");
if cfg.screenshot_cursor {
grim.arg("-c");
}
if ext == "jpg" {
grim.args(["-t", "jpeg", "-q", "90"]);
}
grim.arg(&out_path);
let _ = grim.status();
if !out_path.exists() {
let _ = std::process::Command::new("import").args(["-window", "root"]).arg(&out_path).status();
}
}
#[cfg(target_os = "windows")]
{
let ps_cmd = format!(
"Add-Type -AssemblyName System.Windows.Forms,System.Drawing; \
$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds; \
$bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height; \
$g = [System.Drawing.Graphics]::FromImage($bmp); \
$g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size); \
$bmp.Save('{}'); $g.Dispose(); $bmp.Dispose()",
out_path.to_string_lossy().replace('/', "\\")
);
let _ = std::process::Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", &ps_cmd])
.status();
}
let scale_dims = match cfg.screenshot_resolution.as_str() {
"720p" => Some("1280:720"),
"1080p" => Some("1920:1080"),
"1440p" => Some("2560:1440"),
"2160p" => Some("3840:2160"),
_ => None,
};
if let Some(scale) = scale_dims
&& out_path.exists() {
let tmp_path = dir.join(format!("tmp_{}", filename));
if std::fs::rename(&out_path, &tmp_path).is_ok() {
let _ = std::process::Command::new("ffmpeg")
.args(["-v", "error", "-y", "-i", &tmp_path.to_string_lossy(), "-vf", &format!("scale={}:flags=lanczos", scale), &out_path.to_string_lossy()])
.status();
let _ = std::fs::remove_file(&tmp_path);
}
}
show_shadowplay_toast("SCREENSHOT", &format!("Saved to {}", filename), ToastIcon::Screenshot);
Ok(())
}
fn handle_mute_mic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut cfg = scythe::config::ScytheConfig::load();
let is_muted = cfg.mic_volume < 0.05;
cfg.mic_volume = if is_muted { 0.60 } else { 0.0 };
let _ = cfg.save();
scythe::config::ScytheConfig::notify_daemon_reload();
show_shadowplay_toast("MICROPHONE", if is_muted { "Unmuted" } else { "Muted" }, ToastIcon::Info);
Ok(())
}
fn handle_mute_sys() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut cfg = scythe::config::ScytheConfig::load();
let is_muted = cfg.system_volume < 0.05;
cfg.system_volume = if is_muted { 1.00 } else { 0.0 };
let _ = cfg.save();
scythe::config::ScytheConfig::notify_daemon_reload();
show_shadowplay_toast("SYSTEM AUDIO", if is_muted { "Unmuted" } else { "Muted" }, ToastIcon::Info);
Ok(())
}
fn handle_toggle_streaming() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
ensure_daemon_running();
let cfg = scythe::config::ScytheConfig::load();
@ -384,45 +304,9 @@ fn handle_toggle_streaming() -> Result<(), Box<dyn std::error::Error + Send + Sy
}
}
/// Name the binary was invoked as.
///
/// `current_exe()` reads /proc/self/exe, which resolves symlinks to the real
/// file, so the installed `scythe-daemon` / `scythe-ui` aliases would all
/// report "scythe" and dispatch to the client. argv[0] keeps the invocation
/// name, which is what multicall dispatch needs.
fn invoked_stem() -> String {
if let Some(arg0) = env::args_os().next() {
let path = std::path::Path::new(&arg0);
if let Some(stem) = path.file_stem() {
let stem = stem.to_string_lossy().to_string();
if !stem.is_empty() {
return stem;
}
}
}
env::current_exe()
.ok()
.and_then(|p| p.file_stem().map(|s| s.to_string_lossy().to_string()))
.unwrap_or_default()
}
fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let args: Vec<String> = env::args().collect();
let exe_name = invoked_stem();
// Multicall dispatch: scythe-daemon executable, symlink, or subcommand
let is_daemon = exe_name == "scythe-daemon"
|| exe_name == "vrec-daemon"
|| (args.len() > 1 && (args[1] == "daemon" || args[1] == "--daemon" || args[1] == "--mock"));
if is_daemon {
return scythe::daemon::run_daemon();
}
run_client(args)
}
fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg(target_os = "windows")]
unsafe {
let is_cli = args.iter().any(|a| a == "--status" || a == "--help" || a == "-h");
@ -436,7 +320,7 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
if args.len() > 1 {
match args[1].as_str() {
"--save" | "--save-replay" | "save" => {
"--save" | "--save-replay" => {
return handle_save_replay();
}
"--notify-save" => {
@ -451,29 +335,6 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
show_shadowplay_toast("RECORDING", "Recording saved", ToastIcon::Save);
return Ok(());
}
"--screenshot" | "screenshot" => {
return handle_screenshot();
}
"--mute-mic" => {
return handle_mute_mic();
}
"--mute-sys" => {
return handle_mute_sys();
}
"--pause" => {
return handle_toggle_recording();
}
"--show-overlay" | "--open" => {
ensure_daemon_running();
// Daemon owns overlay lifetime; if it is unreachable, open the HUD directly.
if send_command(Command::ShowOverlay).is_err() {
ensure_hotkeys_running();
if !check_and_toggle_overlay() {
scythe::overlay_egui::run_egui_overlay();
}
}
return Ok(());
}
"--toast" => {
let title = args.get(2).map(|s| s.as_str()).unwrap_or("SCYTHE");
let subtitle = args.get(3).map(|s| s.as_str()).unwrap_or("");
@ -481,7 +342,7 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
scythe::overlay_egui::run_egui_toast(title, subtitle, ToastIcon::from_name(icon_name));
return Ok(());
}
"--menu" | "menu" => {
"--menu" => {
ensure_daemon_running_async();
ensure_hotkeys_running();
if check_and_toggle_overlay() {
@ -500,18 +361,18 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
return Ok(());
}
"--gtk" => {
ensure_daemon_running_async();
ensure_daemon_running();
ensure_hotkeys_running();
if check_and_toggle_overlay() {
return Ok(());
}
#[cfg(target_os = "linux")]
scythe::overlay::show_menu_overlay();
#[cfg(not(target_os = "linux"))]
scythe::overlay_egui::run_egui_overlay();
return Ok(());
}
"--hotkeys" | "--background" => {
// fall through to hotkey loop
}
"--record" | "--toggle" | "record" => {
"--record" | "--toggle" => {
return handle_toggle_recording();
}
"--stream" | "--toggle-stream" => {
@ -530,7 +391,7 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
ensure_daemon_running();
return send_command(Command::ReloadConfig);
}
"--status" | "status" => {
"--status" => {
ensure_daemon_running();
match query_status() {
Ok(st) => {
@ -550,38 +411,33 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
}
}
}
"--quit" | "quit" => {
"--quit" => {
return send_command(Command::StopDaemon);
}
"--help" | "-h" => {
println!("scythe {} - GPU screen recorder, instant replay and HUD overlay", scythe::updater::CURRENT_VERSION);
println!("scythe-ui - UI Overlay and Hotkey listener for scythe");
println!("Usage:");
println!(" scythe Open the interactive overlay UI menu (default)");
println!(" scythe --menu Open the interactive overlay UI menu");
println!(" scythe --gtk Deprecated alias for --menu (GTK backend retired)");
println!(" scythe --hotkeys Run global hotkey manager in background");
println!(" scythe --status Query current daemon status");
println!(" scythe --save Save instant replay and show notification");
println!(" scythe --save-replay Alias for --save");
println!(" scythe --notify-save Show instant replay saved notification toast");
println!(" scythe --notify-start Show recording started notification toast");
println!(" scythe --notify-stop Show recording saved notification toast");
println!(" scythe --toast <t> <s> Show custom ShadowPlay notification toast");
println!(" scythe --record Toggle normal recording on/off (with notification)");
println!(" scythe --stream Toggle livestreaming on/off (with notification)");
println!(" scythe --cursor Toggle mouse cursor recording on/off (with notification)");
println!(" scythe --show-overlay Open the HUD overlay via the daemon (no toggle)");
println!(" scythe --start Start normal recording");
println!(" scythe --stop Stop normal recording");
println!(" scythe --reload Reload daemon configuration");
println!(" scythe --quit Stop background daemon");
println!(" scythe-ui Open the interactive overlay UI menu (default)");
println!(" scythe-ui --menu Open the interactive overlay UI menu");
println!(" scythe-ui --gtk Open legacy GTK layer-shell overlay (Linux)");
println!(" scythe-ui --hotkeys Run global hotkey manager in background");
println!(" scythe-ui --status Query current daemon status");
println!(" scythe-ui --save Save instant replay and show notification");
println!(" scythe-ui --save-replay Alias for --save");
println!(" scythe-ui --notify-save Show instant replay saved notification toast");
println!(" scythe-ui --notify-start Show recording started notification toast");
println!(" scythe-ui --notify-stop Show recording saved notification toast");
println!(" scythe-ui --toast <t> <s> Show custom ShadowPlay notification toast");
println!(" scythe-ui --record Toggle normal recording on/off (with notification)");
println!(" scythe-ui --stream Toggle livestreaming on/off (with notification)");
println!(" scythe-ui --cursor Toggle mouse cursor recording on/off (with notification)");
println!(" scythe-ui --start Start normal recording");
println!(" scythe-ui --stop Stop normal recording");
println!(" scythe-ui --reload Reload daemon configuration");
println!(" scythe-ui --quit Stop background daemon");
return Ok(());
}
other => {
eprintln!("scythe: unknown argument '{}'", other);
eprintln!("Run 'scythe --help' for usage.");
std::process::exit(2);
}
_ => {}
}
} else {
ensure_daemon_running_async();
@ -635,22 +491,10 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
}
};
#[derive(Default)]
struct RegisteredIds {
menu: Option<u32>,
save: Option<u32>,
rec: Option<u32>,
pause: Option<u32>,
cur: Option<u32>,
shot: Option<u32>,
mute_mic: Option<u32>,
mute_sys: Option<u32>,
}
let mut current_config = scythe::config::ScytheConfig::load();
let mut registered_hotkeys: Vec<HotKey> = Vec::new();
let register_all = |mgr: &GlobalHotKeyManager, cfg: &scythe::config::ScytheConfig, reg: &mut Vec<HotKey>| -> RegisteredIds {
let register_all = |mgr: &GlobalHotKeyManager, cfg: &scythe::config::ScytheConfig, reg: &mut Vec<HotKey>| -> (Option<u32>, Option<u32>, Option<u32>, Option<u32>) {
for hk in reg.drain(..) {
let _ = mgr.unregister(hk);
}
@ -658,62 +502,41 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
let m_menu = scythe::hotkey::parse_hotkey(&cfg.menu_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::ALT), Code::KeyZ)));
let m_save = scythe::hotkey::parse_hotkey(&cfg.save_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::KeyR)));
let m_rec = scythe::hotkey::parse_hotkey(&cfg.record_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::F9)));
let m_pause = scythe::hotkey::parse_hotkey(&cfg.pause_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::F8)));
let m_cur = scythe::hotkey::parse_hotkey(&cfg.cursor_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::F10)));
let m_shot = scythe::hotkey::parse_hotkey(&cfg.screenshot_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::KeyS)));
let m_mute_mic = scythe::hotkey::parse_hotkey(&cfg.mute_mic_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::KeyM)));
let m_mute_sys = scythe::hotkey::parse_hotkey(&cfg.mute_sys_hotkey).or_else(|| Some(HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::KeyN)));
let mut ids = RegisteredIds::default();
let mut id_menu = None;
let mut id_save = None;
let mut id_rec = None;
let mut id_cur = None;
if !is_on_hyprland
&& let Some(hk) = m_menu {
ids.menu = Some(hk.id());
id_menu = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_save {
ids.save = Some(hk.id());
id_save = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_rec {
ids.rec = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_pause {
ids.pause = Some(hk.id());
id_rec = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_cur {
ids.cur = Some(hk.id());
id_cur = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_shot {
ids.shot = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_mute_mic {
ids.mute_mic = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
if let Some(hk) = m_mute_sys {
ids.mute_sys = Some(hk.id());
let _ = mgr.register(hk);
reg.push(hk);
}
ids
(id_menu, id_save, id_rec, id_cur)
};
let mut current_ids = register_all(&manager, &current_config, &mut registered_hotkeys);
let (mut id_menu, mut id_save, mut id_rec, mut id_cur) = register_all(&manager, &current_config, &mut registered_hotkeys);
println!("Listening for global hotkeys (Overlay: {}, Replay: {}, Record: {}, Screenshot: {})...",
current_config.menu_hotkey, current_config.save_hotkey, current_config.record_hotkey, current_config.screenshot_hotkey);
println!("Listening for global hotkeys (Overlay: {}, Replay: {}, Record: {}, Cursor: {})...",
current_config.menu_hotkey, current_config.save_hotkey, current_config.record_hotkey, current_config.cursor_hotkey);
let receiver = GlobalHotKeyEvent::receiver();
let mut last_config_check = std::time::Instant::now();
@ -737,14 +560,14 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
if new_cfg.menu_hotkey != current_config.menu_hotkey
|| new_cfg.save_hotkey != current_config.save_hotkey
|| new_cfg.record_hotkey != current_config.record_hotkey
|| new_cfg.pause_hotkey != current_config.pause_hotkey
|| new_cfg.cursor_hotkey != current_config.cursor_hotkey
|| new_cfg.screenshot_hotkey != current_config.screenshot_hotkey
|| new_cfg.mute_mic_hotkey != current_config.mute_mic_hotkey
|| new_cfg.mute_sys_hotkey != current_config.mute_sys_hotkey
{
current_config = new_cfg;
current_ids = register_all(&manager, &current_config, &mut registered_hotkeys);
let (im, is, ir, ic) = register_all(&manager, &current_config, &mut registered_hotkeys);
id_menu = im;
id_save = is;
id_rec = ir;
id_cur = ic;
}
}
@ -752,49 +575,25 @@ fn run_client(args: Vec<String>) -> Result<(), Box<dyn std::error::Error + Send
if event.state != HotKeyState::Pressed {
continue;
}
if Some(event.id) == current_ids.menu {
if Some(event.id) == id_menu {
std::thread::spawn(|| {
ensure_daemon_running();
let _ = get_ui_cmd().arg("--menu").spawn();
});
} else if Some(event.id) == current_ids.save {
} else if Some(event.id) == id_save {
std::thread::spawn(|| {
let _ = handle_save_replay();
});
} else if Some(event.id) == current_ids.rec {
} else if Some(event.id) == id_rec {
std::thread::spawn(|| {
let _ = handle_toggle_recording();
});
} else if Some(event.id) == current_ids.pause {
std::thread::spawn(|| {
let _ = handle_toggle_recording();
});
} else if Some(event.id) == current_ids.cur {
} else if Some(event.id) == id_cur {
std::thread::spawn(|| {
let _ = handle_toggle_cursor();
});
} else if Some(event.id) == current_ids.shot {
std::thread::spawn(|| {
let _ = handle_screenshot();
});
} else if Some(event.id) == current_ids.mute_mic {
std::thread::spawn(|| {
let _ = handle_mute_mic();
});
} else if Some(event.id) == current_ids.mute_sys {
std::thread::spawn(|| {
let _ = handle_mute_sys();
});
}
}
#[cfg(target_os = "windows")]
unsafe {
use windows::Win32::UI::WindowsAndMessaging::{
MsgWaitForMultipleObjectsEx, QS_ALLINPUT, MWMO_INPUTAVAILABLE,
};
let _ = MsgWaitForMultipleObjectsEx(None, 200, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
}
#[cfg(not(target_os = "windows"))]
std::thread::sleep(std::time::Duration::from_millis(30));
std::thread::sleep(std::time::Duration::from_millis(20));
}
}

View file

@ -528,13 +528,9 @@ impl AudioCapture {
let stream_config: cpal::StreamConfig = config.into();
let lvl_f32 = Arc::clone(&levels_for_cpal);
let lvl_i16 = Arc::clone(&levels_for_cpal);
let lvl_i32 = Arc::clone(&levels_for_cpal);
let lvl_u16 = Arc::clone(&levels_for_cpal);
let mut resample_state_f32 = ResampleState::default();
let mut resample_state_i16 = ResampleState::default();
let mut resample_state_i32 = ResampleState::default();
let mut resample_state_u16 = ResampleState::default();
let stream = match format {
cpal::SampleFormat::F32 => {
@ -570,40 +566,6 @@ impl AudioCapture {
None,
)?
}
cpal::SampleFormat::I32 => {
dev.build_input_stream(
stream_config,
move |data: &[i32], _: &_| {
let converted_f32: Vec<f32> = data.iter().map(|&s| s as f32 / 2147483648.0).collect();
let f32_data = convert_to_stereo_48k(&converted_f32, in_channels, in_sample_rate, gain, &mut resample_state_i32);
if is_mic {
lvl_i32.update_mic(&f32_data);
} else {
lvl_i32.update_system(&f32_data);
}
let _ = tx.try_send(f32_data);
},
err_fn,
None,
)?
}
cpal::SampleFormat::U16 => {
dev.build_input_stream(
stream_config,
move |data: &[u16], _: &_| {
let converted_f32: Vec<f32> = data.iter().map(|&s| (s as f32 - 32768.0) / 32768.0).collect();
let f32_data = convert_to_stereo_48k(&converted_f32, in_channels, in_sample_rate, gain, &mut resample_state_u16);
if is_mic {
lvl_u16.update_mic(&f32_data);
} else {
lvl_u16.update_system(&f32_data);
}
let _ = tx.try_send(f32_data);
},
err_fn,
None,
)?
}
_ => return Err("Unsupported audio format".into()),
};
stream.play()?;
@ -727,13 +689,6 @@ mod tests {
#[test]
fn test_audio_probe() {
// Requires a live PulseAudio/PipeWire or CoreAudio/WASAPI session. CI runners
// have no audio server, so this is opt-in rather than a hard assertion.
if std::env::var("SCYTHE_HW_TESTS").is_err() {
eprintln!("skipping test_audio_probe: set SCYTHE_HW_TESTS=1 to run hardware audio tests");
return;
}
// 1. Test System audio
let (tx, rx) = crossbeam_channel::unbounded();
let sys_cap = AudioCapture::new_with_device_and_mode(tx, None, "system");

View file

@ -6,9 +6,6 @@ pub struct WaylandCapture {
_proxy: Screencast,
_session: ashpd::desktop::Session<Screencast>,
stream: crate::capture::wayland_stream::PipeWireStream,
show_cursor: bool,
last_frame: Option<Frame>,
last_reconnect_attempt: std::time::Instant,
}
impl WaylandCapture {
@ -62,79 +59,16 @@ impl WaylandCapture {
let stream = crate::capture::wayland_stream::PipeWireStream::new(node_id, fd)?;
Ok(Self {
_proxy: proxy,
_session: session,
stream,
show_cursor,
last_frame: None,
last_reconnect_attempt: std::time::Instant::now() - std::time::Duration::from_secs(5),
})
}
fn try_reconnect(&mut self) -> bool {
if self.last_reconnect_attempt.elapsed() < std::time::Duration::from_millis(1500) {
return false;
}
self.last_reconnect_attempt = std::time::Instant::now();
eprintln!("Wayland PipeWire stream disconnected. Attempting auto-reconnect...");
let cursor = self.show_cursor;
// Run on an independent OS thread so block_on never conflicts with Tokio runtime threads
let res = std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.ok()?;
rt.block_on(WaylandCapture::new_with_cursor(cursor)).ok()
}).join();
if let Ok(Some(new_cap)) = res {
eprintln!("Wayland ScreenCast session reconnected successfully.");
self._proxy = new_cap._proxy;
self._session = new_cap._session;
self.stream = new_cap.stream;
true
} else {
false
}
Ok(Self { _proxy: proxy, _session: session, stream })
}
}
impl FrameSource for WaylandCapture {
fn next_frame(&mut self) -> Result<Frame, Box<dyn std::error::Error + Send + Sync>> {
match self.stream.next_frame() {
Ok(f) => {
self.last_frame = Some(f.clone());
Ok(f)
}
Err(e) => {
if self.try_reconnect() {
return self.stream.next_frame();
}
if let Some(ref f) = self.last_frame {
return Ok(f.clone());
}
Err(e)
}
}
self.stream.next_frame()
}
fn next_frame_timeout(&mut self, timeout: std::time::Duration) -> Result<Frame, Box<dyn std::error::Error + Send + Sync>> {
match self.stream.next_frame_timeout(timeout) {
Ok(f) => {
self.last_frame = Some(f.clone());
Ok(f)
}
Err(e) => {
if self.try_reconnect() {
return self.stream.next_frame_timeout(timeout);
}
if let Some(ref f) = self.last_frame {
return Ok(f.clone());
}
Err(e)
}
}
self.stream.next_frame_timeout(timeout)
}
}

View file

@ -77,16 +77,10 @@ impl PipeWireStream {
let stride = data.chunk().stride() as u32;
let offset = data.chunk().offset();
let frame = if fd > 0 {
let drm_fourcc = match user_data.format.format() {
spa::param::video::VideoFormat::BGRx | spa::param::video::VideoFormat::BGRA => 0x34325258, // DRM_FORMAT_XRGB8888
spa::param::video::VideoFormat::RGBx | spa::param::video::VideoFormat::RGBA => 0x34324258, // DRM_FORMAT_XBGR8888
spa::param::video::VideoFormat::NV12 => 0x3231564e, // DRM_FORMAT_NV12
_ => 0x34325241, // DRM_FORMAT_ARGB8888
};
Frame::DmaBuf {
width: user_data.format.size().width,
height: user_data.format.size().height,
format: drm_fourcc,
format: 0x34325241, // DRM_FORMAT_ARGB8888
modifier: user_data.format.modifier(),
fd,
stride,

View file

@ -32,9 +32,8 @@ pub struct WindowsCapture {
pub width: u32,
pub height: u32,
pub last_stride: u32,
buffer_pool: Vec<Arc<Vec<u8>>>,
buffer_pool: Vec<Option<Arc<Vec<u8>>>>,
last_frame: Option<Arc<Vec<u8>>>,
last_reinit_attempt: std::time::Instant,
}
#[cfg(target_os = "windows")]
@ -53,22 +52,14 @@ impl WindowsCapture {
let mut a_idx = 0;
'adapter_loop: while let Ok(adapter) = factory.EnumAdapters1(a_idx) {
if let Ok(desc1) = adapter.GetDesc1() {
// Skip software rasterizers (e.g. Microsoft Basic Render Driver) when hardware GPU exists
if (desc1.Flags & (DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32)) != 0 {
a_idx += 1;
continue;
}
}
let mut o_idx = 0;
while let Ok(output) = adapter.EnumOutputs(o_idx) {
if let Ok(output1) = output.cast::<IDXGIOutput1>()
&& let Ok(desc) = output1.GetDesc() {
let is_attached = desc.AttachedToDesktop.as_bool();
if let Ok(output1) = output.cast::<IDXGIOutput1>() {
if let Ok(desc) = output1.GetDesc() {
let width = (desc.DesktopCoordinates.right - desc.DesktopCoordinates.left).unsigned_abs();
let height = (desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top).unsigned_abs();
if is_attached && width > 0 && height > 0
&& let Ok(adapter_base) = adapter.cast::<IDXGIAdapter>() {
if width > 0 && height > 0 {
if let Ok(adapter_base) = adapter.cast::<IDXGIAdapter>() {
let mut device: Option<ID3D11Device> = None;
let mut context: Option<ID3D11DeviceContext> = None;
let mut feature_level = D3D_FEATURE_LEVEL_11_0;
@ -90,8 +81,8 @@ impl WindowsCapture {
Some(&mut context),
);
if create_res.is_ok()
&& let (Some(dev), Some(ctx)) = (device, context) {
if create_res.is_ok() {
if let (Some(dev), Some(ctx)) = (device, context) {
match output1.DuplicateOutput(&dev) {
Ok(dup) => {
successful_session = Some((dev, ctx, dup, width, height));
@ -101,8 +92,11 @@ impl WindowsCapture {
eprintln!("Adapter {} Output {} DuplicateOutput failed: {:?}", a_idx, o_idx, e);
}
}
}
}
}
}
}
}
o_idx += 1;
}
@ -139,19 +133,15 @@ impl WindowsCapture {
width,
height,
last_stride: width * 4,
buffer_pool: Vec::with_capacity(8),
buffer_pool: Vec::with_capacity(4),
last_frame: None,
last_reinit_attempt: std::time::Instant::now() - std::time::Duration::from_secs(5),
})
}
}
fn reinit_duplication(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if self.last_reinit_attempt.elapsed() < std::time::Duration::from_millis(250) {
return Err("Reinitialization throttled".into());
}
self.last_reinit_attempt = std::time::Instant::now();
self.duplication = None;
std::thread::sleep(std::time::Duration::from_millis(50));
if let Ok(new_cap) = WindowsCapture::new() {
self.device = new_cap.device;
self.context = new_cap.context;
@ -175,7 +165,7 @@ impl FrameSource for WindowsCapture {
let _ = self.reinit_duplication();
}
let dup = match self.duplication.clone() {
let mut dup = match self.duplication.clone() {
Some(d) => d,
None => {
return Ok(Frame::Raw {
@ -206,12 +196,14 @@ impl FrameSource for WindowsCapture {
let target_stride = (self.width * 4) as usize;
let total_bytes = target_stride * self.height as usize;
// Acquire buffer from pool or allocate if pool has room
// Acquire buffer from pool
let mut arc_buf = None;
for i in 0..self.buffer_pool.len() {
if Arc::strong_count(&self.buffer_pool[i]) == 1 {
arc_buf = Some(self.buffer_pool.swap_remove(i));
break;
for slot in &mut self.buffer_pool {
if let Some(buf) = slot {
if Arc::strong_count(buf) == 1 {
arc_buf = slot.take();
break;
}
}
}
let mut arc_buf = arc_buf.unwrap_or_else(|| Arc::new(vec![0u8; total_bytes]));
@ -242,8 +234,8 @@ impl FrameSource for WindowsCapture {
self.last_frame = Some(Arc::clone(&arc_buf));
self.last_stride = target_stride as u32;
if self.buffer_pool.len() < 8 {
self.buffer_pool.push(arc_buf);
if self.buffer_pool.len() < 4 {
self.buffer_pool.push(Some(arc_buf));
}
return Ok(Frame::Raw {
@ -262,12 +254,14 @@ impl FrameSource for WindowsCapture {
Err(e) if e.code() == DXGI_ERROR_ACCESS_LOST
|| e.code() == DXGI_ERROR_ACCESS_DENIED
|| e.code() == DXGI_ERROR_INVALID_CALL => {
let _ = dup.ReleaseFrame();
drop(dup);
self.duplication = None;
let _ = self.reinit_duplication();
break;
}
Err(e) => {
let _ = dup.ReleaseFrame();
drop(dup);
self.duplication = None;
let _ = self.reinit_duplication();

View file

@ -10,6 +10,8 @@ fn default_fps() -> u32 { 60 }
fn default_video_codec() -> String { "h264".to_string() }
fn default_audio_device() -> String { "default".to_string() }
fn default_audio_mode() -> String { "system".to_string() }
fn default_lang() -> String { "en".to_string() }
fn default_theme() -> String { "dark".to_string() }
fn default_save_hotkey() -> String { "Ctrl+Shift+R".to_string() }
fn default_menu_hotkey() -> String { "Alt+Z".to_string() }
fn default_record_hotkey() -> String { "Ctrl+Shift+F9".to_string() }
@ -20,17 +22,6 @@ fn default_accent_color() -> String { "blue".to_string() }
fn default_stream_service() -> String { "twitch".to_string() }
fn default_stream_url() -> String { "rtmp://live.twitch.tv/app/".to_string() }
fn default_screenshot_hotkey() -> String { "Ctrl+Shift+S".to_string() }
fn default_screenshot_format() -> String { "png".to_string() }
fn default_video_quality_mode() -> String { "cbr".to_string() }
fn default_color_range() -> String { "limited".to_string() }
fn default_audio_codec() -> String { "opus".to_string() }
fn default_screenshot_quality() -> u32 { 90 }
fn default_screenshot_preset() -> String { "balanced".to_string() }
fn default_pause_hotkey() -> String { "Ctrl+Shift+F8".to_string() }
fn default_mute_mic_hotkey() -> String { "Ctrl+Shift+M".to_string() }
fn default_mute_sys_hotkey() -> String { "Ctrl+Shift+N".to_string() }
fn default_screenshot_resolution() -> String { "native".to_string() }
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ScytheConfig {
@ -43,6 +34,8 @@ pub struct ScytheConfig {
#[serde(default = "default_replay_bitrate")]
pub replay_bitrate_kbps: u32,
#[serde(default)]
pub record_enabled: bool,
#[serde(default = "default_record_bitrate")]
pub record_bitrate_kbps: u32,
#[serde(default = "default_fps")]
@ -68,6 +61,10 @@ pub struct ScytheConfig {
pub autostart_replay: bool,
#[serde(default)]
pub autostart_overlay: bool,
#[serde(default = "default_lang")]
pub language: String,
#[serde(default = "default_theme")]
pub ui_color_theme: String,
#[serde(default = "default_save_hotkey")]
pub save_hotkey: String,
#[serde(default = "default_menu_hotkey")]
@ -86,46 +83,6 @@ pub struct ScytheConfig {
pub stream_url: String,
#[serde(default)]
pub stream_key: String,
#[serde(default = "default_screenshot_hotkey")]
pub screenshot_hotkey: String,
#[serde(default = "ScytheConfig::default_screenshot_directory")]
pub screenshot_directory: String,
#[serde(default = "default_screenshot_format")]
pub screenshot_format: String,
#[serde(default)]
pub screenshot_cursor: bool,
#[serde(default = "default_video_quality_mode")]
pub video_quality_mode: String,
#[serde(default = "default_color_range")]
pub color_range: String,
#[serde(default = "default_audio_codec")]
pub audio_codec: String,
#[serde(default)]
pub record_low_power: bool,
#[serde(default = "default_true")]
pub show_replay_notifications: bool,
#[serde(default = "default_true")]
pub restart_replay_on_save: bool,
#[serde(default)]
pub autostart_power_only: bool,
#[serde(default = "default_screenshot_quality")]
pub screenshot_quality: u32,
#[serde(default = "default_screenshot_preset")]
pub screenshot_preset: String,
#[serde(default = "default_pause_hotkey")]
pub pause_hotkey: String,
#[serde(default = "default_mute_mic_hotkey")]
pub mute_mic_hotkey: String,
#[serde(default = "default_mute_sys_hotkey")]
pub mute_sys_hotkey: String,
#[serde(default = "default_screenshot_resolution")]
pub screenshot_resolution: String,
#[serde(default)]
pub use_monospace_font: bool,
}
pub type VrecConfig = ScytheConfig;
@ -138,6 +95,7 @@ impl Default for ScytheConfig {
replay_duration_sec: 60,
replay_bitrate_kbps: 18000,
record_enabled: false,
record_bitrate_kbps: 20000,
fps: 60,
video_codec: "h264".to_string(),
@ -151,6 +109,8 @@ impl Default for ScytheConfig {
autostart: false,
autostart_replay: false,
autostart_overlay: false,
language: "en".to_string(),
ui_color_theme: "dark".to_string(),
save_hotkey: "Ctrl+Shift+R".to_string(),
menu_hotkey: "Alt+Z".to_string(),
record_hotkey: "Ctrl+Shift+F9".to_string(),
@ -160,28 +120,6 @@ impl Default for ScytheConfig {
stream_service: "twitch".to_string(),
stream_url: "rtmp://live.twitch.tv/app/".to_string(),
stream_key: String::new(),
screenshot_hotkey: default_screenshot_hotkey(),
screenshot_directory: Self::default_screenshot_directory(),
screenshot_format: default_screenshot_format(),
screenshot_cursor: false,
video_quality_mode: default_video_quality_mode(),
color_range: default_color_range(),
audio_codec: default_audio_codec(),
record_low_power: false,
show_replay_notifications: true,
restart_replay_on_save: true,
autostart_power_only: false,
screenshot_quality: default_screenshot_quality(),
screenshot_preset: default_screenshot_preset(),
pause_hotkey: default_pause_hotkey(),
mute_mic_hotkey: default_mute_mic_hotkey(),
mute_sys_hotkey: default_mute_sys_hotkey(),
screenshot_resolution: default_screenshot_resolution(),
use_monospace_font: false,
}
}
}
@ -197,16 +135,6 @@ impl ScytheConfig {
"~/Videos".to_string()
}
pub fn default_screenshot_directory() -> String {
if let Some(pic) = dirs::picture_dir() {
return pic.join("Screenshots").to_string_lossy().to_string();
}
if let Some(home) = dirs::home_dir() {
return home.join("Pictures").join("Screenshots").to_string_lossy().to_string();
}
Self::default_output_directory()
}
pub fn config_path() -> PathBuf {
let base = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
base.join("scythe").join("config.json")
@ -319,7 +247,7 @@ Type=Application\n\
Name=Scythe Replay Engine\n\
Comment=Scythe Background Screen Recorder & Instant Replay Daemon\n\
Icon=media-record\n\
Exec=scythe daemon\n\
Exec=scythe-daemon\n\
Terminal=false\n\
Hidden=false\n\
X-GNOME-Autostart-enabled=true\n";
@ -336,7 +264,7 @@ Type=Application\n\
Name=Scythe Overlay\n\
Comment=Scythe Screen Recorder HUD Overlay\n\
Icon=media-record\n\
Exec=scythe --menu\n\
Exec=scythe-ui --menu\n\
Terminal=false\n\
Hidden=false\n\
X-GNOME-Autostart-enabled=true\n";
@ -351,8 +279,8 @@ X-GNOME-Autostart-enabled=true\n";
&& let Ok(mut text) = fs::read_to_string(&hypr_execs_lua) {
let mut modified = false;
let daemon_cmd_pattern = "scythe daemon";
let daemon_cmd_line = " hl.exec_cmd(\"scythe daemon\")\n";
let daemon_cmd_pattern = "scythe-daemon";
let daemon_cmd_line = " hl.exec_cmd(\"scythe-daemon\")\n";
if self.autostart_replay {
if !text.contains(daemon_cmd_pattern)
&& let Some(pos) = text.rfind("end)") {
@ -367,8 +295,8 @@ X-GNOME-Autostart-enabled=true\n";
modified = true;
}
let overlay_cmd_pattern = "scythe --menu";
let overlay_cmd_line = " hl.exec_cmd(\"scythe --menu\")\n";
let overlay_cmd_pattern = "scythe-ui --menu";
let overlay_cmd_line = " hl.exec_cmd(\"scythe-ui --menu\")\n";
if self.autostart_overlay {
if !text.contains(overlay_cmd_pattern)
&& let Some(pos) = text.rfind("end)") {
@ -390,49 +318,6 @@ X-GNOME-Autostart-enabled=true\n";
}
}
/// Enable or disable session autostart for the daemon and the overlay.
///
/// Linux only: systemd user units and XDG autostart entries. Windows has no
/// equivalent implementation yet, so the call is a no-op there.
#[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
pub fn apply_autostart_system(enable_replay: bool, enable_overlay: bool) {
#[cfg(target_os = "linux")]
{
// 1. systemd user service enable / disable
if enable_replay {
let _ = std::process::Command::new("systemctl")
.args(["--user", "enable", "scythe-daemon.service"])
.status();
} else {
let _ = std::process::Command::new("systemctl")
.args(["--user", "disable", "scythe-daemon.service"])
.status();
}
// 2. Standard XDG autostart desktop entry for session login
if let Some(config_dir) = dirs::config_dir() {
let autostart_dir = config_dir.join("autostart");
let _ = std::fs::create_dir_all(&autostart_dir);
let daemon_desktop = autostart_dir.join("scythe-daemon.desktop");
let overlay_desktop = autostart_dir.join("scythe-overlay.desktop");
if enable_replay {
let content = "[Desktop Entry]\nType=Application\nName=Scythe Replay Daemon\nExec=scythe daemon\nTerminal=false\nCategories=AudioVideo;Recorder;\nX-GNOME-Autostart-enabled=true\n";
let _ = std::fs::write(&daemon_desktop, content);
} else {
let _ = std::fs::remove_file(&daemon_desktop);
}
if enable_overlay {
let content = "[Desktop Entry]\nType=Application\nName=Scythe Overlay\nExec=scythe --menu\nTerminal=false\nCategories=AudioVideo;Recorder;\nX-GNOME-Autostart-enabled=true\n";
let _ = std::fs::write(&overlay_desktop, content);
} else {
let _ = std::fs::remove_file(&overlay_desktop);
}
}
}
}
pub fn notify_daemon_reload() {
std::thread::spawn(|| {
let _ = crate::ipc::send_command(crate::ipc::Command::ReloadConfig);
@ -440,53 +325,6 @@ X-GNOME-Autostart-enabled=true\n";
}
/// Formats video filenames with informative local timestamps, e.g. "Replay-18-30-00_05-09-2026.mp4"
pub fn is_ac_power_connected() -> bool {
#[cfg(target_os = "linux")]
{
if let Ok(entries) = std::fs::read_dir("/sys/class/power_supply") {
let mut has_power_status = false;
for entry in entries.flatten() {
let path = entry.path();
// Check AC online status
let online_path = path.join("online");
if let Ok(content) = std::fs::read_to_string(&online_path) {
has_power_status = true;
if content.trim() == "1" {
return true;
}
}
// Check battery status
let status_path = path.join("status");
if let Ok(content) = std::fs::read_to_string(&status_path) {
let s = content.trim().to_lowercase();
if s == "charging" || s == "full" {
return true;
}
}
}
if has_power_status {
return false;
}
}
true
}
#[cfg(target_os = "windows")]
{
unsafe {
use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};
let mut status = SYSTEM_POWER_STATUS::default();
if GetSystemPowerStatus(&mut status).is_ok() {
return status.ACLineStatus == 1;
}
}
true
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
true
}
pub fn format_video_filename(prefix: &str, ext: &str) -> String {
unsafe {
let t = libc::time(std::ptr::null_mut());
@ -535,25 +373,6 @@ mod tests {
assert_eq!(parsed.stream_service, "twitch");
assert_eq!(parsed.stream_url, "rtmp://live.twitch.tv/app/");
assert_eq!(parsed.stream_key, "");
assert!(parsed.restart_replay_on_save);
assert!(!parsed.autostart_power_only);
assert_eq!(parsed.video_quality_mode, "cbr");
assert_eq!(parsed.color_range, "limited");
assert_eq!(parsed.audio_codec, "opus");
assert!(!parsed.record_low_power);
assert!(parsed.show_replay_notifications);
assert_eq!(parsed.screenshot_hotkey, "Ctrl+Shift+S");
assert_eq!(parsed.screenshot_format, "png");
assert!(!parsed.screenshot_cursor);
assert_eq!(parsed.screenshot_quality, 90);
assert_eq!(parsed.screenshot_preset, "balanced");
assert_eq!(parsed.pause_hotkey, "Ctrl+Shift+F8");
assert_eq!(parsed.mute_mic_hotkey, "Ctrl+Shift+M");
assert_eq!(parsed.mute_sys_hotkey, "Ctrl+Shift+N");
assert_eq!(parsed.screenshot_resolution, "native");
assert!(!parsed.use_monospace_font);
}
#[test]

View file

@ -1,6 +1,5 @@
use ffmpeg_next::ffi::*;
use std::ptr;
#[cfg(unix)]
use std::collections::HashMap;
use crate::capture::Frame;
@ -33,24 +32,7 @@ impl VaapiEncoder {
}
pub fn new_with_params(width: u32, height: u32, bitrate_kbps: u32, fps: u32, codec_pref: &str) -> Result<Self, String> {
Self::new_with_options(width, height, bitrate_kbps, fps, codec_pref, "vbr", "limited", false)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_options(
width: u32,
height: u32,
bitrate_kbps: u32,
fps: u32,
codec_pref: &str,
quality_mode: &str,
color_range: &str,
low_power: bool,
) -> Result<Self, String> {
let fps = fps.clamp(20, 144) as i32;
let is_full = color_range.to_lowercase() == "full";
let is_cbr = quality_mode.to_lowercase() == "cbr";
unsafe {
let codec_candidates: &[&std::ffi::CStr] = match codec_pref.to_lowercase().as_str() {
"hevc" | "h265" => &[c"hevc_vaapi", c"h264_vaapi"],
@ -84,40 +66,25 @@ impl VaapiEncoder {
(*codec_ctx).gop_size = fps; // Emit IDR keyframe every second
(*codec_ctx).max_b_frames = 0; // Zero latency, no frame reordering
// High Quality & Clean VBR Rate Control matching GPU Screen Recorder standards
// High Quality & Clean VBR Rate Control
let rate = (bitrate_kbps as i64) * 1000;
(*codec_ctx).bit_rate = rate;
if is_cbr {
(*codec_ctx).rc_max_rate = rate;
(*codec_ctx).rc_buffer_size = rate as i32;
let _ = av_opt_set((*codec_ctx).priv_data, c"rc_mode".as_ptr(), c"CBR".as_ptr(), 0);
} else {
(*codec_ctx).rc_max_rate = rate * 2; // Allow 2x burst for high-motion gaming scenes
(*codec_ctx).rc_buffer_size = (rate * 2) as i32; // 2 seconds rate control window
let _ = av_opt_set((*codec_ctx).priv_data, c"rc_mode".as_ptr(), c"VBR".as_ptr(), 0);
}
(*codec_ctx).qmin = 1; // Allow high-fidelity crisp detail
(*codec_ctx).qmax = 32;
(*codec_ctx).rc_max_rate = rate * 3 / 2; // Allow burst for fast motion scenes
(*codec_ctx).rc_buffer_size = (rate / 2) as i32;
(*codec_ctx).qmin = 16;
(*codec_ctx).qmax = 28; // Prevent compression blockiness
(*codec_ctx).profile = match codec_pref.to_lowercase().as_str() {
"hevc" | "h265" => FF_PROFILE_HEVC_MAIN,
"av1" => FF_PROFILE_UNKNOWN,
_ => FF_PROFILE_H264_HIGH,
};
(*codec_ctx).flags |= AV_CODEC_FLAG_GLOBAL_HEADER as libc::c_int;
let async_depth = if low_power { 2 } else { 4 };
let _ = av_opt_set_int((*codec_ctx).priv_data, c"async_depth".as_ptr(), async_depth, 0);
if low_power {
let _ = av_opt_set_int((*codec_ctx).priv_data, c"low_power".as_ptr(), 1, 0);
let _ = av_opt_set_int((*codec_ctx).priv_data, c"compression_level".as_ptr(), 1, 0);
}
// Rec.709 Color Space & Color Range
// Rec.709 Color Space & MPEG Limited Range (Broadcast / Web standard, avoids yellow tint)
(*codec_ctx).colorspace = AVColorSpace::AVCOL_SPC_BT709;
(*codec_ctx).color_primaries = AVColorPrimaries::AVCOL_PRI_BT709;
(*codec_ctx).color_trc = AVColorTransferCharacteristic::AVCOL_TRC_BT709;
(*codec_ctx).color_range = if is_full { AVColorRange::AVCOL_RANGE_JPEG } else { AVColorRange::AVCOL_RANGE_MPEG };
(*codec_ctx).color_range = AVColorRange::AVCOL_RANGE_MPEG;
let mut hw_device_ctx: *mut AVBufferRef = ptr::null_mut();
let ret = av_hwdevice_ctx_create(
@ -155,15 +122,7 @@ impl VaapiEncoder {
(*codec_ctx).hw_frames_ctx = av_buffer_ref(hw_frames_ref);
let mut ret = avcodec_open2(codec_ctx, codec, ptr::null_mut());
if ret < 0 && low_power {
// If low_power mode is unsupported on this GPU driver, fallback to standard encoding entrypoint
let _ = av_opt_set_int((*codec_ctx).priv_data, c"low_power".as_ptr(), 0, 0);
if (*codec_ctx).hw_frames_ctx.is_null() {
(*codec_ctx).hw_frames_ctx = av_buffer_ref(hw_frames_ref);
}
ret = avcodec_open2(codec_ctx, codec, ptr::null_mut());
}
let ret = avcodec_open2(codec_ctx, codec, ptr::null_mut());
if ret < 0 {
av_buffer_unref(&mut (hw_frames_ref as *mut _));
av_buffer_unref(&mut hw_device_ctx);
@ -186,7 +145,7 @@ impl VaapiEncoder {
(*hw_frame).colorspace = AVColorSpace::AVCOL_SPC_BT709;
(*hw_frame).color_primaries = AVColorPrimaries::AVCOL_PRI_BT709;
(*hw_frame).color_trc = AVColorTransferCharacteristic::AVCOL_TRC_BT709;
(*hw_frame).color_range = if is_full { AVColorRange::AVCOL_RANGE_JPEG } else { AVColorRange::AVCOL_RANGE_MPEG };
(*hw_frame).color_range = AVColorRange::AVCOL_RANGE_MPEG;
let sws_ctx = sws_getContext(
width as i32,
@ -205,13 +164,12 @@ impl VaapiEncoder {
if !sws_ctx.is_null() {
let coeffs = sws_getCoefficients(SWS_CS_ITU709);
if !coeffs.is_null() {
let dst_range = if is_full { 1 } else { 0 };
sws_setColorspaceDetails(
sws_ctx,
coeffs,
1, // srcRange: 1 (sRGB full range 0-255)
coeffs,
dst_range,
0, // dstRange: 0 (MPEG limited range 16-235)
0,
1 << 16,
1 << 16,
@ -295,11 +253,9 @@ impl VaapiEncoder {
self.has_frame = true;
self.send_staged_frame(&mut packets, pts)?;
}
#[allow(unused_variables)]
Frame::DmaBuf { width: dma_width, height: dma_height, format, modifier, fd, stride, offset } => {
#[allow(unused_variables)]
let mmap_size = (*offset as usize) + (*stride as usize) * (*dma_height as usize);
#[allow(unused_mut)]
let mut mapped_direct = false;
#[cfg(unix)]
@ -354,7 +310,6 @@ impl VaapiEncoder {
}
av_packet_free(&mut pkt);
mapped_direct = true;
self.has_frame = true;
}
} else {
self.direct_drm_unsupported = true;
@ -423,7 +378,7 @@ impl VaapiEncoder {
pub fn encode_cached_frame(&mut self, pts: i64) -> Result<Vec<crate::ring::Packet>, String> {
let mut packets = Vec::new();
if !self.has_frame {
return Err("No cached frame available in encoder".into());
return Ok(packets);
}
unsafe {
self.send_staged_frame(&mut packets, pts)?;
@ -468,7 +423,6 @@ impl Drop for VaapiEncoder {
#[cfg(target_os = "windows")]
pub struct WindowsHwEncoder {
codec_ctx: *mut AVCodecContext,
#[allow(dead_code)]
encoder_name: String,
sws_ctx: *mut SwsContext,
sw_frame: *mut AVFrame,
@ -487,24 +441,7 @@ impl WindowsHwEncoder {
}
pub fn new_with_params(width: u32, height: u32, bitrate_kbps: u32, fps: u32, codec_pref: &str) -> Result<Self, String> {
Self::new_with_options(width, height, bitrate_kbps, fps, codec_pref, "vbr", "limited", false)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_options(
width: u32,
height: u32,
bitrate_kbps: u32,
fps: u32,
codec_pref: &str,
quality_mode: &str,
color_range: &str,
low_power: bool,
) -> Result<Self, String> {
let fps = fps.clamp(20, 144) as i32;
let is_full = color_range.to_lowercase() == "full";
let is_cbr = quality_mode.to_lowercase() == "cbr";
unsafe {
let candidates: &[(&std::ffi::CStr, &str)] = match codec_pref.to_lowercase().as_str() {
"hevc" | "h265" => &[
@ -561,15 +498,10 @@ impl WindowsHwEncoder {
let rate = (bitrate_kbps as i64) * 1000;
(*ctx).bit_rate = rate;
if is_cbr {
(*ctx).rc_max_rate = rate;
(*ctx).rc_buffer_size = rate as i32;
} else {
(*ctx).rc_max_rate = rate * 2;
(*ctx).rc_buffer_size = (rate * 2) as i32;
}
(*ctx).qmin = 1;
(*ctx).qmax = 32;
(*ctx).rc_max_rate = rate * 3 / 2;
(*ctx).rc_buffer_size = (rate / 2) as i32;
(*ctx).qmin = 16;
(*ctx).qmax = 28;
let codec_id = (*c).id;
(*ctx).profile = if codec_id == AVCodecID::AV_CODEC_ID_HEVC {
FF_PROFILE_HEVC_MAIN
@ -581,32 +513,23 @@ impl WindowsHwEncoder {
(*ctx).flags |= AV_CODEC_FLAG_GLOBAL_HEADER as libc::c_int;
(*ctx).pix_fmt = pix_fmt;
// ITU-R BT.709 Color Space & Color Range standard
// ITU-R BT.709 Color Space & MPEG Limited Range standard for clean broadcast playback
(*ctx).colorspace = AVColorSpace::AVCOL_SPC_BT709;
(*ctx).color_primaries = AVColorPrimaries::AVCOL_PRI_BT709;
(*ctx).color_trc = AVColorTransferCharacteristic::AVCOL_TRC_BT709;
(*ctx).color_range = if is_full { AVColorRange::AVCOL_RANGE_JPEG } else { AVColorRange::AVCOL_RANGE_MPEG };
(*ctx).color_range = AVColorRange::AVCOL_RANGE_MPEG;
if desc.contains("NVENC") {
let preset = if low_power { c"p1".as_ptr() } else { c"p3".as_ptr() };
let rc = if is_cbr { c"cbr".as_ptr() } else { c"vbr".as_ptr() };
let _ = av_opt_set((*ctx).priv_data, c"preset".as_ptr(), preset, 0);
let _ = av_opt_set((*ctx).priv_data, c"preset".as_ptr(), c"p1".as_ptr(), 0);
let _ = av_opt_set((*ctx).priv_data, c"tune".as_ptr(), c"ull".as_ptr(), 0);
let _ = av_opt_set((*ctx).priv_data, c"forced-idr".as_ptr(), c"1".as_ptr(), 0);
let _ = av_opt_set((*ctx).priv_data, c"rc".as_ptr(), rc, 0);
} else if desc.contains("AMF") {
let rc = if is_cbr { c"cbr".as_ptr() } else { c"vbr_latency".as_ptr() };
let _ = av_opt_set((*ctx).priv_data, c"usage".as_ptr(), c"ultralowlatency".as_ptr(), 0);
let _ = av_opt_set((*ctx).priv_data, c"rc".as_ptr(), rc, 0);
if low_power {
let _ = av_opt_set((*ctx).priv_data, c"quality".as_ptr(), c"speed".as_ptr(), 0);
}
} else if desc.contains("QuickSync") {
let _ = av_opt_set((*ctx).priv_data, c"preset".as_ptr(), c"veryfast".as_ptr(), 0);
} else {
let _ = av_opt_set((*ctx).priv_data, c"preset".as_ptr(), c"ultrafast".as_ptr(), 0);
let _ = av_opt_set((*ctx).priv_data, c"tune".as_ptr(), c"zerolatency".as_ptr(), 0);
(*ctx).thread_count = 0;
}
let ret = avcodec_open2(ctx, c, ptr::null_mut());
@ -642,7 +565,7 @@ impl WindowsHwEncoder {
(*sw_frame).colorspace = AVColorSpace::AVCOL_SPC_BT709;
(*sw_frame).color_primaries = AVColorPrimaries::AVCOL_PRI_BT709;
(*sw_frame).color_trc = AVColorTransferCharacteristic::AVCOL_TRC_BT709;
(*sw_frame).color_range = if is_full { AVColorRange::AVCOL_RANGE_JPEG } else { AVColorRange::AVCOL_RANGE_MPEG };
(*sw_frame).color_range = AVColorRange::AVCOL_RANGE_MPEG;
if av_frame_get_buffer(sw_frame, 32) < 0 {
av_frame_free(&mut sw_frame);
avcodec_free_context(&mut opened_codec_ctx);
@ -670,13 +593,12 @@ impl WindowsHwEncoder {
let coeffs = sws_getCoefficients(SWS_CS_ITU709);
if !coeffs.is_null() {
let dst_range = if is_full { 1 } else { 0 };
sws_setColorspaceDetails(
sws_ctx,
coeffs,
1, // srcRange: 1 (sRGB full range 0-255)
coeffs,
dst_range,
0, // dstRange: 0 (MPEG limited range 16-235)
0,
1 << 16,
1 << 16,
@ -701,43 +623,46 @@ impl WindowsHwEncoder {
pub fn encode_frame(&mut self, frame: &Frame, pts: i64) -> Result<Vec<crate::ring::Packet>, String> {
let mut packets = Vec::new();
unsafe {
if let Frame::Raw { width: _, height, stride, data } = frame {
if av_frame_make_writable(self.sw_frame) < 0 {
let _ = av_frame_get_buffer(self.sw_frame, 32);
}
if !self.sws_ctx.is_null() {
let src_data = [data.as_ptr(), ptr::null(), ptr::null(), ptr::null()];
let src_linesize = [*stride as i32, 0, 0, 0];
sws_scale(
self.sws_ctx,
src_data.as_ptr(),
src_linesize.as_ptr(),
0,
*height as i32,
(*self.sw_frame).data.as_mut_ptr(),
(*self.sw_frame).linesize.as_mut_ptr(),
);
}
(*self.sw_frame).pts = pts;
if self.force_idr {
(*self.sw_frame).pict_type = AVPictureType::AV_PICTURE_TYPE_I;
self.force_idr = false;
} else {
(*self.sw_frame).pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
}
if avcodec_send_frame(self.codec_ctx, self.sw_frame) >= 0 {
let mut pkt = av_packet_alloc();
while avcodec_receive_packet(self.codec_ctx, pkt) >= 0 {
let new_pkt = av_packet_alloc();
av_packet_move_ref(new_pkt, pkt);
packets.push(crate::ring::Packet::new(new_pkt));
match frame {
Frame::Raw { width: _, height, stride, data } => {
if av_frame_make_writable(self.sw_frame) < 0 {
let _ = av_frame_get_buffer(self.sw_frame, 32);
}
if !self.sws_ctx.is_null() {
let src_data = [data.as_ptr(), ptr::null(), ptr::null(), ptr::null()];
let src_linesize = [*stride as i32, 0, 0, 0];
sws_scale(
self.sws_ctx,
src_data.as_ptr(),
src_linesize.as_ptr(),
0,
*height as i32,
(*self.sw_frame).data.as_mut_ptr(),
(*self.sw_frame).linesize.as_mut_ptr(),
);
}
(*self.sw_frame).pts = pts;
if self.force_idr {
(*self.sw_frame).pict_type = AVPictureType::AV_PICTURE_TYPE_I;
self.force_idr = false;
} else {
(*self.sw_frame).pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
}
if avcodec_send_frame(self.codec_ctx, self.sw_frame) >= 0 {
let mut pkt = av_packet_alloc();
while avcodec_receive_packet(self.codec_ctx, pkt) >= 0 {
let new_pkt = av_packet_alloc();
av_packet_move_ref(new_pkt, pkt);
packets.push(crate::ring::Packet::new(new_pkt));
}
av_packet_free(&mut pkt);
self.has_frame = true;
}
av_packet_free(&mut pkt);
self.has_frame = true;
}
_ => {}
}
}
Ok(packets)
@ -747,7 +672,7 @@ impl WindowsHwEncoder {
pub fn encode_cached_frame(&mut self, pts: i64) -> Result<Vec<crate::ring::Packet>, String> {
let mut packets = Vec::new();
if !self.has_frame {
return Err("No cached frame available in encoder".into());
return Ok(packets);
}
unsafe {
if self.sw_frame.is_null() {
@ -811,82 +736,57 @@ pub struct AudioEncoder {
impl AudioEncoder {
pub fn new(sample_rate: i32, channels: i32) -> Result<Self, String> {
Self::new_with_codec(sample_rate, channels, "aac")
}
pub fn new_with_codec(sample_rate: i32, channels: i32, codec_pref: &str) -> Result<Self, String> {
unsafe {
let wants_opus = codec_pref.to_lowercase() == "opus";
let mut codec = if wants_opus {
avcodec_find_encoder(AVCodecID::AV_CODEC_ID_OPUS)
} else {
avcodec_find_encoder(AVCodecID::AV_CODEC_ID_AAC)
};
if codec.is_null() && wants_opus {
codec = avcodec_find_encoder_by_name(c"libopus".as_ptr());
if codec.is_null() {
codec = avcodec_find_encoder(AVCodecID::AV_CODEC_ID_AAC);
}
} else if codec.is_null() {
codec = avcodec_find_encoder(AVCodecID::AV_CODEC_ID_AAC);
}
let codec = avcodec_find_encoder(AVCodecID::AV_CODEC_ID_AAC);
if codec.is_null() {
return Err("No compatible audio encoder found (AAC/Opus)".into());
return Err("AAC encoder not found".into());
}
let codec_ctx = avcodec_alloc_context3(codec);
if codec_ctx.is_null() {
return Err("Failed to allocate audio codec context".into());
return Err("Failed to allocate AAC codec context".into());
}
let sample_fmt = if (*codec).id == AVCodecID::AV_CODEC_ID_OPUS {
AVSampleFormat::AV_SAMPLE_FMT_FLT
} else {
AVSampleFormat::AV_SAMPLE_FMT_FLTP
};
(*codec_ctx).sample_rate = sample_rate;
(*codec_ctx).time_base = AVRational { num: 1, den: sample_rate };
(*codec_ctx).sample_fmt = sample_fmt;
(*codec_ctx).bit_rate = if (*codec).id == AVCodecID::AV_CODEC_ID_OPUS { 160_000 } else { 192_000 };
(*codec_ctx).sample_fmt = AVSampleFormat::AV_SAMPLE_FMT_FLTP;
(*codec_ctx).bit_rate = 192_000;
(*codec_ctx).flags |= AV_CODEC_FLAG_GLOBAL_HEADER as libc::c_int;
av_channel_layout_default(&mut (*codec_ctx).ch_layout, channels);
let ret = avcodec_open2(codec_ctx, codec, ptr::null_mut());
if ret < 0 {
avcodec_free_context(&mut (codec_ctx as *mut _));
return Err("Failed to open audio encoder".into());
return Err("Failed to open AAC encoder".into());
}
let mut swr_ctx: *mut SwrContext = ptr::null_mut();
swr_alloc_set_opts2(
&mut swr_ctx,
&(*codec_ctx).ch_layout,
sample_fmt,
AVSampleFormat::AV_SAMPLE_FMT_FLTP,
sample_rate,
&(*codec_ctx).ch_layout,
AVSampleFormat::AV_SAMPLE_FMT_FLT,
sample_rate,
0,
ptr::null_mut(),
ptr::null_mut()
);
swr_init(swr_ctx);
let frame_size = if (*codec_ctx).frame_size > 0 { (*codec_ctx).frame_size } else { 960 };
let fifo = av_audio_fifo_alloc(sample_fmt, channels, 1024 * 32);
let frame_size = (*codec_ctx).frame_size;
let fifo = av_audio_fifo_alloc(AVSampleFormat::AV_SAMPLE_FMT_FLTP, channels, 1024 * 32);
let enc_frame = av_frame_alloc();
(*enc_frame).nb_samples = frame_size;
(*enc_frame).format = sample_fmt as i32;
(*enc_frame).format = AVSampleFormat::AV_SAMPLE_FMT_FLTP as i32;
(*enc_frame).ch_layout = (*codec_ctx).ch_layout;
(*enc_frame).sample_rate = sample_rate;
av_frame_get_buffer(enc_frame, 0);
let staging_out_frame = av_frame_alloc();
(*staging_out_frame).nb_samples = 8192;
(*staging_out_frame).format = sample_fmt as i32;
(*staging_out_frame).format = AVSampleFormat::AV_SAMPLE_FMT_FLTP as i32;
(*staging_out_frame).ch_layout = (*codec_ctx).ch_layout;
(*staging_out_frame).sample_rate = sample_rate;
av_frame_get_buffer(staging_out_frame, 0);
@ -1004,12 +904,6 @@ mod tests {
}
}
#[test]
fn test_opus_audio_encoder_initialization() {
let enc_res = AudioEncoder::new_with_codec(48000, 2, "opus");
assert!(enc_res.is_ok(), "Opus encoder initialization should succeed");
}
#[test]
fn test_audio_encode_sine_wave() {
let mut enc = AudioEncoder::new(48000, 2).expect("AudioEncoder creation");

View file

@ -95,22 +95,5 @@ mod tests {
assert!(parse_hotkey("").is_none());
assert!(parse_hotkey("invalid_key_xyz").is_none());
}
#[test]
fn test_all_eight_default_scythe_hotkeys() {
let defaults = [
("Alt+Z", "menu"),
("Ctrl+Shift+R", "save_replay"),
("Ctrl+Shift+F9", "record_toggle"),
("Ctrl+Shift+F8", "pause_record"),
("Ctrl+Shift+S", "screenshot"),
("Ctrl+Shift+F10", "toggle_cursor"),
("Ctrl+Shift+M", "mute_mic"),
("Ctrl+Shift+N", "mute_sys"),
];
for (hk_str, label) in defaults {
assert!(parse_hotkey(hk_str).is_some(), "Hotkey '{}' for '{}' must parse successfully", hk_str, label);
}
}
}

View file

@ -182,11 +182,7 @@ pub fn register_hyprland_binds(config: &ScytheConfig) {
(&config.menu_hotkey, "scythe-ui --menu"),
(&config.save_hotkey, "scythe-ui --save"),
(&config.record_hotkey, "scythe-ui --record"),
(&config.pause_hotkey, "scythe-ui --pause"),
(&config.cursor_hotkey, "scythe-ui --cursor"),
(&config.screenshot_hotkey, "scythe-ui --screenshot"),
(&config.mute_mic_hotkey, "scythe-ui --mute-mic"),
(&config.mute_sys_hotkey, "scythe-ui --mute-sys"),
];
for (hotkey, cmd) in binds {

View file

@ -1,30 +1,5 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToastIcon {
Info,
Record,
Save,
Replay,
Cursor,
Screenshot,
Error,
}
impl ToastIcon {
pub fn from_name(name: &str) -> Self {
match name.to_lowercase().as_str() {
"replay" | "save_replay" => ToastIcon::Replay,
"record" | "recording" | "start" => ToastIcon::Record,
"save" | "saved" | "stop" => ToastIcon::Save,
"cursor" => ToastIcon::Cursor,
"screenshot" => ToastIcon::Screenshot,
"error" => ToastIcon::Error,
_ => ToastIcon::Info,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum Command {
SaveReplay,
@ -38,7 +13,6 @@ pub enum Command {
CycleAudioMode,
ToggleCursor,
ReloadConfig,
PowerStateChanged(bool),
StopDaemon,
ShowOverlay,
GetStatus,
@ -105,28 +79,18 @@ pub fn get_ipc_port_path() -> std::path::PathBuf {
#[cfg(windows)]
pub fn read_active_ipc_port() -> u16 {
if let Ok(content) = std::fs::read_to_string(get_ipc_port_path())
&& let Ok(port) = content.trim().parse::<u16>() {
if let Ok(content) = std::fs::read_to_string(get_ipc_port_path()) {
if let Ok(port) = content.trim().parse::<u16>() {
return port;
}
let legacy = std::env::temp_dir().join("vrec-ipc.port");
if let Ok(content) = std::fs::read_to_string(legacy)
&& let Ok(port) = content.trim().parse::<u16>() {
return port;
}
42069
}
#[cfg(windows)]
pub fn get_candidate_ipc_ports() -> Vec<u16> {
let active_port = read_active_ipc_port();
let mut ports = vec![active_port];
for p in [42069, 42070, 42071, 42072] {
if !ports.contains(&p) {
ports.push(p);
}
}
ports
let legacy = std::env::temp_dir().join("vrec-ipc.port");
if let Ok(content) = std::fs::read_to_string(legacy) {
if let Ok(port) = content.trim().parse::<u16>() {
return port;
}
}
42069
}
pub fn is_daemon_running() -> bool {
@ -169,15 +133,17 @@ pub fn send_command(cmd: Command) -> Result<(), Box<dyn std::error::Error + Send
#[cfg(windows)]
{
use std::net::{SocketAddr, TcpStream};
let candidate_ports = get_candidate_ipc_ports();
let active_port = read_active_ipc_port();
let candidate_ports = [active_port, 42069, 42070, 42071, 42072];
for &port in &candidate_ports {
if let Ok(addr) = format!("127.0.0.1:{}", port).parse::<SocketAddr>()
&& let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(150)) {
if let Ok(addr) = format!("127.0.0.1:{}", port).parse::<SocketAddr>() {
if let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(150)) {
let _ = stream.set_write_timeout(Some(Duration::from_millis(600)));
let _ = stream.set_read_timeout(Some(Duration::from_millis(600)));
if stream.write_all(&len_buf).is_ok() && stream.write_all(&payload).is_ok() {
return Ok(());
}
}
}
}
last_err = Some("Could not connect to daemon on any TCP IPC port".into());
@ -237,13 +203,15 @@ pub fn query_status() -> Result<DaemonStatus, Box<dyn std::error::Error + Send +
#[cfg(windows)]
let stream_res = {
use std::net::{SocketAddr, TcpStream};
let candidate_ports = get_candidate_ipc_ports();
let active_port = read_active_ipc_port();
let candidate_ports = [active_port, 42069, 42070, 42071, 42072];
let mut conn = None;
for &port in &candidate_ports {
if let Ok(addr) = format!("127.0.0.1:{}", port).parse::<SocketAddr>()
&& let Ok(stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(150)) {
if let Ok(addr) = format!("127.0.0.1:{}", port).parse::<SocketAddr>() {
if let Ok(stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(150)) {
conn = Some(stream);
break;
}
}
}
conn.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotConnected, "No active daemon port reachable"))

View file

@ -1,5 +1,3 @@
#![allow(clippy::chunks_exact_to_as_chunks)]
pub mod capture;
pub mod encoder;
pub mod ring;
@ -8,7 +6,7 @@ pub mod hotkey;
pub mod ipc;
pub mod overlay;
pub mod config;
pub mod settings_ui;
pub mod overlay_egui;
pub mod hyprland_binds;
pub mod updater;
pub mod daemon;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

187
src/settings_ui.rs Normal file
View file

@ -0,0 +1,187 @@
use gtk::prelude::*;
use gtk::{Window, WindowType, Box, Orientation, Label, Entry, Button, Switch, ComboBoxText};
use crate::config::ScytheConfig;
pub fn open_replay_settings(config_in: &ScytheConfig) {
let window = Window::new(WindowType::Toplevel);
window.set_title("Replay Settings");
window.set_default_size(320, 200);
let vbox = Box::new(Orientation::Vertical, 10);
vbox.set_margin(15);
let duration_label = Label::new(Some("Replay Duration (seconds):"));
duration_label.set_halign(gtk::Align::Start);
let duration_entry = Entry::new();
duration_entry.set_text(&config_in.replay_duration_sec.to_string());
let bitrate_label = Label::new(Some("Bitrate (kbps):"));
bitrate_label.set_halign(gtk::Align::Start);
let bitrate_entry = Entry::new();
bitrate_entry.set_text(&config_in.replay_bitrate_kbps.to_string());
let save_btn = Button::with_label("Save");
vbox.pack_start(&duration_label, false, false, 0);
vbox.pack_start(&duration_entry, false, false, 0);
vbox.pack_start(&bitrate_label, false, false, 0);
vbox.pack_start(&bitrate_entry, false, false, 0);
vbox.pack_start(&save_btn, false, false, 0);
window.add(&vbox);
let window_clone = window.clone();
save_btn.connect_clicked(move |_| {
let mut cfg = ScytheConfig::load();
if let Ok(val) = duration_entry.text().parse() {
cfg.replay_duration_sec = val;
}
if let Ok(val) = bitrate_entry.text().parse() {
cfg.replay_bitrate_kbps = val;
}
let _ = cfg.save();
ScytheConfig::notify_daemon_reload();
window_clone.close();
});
let window_esc = window.clone();
window.connect_key_press_event(move |_, key| {
if key.keyval() == gdk::keys::constants::Escape {
window_esc.close();
gtk::glib::Propagation::Stop
} else {
gtk::glib::Propagation::Proceed
}
});
window.show_all();
}
pub fn open_record_settings(config_in: &ScytheConfig) {
let window = Window::new(WindowType::Toplevel);
window.set_title("Record Settings");
window.set_default_size(320, 150);
let vbox = Box::new(Orientation::Vertical, 10);
vbox.set_margin(15);
let bitrate_label = Label::new(Some("Recording Bitrate (kbps):"));
bitrate_label.set_halign(gtk::Align::Start);
let bitrate_entry = Entry::new();
bitrate_entry.set_text(&config_in.record_bitrate_kbps.to_string());
let save_btn = Button::with_label("Save");
vbox.pack_start(&bitrate_label, false, false, 0);
vbox.pack_start(&bitrate_entry, false, false, 0);
vbox.pack_start(&save_btn, false, false, 0);
window.add(&vbox);
let window_clone = window.clone();
save_btn.connect_clicked(move |_| {
let mut cfg = ScytheConfig::load();
if let Ok(val) = bitrate_entry.text().parse() {
cfg.record_bitrate_kbps = val;
}
let _ = cfg.save();
ScytheConfig::notify_daemon_reload();
window_clone.close();
});
let window_esc = window.clone();
window.connect_key_press_event(move |_, key| {
if key.keyval() == gdk::keys::constants::Escape {
window_esc.close();
gtk::glib::Propagation::Stop
} else {
gtk::glib::Propagation::Proceed
}
});
window.show_all();
}
pub fn open_general_settings(config_in: &ScytheConfig) {
let window = Window::new(WindowType::Toplevel);
window.set_title("General Settings");
window.set_default_size(380, 320);
let vbox = Box::new(Orientation::Vertical, 10);
vbox.set_margin(15);
// Autostart
let hbox_auto = Box::new(Orientation::Horizontal, 10);
let auto_label = Label::new(Some("Autostart with system:"));
let auto_switch = Switch::new();
auto_switch.set_active(config_in.autostart);
hbox_auto.pack_start(&auto_label, false, false, 0);
hbox_auto.pack_start(&auto_switch, false, false, 0);
// Theme
let theme_label = Label::new(Some("UI Theme:"));
theme_label.set_halign(gtk::Align::Start);
let theme_combo = ComboBoxText::new();
theme_combo.append_text("dark");
theme_combo.append_text("light");
theme_combo.set_active(Some(if config_in.ui_color_theme == "dark" { 0 } else { 1 }));
// Language
let lang_label = Label::new(Some("Language Code (e.g. en, fr):"));
lang_label.set_halign(gtk::Align::Start);
let lang_entry = Entry::new();
lang_entry.set_text(&config_in.language);
// Hotkeys
let menu_hk_label = Label::new(Some("Menu Hotkey:"));
menu_hk_label.set_halign(gtk::Align::Start);
let menu_hk_entry = Entry::new();
menu_hk_entry.set_text(&config_in.menu_hotkey);
let save_hk_label = Label::new(Some("Save Replay Hotkey:"));
save_hk_label.set_halign(gtk::Align::Start);
let save_hk_entry = Entry::new();
save_hk_entry.set_text(&config_in.save_hotkey);
let save_btn = Button::with_label("Save General Settings");
vbox.pack_start(&hbox_auto, false, false, 0);
vbox.pack_start(&theme_label, false, false, 0);
vbox.pack_start(&theme_combo, false, false, 0);
vbox.pack_start(&lang_label, false, false, 0);
vbox.pack_start(&lang_entry, false, false, 0);
vbox.pack_start(&menu_hk_label, false, false, 0);
vbox.pack_start(&menu_hk_entry, false, false, 0);
vbox.pack_start(&save_hk_label, false, false, 0);
vbox.pack_start(&save_hk_entry, false, false, 0);
vbox.pack_start(&save_btn, false, false, 0);
window.add(&vbox);
let window_clone = window.clone();
save_btn.connect_clicked(move |_| {
let mut cfg = ScytheConfig::load();
cfg.autostart = auto_switch.is_active();
if let Some(txt) = theme_combo.active_text() {
cfg.ui_color_theme = txt.to_string();
}
cfg.language = lang_entry.text().to_string();
cfg.menu_hotkey = menu_hk_entry.text().to_string();
cfg.save_hotkey = save_hk_entry.text().to_string();
let _ = cfg.save();
ScytheConfig::notify_daemon_reload();
window_clone.close();
});
let window_esc = window.clone();
window.connect_key_press_event(move |_, key| {
if key.keyval() == gdk::keys::constants::Escape {
window_esc.close();
gtk::glib::Propagation::Stop
} else {
gtk::glib::Propagation::Proceed
}
});
window.show_all();
}

View file

@ -2,8 +2,6 @@ use std::sync::{Arc, Mutex};
use serde::Deserialize;
pub const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const FORGEJO_HOST: &str = "https://git.oiupoyt.space";
pub const REPO_OWNER_NAME: &str = "oiupoyt/scythe";
pub const GITHUB_REPO: &str = "oiupoyt/scythe";
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, Default)]
@ -26,7 +24,7 @@ pub struct ReleaseInfo {
}
#[derive(Deserialize, Debug)]
struct ForgejoRelease {
struct GitHubRelease {
tag_name: String,
name: Option<String>,
html_url: String,
@ -56,43 +54,41 @@ pub fn is_newer(latest: &str, current: &str) -> bool {
}
pub fn check_for_updates() -> Option<ReleaseInfo> {
let urls = [
format!("{}/api/v1/repos/{}/releases/latest", FORGEJO_HOST, REPO_OWNER_NAME),
format!("https://api.github.com/repos/{}/releases/latest", REPO_OWNER_NAME),
];
let url = format!("https://api.github.com/repos/{}/releases/latest", GITHUB_REPO);
for url in urls {
let mut cmd = std::process::Command::new("curl");
cmd.args([
"-s",
"-H", "User-Agent: scythe-updater",
"-H", "Accept: application/json",
"--max-time", "6",
&url,
]);
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000);
}
if let Ok(output) = cmd.output()
&& output.status.success()
&& let Ok(release) = serde_json::from_slice::<ForgejoRelease>(&output.stdout) {
let clean_ver = release.tag_name.trim().trim_start_matches('v').to_string();
let has_update = is_newer(&clean_ver, CURRENT_VERSION);
return Some(ReleaseInfo {
tag_name: release.tag_name,
version: clean_ver,
name: release.name.unwrap_or_else(|| format!("v{}", CURRENT_VERSION)),
html_url: release.html_url,
release_notes: release.body.unwrap_or_default(),
has_update,
assets: release.assets,
});
}
// Run curl with a 6-second timeout to avoid blocking
let mut cmd = std::process::Command::new("curl");
cmd.args([
"-s",
"-H", "User-Agent: scythe-updater",
"-H", "Accept: application/vnd.github.v3+json",
"--max-time", "6",
&url,
]);
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000);
}
None
let output = cmd.output().ok()?;
if !output.status.success() {
return None;
}
let release: GitHubRelease = serde_json::from_slice(&output.stdout).ok()?;
let clean_ver = release.tag_name.trim().trim_start_matches('v').to_string();
let has_update = is_newer(&clean_ver, CURRENT_VERSION);
Some(ReleaseInfo {
tag_name: release.tag_name,
version: clean_ver,
name: release.name.unwrap_or_else(|| format!("Scythe v{}", CURRENT_VERSION)),
html_url: release.html_url,
release_notes: release.body.unwrap_or_default(),
has_update,
assets: release.assets,
})
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
@ -357,34 +353,18 @@ fn run_auto_update(info: &ReleaseInfo, status: &Arc<Mutex<UpdateStatus>>) -> Res
let current_exe = std::env::current_exe().map_err(|e| format!("Cannot locate current executable: {}", e))?;
let exe_dir = current_exe.parent().ok_or_else(|| "Invalid executable path".to_string())?;
set_progress("Replacing binaries and libraries...");
let mut files_to_update = Vec::new();
let mut search_dirs = vec![temp_dir.clone()];
while let Some(dir) = search_dirs.pop() {
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
search_dirs.push(path);
} else if path.is_file() {
let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let lower = name.to_lowercase();
if lower.ends_with(".exe") || lower.ends_with(".dll") {
files_to_update.push((path, name));
}
}
}
set_progress("Replacing binaries...");
for bin_name in ["scythe-ui.exe", "scythe-daemon.exe"] {
let src = temp_dir.join(bin_name);
if src.exists() {
let dest = exe_dir.join(bin_name);
let dest_old = exe_dir.join(format!("{}.old", bin_name));
let _ = std::fs::remove_file(&dest_old);
let _ = std::fs::rename(&dest, &dest_old);
let _ = std::fs::copy(&src, &dest);
}
}
for (src, name) in files_to_update {
let dest = exe_dir.join(&name);
let dest_old = exe_dir.join(format!("{}.old", name));
let _ = std::fs::remove_file(&dest_old);
let _ = std::fs::rename(&dest, &dest_old);
let _ = std::fs::copy(&src, &dest);
}
let _ = std::fs::remove_dir_all(&temp_dir);
return Ok(format!("Updated binaries to v{} in {}", info.version, exe_dir.display()));
}

View file

@ -10,75 +10,21 @@ echo "[1/6] Building release binaries..."
cargo build --release --quiet
SOCKET_PATH="${XDG_RUNTIME_DIR:-/tmp}/scythe.sock"
# Liveness probe with no side effects. `scythe --status` calls
# ensure_daemon_running(), so probing with it spawns a daemon and the check
# starts chasing its own tail.
daemon_alive() {
[ -S "$SOCKET_PATH" ] || return 1
python3 -c '
import socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(0.5)
try:
s.connect(sys.argv[1])
except OSError:
sys.exit(1)
finally:
s.close()
' "$SOCKET_PATH" 2>/dev/null
}
# A live daemon owns this socket. Removing the path entry while it runs leaves the
# kernel socket bound but unreachable, breaking the user's session until restart.
# Stop it gracefully, remember how it ran, and put it back when the test finishes.
PREVIOUS_DAEMON_CMD=""
PREVIOUS_DAEMON_CWD=""
if daemon_alive; then
PREVIOUS_DAEMON_CMD=$(pgrep -af 'scythe.*daemon' 2>/dev/null | head -1 | cut -d' ' -f2- || true)
PREVIOUS_DAEMON_CWD=$(readlink -f /proc/"$(pgrep -f 'scythe.*daemon' 2>/dev/null | head -1)"/cwd 2>/dev/null || true)
echo "[0/6] Existing daemon detected; stopping it for the test run..."
target/release/scythe --quit >/dev/null 2>&1 || true
for _ in $(seq 1 80); do
daemon_alive || break
sleep 0.1
done
if daemon_alive; then
echo "ERROR: A scythe daemon is running and did not stop cleanly."
echo " Refusing to unlink its socket. Stop it first: scythe --quit"
exit 1
fi
fi
rm -f "$SOCKET_PATH"
rm -f record_*.mp4 replay_*.mp4
SAVE_DIR=$(python3 -c 'import json, os; p=os.path.expanduser("~/.config/scythe/config.json"); print(os.path.expanduser(json.load(open(p))["output_directory"])) if os.path.exists(p) else print(os.path.expanduser("~/Videos/Scythe"))' 2>/dev/null || echo "$HOME/Videos/Scythe")
SAVE_DIR=$(python3 -c 'import json, os; p=os.path.expanduser("~/.config/scythe/config.json"); print(json.load(open(p))["output_directory"]) if os.path.exists(p) else print(os.path.expanduser("~/Videos/Scythe"))' 2>/dev/null || echo "$HOME/Videos/Scythe")
mkdir -p "$SAVE_DIR"
WAS_SERVICE_ACTIVE=0
if systemctl --user is-active --quiet scythe-daemon.service 2>/dev/null; then
WAS_SERVICE_ACTIVE=1
systemctl --user stop scythe-daemon.service 2>/dev/null || true
sleep 0.5
fi
echo "[2/6] Starting scythe daemon with mock capture..."
target/release/scythe daemon --mock > daemon_test.log 2>&1 &
echo "[2/6] Starting scythe-daemon with mock capture..."
target/release/scythe-daemon --mock > daemon_test.log 2>&1 &
DAEMON_PID=$!
cleanup() {
if kill -0 $DAEMON_PID 2>/dev/null; then
target/release/scythe --quit 2>/dev/null || kill -9 $DAEMON_PID 2>/dev/null || true
target/release/scythe-ui --quit 2>/dev/null || kill -9 $DAEMON_PID 2>/dev/null || true
fi
rm -f daemon_test.log
if [ "$WAS_SERVICE_ACTIVE" -eq 1 ]; then
systemctl --user start scythe-daemon.service 2>/dev/null || true
elif [ -n "$PREVIOUS_DAEMON_CMD" ]; then
echo "Restoring the daemon that was running before the test..."
( cd "${PREVIOUS_DAEMON_CWD:-$PWD}" && setsid $PREVIOUS_DAEMON_CMD >/dev/null 2>&1 & ) || true
sleep 1
fi
}
trap cleanup EXIT
@ -100,23 +46,23 @@ echo "Daemon is live (PID: $DAEMON_PID, Socket: $SOCKET_PATH)"
# Test 1: Start Normal Recording
echo "[3/6] Testing: Start Normal Recording..."
target/release/scythe --start
target/release/scythe-ui --start
echo "Recording in progress for 3 seconds..."
sleep 3
# Test 2: Stop Normal Recording
echo "[4/6] Testing: Stop Normal Recording..."
target/release/scythe --stop
target/release/scythe-ui --stop
sleep 1
# Test 3: Save Instant Replay
echo "[5/6] Testing: Save Instant Replay buffer..."
target/release/scythe --save
target/release/scythe-ui --save
sleep 2
# Test 4: Quit Daemon
echo "[6/6] Testing: Clean Daemon Shutdown..."
target/release/scythe --quit
target/release/scythe-ui --quit
wait $DAEMON_PID 2>/dev/null || true
echo "Daemon shutdown cleanly."
@ -126,7 +72,7 @@ echo " Verifying Generated Recordings with ffprobe"
echo "============================================="
FOUND_ANY=0
while IFS= read -r -d '' f; do
for f in $(find "$SAVE_DIR" "$HOME/Videos/Scythe" "$HOME/Videos/vrec" . -maxdepth 2 \( -name "record_*.mp4" -o -name "replay_*.mp4" \) 2>/dev/null); do
if [ -f "$f" ]; then
FOUND_ANY=1
echo "--> Testing file: $f ($(ls -lh "$f" | awk '{print $5}'))"
@ -141,7 +87,7 @@ while IFS= read -r -d '' f; do
echo "---------------------------------------------"
rm -f "$f"
fi
done < <(find "$SAVE_DIR" "$HOME/Videos/Scythe" "$HOME/Videos/vrec" . -maxdepth 2 -mmin -2 \( -iname "record*.mp4" -o -iname "replay*.mp4" \) -print0 2>/dev/null)
done
if [ $FOUND_ANY -eq 0 ]; then
echo "FAILED: No recording or replay files were produced!"

View file

@ -1,16 +0,0 @@
import socket
import json
import struct
import os
def send(cmd):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
rt = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
sock_path = f"{rt}/scythe.sock" if os.path.exists(f"{rt}/scythe.sock") else f"{rt}/vrec.sock"
sock.connect(sock_path)
payload = json.dumps(cmd).encode('utf-8')
sock.sendall(struct.pack('<I', len(payload)))
sock.sendall(payload)
import sys
send(sys.argv[1])

View file

@ -1,13 +0,0 @@
import socket
import json
import struct
import os
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
rt = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
sock_path = f"{rt}/scythe.sock" if os.path.exists(f"{rt}/scythe.sock") else f"{rt}/vrec.sock"
sock.connect(sock_path)
payload = b'"SaveReplay"'
sock.sendall(struct.pack('<I', len(payload)))
sock.sendall(payload)
print("Sent SaveReplay")

View file

@ -1,9 +0,0 @@
import socket, struct, os
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
rt = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
sock_path = f"{rt}/scythe.sock" if os.path.exists(f"{rt}/scythe.sock") else f"{rt}/vrec.sock"
sock.connect(sock_path)
payload = b'"StartRecording"'
sock.sendall(struct.pack('<I', len(payload)))
sock.sendall(payload)
print("Sent StartRecording")

View file

@ -1,9 +0,0 @@
import socket, struct, os
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
rt = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
sock_path = f"{rt}/scythe.sock" if os.path.exists(f"{rt}/scythe.sock") else f"{rt}/vrec.sock"
sock.connect(sock_path)
payload = b'"ReloadConfig"'
sock.sendall(struct.pack('<I', len(payload)))
sock.sendall(payload)
print("Sent ReloadConfig")

View file

@ -1,9 +0,0 @@
import socket, struct, os
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
rt = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
sock_path = f"{rt}/scythe.sock" if os.path.exists(f"{rt}/scythe.sock") else f"{rt}/vrec.sock"
sock.connect(sock_path)
payload = b'"StopRecording"'
sock.sendall(struct.pack('<I', len(payload)))
sock.sendall(payload)
print("Sent StopRecording")