From 2817cc0da81e69423ed1ad02aa00cc715eeceecb Mon Sep 17 00:00:00 2001 From: Chloe Date: Mon, 28 Sep 2026 01:41:46 -0400 Subject: [PATCH 1/5] First pass --- .github/workflows/cli-release.yml | 264 ++++++++++ .github/workflows/publish.yml | 11 + Cargo.lock | 2 + apps/cli/Cargo.toml | 1 + apps/cli/README.md | 3 + apps/cli/src/doctor.rs | 99 +++- apps/cli/src/guide.rs | 4 +- apps/cli/src/record.rs | 139 +++++- apps/cli/tests/cli.rs | 17 +- .../desktop/src-tauri/src/deeplink_actions.rs | 7 +- apps/desktop/src-tauri/src/lib.rs | 3 +- apps/desktop/src-tauri/src/recording.rs | 53 ++- .../src-tauri/src/recording_settings.rs | 42 +- .../src-tauri/src/stop_editor_benchmark.rs | 7 +- .../new-main/CursorVisibility.tsx | 39 ++ .../(window-chrome)/new-main/SystemAudio.tsx | 59 ++- .../routes/(window-chrome)/new-main/index.tsx | 6 +- .../src/routes/target-select-overlay.tsx | 8 +- apps/desktop/src/store.ts | 3 +- apps/desktop/src/utils/queries.ts | 24 +- crates/recording/Cargo.toml | 3 + crates/recording/build.rs | 8 + crates/recording/src/instant_recording.rs | 39 +- crates/recording/src/lib.rs | 8 +- .../src/sources/screen_capture/linux.rs | 449 +++++++++++++++++- .../src/sources/screen_capture/macos.rs | 289 +++++++---- .../src/sources/screen_capture/mod.rs | 104 +++- .../screen_capture/process_loopback.cpp | 251 ++++++++++ .../src/sources/screen_capture/windows.rs | 297 ++++++++++-- crates/recording/src/studio_recording.rs | 61 ++- crates/scap-screencapturekit/src/capture.rs | 15 +- crates/scap-targets/src/platform/linux.rs | 8 + crates/scap-targets/src/platform/win.rs | 6 + scripts/windows-release-signing.ps1 | 16 +- 34 files changed, 2107 insertions(+), 238 deletions(-) create mode 100644 .github/workflows/cli-release.yml create mode 100644 apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx create mode 100644 crates/recording/build.rs create mode 100644 crates/recording/src/sources/screen_capture/process_loopback.cpp diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml new file mode 100644 index 00000000000..9c494726d81 --- /dev/null +++ b/.github/workflows/cli-release.yml @@ -0,0 +1,264 @@ +name: "cli-release" + +on: + workflow_call: + inputs: + version: + required: true + type: string + sha: + required: true + type: string + release_tag: + required: false + type: string + default: "" + secrets: + APPLE_API_ISSUER: + required: false + APPLE_API_KEY: + required: false + APPLE_API_KEY_FILE: + required: false + APPLE_CERTIFICATE: + required: false + APPLE_CERTIFICATE_PASSWORD: + required: false + APPLE_SIGNING_IDENTITY: + required: false + SIGNPATH_API_TOKEN: + required: false + SIGNPATH_ORGANIZATION_ID: + required: false + SIGNPATH_PROJECT_SLUG: + required: false + SIGNPATH_SIGNING_POLICY_SLUG: + required: false + SIGNPATH_ARTIFACT_CONFIGURATION_SLUG: + required: false + workflow_dispatch: + inputs: + version: + description: "Version used in artifact names" + required: true + type: string + sha: + description: "Commit to build" + required: false + type: string + release_tag: + description: "Existing GitHub release tag to receive the archives" + required: false + type: string + +jobs: + build: + permissions: + contents: write + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-pc-windows-msvc + runner: windows-2022 + platform: windows + arch: x86_64 + - target: x86_64-unknown-linux-gnu + runner: ubuntu-24.04 + platform: linux + arch: x86_64 + - target: x86_64-apple-darwin + runner: macos-15 + platform: macos + arch: x86_64 + - target: aarch64-apple-darwin + runner: macos-15 + platform: macos + arch: aarch64 + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.sha || github.sha }} + + - name: Install Linux dependencies + if: ${{ runner.os == 'Linux' }} + uses: ./.github/actions/install-desktop-deps + + - uses: dtolnay/rust-toolchain@1.88.0 + with: + targets: ${{ matrix.target }} + + - uses: ./.github/actions/setup-rust-cache + with: + target: ${{ matrix.target }} + prefix-key: v1-rust-cli-release + save-cache: true + + - uses: ./.github/actions/setup-js + + - name: Create Apple API key + if: ${{ runner.os == 'macOS' }} + shell: bash + run: echo "${{ secrets.APPLE_API_KEY_FILE }}" > api.p8 + + - uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 + if: ${{ runner.os == 'macOS' }} + with: + p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} + p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + + - name: Prepare native dependencies + shell: bash + env: + RUST_TARGET_TRIPLE: ${{ matrix.target }} + run: bun run cap-setup + + - name: Build CLI + shell: bash + env: + RUST_TARGET_TRIPLE: ${{ matrix.target }} + CAP_BUILD_REVISION: ${{ inputs.sha || github.sha }} + run: cargo build --locked --release -p cap --target ${{ matrix.target }} + + - name: Stage Windows CLI for Authenticode signing + if: ${{ runner.os == 'Windows' }} + shell: pwsh + run: ./scripts/windows-release-signing.ps1 -Operation Stage -PayloadKind Cli -Target "${{ matrix.target }}" -WorkspaceRoot "$env:GITHUB_WORKSPACE" + + - name: Upload unsigned Windows CLI + if: ${{ runner.os == 'Windows' }} + id: upload_unsigned_windows_cli + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: unsigned-windows-cli + path: target/${{ matrix.target }}/release/windows-signing-cli/payload + if-no-files-found: error + + - name: Submit Windows CLI signing request + if: ${{ runner.os == 'Windows' }} + timeout-minutes: 90 + uses: signpath/github-action-submit-signing-request@ced31329c0317e779dad2eec2a7c3bb46ea1343e + with: + api-token: ${{ secrets.SIGNPATH_API_TOKEN }} + organization-id: ${{ secrets.SIGNPATH_ORGANIZATION_ID }} + project-slug: ${{ secrets.SIGNPATH_PROJECT_SLUG }} + signing-policy-slug: ${{ secrets.SIGNPATH_SIGNING_POLICY_SLUG }} + artifact-configuration-slug: ${{ secrets.SIGNPATH_ARTIFACT_CONFIGURATION_SLUG }} + github-artifact-id: ${{ steps.upload_unsigned_windows_cli.outputs.artifact-id }} + wait-for-completion: true + wait-for-completion-timeout-in-seconds: 5400 + service-unavailable-timeout-in-seconds: 5400 + output-artifact-directory: signed-windows-payload + + - name: Restore signed Windows CLI + if: ${{ runner.os == 'Windows' }} + shell: pwsh + run: ./scripts/windows-release-signing.ps1 -Operation Restore -PayloadKind Cli -Target "${{ matrix.target }}" -WorkspaceRoot "$env:GITHUB_WORKSPACE" + + - name: Package Windows CLI + if: ${{ runner.os == 'Windows' }} + shell: pwsh + env: + VERSION: ${{ inputs.version }} + TARGET: ${{ matrix.target }} + run: | + $archive = "Cap-CLI-$env:VERSION-windows-x86_64.zip" + $stage = Join-Path $env:RUNNER_TEMP "cap-cli" + New-Item -ItemType Directory -Force -Path $stage | Out-Null + $binary = "target/$env:TARGET/release/cap.exe" + Copy-Item -LiteralPath $binary -Destination (Join-Path $stage "cap.exe") + Copy-Item -LiteralPath "LICENSE" -Destination (Join-Path $stage "LICENSE") + $queue = [System.Collections.Generic.Queue[string]]::new() + $queue.Enqueue((Resolve-Path -LiteralPath $binary).Path) + $seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) + while ($queue.Count -gt 0) { + $file = $queue.Dequeue() + $dependencies = & dumpbin /nologo /dependents $file | ForEach-Object { + if ($_ -match '^\s+([^\s]+\.dll)\s*$') { $Matches[1] } + } + foreach ($dependency in $dependencies) { + if (-not $seen.Add($dependency)) { continue } + $candidate = Get-ChildItem -Path "target/native-deps","target/$env:TARGET/release" -Filter $dependency -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -eq $candidate) { continue } + $destination = Join-Path $stage $candidate.Name + Copy-Item -LiteralPath $candidate.FullName -Destination $destination + $queue.Enqueue($candidate.FullName) + } + } + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $archive + "ARCHIVE=$archive" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + - name: Package macOS CLI + if: ${{ runner.os == 'macOS' }} + shell: bash + env: + VERSION: ${{ inputs.version }} + TARGET: ${{ matrix.target }} + ARCH: ${{ matrix.arch }} + run: | + archive="Cap-CLI-$VERSION-macos-$ARCH.tar.gz" + stage="$RUNNER_TEMP/cap-cli" + mkdir -p "$stage" + cp "target/$TARGET/release/cap" "$stage/cap" + cp LICENSE "$stage/LICENSE" + if otool -L "$stage/cap" | grep -q 'Spacedrive.framework'; then + cp -R target/native-deps/Spacedrive.framework "$stage/Spacedrive.framework" + install_name_tool -add_rpath '@executable_path' "$stage/cap" 2>/dev/null || true + codesign --force --options runtime --timestamp --sign "${{ secrets.APPLE_SIGNING_IDENTITY }}" "$stage/Spacedrive.framework" + fi + codesign --force --options runtime --timestamp --sign "${{ secrets.APPLE_SIGNING_IDENTITY }}" "$stage/cap" + codesign --verify --strict "$stage/cap" + ditto -c -k --keepParent "$stage" "$RUNNER_TEMP/cap-cli-notary.zip" + xcrun notarytool submit "$RUNNER_TEMP/cap-cli-notary.zip" --key api.p8 --key-id "${{ secrets.APPLE_API_KEY }}" --issuer "${{ secrets.APPLE_API_ISSUER }}" --wait + tar -C "$stage" -czf "$archive" . + echo "ARCHIVE=$archive" >> "$GITHUB_ENV" + + - name: Package Linux CLI + if: ${{ runner.os == 'Linux' }} + shell: bash + env: + VERSION: ${{ inputs.version }} + TARGET: ${{ matrix.target }} + run: | + archive="Cap-CLI-$VERSION-linux-x86_64.tar.gz" + stage="$RUNNER_TEMP/cap-cli" + mkdir -p "$stage/lib" + cp "target/$TARGET/release/cap" "$stage/cap" + cp /usr/bin/pactl "$stage/pactl" + cp LICENSE "$stage/LICENSE" + ldd "$stage/cap" | awk '/=> \/.*\/target\// { print $3 }' | sort -u | while read -r library; do + cp -L "$library" "$stage/lib/" + done + ldd "$stage/pactl" | awk '/=>/ && /lib(pulse|sndfile|asyncns|FLAC|ogg|vorbis|dbus)/ { print $3 }' | sort -u | while read -r library; do + cp -L "$library" "$stage/lib/" + done + if ! find "$stage/lib" -type f -print -quit | grep -q .; then + rmdir "$stage/lib" + else + patchelf --set-rpath '$ORIGIN/lib' "$stage/cap" + patchelf --set-rpath '$ORIGIN/lib' "$stage/pactl" + find "$stage/lib" -type f -exec patchelf --set-rpath '$ORIGIN' {} \; + fi + tar -C "$stage" -czf "$archive" . + echo "ARCHIVE=$archive" >> "$GITHUB_ENV" + + - name: Verify packaged CLI + shell: bash + run: | + test -s "$ARCHIVE" + "target/${{ matrix.target }}/release/cap${{ runner.os == 'Windows' && '.exe' || '' }}" --version + "target/${{ matrix.target }}/release/cap${{ runner.os == 'Windows' && '.exe' || '' }}" --help >/dev/null + + - uses: actions/upload-artifact@v4 + with: + name: Cap-CLI-${{ inputs.version }}-${{ matrix.platform }}-${{ matrix.arch }} + path: ${{ env.ARCHIVE }} + if-no-files-found: error + + - name: Attach CLI archive to release + if: ${{ inputs.release_tag != '' }} + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "${{ inputs.release_tag }}" "$ARCHIVE" --clobber diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 77054493473..80872caa124 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -42,3 +42,14 @@ jobs: auto_publish: false interactionId: ${{ inputs.interactionId }} secrets: inherit + + cli: + needs: [version, release] + permissions: + contents: write + uses: ./.github/workflows/cli-release.yml + with: + version: ${{ needs.version.outputs.version }} + sha: ${{ github.sha }} + release_tag: cap-v${{ needs.version.outputs.version }} + secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index e56c17c25d3..6b3f5f3adda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1291,6 +1291,7 @@ dependencies = [ "reqwest", "rmcp", "rpassword", + "scap-direct3d", "scap-screencapturekit", "scap-targets", "serde", @@ -1926,6 +1927,7 @@ dependencies = [ "cap-rendering", "cap-timestamp", "cap-utils", + "cc", "chrono", "cidre", "clap", diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml index b66b0c7aee0..86657ebf857 100644 --- a/apps/cli/Cargo.toml +++ b/apps/cli/Cargo.toml @@ -52,6 +52,7 @@ workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" } libc = "0.2" [target.'cfg(windows)'.dependencies] +scap-direct3d = { path = "../../crates/scap-direct3d" } windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Storage_FileSystem", diff --git a/apps/cli/README.md b/apps/cli/README.md index e33a97c0e88..5a44838a951 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -65,6 +65,7 @@ is taken from `CAP_SERVER_URL`, else Cap Desktop's configured server, else `http cap doctor --json # verify permissions & capture readiness (exits 0; read `ok`/`captureReady`) cap targets --json # discover screens/windows/cameras/mics (ids feed the next steps) cap record start --screen --json --detach # start in the background -> {"type":"started","recordingId","pid","path"} +cap record start --window --audio-source application --hide-cursor --duration 30 --json # ... the agent performs whatever it needs to capture ... cap record stop --id --json # finalize -> {"type":"stopped","path","recordingMetaExists":true} cap project validate --json # confirm the recording is complete before exporting @@ -90,6 +91,8 @@ step. - `cap desktop status|install-cli|uninstall-cli` — manage the `cap` shim on PATH. - `cap completions ` — shell completion scripts (bash/zsh/fish/powershell). +Application audio requires a window target and follows that window's owning process tree without falling back to the system mix. On Linux this requires X11 because the Wayland screen-cast portal does not expose the selected window's process identity. Use `--audio-source none|system|application`; `--system-audio` remains an alias for `system`. `--hide-cursor` applies to native display, area, and window capture. + ## Automations Automations are `trigger → (conditions) → actions` rules authored in Cap Desktop (Settings → diff --git a/apps/cli/src/doctor.rs b/apps/cli/src/doctor.rs index 7af92616571..ad2a2bf5eec 100644 --- a/apps/cli/src/doctor.rs +++ b/apps/cli/src/doctor.rs @@ -7,7 +7,7 @@ use crate::{OutputFormat, write_json}; /// Version of the machine-readable JSON contracts the CLI emits. Bump on breaking changes so an /// agent can detect drift via `cap version`/`cap doctor`. -pub const SCHEMA_VERSION: u32 = 2; +pub const SCHEMA_VERSION: u32 = 3; #[cfg(windows)] const BINARY_SUFFIX: &str = ".exe"; @@ -216,6 +216,7 @@ pub enum CheckId { ScreenRecordingPermission, #[cfg(target_os = "macos")] ScreenCaptureKit, + ApplicationAudio, CliInstall, } @@ -226,6 +227,7 @@ impl CheckId { Self::ScreenRecordingPermission => "screenRecordingPermission", #[cfg(target_os = "macos")] Self::ScreenCaptureKit => "screenCaptureKit", + Self::ApplicationAudio => "applicationAudio", Self::CliInstall => "cliInstall", } } @@ -455,6 +457,100 @@ fn install_check(install: &Result) -> } } +#[cfg(windows)] +fn application_audio_check() -> Check { + let Some(version) = scap_direct3d::WindowsVersion::detect() else { + return Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Unknown, + message: "Could not determine whether Windows process-loopback capture is available" + .to_string(), + }; + }; + if version.build >= 20_348 { + Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Ok, + message: format!( + "Windows build {} supports process-tree application audio capture", + version.build + ), + } + } else { + Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Warn, + message: format!( + "Application audio requires Windows build 20348 or newer; this system is build {}", + version.build + ), + } + } +} + +#[cfg(target_os = "macos")] +fn application_audio_check() -> Check { + if scap_screencapturekit::is_system_audio_supported() { + Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Ok, + message: "ScreenCaptureKit supports selected-application audio capture".to_string(), + } + } else { + Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Warn, + message: "Application audio requires macOS 13.0 or newer".to_string(), + } + } +} + +#[cfg(target_os = "linux")] +fn application_audio_check() -> Check { + let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() + && (std::env::var_os("DISPLAY").is_none() + || std::env::var("XDG_SESSION_TYPE") + .is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))); + if wayland { + return Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Warn, + message: "Application audio requires X11 window process identity; the Wayland screen-cast portal does not expose it" + .to_string(), + }; + } + let bundled_pactl = std::env::current_exe() + .ok() + .and_then(|executable| executable.parent().map(|parent| parent.join("pactl"))) + .filter(|path| path.is_file()); + match std::process::Command::new(bundled_pactl.unwrap_or_else(|| "pactl".into())) + .args(["list", "short", "sinks"]) + .output() + { + Ok(output) if output.status.success() => Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Ok, + message: "PulseAudio/PipeWire routing is available for isolated application audio" + .to_string(), + }, + Ok(output) => Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Warn, + message: format!( + "pactl could not reach PulseAudio/PipeWire: {}", + String::from_utf8_lossy(&output.stderr).trim() + ), + }, + Err(error) => Check { + id: CheckId::ApplicationAudio, + status: CheckStatus::Warn, + message: format!( + "Application audio needs pactl and PulseAudio/PipeWire compatibility modules: {error}" + ), + }, + } +} + #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] fn capture_ready(permissions: &Permissions, checks: &[Check]) -> bool { let permission_ready = match permissions.screen_recording { @@ -548,6 +644,7 @@ pub async fn run_doctor(format: OutputFormat) -> Result<(), String> { #[cfg(target_os = "macos")] checks.push(screen_capture_kit_check(&permissions).await); + checks.push(application_audio_check()); checks.push(install_check(&install)); let ok = !checks diff --git a/apps/cli/src/guide.rs b/apps/cli/src/guide.rs index 5a99d462234..75b8f640c07 100644 --- a/apps/cli/src/guide.rs +++ b/apps/cli/src/guide.rs @@ -2,7 +2,7 @@ use serde::Serialize; use crate::{OutputFormat, write_json}; -const GUIDE_SCHEMA_VERSION: u32 = 3; +const GUIDE_SCHEMA_VERSION: u32 = 4; /// Machine-readable capability + schema manifest. `cap guide --json` is the single document an agent /// can fetch to learn the output convention, env vars, exit codes, and the per-command output shape @@ -169,7 +169,7 @@ fn build() -> Guide { CommandDoc { requires_duration: false, notes: Some( - "The `started` then `stopped` sequence applies to the foreground run. With `--detach` the stream emits only `started` (or `error`) and returns immediately with recordingId+pid; the `stopped` event is delivered by `cap record stop`.", + "Select exactly one screen or window. --hide-cursor disables cursor capture. --audio-source accepts none, system, or application; application requires --window and captures the owning process tree without falling back to the system mix. Linux application audio requires X11 because the Wayland screen-cast portal does not expose process identity. --system-audio remains an alias for --audio-source system. With --detach all capture flags are forwarded to the worker; the stream emits only started (or error) and returns immediately with recordingId+pid, then cap record stop delivers stopped.", ), ..cmd( "record start", diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs index 6416a8d31c4..b1ade54e8af 100644 --- a/apps/cli/src/record.rs +++ b/apps/cli/src/record.rs @@ -5,7 +5,7 @@ use cap_recording::{ CameraFeed, DoneFut, MicrophoneFeed, PipelineStoppedByUser, feeds::{camera, microphone}, instant_recording, - screen_capture::ScreenCaptureTarget, + screen_capture::{AudioCaptureSource, ScreenCaptureTarget}, studio_recording::{self, ActorHandle as StudioActorHandle}, upload_resume::UploadLock, }; @@ -48,9 +48,15 @@ pub struct RecordParams { /// Capture from the microphone with this device name (see `cap targets mics`) #[arg(long)] mic: Option, - /// Whether to capture system audio + /// Capture the full system mix (alias for --audio-source system) #[arg(long)] system_audio: bool, + /// Audio to capture with the recording + #[arg(long, value_enum)] + audio_source: Option, + /// Exclude the cursor from the captured video + #[arg(long)] + hide_cursor: bool, #[arg( long, help = "New '.cap' project path (defaults to .cap in the working directory). The path must not already exist, including an empty directory." @@ -75,9 +81,39 @@ impl RecordParams { if self.fps == Some(0) { return Err("--fps must be greater than 0".to_string()); } + if self.system_audio + && self + .audio_source + .is_some_and(|source| source != AudioSourceArg::System) + { + return Err( + "--system-audio conflicts with --audio-source none/application; use one audio selection" + .to_string(), + ); + } + if self.resolved_audio_source() == AudioCaptureSource::Application + && self.target.window.is_none() + { + return Err( + "--audio-source application requires --window so Cap can identify the selected application" + .to_string(), + ); + } Ok(()) } + fn resolved_audio_source(&self) -> AudioCaptureSource { + self.audio_source + .map(AudioCaptureSource::from) + .unwrap_or_else(|| { + if self.system_audio { + AudioCaptureSource::System + } else { + AudioCaptureSource::None + } + }) + } + fn to_cli_args(&self) -> Vec { let mut args = Vec::new(); if let Some(id) = &self.target.screen { @@ -101,6 +137,13 @@ impl RecordParams { if self.system_audio { args.push("--system-audio".to_string()); } + if let Some(audio_source) = self.audio_source { + args.push("--audio-source".to_string()); + args.push(audio_source.to_string()); + } + if self.hide_cursor { + args.push("--hide-cursor".to_string()); + } if let Some(path) = &self.path { args.push("--path".to_string()); args.push(path.display().to_string()); @@ -123,6 +166,33 @@ pub enum RecordMode { Instant, } +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +pub enum AudioSourceArg { + None, + System, + Application, +} + +impl From for AudioCaptureSource { + fn from(value: AudioSourceArg) -> Self { + match value { + AudioSourceArg::None => Self::None, + AudioSourceArg::System => Self::System, + AudioSourceArg::Application => Self::Application, + } + } +} + +impl std::fmt::Display for AudioSourceArg { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => f.write_str("none"), + Self::System => f.write_str("system"), + Self::Application => f.write_str("application"), + } + } +} + impl std::fmt::Display for RecordMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -746,18 +816,21 @@ async fn start_recording( target: ScreenCaptureTarget, path: PathBuf, ) -> Result { + let audio_source = params.resolved_audio_source(); let upload_lock = prepare_recording_project( &path, params.mode, - params.mic.is_some() || params.system_audio, + params.mic.is_some() || audio_source.is_enabled(), )?; #[cfg(target_os = "macos")] let target_for_shareable_content = target.clone(); let mut studio_builder = studio_recording::Actor::builder(path.clone(), target.clone()) - .with_system_audio(params.system_audio); - let mut instant_builder = - instant_recording::Actor::builder(path, target).with_system_audio(params.system_audio); + .with_audio_source(audio_source) + .with_show_cursor(!params.hide_cursor); + let mut instant_builder = instant_recording::Actor::builder(path, target) + .with_audio_source(audio_source) + .with_show_cursor(!params.hide_cursor); let mut camera_active = false; // Feeds must be locked and attached before build(); the lock keeps the device open for the whole @@ -1317,6 +1390,60 @@ fn emit_record_event(format: OutputFormat, event: &RecordEvent<'_>) -> Result<() mod tests { use super::*; + fn params(window: bool) -> RecordParams { + RecordParams { + target: RecordTargets { + screen: None, + window: window.then(|| "1".parse().unwrap()), + }, + mode: RecordMode::Studio, + camera: None, + mic: None, + system_audio: false, + audio_source: None, + hide_cursor: false, + path: None, + fps: None, + duration: Some(1.0), + } + } + + #[test] + fn application_audio_requires_window_target() { + let mut params = params(false); + params.audio_source = Some(AudioSourceArg::Application); + assert!(params.validate().unwrap_err().contains("requires --window")); + + params.target.window = Some("1".parse().unwrap()); + assert!(params.validate().is_ok()); + assert_eq!( + params.resolved_audio_source(), + AudioCaptureSource::Application + ); + } + + #[test] + fn legacy_system_audio_alias_rejects_conflicting_source() { + let mut params = params(true); + params.system_audio = true; + params.audio_source = Some(AudioSourceArg::None); + assert!(params.validate().unwrap_err().contains("conflicts")); + } + + #[test] + fn detached_worker_preserves_audio_and_cursor_flags() { + let mut params = params(true); + params.audio_source = Some(AudioSourceArg::Application); + params.hide_cursor = true; + let args = params.to_cli_args(); + + assert!( + args.windows(2) + .any(|args| args == ["--audio-source", "application"]) + ); + assert!(args.iter().any(|arg| arg == "--hide-cursor")); + } + #[test] fn instant_project_is_discoverable_before_capture_with_required_audio_intent() { let root = tempfile::tempdir().unwrap(); diff --git a/apps/cli/tests/cli.rs b/apps/cli/tests/cli.rs index 14d3b52fbed..86113396850 100644 --- a/apps/cli/tests/cli.rs +++ b/apps/cli/tests/cli.rs @@ -583,7 +583,7 @@ fn guide_json_is_parseable_and_self_describing() { assert!(output.status.success(), "stderr: {}", stderr(&output)); let json = parse_json(&output); assert_eq!(json["binary"], "cap"); - assert_eq!(json["schemaVersion"], 3); + assert_eq!(json["schemaVersion"], 4); assert!(json["commands"].is_array()); assert!(json["env"].is_array()); assert!(json["outputConvention"].is_object()); @@ -767,7 +767,9 @@ fn agent_installer_dry_run_is_machine_readable() { assert_eq!(json["target"], "codex"); assert_eq!(json["dryRun"], true); assert_eq!(json["applied"], false); - assert_eq!(json["changes"].as_array().map(Vec::len), Some(2)); + let changes = json["changes"].as_array().unwrap(); + assert!(changes.iter().any(|change| change["component"] == "skill")); + assert!(changes.iter().any(|change| change["component"] == "mcp")); } #[test] @@ -1112,12 +1114,21 @@ fn doctor_check_ids_are_the_pinned_vocabulary() { "ffmpeg", "screenRecordingPermission", "screenCaptureKit", + "applicationAudio", "cliInstall" ] ); #[cfg(not(target_os = "macos"))] - assert_eq!(ids, ["ffmpeg", "screenRecordingPermission", "cliInstall"]); + assert_eq!( + ids, + [ + "ffmpeg", + "screenRecordingPermission", + "applicationAudio", + "cliInstall" + ] + ); } #[test] diff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rs index 5372d58785f..a21d998dc25 100644 --- a/apps/desktop/src-tauri/src/deeplink_actions.rs +++ b/apps/desktop/src-tauri/src/deeplink_actions.rs @@ -249,7 +249,12 @@ impl DeepLinkAction { let inputs = StartRecordingInputs { mode, capture_target, - capture_system_audio, + audio_source: if capture_system_audio { + cap_recording::screen_capture::AudioCaptureSource::System + } else { + cap_recording::screen_capture::AudioCaptureSource::None + }, + show_cursor: true, organization_id: None, }; diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index a78c370641e..585b8f32dc8 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -7497,7 +7497,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) { } }), mode: event.mode, - capture_system_audio: settings.system_audio, + audio_source: settings.audio_source, + show_cursor: settings.show_cursor, organization_id: settings.organization_id, } }) diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs index 87cae9cedb8..dc15a0fc4c1 100644 --- a/apps/desktop/src-tauri/src/recording.rs +++ b/apps/desktop/src-tauri/src/recording.rs @@ -22,7 +22,7 @@ use cap_recording::{ sources::MicrophoneSourceError, sources::{ screen_capture, - screen_capture::{CaptureDisplay, CaptureWindow, ScreenCaptureTarget}, + screen_capture::{AudioCaptureSource, CaptureDisplay, CaptureWindow, ScreenCaptureTarget}, }, studio_recording, }; @@ -1158,13 +1158,23 @@ where #[derive(Deserialize, Type, Clone, Debug)] pub struct StartRecordingInputs { pub capture_target: ScreenCaptureTarget, - #[serde(default)] - pub capture_system_audio: bool, + #[serde( + default, + alias = "capture_system_audio", + deserialize_with = "screen_capture::deserialize_audio_capture_source" + )] + pub audio_source: AudioCaptureSource, + #[serde(default = "default_show_cursor")] + pub show_cursor: bool, pub mode: RecordingMode, #[serde(default)] pub organization_id: Option, } +fn default_show_cursor() -> bool { + true +} + fn desktop_recording_defaults( general_settings: Option<&GeneralSettingsStore>, ) -> cap_recording::RecordingDefaults { @@ -2025,12 +2035,17 @@ async fn start_recording_prepared( } let is_camera_only = matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly); + if inputs.audio_source == AudioCaptureSource::Application + && !matches!(inputs.capture_target, ScreenCaptureTarget::Window { .. }) + { + return Err("Application audio requires a window capture target".to_string()); + } #[cfg(target_os = "linux")] linux_instant::validate_inputs(&inputs)?; if is_camera_only { - inputs.capture_system_audio = false; + inputs.audio_source = AudioCaptureSource::None; } { @@ -2684,7 +2699,8 @@ async fn start_recording_prepared( recording_dir.clone(), inputs.capture_target.clone(), ) - .with_system_audio(inputs.capture_system_audio), + .with_audio_source(inputs.audio_source) + .with_show_cursor(inputs.show_cursor), camera_feed.is_some(), None, ); @@ -2733,7 +2749,8 @@ async fn start_recording_prepared( recording_dir.clone(), inputs.capture_target.clone(), ) - .with_system_audio(inputs.capture_system_audio) + .with_audio_source(inputs.audio_source) + .with_show_cursor(inputs.show_cursor) .with_max_output_size(instant_mode_max_resolution); builder = builder.with_start_gate(start_gate.clone()); @@ -2787,7 +2804,7 @@ async fn start_recording_prepared( &app_handle, &recording_dir, &video_upload_info.id, - inputs.capture_system_audio || mic_feed.is_some(), + inputs.audio_source.is_enabled() || mic_feed.is_some(), ) .await .map_err(anyhow::Error::from)?; @@ -2821,7 +2838,7 @@ async fn start_recording_prepared( video_upload_info.clone(), events, attempt.upload(), - inputs.capture_system_audio || mic_feed.is_some(), + inputs.audio_source.is_enabled() || mic_feed.is_some(), ), )) }; @@ -2836,7 +2853,7 @@ async fn start_recording_prepared( Some(finish_upload_rx.clone()), upload_session, video_upload_info.clone(), - inputs.capture_system_audio || mic_feed.is_some(), + inputs.audio_source.is_enabled() || mic_feed.is_some(), ) } else { let progressive_upload = InstantMultipartUpload::spawn( @@ -2845,7 +2862,7 @@ async fn start_recording_prepared( video_upload_info.clone(), upload_session, Some(finish_upload_rx.clone()), - inputs.capture_system_audio || mic_feed.is_some(), + inputs.audio_source.is_enabled() || mic_feed.is_some(), ); SegmentUploader { handle: progressive_upload.handle, @@ -7037,7 +7054,7 @@ async fn emit_recording_started_telemetry(app: &AppHandle, state_mtx: &MutableSt target_kind, has_camera, state.selected_mic_label.is_some(), - inputs.capture_system_audio, + inputs.audio_source.is_enabled(), ) }; @@ -8068,7 +8085,7 @@ pub(crate) mod linux_instant { pub fn validate_inputs(inputs: &StartRecordingInputs) -> Result<(), String> { if inputs.mode == RecordingMode::Instant && matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly) - && inputs.capture_system_audio + && inputs.audio_source.is_enabled() { Err("System audio is not supported for Linux Instant CameraOnly. Disable it before recording.".into()) } else { @@ -8968,7 +8985,8 @@ pub(crate) mod linux_instant { capture_target: ScreenCaptureTarget::Window { id: "1".parse().unwrap(), }, - capture_system_audio: false, + audio_source: AudioCaptureSource::None, + show_cursor: true, mode: RecordingMode::Instant, organization_id: None, }; @@ -9079,15 +9097,16 @@ pub(crate) mod linux_instant { fn explicit_camera_only_system_audio_request_is_rejected_before_normalization() { let mut inputs = StartRecordingInputs { capture_target: ScreenCaptureTarget::CameraOnly, - capture_system_audio: true, + audio_source: AudioCaptureSource::System, + show_cursor: true, mode: RecordingMode::Instant, organization_id: None, }; assert!(validate_inputs(&inputs).is_err()); - assert!(inputs.capture_system_audio); - inputs.capture_system_audio = false; + assert!(inputs.audio_source.is_enabled()); + inputs.audio_source = AudioCaptureSource::None; assert!(validate_inputs(&inputs).is_ok()); - inputs.capture_system_audio = true; + inputs.audio_source = AudioCaptureSource::System; inputs.mode = RecordingMode::Studio; assert!(validate_inputs(&inputs).is_ok()); } diff --git a/apps/desktop/src-tauri/src/recording_settings.rs b/apps/desktop/src-tauri/src/recording_settings.rs index 4341d34688b..d7219d9c44b 100644 --- a/apps/desktop/src-tauri/src/recording_settings.rs +++ b/apps/desktop/src-tauri/src/recording_settings.rs @@ -4,7 +4,9 @@ use cap_recording::{ camera::{CameraDeviceSettings, DeviceOrModelID}, microphone::MicrophoneDeviceSettings, }, - sources::screen_capture::ScreenCaptureTarget, + sources::screen_capture::{ + AudioCaptureSource, ScreenCaptureTarget, deserialize_audio_capture_source, + }, }; use std::collections::HashMap; use tauri::{AppHandle, Wry}; @@ -21,7 +23,7 @@ pub enum RecordingTargetMode { Camera, } -#[derive(serde::Serialize, serde::Deserialize, specta::Type, Debug, Clone, Default)] +#[derive(serde::Serialize, serde::Deserialize, specta::Type, Debug, Clone)] #[serde(rename_all = "camelCase", default)] pub struct RecordingSettingsStore { pub target: Option, @@ -29,12 +31,39 @@ pub struct RecordingSettingsStore { #[serde(deserialize_with = "deserialize_camera_id")] pub camera_id: Option, pub mode: Option, - pub system_audio: bool, + #[serde( + default, + alias = "systemAudio", + deserialize_with = "deserialize_audio_capture_source" + )] + pub audio_source: AudioCaptureSource, + #[serde(default = "default_show_cursor")] + pub show_cursor: bool, pub organization_id: Option, pub camera_device_settings: HashMap, pub microphone_device_settings: HashMap, } +fn default_show_cursor() -> bool { + true +} + +impl Default for RecordingSettingsStore { + fn default() -> Self { + Self { + target: None, + mic_name: None, + camera_id: None, + mode: None, + audio_source: AudioCaptureSource::None, + show_cursor: true, + organization_id: None, + camera_device_settings: HashMap::new(), + microphone_device_settings: HashMap::new(), + } + } +} + fn deserialize_camera_id<'de, D>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, @@ -114,7 +143,7 @@ pub fn set_recording_mode(app: AppHandle, mode: RecordingMode) -> Result<(), Str #[cfg(test)] mod tests { - use super::RecordingSettingsStore; + use super::{AudioCaptureSource, RecordingSettingsStore}; use serde_json::json; #[test] @@ -143,7 +172,12 @@ mod tests { }); let settings: RecordingSettingsStore = serde_json::from_value(saved.clone()).unwrap(); assert!(settings.camera_id.is_none()); + assert_eq!(settings.audio_source, AudioCaptureSource::System); + assert!(settings.show_cursor); saved["cameraId"] = serde_json::Value::Null; + saved.as_object_mut().unwrap().remove("systemAudio"); + saved["audioSource"] = json!("system"); + saved["showCursor"] = json!(true); assert_eq!(serde_json::to_value(settings).unwrap(), saved); } } diff --git a/apps/desktop/src-tauri/src/stop_editor_benchmark.rs b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs index 43f3ea1c831..f937bce5d91 100644 --- a/apps/desktop/src-tauri/src/stop_editor_benchmark.rs +++ b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs @@ -224,7 +224,12 @@ async fn measure( state.clone(), crate::recording::StartRecordingInputs { capture_target, - capture_system_audio: config.system_audio, + audio_source: if config.system_audio { + cap_recording::screen_capture::AudioCaptureSource::System + } else { + cap_recording::screen_capture::AudioCaptureSource::None + }, + show_cursor: true, mode: cap_recording::RecordingMode::Studio, organization_id: None, }, diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx new file mode 100644 index 00000000000..d6cf52ce05d --- /dev/null +++ b/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx @@ -0,0 +1,39 @@ +import { createQuery } from "@tanstack/solid-query"; +import { cx } from "cva"; +import IconPhCursorClickBold from "~icons/ph/cursor-click-bold"; +import { createCurrentRecordingQuery } from "~/utils/queries"; + +import { useRecordingOptions } from "../OptionsContext"; +import { + DEVICE_ROW_CLASS, + DEVICE_ROW_ICON_CLASS, + DEVICE_ROW_LABEL_CLASS, + DEVICE_ROW_TRAILING_CLASS, +} from "./deviceRowStyles"; +import InfoPill from "./InfoPill"; + +export default function CursorVisibility() { + const { rawOptions, setOptions } = useRecordingOptions(); + const currentRecording = createQuery(createCurrentRecordingQuery); + const showCursor = () => rawOptions.showCursor !== false; + const isDisabled = () => + !!currentRecording.data || rawOptions.captureTarget.variant === "cameraOnly"; + + return ( + + ); +} diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/SystemAudio.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/SystemAudio.tsx index 40602015f26..61559798778 100644 --- a/apps/desktop/src/routes/(window-chrome)/new-main/SystemAudio.tsx +++ b/apps/desktop/src/routes/(window-chrome)/new-main/SystemAudio.tsx @@ -1,4 +1,5 @@ import { createQuery } from "@tanstack/solid-query"; +import { CheckMenuItem, Menu } from "@tauri-apps/api/menu"; import { cx } from "cva"; import type { Component, ComponentProps, JSX } from "solid-js"; import { Dynamic } from "solid-js/web"; @@ -7,6 +8,7 @@ import { createCurrentRecordingQuery, isSystemAudioSupported, } from "~/utils/queries"; +import type { AudioCaptureSource } from "~/utils/tauri"; import { useRecordingOptions } from "../OptionsContext"; import { DEVICE_ROW_CLASS, @@ -44,6 +46,46 @@ export function SystemAudioToggleRoot( const isDisabled = () => !!currentRecording.data || systemAudioSupported.data === false; + const audioSource = () => rawOptions.audioSource ?? "none"; + const applicationAvailable = () => + rawOptions.captureTarget.variant === "window"; + const sourceLabel = () => { + switch (audioSource()) { + case "system": + return "System audio"; + case "application": + return "Selected application"; + default: + return "No audio"; + } + }; + const selectSource = (source: AudioCaptureSource) => { + setOptions({ audioSource: source }); + }; + const openMenu = async () => { + if (!rawOptions || isDisabled()) return; + const menu = await Menu.new({ + items: [ + await CheckMenuItem.new({ + text: "None", + checked: audioSource() === "none", + action: () => selectSource("none"), + }), + await CheckMenuItem.new({ + text: "System audio", + checked: audioSource() === "system", + action: () => selectSource("system"), + }), + await CheckMenuItem.new({ + text: "Selected application", + checked: audioSource() === "application", + enabled: applicationAvailable(), + action: () => selectSource("application"), + }), + ], + }); + await menu.popup(); + }; const tooltipMessage = () => { if (systemAudioSupported.data === false) { return "System audio capture requires macOS 13.0 or later"; @@ -56,25 +98,18 @@ export function SystemAudioToggleRoot( {...props} type="button" title={tooltipMessage()} - onClick={() => { - if (!rawOptions || isDisabled()) return; - setOptions({ captureSystemAudio: !rawOptions.captureSystemAudio }); - }} + onClick={() => void openMenu()} disabled={isDisabled()} - aria-pressed={rawOptions.captureSystemAudio ? "true" : "false"} + aria-haspopup="menu" > {props.icon} -

- {rawOptions.captureSystemAudio - ? "Record System Audio" - : "No System Audio"} -

+

{sourceLabel()}

- {rawOptions.captureSystemAudio ? "On" : "Off"} + {audioSource() === "none" ? "Off" : "On"}
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx index b0981c60573..17b4f136d3c 100644 --- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx +++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx @@ -118,6 +118,7 @@ import { } from "../OptionsContext"; import CameraSelect from "./CameraSelect"; import ChangelogButton from "./ChangeLogButton"; +import CursorVisibility from "./CursorVisibility"; import MicrophoneSelect from "./MicrophoneSelect"; import ModeInfoPanel from "./ModeInfoPanel"; import SystemAudio from "./SystemAudio"; @@ -2674,7 +2675,7 @@ function Page() { "captureTarget", reconcile({ variant: "cameraOnly" } as ScreenCaptureTarget), ); - setOptions("captureSystemAudio", false); + setOptions("audioSource", "none"); } await commands.openTargetSelectOverlays( null, @@ -2865,6 +2866,9 @@ function Page() {
+
+ +
); diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsx index bf7816745e6..5e4551fb68d 100644 --- a/apps/desktop/src/routes/target-select-overlay.tsx +++ b/apps/desktop/src/routes/target-select-overlay.tsx @@ -339,7 +339,7 @@ function Inner() { "captureTarget", reconcile({ variant: "cameraOnly" } as ScreenCaptureTarget), ); - setOptions("captureSystemAudio", false); + setOptions("audioSource", "none"); getCameraWindow().then((win) => { if (win) win.close(); }); @@ -1950,7 +1950,8 @@ function RecordingControls(props: { selectedMicrophone: selectedMicName(), camera: rawOptions.cameraID, cameraAvailable: selectedCamera() !== null, - systemAudio: rawOptions.captureSystemAudio, + audioSource: rawOptions.audioSource ?? "none", + showCursor: rawOptions.showCursor !== false, targetModeSource: rawOptions.targetModeSource, organizationId: rawOptions.organizationId, }), @@ -2074,7 +2075,8 @@ function RecordingControls(props: { .startRecording({ capture_target: target, mode: rawOptions.mode, - capture_system_audio: rawOptions.captureSystemAudio, + audio_source: rawOptions.audioSource ?? "none", + show_cursor: rawOptions.showCursor !== false, }) .then((action) => { // On success the backend closes the overlay windows; the diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.ts index 205741c9eb3..565f37375f9 100644 --- a/apps/desktop/src/store.ts +++ b/apps/desktop/src/store.ts @@ -139,7 +139,8 @@ export const recordingSettingsStore = declareStore( micName: null, cameraId: null, mode: "instant", - systemAudio: false, + audioSource: "none", + showCursor: true, organizationId: null, cameraDeviceSettings: {}, microphoneDeviceSettings: {}, diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts index 70fa5ce0e58..7e5edcd4dbc 100644 --- a/apps/desktop/src/utils/queries.ts +++ b/apps/desktop/src/utils/queries.ts @@ -18,6 +18,7 @@ import { import { createQueryInvalidate } from "./events"; import { type CameraInfo, + type AudioCaptureSource, commands, type DeviceOrModelID, type RecordingMode, @@ -190,7 +191,8 @@ export function createOptionsQuery() { captureTarget: CameraCaptureTarget; micName: string | null; mode: RecordingMode; - captureSystemAudio?: boolean; + audioSource?: AudioCaptureSource; + showCursor?: boolean; targetMode?: ExtendedRecordingTargetMode; targetModeSource?: RecordingTargetModeSource; targetModeDismissal?: TargetModeDismissal | null; @@ -203,6 +205,8 @@ export function createOptionsQuery() { micName: null, cameraLabel: null, mode: "studio", + audioSource: "none", + showCursor: true, organizationId: null, }); @@ -259,8 +263,11 @@ export function createOptionsQuery() { if (data?.mode && data.mode !== _state.mode) { _setState("mode", data.mode); } - if (data?.systemAudio !== undefined) { - _setState("captureSystemAudio", data.systemAudio); + if (data?.audioSource !== undefined) { + _setState("audioSource", data.audioSource); + } + if (data?.showCursor !== undefined) { + _setState("showCursor", data.showCursor); } if (data?.organizationId !== undefined) { _setState("organizationId", data.organizationId); @@ -275,7 +282,8 @@ export function createOptionsQuery() { micName: _state.micName, cameraId: _state.cameraID, mode: _state.mode, - systemAudio: _state.captureSystemAudio, + audioSource: _state.audioSource ?? "none", + showCursor: _state.showCursor !== false, organizationId: _state.organizationId, }; @@ -297,6 +305,14 @@ export function createOptionsQuery() { if (state.cameraID !== undefined && !isStoredCameraId(state.cameraID)) { setState("cameraID", null); } + createEffect(() => { + if ( + state.audioSource === "application" && + state.captureTarget.variant !== "window" + ) { + setState("audioSource", "none"); + } + }); const setOptions = new Proxy(setState, { apply(target, thisArg, args) { diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml index 3cd5ce44fdb..03c3c416cae 100644 --- a/crates/recording/Cargo.toml +++ b/crates/recording/Cargo.toml @@ -100,6 +100,9 @@ cap-camera-windows = { path = "../camera-windows" } scap-direct3d = { path = "../scap-direct3d" } scap-cpal = { path = "../scap-cpal" } +[target.'cfg(target_os = "windows")'.build-dependencies] +cc = "1.2" + [target.'cfg(target_os = "linux")'.dependencies] ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] } pipewire = "0.10.0" diff --git a/crates/recording/build.rs b/crates/recording/build.rs new file mode 100644 index 00000000000..6474bd642d2 --- /dev/null +++ b/crates/recording/build.rs @@ -0,0 +1,8 @@ +fn main() { + #[cfg(windows)] + cc::Build::new() + .cpp(true) + .file("src/sources/screen_capture/process_loopback.cpp") + .flag_if_supported("/std:c++17") + .compile("cap_process_loopback"); +} diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs index 759025f1f01..7156683fd21 100644 --- a/crates/recording/src/instant_recording.rs +++ b/crates/recording/src/instant_recording.rs @@ -846,7 +846,8 @@ impl Actor { pub struct ActorBuilder { output_path: PathBuf, capture_target: ScreenCaptureTarget, - system_audio: bool, + audio_source: crate::screen_capture::AudioCaptureSource, + show_cursor: bool, mic_feed: Option>, camera_feed: Option>, #[cfg(target_os = "linux")] @@ -871,7 +872,8 @@ impl ActorBuilder { Self { output_path: output, capture_target, - system_audio: false, + audio_source: crate::screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, #[cfg(target_os = "linux")] @@ -905,7 +907,24 @@ impl ActorBuilder { } pub fn with_system_audio(mut self, system_audio: bool) -> Self { - self.system_audio = system_audio; + self.audio_source = if system_audio { + crate::screen_capture::AudioCaptureSource::System + } else { + crate::screen_capture::AudioCaptureSource::None + }; + self + } + + pub fn with_audio_source( + mut self, + audio_source: crate::screen_capture::AudioCaptureSource, + ) -> Self { + self.audio_source = audio_source; + self + } + + pub fn with_show_cursor(mut self, show_cursor: bool) -> Self { + self.show_cursor = show_cursor; self } @@ -973,7 +992,8 @@ impl ActorBuilder { self.output_path, RecordingBaseInputs { capture_target: self.capture_target, - capture_system_audio: self.system_audio, + audio_source: self.audio_source, + show_cursor: self.show_cursor, mic_feed: self.mic_feed, camera_feed: self.camera_feed, start_gate: self.start_gate, @@ -1140,7 +1160,7 @@ async fn build_instant_recording_actor( cap_utils::operation_diagnostics::resource_id(&recording_dir), ), Field::number("requested_fps", max_fps as u64), - Field::flag("system_audio", inputs.capture_system_audio), + Field::label("audio_source", inputs.audio_source.as_str()), Field::flag("microphone", inputs.mic_feed.is_some()), Field::flag("camera", inputs.camera_feed.is_some()), ], @@ -1175,8 +1195,8 @@ async fn build_instant_recording_actor( #[cfg(target_os = "linux")] anyhow::ensure!( !matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly) - || !inputs.capture_system_audio, - "System audio is not supported for Linux Instant CameraOnly recordings. Disable system audio or choose a screen target." + || !inputs.audio_source.is_enabled(), + "Audio capture is not supported for Linux Instant CameraOnly recordings. Disable audio capture or choose a screen target." ); #[cfg(target_os = "linux")] let LinuxCameraConfig { @@ -1325,13 +1345,14 @@ async fn build_instant_recording_actor( let max_capture_size = None; let screen_source = ScreenCaptureConfig::::init( + inputs.capture_target.clone(), display, crop_bounds, - true, + inputs.show_cursor, max_fps, max_capture_size, timestamps.system_time(), - inputs.capture_system_audio, + inputs.audio_source, #[cfg(target_os = "linux")] crate::sources::screen_capture::LinuxCaptureSource::from_target( &inputs.capture_target, diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs index a7dcbbcc4c9..634a3760fa6 100644 --- a/crates/recording/src/lib.rs +++ b/crates/recording/src/lib.rs @@ -48,7 +48,10 @@ use serde::{Deserialize, Serialize}; use std::sync::Arc; use thiserror::Error; -use crate::{feeds::camera::CameraFeedLock, sources::screen_capture::ScreenCaptureTarget}; +use crate::{ + feeds::camera::CameraFeedLock, + sources::screen_capture::{AudioCaptureSource, ScreenCaptureTarget}, +}; #[derive(specta::Type, Serialize, Deserialize, Clone, Debug, Copy, Default, PartialEq, Eq)] #[serde(rename_all = "camelCase")] @@ -82,7 +85,8 @@ pub struct RecordingOptions { #[derive(Clone)] pub struct RecordingBaseInputs { pub capture_target: ScreenCaptureTarget, - pub capture_system_audio: bool, + pub audio_source: AudioCaptureSource, + pub show_cursor: bool, pub mic_feed: Option>, pub camera_feed: Option>, #[cfg(target_os = "macos")] diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rs index e1e792a5f9e..0a826cc1972 100644 --- a/crates/recording/src/sources/screen_capture/linux.rs +++ b/crates/recording/src/sources/screen_capture/linux.rs @@ -17,10 +17,11 @@ use kameo::{Actor as _, actor::ActorRef}; use pipewire as pw; use pw::{properties::properties, spa}; use std::{ + collections::{HashMap, HashSet}, os::fd::OwnedFd, process::Command, sync::{ - Arc, + Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}, }, time::{Duration, Instant}, @@ -34,6 +35,14 @@ use x11rb::protocol::xproto::{ }; use x11rb::rust_connection::RustConnection; +fn pactl_command() -> Command { + let bundled = std::env::current_exe() + .ok() + .and_then(|executable| executable.parent().map(|parent| parent.join("pactl"))) + .filter(|path| path.is_file()); + Command::new(bundled.unwrap_or_else(|| "pactl".into())) +} + #[derive(Debug)] pub struct X11Capture; @@ -165,10 +174,17 @@ impl ScreenCaptureConfig { }), } }; - let system_audio = if self.system_audio { - Some(create_system_audio_source_config().await?) - } else { - None + let system_audio = match self.audio_source { + AudioCaptureSource::None => None, + AudioCaptureSource::System => Some(create_system_audio_source_config().await?), + AudioCaptureSource::Application => { + let process_id = self.config.target.application_pid().ok_or_else(|| { + anyhow!( + "Application audio requires an X11 window with an owning process; the Wayland portal does not expose process identity" + ) + })?; + Some(create_application_audio_source_config(process_id).await?) + } }; Ok((source, system_audio)) @@ -902,12 +918,14 @@ pub struct SystemAudioSourceConfig { feed_lock: Arc, device_name: String, monitor_route: Option, + application_route: Option>, feed: OwnedSystemAudioFeed, } pub struct SystemAudioSource { inner: crate::sources::Microphone, monitor_route: Option, + application_route: Option>, feed: OwnedSystemAudioFeed, } @@ -938,6 +956,7 @@ impl Drop for OwnedSystemAudioFeed { impl Drop for SystemAudioSource { fn drop(&mut self) { drop(self.monitor_route.take()); + drop(self.application_route.take()); } } @@ -981,6 +1000,300 @@ impl Drop for PactlMonitorRoute { } } +struct ApplicationAudioRouteState { + routed_inputs: HashMap, + playback_sink: Option, + loopback_module: Option, +} + +struct ApplicationAudioRoute { + process_id: u32, + sink_name: String, + sink_index: u32, + null_sink_module: u32, + state: Mutex, +} + +impl ApplicationAudioRoute { + fn create(process_id: u32) -> anyhow::Result { + let sink_name = format!( + "cap_application_{}_{}", + std::process::id(), + uuid::Uuid::new_v4().simple() + ); + let null_sink_module = load_pactl_module(&[ + "module-null-sink", + &format!("sink_name={sink_name}"), + "rate=48000", + "channels=2", + "sink_properties=device.description=Cap_Application_Audio", + ]) + .context("create isolated Linux application-audio sink")?; + let sink_index = wait_for_pactl_sink(&sink_name).inspect_err(|_| { + let _ = unload_pactl_module(null_sink_module); + })?; + + Ok(Self { + process_id, + sink_name, + sink_index, + null_sink_module, + state: Mutex::new(ApplicationAudioRouteState { + routed_inputs: HashMap::new(), + playback_sink: None, + loopback_module: None, + }), + }) + } + + fn monitor_source(&self) -> String { + format!("{}.monitor", self.sink_name) + } + + fn reconcile(&self) -> anyhow::Result<()> { + let process_ids = process_tree_ids(self.process_id)?; + let inputs = pactl_sink_inputs()?; + let mut state = self + .state + .lock() + .map_err(|_| anyhow!("Application audio route state lock poisoned"))?; + + let active_ids = inputs.iter().map(|input| input.id).collect::>(); + let restore = state + .routed_inputs + .iter() + .filter_map(|(id, original_sink)| { + inputs + .iter() + .find(|input| input.id == *id) + .filter(|input| { + !input + .process_id + .is_some_and(|pid| process_ids.contains(&pid)) + }) + .map(|_| (*id, *original_sink)) + }) + .collect::>(); + for (id, original_sink) in restore { + move_pactl_sink_input(id, original_sink)?; + state.routed_inputs.remove(&id); + } + state.routed_inputs.retain(|id, _| active_ids.contains(id)); + if state.routed_inputs.is_empty() + && let Some(loopback_module) = state.loopback_module + { + unload_pactl_module(loopback_module)?; + state.loopback_module = None; + state.playback_sink = None; + } + + for input in inputs { + if state.routed_inputs.contains_key(&input.id) + || !input + .process_id + .is_some_and(|pid| process_ids.contains(&pid)) + { + continue; + } + if input.sink == self.sink_index { + continue; + } + + if let Some(playback_sink) = state.playback_sink { + anyhow::ensure!( + playback_sink == input.sink, + "Selected application is playing through multiple Linux audio outputs; isolated capture cannot preserve playback routing safely" + ); + } else { + let loopback_module = load_pactl_module(&[ + "module-loopback", + &format!("source={}.monitor", self.sink_name), + &format!("sink={}", input.sink), + "latency_msec=20", + "source_dont_move=true", + "sink_dont_move=true", + ]) + .context("preserve application playback while capturing its audio")?; + state.playback_sink = Some(input.sink); + state.loopback_module = Some(loopback_module); + } + + move_pactl_sink_input(input.id, self.sink_index)?; + state.routed_inputs.insert(input.id, input.sink); + } + + Ok(()) + } +} + +impl Drop for ApplicationAudioRoute { + fn drop(&mut self) { + let Ok(mut state) = self.state.lock() else { + tracing::warn!("Could not lock Linux application-audio routes during cleanup"); + return; + }; + for (input, original_sink) in state.routed_inputs.drain() { + if let Err(error) = move_pactl_sink_input(input, original_sink) { + tracing::warn!(%error, input, "Could not restore application audio stream"); + } + } + if let Some(module) = state.loopback_module.take() + && let Err(error) = unload_pactl_module(module) + { + tracing::warn!(%error, "Could not unload application audio playback loopback"); + } + if let Err(error) = unload_pactl_module(self.null_sink_module) { + tracing::warn!(%error, "Could not unload application audio capture sink"); + } + } +} + +struct PactlSinkInput { + id: u32, + sink: u32, + process_id: Option, +} + +fn pactl_sink_inputs() -> anyhow::Result> { + let output = pactl_command() + .args(["-f", "json", "list", "sink-inputs"]) + .output() + .context("list Linux application playback streams")?; + anyhow::ensure!( + output.status.success(), + "Could not inspect Linux application playback streams" + ); + parse_pactl_sink_inputs(&output.stdout) +} + +fn parse_pactl_sink_inputs(output: &[u8]) -> anyhow::Result> { + let inputs: Vec = + serde_json::from_slice(output).context("parse Linux playback streams")?; + inputs + .into_iter() + .map(|input| { + let id = input["index"] + .as_u64() + .and_then(|value| u32::try_from(value).ok()) + .ok_or_else(|| anyhow!("Linux playback stream has an invalid index"))?; + let sink = input["sink"] + .as_u64() + .and_then(|value| u32::try_from(value).ok()) + .ok_or_else(|| anyhow!("Linux playback stream has an invalid sink"))?; + let process_id = input["properties"]["application.process.id"] + .as_str() + .and_then(|value| value.parse().ok()); + Ok(PactlSinkInput { + id, + sink, + process_id, + }) + }) + .collect() +} + +fn process_tree_ids(root: u32) -> anyhow::Result> { + let mut parents = HashMap::new(); + for entry in std::fs::read_dir("/proc").context("inspect Linux process tree")? { + let entry = entry?; + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + let Ok(process_id) = name.parse::() else { + continue; + }; + let Ok(status) = std::fs::read_to_string(entry.path().join("status")) else { + continue; + }; + let parent = status.lines().find_map(|line| { + line.strip_prefix("PPid:") + .and_then(|value| value.trim().parse::().ok()) + }); + if let Some(parent) = parent { + parents.insert(process_id, parent); + } + } + + let mut tree = HashSet::from([root]); + loop { + let before = tree.len(); + for (process_id, parent) in &parents { + if tree.contains(parent) { + tree.insert(*process_id); + } + } + if tree.len() == before { + break; + } + } + Ok(tree) +} + +fn load_pactl_module(arguments: &[&str]) -> anyhow::Result { + let output = pactl_command() + .arg("load-module") + .args(arguments) + .output() + .context("load PulseAudio/PipeWire compatibility module")?; + anyhow::ensure!( + output.status.success(), + "PulseAudio/PipeWire rejected module '{}': {}", + arguments.first().copied().unwrap_or_default(), + String::from_utf8_lossy(&output.stderr).trim() + ); + String::from_utf8_lossy(&output.stdout) + .trim() + .parse() + .context("parse PulseAudio/PipeWire module id") +} + +fn unload_pactl_module(module: u32) -> anyhow::Result<()> { + let status = pactl_command() + .args(["unload-module", &module.to_string()]) + .status() + .context("unload PulseAudio/PipeWire compatibility module")?; + anyhow::ensure!( + status.success(), + "Could not unload Linux audio module {module}" + ); + Ok(()) +} + +fn wait_for_pactl_sink(name: &str) -> anyhow::Result { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(3) { + let output = pactl_command() + .args(["list", "short", "sinks"]) + .output() + .context("find isolated Linux application-audio sink")?; + if output.status.success() + && let Some(index) = String::from_utf8_lossy(&output.stdout) + .lines() + .find_map(|line| { + let mut fields = line.split_whitespace(); + let index = fields.next()?.parse::().ok()?; + (fields.next()? == name).then_some(index) + }) + { + return Ok(index); + } + std::thread::sleep(Duration::from_millis(20)); + } + bail!("Isolated Linux application-audio sink did not appear within three seconds") +} + +fn move_pactl_sink_input(input: u32, sink: u32) -> anyhow::Result<()> { + let status = pactl_command() + .args(["move-sink-input", &input.to_string(), &sink.to_string()]) + .status() + .context("route Linux application playback stream")?; + anyhow::ensure!( + status.success(), + "Could not route Linux application playback stream {input}" + ); + Ok(()) +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum PulseInputRole { #[default] @@ -1207,7 +1520,7 @@ impl PulseInputRoute { return Ok(None); } let default_sink = pactl_default_sink(); - let sources = Command::new("pactl") + let sources = pactl_command() .args(["list", "short", "sources"]) .output() .context("inspect the default PulseAudio/PipeWire input")?; @@ -1340,6 +1653,17 @@ impl AudioSource for SystemAudioSource { { let device_name = config.device_name.clone(); let setup = ::setup(config.feed_lock, tx, ctx); + if let Some(route) = config.application_route.clone() { + let cancel = ctx.stop_token().child_token(); + ctx.tasks() + .spawn_thread("application-audio-route-watcher", move || { + while !cancel.is_cancelled() { + route.reconcile()?; + std::thread::sleep(Duration::from_millis(250)); + } + Ok(()) + }); + } async move { let inner = setup .await @@ -1352,6 +1676,7 @@ impl AudioSource for SystemAudioSource { Ok(Self { inner, monitor_route: config.monitor_route, + application_route: config.application_route, feed: config.feed, }) } @@ -1363,6 +1688,7 @@ impl AudioSource for SystemAudioSource { async fn stop(&mut self) -> anyhow::Result<()> { drop(self.monitor_route.take()); + drop(self.application_route.take()); self.inner.stop().await?; self.feed.actor.kill(); self.feed.actor.wait_for_stop().await; @@ -1435,6 +1761,88 @@ async fn create_system_audio_source_config() -> anyhow::Result anyhow::Result { + let application_route = Arc::new(ApplicationAudioRoute::create(process_id)?); + let devices = MicrophoneFeed::list(); + let available = devices.keys().cloned().collect::>(); + let device_name = pulse_cpal_device_name(&available).ok_or_else(|| { + anyhow!( + "Linux application audio requires a PulseAudio/PipeWire-compatible CPAL input. Available input devices: {available:?}" + ) + })?; + let sources = pactl_command() + .args(["list", "short", "sources"]) + .output() + .context("inspect Linux application-audio monitor source")?; + anyhow::ensure!( + sources.status.success(), + "Could not inspect Linux application-audio monitor source" + ); + let monitor_source = application_route.monitor_source(); + let monitor_source_index = + pactl_source_index(&String::from_utf8_lossy(&sources.stdout), &monitor_source) + .ok_or_else(|| anyhow!("Linux application-audio monitor source did not appear"))?; + let default_source = pactl_default_source(); + let default_source_index = default_source + .as_deref() + .and_then(|source| pactl_source_index(&String::from_utf8_lossy(&sources.stdout), source)); + let previous_process_source_outputs = current_process_source_outputs()?; + + let (error_tx, _error_rx) = flume::bounded(16); + let feed = MicrophoneFeed::spawn(MicrophoneFeed::new_system_audio(error_tx)); + let owned_feed = OwnedSystemAudioFeed { + actor: feed.clone(), + build_scope: crate::output_pipeline::PipelineBuildScope::current(), + stopped: false, + }; + feed.ask(microphone::SetInput { + label: device_name.clone(), + settings: None, + }) + .await + .map_err(|error| anyhow!("Failed to set Linux application-audio input: {error}"))? + .await + .with_context(|| format!("Linux application-audio input '{device_name}' failed to connect"))?; + tokio::time::sleep(Duration::from_millis(100)).await; + + let source_output = newly_created_source_output( + &previous_process_source_outputs, + ¤t_process_source_outputs()?, + )?; + let original_source = current_process_source_outputs()? + .into_iter() + .find(|output| output.id == source_output) + .ok_or_else(|| anyhow!("Linux application-audio capture stream disappeared"))? + .source; + let monitor_route = PactlMonitorRoute { + monitor_source, + monitor_source_index, + default_source, + default_source_index, + source_output, + original_source, + previous_process_source_outputs, + }; + apply_pactl_monitor_route(&monitor_route)?; + application_route.reconcile()?; + + let lock = feed + .ask(microphone::Lock) + .await + .map_err(|error| anyhow!("Failed to lock Linux application-audio input: {error}"))?; + + Ok(SystemAudioSourceConfig { + feed_lock: Arc::new(lock), + device_name, + monitor_route: Some(monitor_route), + application_route: Some(application_route), feed: owned_feed, }) } @@ -1644,10 +2052,7 @@ fn system_audio_device_rank(name: &str) -> Option { fn select_pactl_monitor_source( available_devices: &[String], ) -> anyhow::Result> { - let output = match Command::new("pactl") - .args(["list", "short", "sources"]) - .output() - { + let output = match pactl_command().args(["list", "short", "sources"]).output() { Ok(output) if output.status.success() => output, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { return Err(anyhow!( @@ -1725,7 +2130,7 @@ fn previous_source_destination( } fn current_process_source_outputs() -> anyhow::Result> { - let output = Command::new("pactl") + let output = pactl_command() .args(["-f", "json", "list", "source-outputs"]) .output() .context("list PulseAudio/PipeWire source outputs")?; @@ -1793,7 +2198,7 @@ fn move_pactl_source_output(source_output: u32, source: &str) -> anyhow::Result< let source_index = match source.parse::() { Ok(index) => index, Err(_) => { - let sources = Command::new("pactl") + let sources = pactl_command() .args(["list", "short", "sources"]) .output() .context("resolve PulseAudio/PipeWire routing destination")?; @@ -1805,7 +2210,7 @@ fn move_pactl_source_output(source_output: u32, source: &str) -> anyhow::Result< )? } }; - let status = Command::new("pactl") + let status = pactl_command() .args(["move-source-output", &source_output.to_string(), source]) .status() .context("move PulseAudio/PipeWire system-audio stream")?; @@ -1892,7 +2297,7 @@ fn pactl_default_source() -> Option { } fn pactl_default_device(command: &str) -> Option { - let output = Command::new("pactl").arg(command).output().ok()?; + let output = pactl_command().arg(command).output().ok()?; output .status @@ -2436,7 +2841,8 @@ fn x11_source_pixel( mod system_audio_tests { use super::{ OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, newly_created_source_output, - pactl_monitor_preference, pactl_source_index, preferred_system_audio_device, + pactl_monitor_preference, pactl_source_index, parse_pactl_sink_inputs, + preferred_system_audio_device, previous_source_destination, process_source_output_ids, pulse_input_route_destination, retry_system_audio_connection, source_output_needs_move, source_output_route_matches, started_input_source_output, uses_default_pulse_input, wait_for_audio_after_route, @@ -2444,6 +2850,19 @@ mod system_audio_tests { }; use tokio_util::sync::CancellationToken; + #[test] + fn application_audio_reads_sink_and_process_identity_from_pactl_json() { + let inputs = parse_pactl_sink_inputs( + br#"[{"index":17,"sink":4,"properties":{"application.process.id":"812"}}]"#, + ) + .unwrap(); + + assert_eq!(inputs.len(), 1); + assert_eq!(inputs[0].id, 17); + assert_eq!(inputs[0].sink, 4); + assert_eq!(inputs[0].process_id, Some(812)); + } + #[test] fn cancelled_system_route_does_not_probe_or_publish_a_stream() { let cancel = CancellationToken::new(); diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs index 66972d65eb4..c7609033a7e 100644 --- a/crates/recording/src/sources/screen_capture/macos.rs +++ b/crates/recording/src/sources/screen_capture/macos.rs @@ -178,6 +178,98 @@ pub enum SourceError { NoDisplay(DisplayId), #[error("AsContentFilter")] AsContentFilter, + #[error("NoWindow: Id '{0}'")] + NoWindow(WindowId), +} + +fn content_filter_for_target( + target: &ScreenCaptureTarget, + content: arc::R, + excluded_windows: &[WindowId], + capture_phase: &'static str, +) -> Result, SourceError> { + match target { + ScreenCaptureTarget::Window { id } => { + let window = Window::from_id(id).ok_or_else(|| SourceError::NoWindow(id.clone()))?; + let sc_window = window + .raw_handle() + .as_sc(content) + .ok_or_else(|| SourceError::NoWindow(id.clone()))?; + Ok(sc::ContentFilter::with_desktop_independent_window( + sc_window.as_ref(), + )) + } + ScreenCaptureTarget::Display { id } | ScreenCaptureTarget::Area { screen: id, .. } => { + let display = Display::from_id(id).ok_or_else(|| SourceError::NoDisplay(id.clone()))?; + let excluded_sc_windows = + excluded_shareable_windows(excluded_windows, &content, capture_phase); + display + .raw_handle() + .as_content_filter_excluding_windows(content, excluded_sc_windows) + .ok_or(SourceError::AsContentFilter) + } + ScreenCaptureTarget::CameraOnly => Err(SourceError::AsContentFilter), + } +} + +fn forward_audio_sample_buffer( + sample_buffer: &cm::SampleBuf, + audio_tx: &mut mpsc::Sender, + frame_counter: &AtomicU64, + drop_counter: &AtomicU64, + stall_health_tx: &output_pipeline::HealthSender, + source_label: &'static str, +) { + use ffmpeg::ChannelLayout; + + let Ok(buf_list) = sample_buffer.audio_buf_list::<2>() else { + warn!("Failed to extract audio buffer list from sample, dropping audio chunk"); + return; + }; + let Ok(slice) = buf_list.block().as_slice() else { + warn!("Failed to get audio buffer slice, dropping audio chunk"); + return; + }; + + let mut frame = ffmpeg::frame::Audio::new( + ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar), + sample_buffer.num_samples() as usize, + ChannelLayout::STEREO, + ); + frame.set_rate(48_000); + let data_bytes_size = buf_list.list().buffers[0].data_bytes_size as usize; + for i in 0..frame.planes() { + let start = i.saturating_mul(data_bytes_size); + let end = start.saturating_add(data_bytes_size); + let Some(source) = slice.get(start..end) else { + warn!("Audio buffer slice too small for plane data, dropping audio chunk"); + return; + }; + let destination = frame.data_mut(i); + if destination.len() != source.len() { + warn!("Audio frame plane size mismatch, dropping audio chunk"); + return; + } + destination.copy_from_slice(source); + } + + let mach_timestamp = cm::Clock::convert_host_time_to_sys_units(sample_buffer.pts()); + let timestamp = + Timestamp::MachAbsoluteTime(cap_timestamp::MachAbsoluteTimestamp::new(mach_timestamp)); + match output_pipeline::send_with_stall_budget_futures( + audio_tx, + AudioFrame::new(frame, timestamp), + source_label, + stall_health_tx, + ) { + output_pipeline::StallSendOutcome::Sent => { + frame_counter.fetch_add(1, atomic::Ordering::Relaxed); + } + output_pipeline::StallSendOutcome::StalledAndDropped { .. } + | output_pipeline::StallSendOutcome::Disconnected => { + drop_counter.fetch_add(1, atomic::Ordering::Relaxed); + } + } } pub struct VideoFrame { @@ -207,7 +299,15 @@ impl ScreenCaptureConfig { debug!(buffer_size = buffer_size, "Screen capture buffer size"); let (video_tx, video_rx) = flume::bounded(buffer_size); let drop_counter: Arc = Arc::new(AtomicU64::new(0)); - let (mut audio_tx, audio_rx) = if self.system_audio { + let separate_system_audio = matches!( + (&self.audio_source, &self.config.target), + ( + AudioCaptureSource::System, + ScreenCaptureTarget::Window { .. } + ) + ); + let captures_audio = self.audio_source.is_enabled() && !separate_system_audio; + let (audio_tx, audio_rx) = if self.audio_source.is_enabled() { let (tx, rx) = mpsc::channel(128); (Some(tx), Some(rx)) } else { @@ -216,19 +316,12 @@ impl ScreenCaptureConfig { let system_audio_drop_counter: Arc = Arc::new(AtomicU64::new(0)); let system_audio_frame_counter: Arc = Arc::new(AtomicU64::new(0)); - let display = Display::from_id(&self.config.display) - .ok_or_else(|| SourceError::NoDisplay(self.config.display.clone()))?; - - let excluded_sc_windows = - excluded_shareable_windows(&self.excluded_windows, &self.shareable_content, "initial"); - - let content_filter = display - .raw_handle() - .as_content_filter_excluding_windows( - self.shareable_content.clone(), - excluded_sc_windows, - ) - .ok_or(SourceError::AsContentFilter)?; + let content_filter = content_filter_for_target( + &self.config.target, + self.shareable_content.clone(), + &self.excluded_windows, + "initial", + )?; debug!("SCK content filter: {:?}", content_filter); @@ -250,14 +343,16 @@ impl ScreenCaptureConfig { .with_height(size.height() as usize) .with_fps(self.config.fps as f32) .with_shows_cursor(self.config.show_cursor) - .with_captures_audio(self.system_audio) + .with_captures_audio(captures_audio) .with_queue_depth(queue_depth) .build(); settings.set_pixel_format(cv::PixelFormat::_420V); settings.set_color_space_name(cg::color_space::names::srgb()); - if let Some(crop_bounds) = self.config.crop_bounds { + if matches!(self.config.target, ScreenCaptureTarget::Area { .. }) + && let Some(crop_bounds) = self.config.crop_bounds + { debug!("crop bounds: {:?}", crop_bounds); settings.set_src_rect(cg::Rect::new( crop_bounds.position().x(), @@ -283,9 +378,9 @@ impl ScreenCaptureConfig { tokio::sync::mpsc::channel::(32); let rebuild_params = Arc::new(CapturerRebuildParams { - display_id: self.config.display.clone(), + target: self.config.target.clone(), config: self.config.clone(), - system_audio: self.system_audio, + system_audio: captures_audio, excluded_windows: self.excluded_windows.clone(), video_info: self.video_info, video_tx: video_tx.clone(), @@ -301,6 +396,11 @@ impl ScreenCaptureConfig { stall_health_tx: stall_health_tx.clone(), }); + let mut video_audio_tx = if captures_audio { + audio_tx.clone() + } else { + None + }; let builder = scap_screencapturekit::Capturer::builder(content_filter, settings) .with_output_sample_buf_cb({ let video_frame_count = video_frame_counter.clone(); @@ -412,62 +512,19 @@ impl ScreenCaptureConfig { } } scap_screencapturekit::Frame::Audio(_) => { - use ffmpeg::ChannelLayout; - cap_fail::fail_ret!("screen_capture audio frame skip"); - let Some(audio_tx) = &mut audio_tx else { - return; - }; - - let Ok(buf_list) = sample_buffer.audio_buf_list::<2>() else { - warn!("Failed to extract audio buffer list from sample, dropping audio chunk"); + let Some(audio_tx) = &mut video_audio_tx else { return; }; - let Ok(slice) = buf_list.block().as_slice() else { - warn!("Failed to get audio buffer slice, dropping audio chunk"); - return; - }; - - let mut frame = ffmpeg::frame::Audio::new( - ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar), - sample_buffer.num_samples() as usize, - ChannelLayout::STEREO, - ); - frame.set_rate(48_000); - let data_bytes_size = - buf_list.list().buffers[0].data_bytes_size as usize; - for i in 0..frame.planes() { - let start = i.saturating_mul(data_bytes_size); - let end = start.saturating_add(data_bytes_size); - let Some(source) = slice.get(start..end) else { - warn!("Audio buffer slice too small for plane data, dropping audio chunk"); - return; - }; - let destination = frame.data_mut(i); - if destination.len() != source.len() { - warn!("Audio frame plane size mismatch, dropping audio chunk"); - return; - } - destination.copy_from_slice(source); - } - - match output_pipeline::send_with_stall_budget_futures( + forward_audio_sample_buffer( + sample_buffer, audio_tx, - AudioFrame::new(frame, timestamp), - "screen-system-audio", + &sys_audio_frame_counter, + &sys_audio_drop_counter, &stall_health_tx, - ) { - output_pipeline::StallSendOutcome::Sent => { - sys_audio_frame_counter - .fetch_add(1, atomic::Ordering::Relaxed); - } - output_pipeline::StallSendOutcome::StalledAndDropped { .. } - | output_pipeline::StallSendOutcome::Disconnected => { - sys_audio_drop_counter - .fetch_add(1, atomic::Ordering::Relaxed); - } - } + "screen-system-audio", + ); } _ => {} } @@ -488,12 +545,61 @@ impl ScreenCaptureConfig { let cancel_token = CancellationToken::new(); let capturer = Capturer::new(Arc::new(builder.build()?)); + let video_error_rx = error_rx.resubscribe(); + let (system_audio_capturer, system_audio_error_rx, restart_managed) = + if separate_system_audio { + let display = + self.config.target.display().ok_or_else(|| { + anyhow!("Selected window is no longer attached to a display") + })?; + let system_audio_filter = content_filter_for_target( + &ScreenCaptureTarget::Display { id: display.id() }, + self.shareable_content.clone(), + &[], + "system-audio", + )?; + let audio_settings = scap_screencapturekit::StreamCfgBuilder::default() + .with_captures_audio(true) + .build(); + let (audio_error_tx, audio_error_rx) = broadcast::channel(1); + let mut separate_audio_tx = audio_tx + .clone() + .ok_or_else(|| anyhow!("System audio channel was not initialized"))?; + let audio_frame_counter = system_audio_frame_counter.clone(); + let audio_drop_counter = system_audio_drop_counter.clone(); + let audio_health_tx = stall_health_tx.clone(); + let audio_builder = + scap_screencapturekit::Capturer::builder(system_audio_filter, audio_settings) + .with_captures_screen(false) + .with_output_sample_buf_cb(move |frame| { + if let scap_screencapturekit::Frame::Audio(audio_frame) = frame { + forward_audio_sample_buffer( + audio_frame.sample_buf(), + &mut separate_audio_tx, + &audio_frame_counter, + &audio_drop_counter, + &audio_health_tx, + "screen-system-audio", + ); + } + }) + .with_stop_with_err_cb(move |_, err| { + let _ = audio_error_tx.send(err.retained()); + }); + ( + Capturer::new(Arc::new(audio_builder.build()?)), + audio_error_rx, + false, + ) + } else { + (capturer.clone(), error_rx, true) + }; Ok(( VideoSourceConfig { inner: ChannelVideoSourceConfig::new(self.video_info, video_rx), capturer: capturer.clone(), - error_rx: error_rx.resubscribe(), + error_rx: video_error_rx, video_frame_counter: video_frame_counter.clone(), drop_counter, cancel_token: cancel_token.clone(), @@ -504,11 +610,12 @@ impl ScreenCaptureConfig { audio_rx.map(|rx| { SystemAudioSourceConfig( ChannelAudioSourceConfig::new(self.audio_info(), rx), - capturer, - error_rx, + system_audio_capturer, + system_audio_error_rx, system_audio_frame_counter, system_audio_drop_counter, rebuild_params, + restart_managed, ) }), )) @@ -737,20 +844,20 @@ impl output_pipeline::VideoSource for VideoSource { break Ok(()); } - if Display::from_id(&rebuild_params.display_id).is_none() { + if !rebuild_params.target.is_available() { error!( - display_id = ?rebuild_params.display_id, - "Capture target display is gone; aborting restart" + target = rebuild_params.target.kind_str(), + "Capture target is gone; aborting restart" ); output_pipeline::emit_health( &health_tx, output_pipeline::PipelineHealthEvent::CaptureTargetLost { - target: "display".to_string(), + target: rebuild_params.target.kind_str().to_lowercase(), }, ); return Err(anyhow!( - "Capture target display disappeared: {:?}", - rebuild_params.display_id + "Capture target {} disappeared", + rebuild_params.target.kind_str() )); } @@ -919,7 +1026,7 @@ fn system_stop_message() -> &'static str { } struct CapturerRebuildParams { - display_id: DisplayId, + target: ScreenCaptureTarget, config: Config, system_audio: bool, excluded_windows: Vec, @@ -945,16 +1052,13 @@ async fn rebuild_capturer(params: &CapturerRebuildParams) -> anyhow::Result anyhow::Result, Arc, Arc, + bool, ); pub struct SystemAudioSource { @@ -1206,6 +1313,7 @@ impl output_pipeline::AudioSource for SystemAudioSource { frame_counter, drop_counter, _rebuild_params, + restart_managed, ) = config; let cancel_token = CancellationToken::new(); @@ -1235,6 +1343,9 @@ impl output_pipeline::AudioSource for SystemAudioSource { break; } if is_system_stop_error(err.as_ref()) { + if !restart_managed { + return Err(anyhow!(system_stop_message())); + } system_stop_count += 1; if system_stop_count > MAX_CAPTURE_RESTARTS { warn!("Screen capture audio stream stopped by the system (exhausted restarts)"); diff --git a/crates/recording/src/sources/screen_capture/mod.rs b/crates/recording/src/sources/screen_capture/mod.rs index 6a61479f0fd..8a86af4959e 100644 --- a/crates/recording/src/sources/screen_capture/mod.rs +++ b/crates/recording/src/sources/screen_capture/mod.rs @@ -72,6 +72,43 @@ pub enum ScreenCaptureTarget { CameraOnly, } +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum AudioCaptureSource { + #[default] + None, + System, + Application, +} + +impl AudioCaptureSource { + pub fn is_enabled(self) -> bool { + !matches!(self, Self::None) + } + + pub fn as_str(self) -> &'static str { + match self { + Self::None => "None", + Self::System => "System", + Self::Application => "Application", + } + } +} + +pub fn deserialize_audio_capture_source<'de, D>( + deserializer: D, +) -> Result +where + D: serde::Deserializer<'de>, +{ + let value = serde_json::Value::deserialize(deserializer)?; + match value { + serde_json::Value::Bool(true) => Ok(AudioCaptureSource::System), + serde_json::Value::Bool(false) | serde_json::Value::Null => Ok(AudioCaptureSource::None), + value => serde_json::from_value(value).map_err(serde::de::Error::custom), + } +} + #[cfg(target_os = "linux")] #[derive(Clone, Debug)] pub enum LinuxCaptureSource { @@ -92,6 +129,31 @@ impl LinuxCaptureSource { } impl ScreenCaptureTarget { + pub fn application_pid(&self) -> Option { + let Self::Window { id } = self else { + return None; + }; + let window = Window::from_id(id)?; + + #[cfg(target_os = "macos")] + { + u32::try_from(window.raw_handle().owner_pid()?).ok() + } + + #[cfg(any(windows, target_os = "linux"))] + { + window.raw_handle().owner_pid() + } + } + + pub fn is_available(&self) -> bool { + match self { + Self::Display { id } | Self::Area { screen: id, .. } => Display::from_id(id).is_some(), + Self::Window { id } => Window::from_id(id).is_some(), + Self::CameraOnly => true, + } + } + pub fn display(&self) -> Option { match self { Self::Display { id } => Display::from_id(id), @@ -290,7 +352,7 @@ pub struct ScreenCaptureConfig { config: Config, video_info: VideoInfo, start_time: SystemTime, - pub system_audio: bool, + pub audio_source: AudioCaptureSource, _phantom: std::marker::PhantomData, #[cfg(windows)] d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device, @@ -358,7 +420,7 @@ impl Clone for ScreenCaptureConfig Clone for ScreenCaptureConfig, fps: u32, @@ -457,18 +521,21 @@ pub enum ScreenCaptureInitError { NoWindow, #[error("Bounds")] NoBounds, + #[error("Application audio requires a window capture target")] + ApplicationAudioRequiresWindow, } impl ScreenCaptureConfig { #[allow(clippy::too_many_arguments)] pub async fn init( + target: ScreenCaptureTarget, display: scap_targets::Display, crop_bounds: Option, show_cursor: bool, max_fps: u32, max_capture_size: Option<(u32, u32)>, start_time: SystemTime, - system_audio: bool, + audio_source: AudioCaptureSource, #[cfg(target_os = "linux")] linux_source: LinuxCaptureSource, #[cfg(windows)] d3d_device: ::windows::Win32::Graphics::Direct3D11::ID3D11Device, #[cfg(target_os = "macos")] shareable_content: SendableShareableContent, @@ -476,6 +543,12 @@ impl ScreenCaptureConfig { ) -> Result { cap_fail::fail!("ScreenCaptureSource::init"); + if audio_source == AudioCaptureSource::Application + && !matches!(target, ScreenCaptureTarget::Window { .. }) + { + return Err(ScreenCaptureInitError::ApplicationAudioRequiresWindow); + } + let target_refresh = validated_refresh_rate(display.refresh_rate()); let fps = std::cmp::max(1, std::cmp::min(max_fps, target_refresh)); @@ -525,6 +598,8 @@ impl ScreenCaptureConfig { Ok(Self { config: Config { + target, + #[cfg(target_os = "linux")] display: display.id(), crop_bounds, fps, @@ -539,7 +614,7 @@ impl ScreenCaptureConfig { fps, ), start_time, - system_audio, + audio_source, _phantom: std::marker::PhantomData, #[cfg(windows)] d3d_device, @@ -714,6 +789,27 @@ fn list_windows_inner(_include_accessory_panels: bool) -> Vec<(CaptureWindow, Wi mod tests { use super::*; + #[derive(Deserialize)] + struct AudioPreference { + #[serde(deserialize_with = "deserialize_audio_capture_source")] + source: AudioCaptureSource, + } + + #[test] + fn audio_source_deserializes_enum_and_legacy_boolean() { + for (json, expected) in [ + (r#"{"source":false}"#, AudioCaptureSource::None), + (r#"{"source":true}"#, AudioCaptureSource::System), + ( + r#"{"source":"application"}"#, + AudioCaptureSource::Application, + ), + ] { + let preference: AudioPreference = serde_json::from_str(json).unwrap(); + assert_eq!(preference.source, expected); + } + } + #[test] #[cfg(target_os = "linux")] fn linux_window_source_preserves_selected_window_id() { diff --git a/crates/recording/src/sources/screen_capture/process_loopback.cpp b/crates/recording/src/sources/screen_capture/process_loopback.cpp new file mode 100644 index 00000000000..34789246abe --- /dev/null +++ b/crates/recording/src/sources/screen_capture/process_loopback.cpp @@ -0,0 +1,251 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#pragma comment(lib, "Mmdevapi.lib") +#pragma comment(lib, "Ole32.lib") +#pragma comment(lib, "WindowsApp.lib") + +using Microsoft::WRL::ClassicCom; +using Microsoft::WRL::ComPtr; +using Microsoft::WRL::FtmBase; +using Microsoft::WRL::Make; +using Microsoft::WRL::RuntimeClass; +using Microsoft::WRL::RuntimeClassFlags; + +using AudioCallback = void (*)(const float *, uint32_t, uint64_t, void *); + +class ProcessLoopbackCapture final + : public RuntimeClass, FtmBase, + IActivateAudioInterfaceCompletionHandler> { + public: + HRESULT RuntimeClassInitialize() { return S_OK; } + + HRESULT Start(DWORD process_id, AudioCallback callback, void *context) { + callback_ = callback; + context_ = context; + ready_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + activation_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + sample_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr); + stop_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!ready_event_ || !activation_event_ || !sample_event_ || !stop_event_) { + return HRESULT_FROM_WIN32(GetLastError()); + } + + ComPtr self(this); + thread_ = std::thread([self, process_id]() { self->Run(process_id); }); + DWORD wait = WaitForSingleObject(ready_event_, 10000); + if (wait != WAIT_OBJECT_0) { + return wait == WAIT_TIMEOUT ? HRESULT_FROM_WIN32(ERROR_TIMEOUT) + : HRESULT_FROM_WIN32(GetLastError()); + } + return initialization_result_; + } + + void Stop() { + if (stop_event_) { + SetEvent(stop_event_); + } + if (thread_.joinable()) { + thread_.join(); + } + } + + HRESULT Play() { return audio_client_ ? audio_client_->Start() : E_UNEXPECTED; } + + HRESULT Pause() { return audio_client_ ? audio_client_->Stop() : E_UNEXPECTED; } + + HRESULT STDMETHODCALLTYPE + ActivateCompleted(IActivateAudioInterfaceAsyncOperation *operation) override { + HRESULT activation_result = E_FAIL; + ComPtr audio_interface; + HRESULT result = operation->GetActivateResult(&activation_result, &audio_interface); + if (SUCCEEDED(result)) { + result = activation_result; + } + if (SUCCEEDED(result)) { + result = audio_interface.As(&audio_client_); + } + activation_result_ = result; + SetEvent(activation_event_); + return S_OK; + } + + private: + ~ProcessLoopbackCapture() override { + Stop(); + for (HANDLE handle : {ready_event_, activation_event_, sample_event_, stop_event_}) { + if (handle) { + CloseHandle(handle); + } + } + } + + void Run(DWORD process_id) { + HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + bool uninitialize = SUCCEEDED(result); + if (result == RPC_E_CHANGED_MODE) { + result = S_OK; + } + if (SUCCEEDED(result)) { + result = Activate(process_id); + } + if (SUCCEEDED(result)) { + result = InitializeClient(); + } + initialization_result_ = result; + SetEvent(ready_event_); + + if (SUCCEEDED(result)) { + Capture(); + } + if (audio_client_) { + audio_client_->Stop(); + } + capture_client_.Reset(); + audio_client_.Reset(); + if (uninitialize) { + CoUninitialize(); + } + } + + HRESULT Activate(DWORD process_id) { + AUDIOCLIENT_ACTIVATION_PARAMS params{}; + params.ActivationType = AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK; + params.ProcessLoopbackParams.TargetProcessId = process_id; + params.ProcessLoopbackParams.ProcessLoopbackMode = + PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE; + + PROPVARIANT variant{}; + variant.vt = VT_BLOB; + variant.blob.cbSize = sizeof(params); + variant.blob.pBlobData = reinterpret_cast(¶ms); + + ComPtr operation; + HRESULT result = ActivateAudioInterfaceAsync( + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, __uuidof(IAudioClient), &variant, + this, &operation); + if (FAILED(result)) { + return result; + } + DWORD wait = WaitForSingleObject(activation_event_, 10000); + if (wait != WAIT_OBJECT_0) { + return wait == WAIT_TIMEOUT ? HRESULT_FROM_WIN32(ERROR_TIMEOUT) + : HRESULT_FROM_WIN32(GetLastError()); + } + return activation_result_; + } + + HRESULT InitializeClient() { + WAVEFORMATEX format{}; + format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; + format.nChannels = 2; + format.nSamplesPerSec = 48000; + format.wBitsPerSample = 32; + format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8; + format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; + + HRESULT result = audio_client_->Initialize( + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | + AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, + 0, 0, &format, nullptr); + if (FAILED(result)) { + return result; + } + result = audio_client_->SetEventHandle(sample_event_); + if (FAILED(result)) { + return result; + } + result = audio_client_->GetService(IID_PPV_ARGS(&capture_client_)); + if (FAILED(result)) { + return result; + } + return S_OK; + } + + void Capture() { + HANDLE events[] = {stop_event_, sample_event_}; + while (WaitForMultipleObjects(2, events, FALSE, INFINITE) == WAIT_OBJECT_0 + 1) { + UINT32 frames = 0; + while (SUCCEEDED(capture_client_->GetNextPacketSize(&frames)) && frames > 0) { + BYTE *data = nullptr; + DWORD flags = 0; + UINT64 device_position = 0; + UINT64 performance_position = 0; + if (FAILED(capture_client_->GetBuffer(&data, &frames, &flags, + &device_position, + &performance_position))) { + break; + } + if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0) { + silence_.assign(static_cast(frames) * 2, 0.0f); + callback_(silence_.data(), frames, performance_position, context_); + } else { + callback_(reinterpret_cast(data), frames, + performance_position, context_); + } + capture_client_->ReleaseBuffer(frames); + } + } + } + + AudioCallback callback_ = nullptr; + void *context_ = nullptr; + HANDLE ready_event_ = nullptr; + HANDLE activation_event_ = nullptr; + HANDLE sample_event_ = nullptr; + HANDLE stop_event_ = nullptr; + HRESULT initialization_result_ = E_PENDING; + HRESULT activation_result_ = E_PENDING; + ComPtr audio_client_; + ComPtr capture_client_; + std::thread thread_; + std::vector silence_; +}; + +extern "C" void *cap_process_audio_start(uint32_t process_id, + AudioCallback callback, void *context, + int32_t *error) { + auto capture = Make(); + if (!capture) { + *error = E_OUTOFMEMORY; + return nullptr; + } + HRESULT result = capture->Start(process_id, callback, context); + if (FAILED(result)) { + capture->Stop(); + *error = result; + return nullptr; + } + *error = S_OK; + return capture.Detach(); +} + +extern "C" void cap_process_audio_stop(void *handle) { + if (!handle) { + return; + } + auto *capture = static_cast(handle); + capture->Stop(); + capture->Release(); +} + +extern "C" int32_t cap_process_audio_play(void *handle) { + return handle ? static_cast(handle)->Play() : E_POINTER; +} + +extern "C" int32_t cap_process_audio_pause(void *handle) { + return handle ? static_cast(handle)->Pause() : E_POINTER; +} diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rs index 36d5d448386..a8ac6771c29 100644 --- a/crates/recording/src/sources/screen_capture/windows.rs +++ b/crates/recording/src/sources/screen_capture/windows.rs @@ -1,6 +1,9 @@ use crate::{ AudioFrame, SetupCtx, output_pipeline, - screen_capture::{ScreenCaptureConfig, ScreenCaptureFormat, cadence::FrameCadenceGate}, + screen_capture::{ + AudioCaptureSource, ScreenCaptureConfig, ScreenCaptureFormat, ScreenCaptureTarget, + cadence::FrameCadenceGate, + }, }; use ::windows::Win32::Graphics::Direct3D11::{ D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, @@ -16,8 +19,9 @@ use futures::{ channel::{mpsc, oneshot}, }; use scap_ffmpeg::*; -use scap_targets::{Display, DisplayId}; +use scap_targets::{Display, Window}; use std::{ + ffi::c_void, sync::{ Arc, Mutex, atomic::{self, AtomicBool, AtomicU32}, @@ -355,9 +359,13 @@ impl ScreenCaptureConfig { pub async fn to_sources( &self, ) -> anyhow::Result<(VideoSourceConfig, Option)> { + let crop_bounds = match self.config.target { + ScreenCaptureTarget::Area { .. } => self.config.crop_bounds, + _ => None, + }; let mut settings = scap_direct3d::Settings { pixel_format: Direct3DCapture::PIXEL_FORMAT, - crop: self.config.crop_bounds.map(|b| { + crop: crop_bounds.map(|b| { let position = b.position(); let size = b.size().map(|v| (v / 2.0).floor() * 2.0); @@ -382,8 +390,19 @@ impl ScreenCaptureConfig { settings.is_border_required = Some(false); } - if let Ok(true) = scap_direct3d::Settings::can_is_cursor_capture_enabled() { - settings.is_cursor_capture_enabled = Some(self.config.show_cursor); + match scap_direct3d::Settings::can_is_cursor_capture_enabled() { + Ok(true) => settings.is_cursor_capture_enabled = Some(self.config.show_cursor), + Ok(false) if !self.config.show_cursor => { + return Err(anyhow!( + "Cursor hiding is not supported by this Windows version" + )); + } + Err(error) if !self.config.show_cursor => { + return Err(anyhow!( + "Could not enable cursor visibility control: {error}" + )); + } + _ => {} } if let Ok(true) = scap_direct3d::Settings::can_min_update_interval() { @@ -393,16 +412,27 @@ impl ScreenCaptureConfig { settings.fps = Some(self.config.fps); - // Store the display ID instead of GraphicsCaptureItem to avoid COM threading issues - // The GraphicsCaptureItem will be created on the capture thread + let audio_source = match self.audio_source { + AudioCaptureSource::None => None, + AudioCaptureSource::System => Some(SystemAudioSourceConfig::System), + AudioCaptureSource::Application => { + let process_id = self.config.target.application_pid().ok_or_else(|| { + anyhow!( + "Application audio requires a live window target with an owning process" + ) + })?; + Some(SystemAudioSourceConfig::Application { process_id }) + } + }; + Ok(( VideoSourceConfig { video_info: self.video_info, - display_id: self.config.display.clone(), + target: self.config.target.clone(), settings, d3d_device: self.d3d_device.clone(), }, - self.system_audio.then_some(SystemAudioSourceConfig), + audio_source, )) } } @@ -415,7 +445,7 @@ pub enum VideoSourceError { pub struct VideoSourceConfig { video_info: VideoInfo, - display_id: DisplayId, + target: ScreenCaptureTarget, settings: scap_direct3d::Settings, pub d3d_device: ID3D11Device, } @@ -486,7 +516,7 @@ struct CaptureClosureEvent { } struct CreateCapturerParams<'a> { - display_id: &'a DisplayId, + target: &'a ScreenCaptureTarget, settings: &'a scap_direct3d::Settings, d3d_device: &'a ID3D11Device, video_tx: &'a mpsc::Sender, @@ -511,11 +541,23 @@ fn create_d3d_capturer( params: &CreateCapturerParams, error_tx: &mpsc::Sender, ) -> anyhow::Result { - let capture_item = Display::from_id(params.display_id) - .ok_or_else(|| anyhow!("Display not found for ID: {:?}", params.display_id))? - .raw_handle() - .try_as_capture_item() - .map_err(|e| anyhow!("Failed to create GraphicsCaptureItem: {}", e))?; + let capture_item = match params.target { + ScreenCaptureTarget::Display { id } | ScreenCaptureTarget::Area { screen: id, .. } => { + Display::from_id(id) + .ok_or_else(|| anyhow!("Display not found for ID: {id:?}"))? + .raw_handle() + .try_as_capture_item() + .map_err(|error| anyhow!("Failed to create display capture item: {error}"))? + } + ScreenCaptureTarget::Window { id } => Window::from_id(id) + .ok_or_else(|| anyhow!("Window not found for ID: {id:?}"))? + .raw_handle() + .try_as_capture_item() + .map_err(|error| anyhow!("Failed to create window capture item: {error}"))?, + ScreenCaptureTarget::CameraOnly => { + return Err(anyhow!("Camera-only target has no screen capture item")); + } + }; scap_direct3d::Capturer::new( capture_item, @@ -660,7 +702,7 @@ impl output_pipeline::VideoSource for VideoSource { async fn setup( VideoSourceConfig { video_info, - display_id, + target, settings, d3d_device, }: Self::Config, @@ -703,6 +745,7 @@ impl output_pipeline::VideoSource for VideoSource { }; let stats_health_tx = ctx.health_tx().clone(); + let capture_target = target.clone(); ctx.tasks().spawn_thread("d3d-capture-thread", { let restart_counter = restart_counter.clone(); let frame_scaler = frame_scaler.clone(); @@ -722,7 +765,7 @@ impl output_pipeline::VideoSource for VideoSource { macro_rules! build_params { ($device:expr) => { CreateCapturerParams { - display_id: &display_id, + target: &capture_target, settings: &settings, d3d_device: $device, video_tx: &video_tx, @@ -969,7 +1012,7 @@ impl output_pipeline::VideoSource for VideoSource { output_pipeline::emit_health( &monitor_health_tx, output_pipeline::PipelineHealthEvent::CaptureTargetLost { - target: "display".to_string(), + target: target.kind_str().to_lowercase(), }, ); return Err(anyhow!("Windows capture target lost: {}", event.message)); @@ -1066,7 +1109,10 @@ const DEVICE_POLL_INTERVAL: Duration = Duration::from_secs(2); const SILENCE_CHUNK_DURATION: Duration = Duration::from_millis(20); const SILENCE_CHUNKS_ON_SWITCH: usize = 5; -pub struct SystemAudioSourceConfig; +pub enum SystemAudioSourceConfig { + System, + Application { process_id: u32 }, +} struct CapturerState { capturer: Option, @@ -1075,11 +1121,157 @@ struct CapturerState { } pub struct SystemAudioSource { - state: Arc>, + state: SystemAudioState, cancel_token: CancellationToken, audio_info: AudioInfo, } +enum SystemAudioState { + System(Arc>), + Application(ProcessLoopbackCapture), +} + +struct ProcessAudioCallbackContext { + tx: std::sync::Mutex>, + health_tx: output_pipeline::HealthSender, + captured: AtomicU32, + dropped: AtomicU32, +} + +struct ProcessLoopbackCapture { + handle: *mut c_void, + _callback_context: Box, +} + +unsafe impl Send for ProcessLoopbackCapture {} + +unsafe extern "C" { + fn cap_process_audio_start( + process_id: u32, + callback: unsafe extern "C" fn(*const f32, u32, u64, *mut c_void), + context: *mut c_void, + error: *mut i32, + ) -> *mut c_void; + fn cap_process_audio_stop(handle: *mut c_void); + fn cap_process_audio_play(handle: *mut c_void) -> i32; + fn cap_process_audio_pause(handle: *mut c_void) -> i32; +} + +impl ProcessLoopbackCapture { + fn new( + process_id: u32, + tx: mpsc::Sender, + health_tx: output_pipeline::HealthSender, + ) -> anyhow::Result { + let mut callback_context = Box::new(ProcessAudioCallbackContext { + tx: std::sync::Mutex::new(tx), + health_tx, + captured: AtomicU32::new(0), + dropped: AtomicU32::new(0), + }); + let context = std::ptr::from_mut(callback_context.as_mut()).cast::(); + let mut error = 0; + let handle = unsafe { + cap_process_audio_start(process_id, process_audio_callback, context, &mut error) + }; + if handle.is_null() { + return Err(anyhow!( + "Failed to initialize application audio capture for process {process_id} (HRESULT 0x{:08X}). Application audio requires Windows 10 build 20348 or newer", + error as u32 + )); + } + + Ok(Self { + handle, + _callback_context: callback_context, + }) + } + + fn play(&self) -> anyhow::Result<()> { + let result = unsafe { cap_process_audio_play(self.handle) }; + hresult_result(result, "start") + } + + fn pause(&self) -> anyhow::Result<()> { + let result = unsafe { cap_process_audio_pause(self.handle) }; + hresult_result(result, "pause") + } +} + +impl Drop for ProcessLoopbackCapture { + fn drop(&mut self) { + unsafe { cap_process_audio_stop(self.handle) }; + self.handle = std::ptr::null_mut(); + } +} + +fn hresult_result(result: i32, operation: &str) -> anyhow::Result<()> { + if result >= 0 { + Ok(()) + } else { + Err(anyhow!( + "Failed to {operation} application audio capture (HRESULT 0x{:08X})", + result as u32 + )) + } +} + +unsafe extern "C" fn process_audio_callback( + data: *const f32, + frames: u32, + performance_position: u64, + context: *mut c_void, +) { + if data.is_null() || context.is_null() || frames == 0 { + return; + } + + let _ = std::panic::catch_unwind(|| { + let context = unsafe { &*(context.cast::()) }; + let sample_count = frames as usize * 2; + let samples = unsafe { std::slice::from_raw_parts(data, sample_count) }; + let mut frame = ffmpeg::frame::Audio::new( + ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed), + frames as usize, + ffmpeg::util::channel_layout::ChannelLayout::STEREO, + ); + frame.set_rate(48_000); + let destination = frame.data_mut(0); + let byte_len = sample_count * size_of::(); + if destination.len() < byte_len { + context.dropped.fetch_add(1, atomic::Ordering::Relaxed); + return; + } + let source = unsafe { std::slice::from_raw_parts(samples.as_ptr().cast::(), byte_len) }; + destination[..byte_len].copy_from_slice(source); + + let timestamp = i64::try_from(performance_position) + .ok() + .filter(|position| *position > 0) + .map(PerformanceCounterTimestamp::from_100ns) + .unwrap_or_else(PerformanceCounterTimestamp::now); + let audio_frame = AudioFrame::new(frame, Timestamp::PerformanceCounter(timestamp)); + let Ok(mut tx) = context.tx.lock() else { + context.dropped.fetch_add(1, atomic::Ordering::Relaxed); + return; + }; + match output_pipeline::send_with_stall_budget_futures( + &mut tx, + audio_frame, + "screen-application-audio", + &context.health_tx, + ) { + output_pipeline::StallSendOutcome::Sent => { + context.captured.fetch_add(1, atomic::Ordering::Relaxed); + } + output_pipeline::StallSendOutcome::StalledAndDropped { .. } + | output_pipeline::StallSendOutcome::Disconnected => { + context.dropped.fetch_add(1, atomic::Ordering::Relaxed); + } + } + }); +} + struct SystemAudioResampler { context: ffmpeg::software::resampling::Context, } @@ -1270,7 +1462,7 @@ impl output_pipeline::AudioSource for SystemAudioSource { type Config = SystemAudioSourceConfig; fn setup( - _: Self::Config, + config: Self::Config, tx: mpsc::Sender, ctx: &mut SetupCtx, ) -> impl Future> + 'static @@ -1288,6 +1480,22 @@ impl output_pipeline::AudioSource for SystemAudioSource { }); let audio_info = crate::sources::audio_mixer::AudioMixer::INFO; + if let SystemAudioSourceConfig::Application { process_id } = config { + let health_tx = ctx.health_tx().clone(); + return futures::future::Either::Left(async move { + let capture = tokio::task::spawn_blocking(move || { + ProcessLoopbackCapture::new(process_id, tx, health_tx) + }) + .await??; + info!(process_id, "Application audio capture initialized"); + Ok(Self { + state: SystemAudioState::Application(capture), + cancel_token, + audio_info, + }) + }); + } + let device_name = get_current_device_name(); let frame_counter: Arc = Arc::new(AtomicU32::new(0)); @@ -1459,7 +1667,7 @@ impl output_pipeline::AudioSource for SystemAudioSource { let cancel = cancel_token.clone(); - async move { + futures::future::Either::Right(async move { let capturer = setup_result.map_err(|e| anyhow!("{e}"))?; if capturer.has_silence_keepalive() { info!("System audio loopback silence keepalive active"); @@ -1509,11 +1717,11 @@ impl output_pipeline::AudioSource for SystemAudioSource { }); Ok(Self { - state, + state: SystemAudioState::System(state), cancel_token: cancel, audio_info, }) - } + }) } fn audio_info(&self) -> cap_media_info::AudioInfo { @@ -1521,28 +1729,37 @@ impl output_pipeline::AudioSource for SystemAudioSource { } fn start(&mut self) -> impl Future> { - let result = match self.state.lock() { - Ok(mut guard) => { - guard.is_started = true; - match &guard.capturer { - Some(c) => c.play().map_err(|e| anyhow!("{e}")), - None => Ok(()), + let result = match &self.state { + SystemAudioState::System(state) => match state.lock() { + Ok(mut guard) => { + guard.is_started = true; + match &guard.capturer { + Some(c) => c.play().map_err(|e| anyhow!("{e}")), + None => Ok(()), + } } - } - Err(_) => Err(anyhow!("System audio state lock poisoned")), + Err(_) => Err(anyhow!("System audio state lock poisoned")), + }, + SystemAudioState::Application(capture) => capture.play(), }; async move { result } } fn stop(&mut self) -> impl Future> { self.cancel_token.cancel(); - if let Ok(guard) = self.state.lock() - && let Some(ref capturer) = guard.capturer - && let Err(err) = capturer.pause() - { - warn!("system audio capturer pause failed: {err}"); - } - async { Ok(()) } + let result = match &self.state { + SystemAudioState::System(state) => { + if let Ok(guard) = state.lock() + && let Some(ref capturer) = guard.capturer + && let Err(err) = capturer.pause() + { + warn!("system audio capturer pause failed: {err}"); + } + Ok(()) + } + SystemAudioState::Application(capture) => capture.pause(), + }; + async move { result } } } diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 1ff44d06f1b..12035ee7a0a 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -2037,7 +2037,8 @@ pub struct ActorBuilder { lifetime: StudioLifetimeOwner, output_path: PathBuf, capture_target: screen_capture::ScreenCaptureTarget, - system_audio: bool, + audio_source: screen_capture::AudioCaptureSource, + show_cursor: bool, mic_feed: Option>, camera_feed: Option>, custom_cursor: bool, @@ -2061,7 +2062,8 @@ impl ActorBuilder { }, output_path: output, capture_target, - system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, custom_cursor: false, @@ -2077,7 +2079,21 @@ impl ActorBuilder { } pub fn with_system_audio(mut self, system_audio: bool) -> Self { - self.system_audio = system_audio; + self.audio_source = if system_audio { + screen_capture::AudioCaptureSource::System + } else { + screen_capture::AudioCaptureSource::None + }; + self + } + + pub fn with_audio_source(mut self, audio_source: screen_capture::AudioCaptureSource) -> Self { + self.audio_source = audio_source; + self + } + + pub fn with_show_cursor(mut self, show_cursor: bool) -> Self { + self.show_cursor = show_cursor; self } @@ -2152,13 +2168,15 @@ impl ActorBuilder { { *lifecycle.0.runtime.lock().unwrap() = Some(tokio::runtime::Handle::current()); } + let custom_cursor = self.custom_cursor && self.show_cursor; let startup = spawn_studio_recording_actor( #[cfg(target_os = "linux")] self.lifetime, self.output_path, RecordingBaseInputs { capture_target: self.capture_target, - capture_system_audio: self.system_audio, + audio_source: self.audio_source, + show_cursor: self.show_cursor, mic_feed: self.mic_feed, camera_feed: self.camera_feed, start_gate: self.start_gate, @@ -2167,7 +2185,7 @@ impl ActorBuilder { #[cfg(target_os = "macos")] excluded_windows: self.excluded_windows, }, - self.custom_cursor, + custom_cursor, self.keyboard_capture, self.fragmented, self.use_oop_muxer, @@ -2232,7 +2250,7 @@ async fn spawn_studio_recording_actor( cap_utils::operation_diagnostics::resource_id(&recording_dir), ), Field::number("requested_fps", max_fps as u64), - Field::flag("system_audio", base_inputs.capture_system_audio), + Field::label("audio_source", base_inputs.audio_source.as_str()), Field::flag("microphone", base_inputs.mic_feed.is_some()), Field::flag("camera", base_inputs.camera_feed.is_some()), Field::flag("fragmented", fragmented), @@ -3262,16 +3280,20 @@ async fn create_segment_pipeline( max_fps }; + #[cfg(target_os = "linux")] + let linux_source = + sources::screen_capture::LinuxCaptureSource::from_target(&capture_target); let screen_config = ScreenCaptureConfig::::init( + capture_target, display, crop, - !custom_cursor_capture, + base_inputs.show_cursor && !custom_cursor_capture, effective_max_fps, max_capture_size, start_time.system_time(), - base_inputs.capture_system_audio, + base_inputs.audio_source, #[cfg(target_os = "linux")] - sources::screen_capture::LinuxCaptureSource::from_target(&capture_target), + linux_source, #[cfg(windows)] d3d_device, #[cfg(target_os = "macos")] @@ -3803,7 +3825,8 @@ mod tests { root.join("content/cursors"), RecordingBaseInputs { capture_target: screen_capture::ScreenCaptureTarget::CameraOnly, - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -3913,7 +3936,8 @@ mod tests { path.join("content/cursors"), RecordingBaseInputs { capture_target: target.clone(), - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -4011,7 +4035,8 @@ mod tests { path.join("content/cursors"), RecordingBaseInputs { capture_target: target.clone(), - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -4148,7 +4173,8 @@ mod tests { path.join("content/cursors"), RecordingBaseInputs { capture_target: target.clone(), - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -4392,7 +4418,8 @@ mod tests { path.join("content/cursors"), RecordingBaseInputs { capture_target: target.clone(), - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -5892,7 +5919,8 @@ mod tests { recording_dir.join("content/cursors"), RecordingBaseInputs { capture_target: screen_capture::ScreenCaptureTarget::CameraOnly, - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, @@ -6139,7 +6167,8 @@ mod windows_cancel_tests { PathBuf::new(), RecordingBaseInputs { capture_target: screen_capture::ScreenCaptureTarget::CameraOnly, - capture_system_audio: false, + audio_source: screen_capture::AudioCaptureSource::None, + show_cursor: true, mic_feed: None, camera_feed: None, start_gate: None, diff --git a/crates/scap-screencapturekit/src/capture.rs b/crates/scap-screencapturekit/src/capture.rs index 877a4330093..9d23cb789c0 100644 --- a/crates/scap-screencapturekit/src/capture.rs +++ b/crates/scap-screencapturekit/src/capture.rs @@ -127,6 +127,7 @@ impl Capturer { target, config, callbacks: CapturerCallbacksInner::default(), + captures_screen: true, } } @@ -209,9 +210,15 @@ pub struct CapturerBuilder { target: arc::R, config: arc::R, callbacks: CapturerCallbacksInner, + captures_screen: bool, } impl CapturerBuilder { + pub fn with_captures_screen(mut self, captures_screen: bool) -> Self { + self.captures_screen = captures_screen; + self + } + pub fn with_output_sample_buf_cb(mut self, cb: impl FnMut(Frame) + 'static) -> Self { self.callbacks.did_output_sample_buf_cb = Some(Box::new(cb)); self @@ -238,9 +245,11 @@ impl CapturerBuilder { .map_err(|e| e.retained())?; } - stream - .add_stream_output(callbacks.as_ref(), sc::OutputType::Screen, Some(&queue)) - .map_err(|e| e.retained())?; + if self.captures_screen { + stream + .add_stream_output(callbacks.as_ref(), sc::OutputType::Screen, Some(&queue)) + .map_err(|e| e.retained())?; + } Ok(Capturer { _queue: queue, diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rs index 1dbb6c3b966..0dcfea870d2 100644 --- a/crates/scap-targets/src/platform/linux.rs +++ b/crates/scap-targets/src/platform/linux.rs @@ -231,6 +231,14 @@ impl WindowImpl { }) } + pub fn owner_pid(&self) -> Option { + if is_wayland_portal_window(self.0) { + return None; + } + let (conn, _) = x11_connection().ok()?; + window_pid(&conn, self.0) + } + pub fn id(&self) -> WindowIdImpl { WindowIdImpl(self.0) } diff --git a/crates/scap-targets/src/platform/win.rs b/crates/scap-targets/src/platform/win.rs index 0a824ae68c8..c5713125cb4 100644 --- a/crates/scap-targets/src/platform/win.rs +++ b/crates/scap-targets/src/platform/win.rs @@ -349,6 +349,12 @@ impl WindowImpl { self.0 } + pub fn owner_pid(&self) -> Option { + let mut process_id = 0; + unsafe { GetWindowThreadProcessId(self.0, Some(&mut process_id)) }; + (process_id != 0).then_some(process_id) + } + pub fn get_topmost_at_cursor() -> Option { let cursor = get_cursor_position()?; let point = POINT { diff --git a/scripts/windows-release-signing.ps1 b/scripts/windows-release-signing.ps1 index 467cd65a2a4..529fa7f675b 100644 --- a/scripts/windows-release-signing.ps1 +++ b/scripts/windows-release-signing.ps1 @@ -5,7 +5,9 @@ param( [string] $Operation, [string] $Target = $env:RUST_TARGET_TRIPLE, [string] $WorkspaceRoot = $env:GITHUB_WORKSPACE, - [string] $InstallerPath + [string] $InstallerPath, + [ValidateSet("Desktop", "Cli")] + [string] $PayloadKind = "Desktop" ) Set-StrictMode -Version Latest @@ -21,11 +23,19 @@ if ([string]::IsNullOrWhiteSpace($Target)) { } $releaseRoot = Join-Path $WorkspaceRoot "target/$Target/release" -$signingRoot = Join-Path $releaseRoot "windows-signing" +$signingRoot = Join-Path $releaseRoot $(if ($PayloadKind -eq "Cli") { "windows-signing-cli" } else { "windows-signing" }) $payloadRoot = Join-Path $signingRoot "payload" $manifestPath = Join-Path $signingRoot "payload-manifest.json" function Get-PayloadDefinitions { + if ($PayloadKind -eq "Cli") { + return @( + [pscustomobject]@{ + Name = "cap-cli.exe" + Path = Join-Path $releaseRoot "cap.exe" + } + ) + } return @( [pscustomobject]@{ Name = "Cap.exe" @@ -76,7 +86,7 @@ function Read-Manifest { throw "Payload manifest '$manifestPath' does not exist." } $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json - if ($manifest.schemaVersion -ne 1 -or $manifest.target -ne $Target -or @($manifest.entries).Count -ne 5) { + if ($manifest.schemaVersion -ne 1 -or $manifest.target -ne $Target -or @($manifest.entries).Count -ne @(Get-PayloadDefinitions).Count) { throw "Payload manifest '$manifestPath' has an unexpected schema." } $expectedNames = @(Get-PayloadDefinitions | ForEach-Object Name | Sort-Object) From b8e4bdcc125b0043905c52a324e8bcd3e8df3346 Mon Sep 17 00:00:00 2001 From: Chloe Date: Mon, 28 Sep 2026 13:00:54 -0400 Subject: [PATCH 2/5] Finixhed implementation --- .../routes/(window-chrome)/new-main/CursorVisibility.tsx | 8 ++++---- crates/recording/src/sources/screen_capture/linux.rs | 9 ++++----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx index d6cf52ce05d..63c9f0994a9 100644 --- a/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx +++ b/apps/desktop/src/routes/(window-chrome)/new-main/CursorVisibility.tsx @@ -1,7 +1,6 @@ -import { createQuery } from "@tanstack/solid-query"; import { cx } from "cva"; -import IconPhCursorClickBold from "~icons/ph/cursor-click-bold"; import { createCurrentRecordingQuery } from "~/utils/queries"; +import IconPhCursorClickBold from "~icons/ph/cursor-click-bold"; import { useRecordingOptions } from "../OptionsContext"; import { @@ -14,10 +13,11 @@ import InfoPill from "./InfoPill"; export default function CursorVisibility() { const { rawOptions, setOptions } = useRecordingOptions(); - const currentRecording = createQuery(createCurrentRecordingQuery); + const currentRecording = createCurrentRecordingQuery(); const showCursor = () => rawOptions.showCursor !== false; const isDisabled = () => - !!currentRecording.data || rawOptions.captureTarget.variant === "cameraOnly"; + !!currentRecording.data || + rawOptions.captureTarget.variant === "cameraOnly"; return (