Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add av-sync selftest, synthetic device sync matrix and sync CI workflow
Richie McIlroy9e93a9083b40
diff --git a/.github/workflows/sync-tests.yml b/.github/workflows/sync-tests.ymlnew file mode 100644index 000000000..6f393a767--- /dev/null+++ b/.github/workflows/sync-tests.yml@@ -0,0 +1,122 @@+name: A/V Sync Tests++# Verifies audio/video sync correctness on every platform:+# 1. Unit + property tests for the timestamp pipeline (encoders, drift+# trackers, muxers).+# 2. The synthetic device matrix: fake cameras/screens/microphones across+# frame rates, sample rates, channel counts and delivery pathologies+# (jitter, drops, static-screen gaps), driven through the real recording+# pipeline and verified at the container level. No capture hardware or+# GPU required, so results are deterministic on hosted runners.+#+# Findings are published as a job-summary table and a JSON artifact per OS.++on:+ workflow_dispatch:+ schedule:+ - cron: "0 5 * * *"+ pull_request:+ paths:+ - "crates/recording/**"+ - "crates/enc-ffmpeg/**"+ - "crates/enc-avfoundation/**"+ - "crates/enc-mediafoundation/**"+ - "crates/timestamp/**"+ - "crates/rendering/**"+ - "crates/media-info/**"+ - ".github/workflows/sync-tests.yml"++concurrency:+ group: sync-tests-${{ github.head_ref || github.ref_name }}+ cancel-in-progress: true++jobs:+ sync-tests:+ strategy:+ fail-fast: false+ matrix:+ runner:+ - macos-latest+ - windows-2022+ - ubuntu-22.04+ runs-on: ${{ matrix.runner }}+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Rust setup+ uses: dtolnay/[email protected]++ - name: Rust cache+ uses: ./.github/actions/setup-rust-cache+ with:+ target: ${{ runner.os == 'Windows' && 'x86_64-pc-windows-msvc' || runner.os == 'macOS' && 'aarch64-apple-darwin' || 'x86_64-unknown-linux-gnu' }}++ - name: Install desktop dependencies+ uses: ./.github/actions/install-desktop-deps++ - name: Setup Node+ uses: actions/setup-node@v4+ with:+ node-version: 24++ - name: Native dependencies+ run: node scripts/setup.js++ - name: Add FFmpeg DLLs to PATH+ if: runner.os == 'Windows'+ shell: pwsh+ run: Add-Content -Path $env:GITHUB_PATH -Value "${{ github.workspace }}\\target\\ffmpeg\\bin"++ - name: Timestamp pipeline unit + property tests+ shell: bash+ run: |+ cargo test --locked -p cap-timestamp -p cap-enc-ffmpeg+ cargo test --locked -p cap-recording --lib++ - name: Synthetic device matrix+ id: matrix+ continue-on-error: true+ shell: bash+ env:+ CAP_SYNC_MATRIX_REPORT: ${{ github.workspace }}/sync-matrix-${{ matrix.runner }}.json+ run: |+ cargo test --locked -p cap-recording --test sync_matrix -- --nocapture++ - name: Report findings+ if: always()+ shell: bash+ run: |+ REPORT="${{ github.workspace }}/sync-matrix-${{ matrix.runner }}.json"+ {+ echo "## A/V sync matrix — ${{ matrix.runner }}"+ echo ""+ if [ -f "$REPORT" ]; then+ echo "| Case | Result | Detail |"+ echo "| --- | --- | --- |"+ python3 - "$REPORT" << 'PYEOF'+ import json, sys+ for case in json.load(open(sys.argv[1])):+ icon = "✅" if case["pass"] else "❌"+ detail = case["detail"].replace("|", "\\|")+ print(f"| {case['name']} | {icon} | {detail} |")+ PYEOF+ else+ echo "No report produced — the matrix crashed before writing results."+ fi+ } >> "$GITHUB_STEP_SUMMARY"++ - name: Upload findings+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: sync-matrix-${{ matrix.runner }}+ path: ${{ github.workspace }}/sync-matrix-${{ matrix.runner }}.json+ if-no-files-found: ignore++ - name: Fail on matrix failures+ if: steps.matrix.outcome == 'failure'+ shell: bash+ run: |+ echo "Synthetic sync matrix reported failures; see the job summary." >&2+ exit 1diff --git a/Cargo.lock b/Cargo.lockindex 9d7cbc65d..10f153f69 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8,6 +8,22 @@ version = "0.11.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"+[[package]]+name = "ab_glyph"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"+dependencies = [+ "ab_glyph_rasterizer",+ "owned_ttf_parser",+]++[[package]]+name = "ab_glyph_rasterizer"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"+[[package]]name = "actix-codec"version = "0.5.2"@@ -250,6 +266,31 @@ dependencies = ["pkg-config",]+[[package]]+name = "android-activity"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"+dependencies = [+ "android-properties",+ "bitflags 2.9.4",+ "cc",+ "jni 0.22.4",+ "libc",+ "log",+ "ndk 0.9.0",+ "ndk-context",+ "ndk-sys 0.6.0+11769913",+ "num_enum",+ "thiserror 2.0.16",+]++[[package]]+name = "android-properties"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"+[[package]]name = "android_system_properties"version = "0.1.5"@@ -354,7 +395,7 @@ dependencies = ["image 0.25.8","log","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-core-graphics","objc2-foundation 0.3.1",@@ -388,6 +429,12 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "as-raw-xcb-connection"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"+[[package]]name = "ash"version = "0.38.0+1.3.281"@@ -1076,6 +1123,32 @@ dependencies = ["system-deps 6.2.2",]+[[package]]+name = "calloop"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"+dependencies = [+ "bitflags 2.9.4",+ "log",+ "polling",+ "rustix 0.38.44",+ "slab",+ "thiserror 1.0.69",+]++[[package]]+name = "calloop-wayland-source"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"+dependencies = [+ "calloop",+ "rustix 0.38.44",+ "wayland-backend",+ "wayland-client",+]+[[package]]name = "camino"version = "1.2.0"@@ -1099,6 +1172,7 @@ dependencies = ["cidre","clap","clap_complete",+ "cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=3cc779a7b4ca)","dirs 6.0.0","ffmpeg-next","flume",@@ -1111,6 +1185,7 @@ dependencies = ["scap-targets","serde","serde_json",+ "softbuffer","tempfile","tokio","tokio-util",@@ -1118,6 +1193,7 @@ dependencies = ["tracing-subscriber","uuid","windows 0.60.0",+ "winit","workspace-hack",]@@ -1294,7 +1370,7 @@ version = "0.0.0"dependencies = ["hex","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","serde","sha2","specta",@@ -1366,7 +1442,7 @@ dependencies = ["nix 0.29.0","objc","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","opentelemetry","opentelemetry-otlp",@@ -1739,7 +1815,7 @@ dependencies = ["libproc","objc","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","parking_lot","pipewire","relative-path",@@ -2145,7 +2221,7 @@ dependencies = ["clipboard-win","image 0.25.8","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","windows 0.59.0","x11rb",@@ -2374,6 +2450,19 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]+name = "core-graphics"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation 0.9.4",+ "core-graphics-types 0.1.3",+ "foreign-types 0.5.0",+ "libc",+]+[[package]]name = "core-graphics"version = "0.24.0"@@ -2520,7 +2609,7 @@ dependencies = ["core-foundation-sys","coreaudio-rs","dasp_sample",- "jni",+ "jni 0.21.1","js-sys","libc","mach2",@@ -2542,7 +2631,7 @@ dependencies = ["core-foundation-sys","coreaudio-rs","dasp_sample",- "jni",+ "jni 0.21.1","js-sys","libc","mach2",@@ -2709,6 +2798,21 @@ dependencies = ["syn 2.0.106",]+[[package]]+name = "ctor"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf"+dependencies = [+ "dtor",+]++[[package]]+name = "cursor-icon"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]name = "darling"version = "0.20.11"@@ -3101,6 +3205,45 @@ dependencies = ["serde",]+[[package]]+name = "drm"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98888c4bbd601524c11a7ed63f814b8825f420514f78e96f752c437ae9cbb5d1"+dependencies = [+ "bitflags 2.9.4",+ "bytemuck",+ "drm-ffi",+ "drm-fourcc",+ "rustix 0.38.44",+]++[[package]]+name = "drm-ffi"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97c98727e48b7ccb4f4aea8cfe881e5b07f702d17b7875991881b41af7278d53"+dependencies = [+ "drm-sys",+ "rustix 0.38.44",+]++[[package]]+name = "drm-fourcc"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"++[[package]]+name = "drm-sys"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd39dde40b6e196c2e8763f23d119ddb1a8714534bf7d77fa97a65b0feda3986"+dependencies = [+ "libc",+ "linux-raw-sys 0.6.5",+]+[[package]]name = "dtoa"version = "1.0.10"@@ -3116,6 +3259,12 @@ dependencies = ["dtoa",]+[[package]]+name = "dtor"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b"+[[package]]name = "dunce"version = "1.0.5"@@ -4042,7 +4191,7 @@ dependencies = ["crossbeam-channel","keyboard-types","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","once_cell","serde","thiserror 2.0.16",@@ -5003,19 +5152,68 @@ dependencies = ["cesu8","cfg-if","combine",- "jni-sys",+ "jni-sys 0.3.0","log","thiserror 1.0.69","walkdir","windows-sys 0.45.0",]+[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys 0.4.1",+ "log",+ "simd_cesu8",+ "thiserror 2.0.16",+ "walkdir",+ "windows-link 0.2.0",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn 2.0.106",+]+[[package]]name = "jni-sys"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"+[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.106",+]+[[package]]name = "jobserver"version = "0.1.34"@@ -5301,7 +5499,7 @@ checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"dependencies = ["bitflags 2.9.4","libc",- "redox_syscall",+ "redox_syscall 0.5.17",][[package]]@@ -5346,6 +5544,12 @@ version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"+[[package]]+name = "linux-raw-sys"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a385b1be4e5c3e362ad2ffa73c392e53f031eaa5b7d648e64cd87f27f6063d7"+[[package]]name = "linux-raw-sys"version = "0.11.0"@@ -5830,7 +6034,7 @@ dependencies = ["gtk","keyboard-types","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-foundation 0.3.1","once_cell",@@ -5934,7 +6138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"dependencies = ["bitflags 2.9.4",- "jni-sys",+ "jni-sys 0.3.0","log","ndk-sys 0.5.0+25.2.9519653","num_enum",@@ -5948,7 +6152,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"dependencies = ["bitflags 2.9.4",- "jni-sys",+ "jni-sys 0.3.0","log","ndk-sys 0.6.0+11769913","num_enum",@@ -5968,7 +6172,7 @@ version = "0.5.0+25.2.9519653"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"dependencies = [- "jni-sys",+ "jni-sys 0.3.0",][[package]]@@ -5977,7 +6181,7 @@ version = "0.6.0+11769913"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"dependencies = [- "jni-sys",+ "jni-sys 0.3.0",][[package]]@@ -6247,6 +6451,22 @@ dependencies = ["objc2-exception-helper",]+[[package]]+name = "objc2-app-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"+dependencies = [+ "bitflags 2.9.4",+ "block2 0.5.1",+ "libc",+ "objc2 0.5.2",+ "objc2-core-data 0.2.2",+ "objc2-core-image 0.2.2",+ "objc2-foundation 0.2.2",+ "objc2-quartz-core 0.2.2",+]+[[package]]name = "objc2-app-kit"version = "0.3.1"@@ -6257,11 +6477,11 @@ dependencies = ["block2 0.6.1","libc","objc2 0.6.2",- "objc2-cloud-kit",- "objc2-core-data",+ "objc2-cloud-kit 0.3.1",+ "objc2-core-data 0.3.1","objc2-core-foundation","objc2-core-graphics",- "objc2-core-image",+ "objc2-core-image 0.3.1","objc2-foundation 0.3.1","objc2-quartz-core 0.3.1",]@@ -6279,7 +6499,7 @@ dependencies = ["objc2-avf-audio","objc2-core-foundation","objc2-core-graphics",- "objc2-core-image",+ "objc2-core-image 0.3.1","objc2-core-media","objc2-core-video","objc2-foundation 0.3.1",@@ -6296,6 +6516,19 @@ dependencies = ["objc2-foundation 0.3.1",]+[[package]]+name = "objc2-cloud-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"+dependencies = [+ "bitflags 2.9.4",+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-cloud-kit"version = "0.3.1"@@ -6307,6 +6540,17 @@ dependencies = ["objc2-foundation 0.3.1",]+[[package]]+name = "objc2-contacts"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-core-audio"version = "0.3.1"@@ -6329,6 +6573,18 @@ dependencies = ["objc2 0.6.2",]+[[package]]+name = "objc2-core-data"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"+dependencies = [+ "bitflags 2.9.4",+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-core-data"version = "0.3.1"@@ -6364,6 +6620,18 @@ dependencies = ["objc2-io-surface",]+[[package]]+name = "objc2-core-image"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+ "objc2-metal",+]+[[package]]name = "objc2-core-image"version = "0.3.1"@@ -6374,6 +6642,18 @@ dependencies = ["objc2-foundation 0.3.1",]+[[package]]+name = "objc2-core-location"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-contacts",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-core-media"version = "0.3.1"@@ -6425,6 +6705,7 @@ checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"dependencies = ["bitflags 2.9.4","block2 0.5.1",+ "dispatch","libc","objc2 0.5.2",]@@ -6473,6 +6754,18 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-link-presentation"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-app-kit 0.2.2",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-metal"version = "0.2.2"@@ -6493,7 +6786,7 @@ checksum = "26bb88504b5a050dbba515d2414607bf5e57dd56b107bc5f0351197a3e7bdc5d"dependencies = ["bitflags 2.9.4","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1",]@@ -6532,6 +6825,37 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-symbols"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"+dependencies = [+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-ui-kit"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"+dependencies = [+ "bitflags 2.9.4",+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-cloud-kit 0.2.2",+ "objc2-core-data 0.2.2",+ "objc2-core-image 0.2.2",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+ "objc2-link-presentation",+ "objc2-quartz-core 0.2.2",+ "objc2-symbols",+ "objc2-uniform-type-identifiers",+ "objc2-user-notifications",+]+[[package]]name = "objc2-ui-kit"version = "0.3.1"@@ -6544,6 +6868,30 @@ dependencies = ["objc2-foundation 0.3.1",]+[[package]]+name = "objc2-uniform-type-identifiers"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"+dependencies = [+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-foundation 0.2.2",+]++[[package]]+name = "objc2-user-notifications"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"+dependencies = [+ "bitflags 2.9.4",+ "block2 0.5.1",+ "objc2 0.5.2",+ "objc2-core-location",+ "objc2-foundation 0.2.2",+]+[[package]]name = "objc2-web-kit"version = "0.3.1"@@ -6553,7 +6901,7 @@ dependencies = ["bitflags 2.9.4","block2 0.6.1","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-foundation 0.3.1","objc2-javascript-core",@@ -6593,7 +6941,7 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8b61bebd49e5d43f5f8cc7ee2891c16e0f41ec7954d36bcb6c14c5e0de867fb"dependencies = [- "jni",+ "jni 0.21.1","ndk 0.8.0","ndk-context","num-derive",@@ -6795,6 +7143,16 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8c04f5d74368e4d0dfe06c45c8627c81bd7c317d52762d118fb9b3076f6420fd"+[[package]]+name = "orbclient"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"+dependencies = [+ "libc",+ "libredox",+]+[[package]]name = "ordered-channel"version = "1.2.0"@@ -6894,6 +7252,15 @@ dependencies = ["thiserror 2.0.16",]+[[package]]+name = "owned_ttf_parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"+dependencies = [+ "ttf-parser 0.25.1",+]+[[package]]name = "pango"version = "0.18.3"@@ -6959,7 +7326,7 @@ checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"dependencies = ["cfg-if","libc",- "redox_syscall",+ "redox_syscall 0.5.17","smallvec","windows-targets 0.52.6",]@@ -7913,6 +8280,15 @@ dependencies = ["rustfft",]+[[package]]+name = "redox_syscall"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"+dependencies = [+ "bitflags 1.3.2",+]+[[package]]name = "redox_syscall"version = "0.5.17"@@ -8162,7 +8538,7 @@ dependencies = ["js-sys","log","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-foundation 0.3.1","raw-window-handle",@@ -8492,7 +8868,7 @@ dependencies = ["futures","inquire","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","scap-targets","tokio",@@ -8637,6 +9013,19 @@ dependencies = ["untrusted",]+[[package]]+name = "sctk-adwaita"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"+dependencies = [+ "ab_glyph",+ "log",+ "memmap2",+ "smithay-client-toolkit",+ "tiny-skia",+]+[[package]]name = "security-framework"version = "2.11.1"@@ -9124,6 +9513,16 @@ version = "0.3.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"+[[package]]+name = "simd_cesu8"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33"+dependencies = [+ "rustc_version",+ "simdutf8",+]+[[package]]name = "simd_helpers"version = "0.1.0"@@ -9133,6 +9532,12 @@ dependencies = ["quote",]+[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"+[[package]]name = "simplecss"version = "0.2.2"@@ -9224,11 +9629,39 @@ dependencies = ["syn 2.0.106",]+[[package]]+name = "smithay-client-toolkit"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"+dependencies = [+ "bitflags 2.9.4",+ "calloop",+ "calloop-wayland-source",+ "cursor-icon",+ "libc",+ "log",+ "memmap2",+ "rustix 0.38.44",+ "thiserror 1.0.69",+ "wayland-backend",+ "wayland-client",+ "wayland-csd-frame",+ "wayland-cursor",+ "wayland-protocols",+ "wayland-protocols-wlr",+ "wayland-scanner",+ "xkeysym",+]+[[package]]name = "smol_str"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"+dependencies = [+ "serde",+][[package]]name = "socket2"@@ -9267,20 +9700,30 @@ version = "0.4.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08"dependencies = [+ "as-raw-xcb-connection","bytemuck","cfg_aliases 0.2.1","core-graphics 0.24.0",+ "drm",+ "fastrand","foreign-types 0.5.0","js-sys","log",+ "memmap2","objc2 0.5.2","objc2-foundation 0.2.2","objc2-quartz-core 0.2.2","raw-window-handle",- "redox_syscall",+ "redox_syscall 0.5.17",+ "rustix 0.38.44",+ "tiny-xlib","wasm-bindgen",+ "wayland-backend",+ "wayland-client",+ "wayland-sys","web-sys","windows-sys 0.59.0",+ "x11rb",][[package]]@@ -9748,7 +10191,7 @@ dependencies = ["gdkwayland-sys","gdkx11-sys","gtk",- "jni",+ "jni 0.21.1","lazy_static","libc","log",@@ -9756,7 +10199,7 @@ dependencies = ["ndk-context","ndk-sys 0.6.0+11769913","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","once_cell","parking_lot",@@ -9824,15 +10267,15 @@ dependencies = ["http 1.3.1","http-range","image 0.25.8",- "jni",+ "jni 0.21.1","libc","log","mime","muda","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1",- "objc2-ui-kit",+ "objc2-ui-kit 0.3.1","objc2-web-kit","percent-encoding","plist",@@ -10112,7 +10555,7 @@ checksum = "786156aa8e89e03d271fbd3fe642207da8e65f3c961baa9e2930f332bf80a1f5"dependencies = ["dunce","glob",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","open","schemars 0.8.22",@@ -10295,9 +10738,9 @@ dependencies = ["dpi","gtk","http 1.3.1",- "jni",+ "jni 0.21.1","objc2 0.6.2",- "objc2-ui-kit",+ "objc2-ui-kit 0.3.1","objc2-web-kit","raw-window-handle","serde",@@ -10318,10 +10761,10 @@ checksum = "c1fe9d48bd122ff002064e88cfcd7027090d789c4302714e68fcccba0f4b7807"dependencies = ["gtk","http 1.3.1",- "jni",+ "jni 0.21.1","log","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-foundation 0.3.1","once_cell","percent-encoding",@@ -10374,7 +10817,7 @@ dependencies = ["anyhow","brotli","cargo_metadata",- "ctor",+ "ctor 0.2.9","dunce","glob","html5ever",@@ -10603,6 +11046,19 @@ dependencies = ["strict-num",]+[[package]]+name = "tiny-xlib"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4"+dependencies = [+ "as-raw-xcb-connection",+ "ctor 0.10.1",+ "libloading 0.8.8",+ "pkg-config",+ "tracing",+]+[[package]]name = "tinystr"version = "0.8.1"@@ -11084,7 +11540,7 @@ dependencies = ["libappindicator","muda","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-core-graphics","objc2-foundation 0.3.1",@@ -11710,6 +12166,28 @@ dependencies = ["wayland-scanner",]+[[package]]+name = "wayland-csd-frame"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"+dependencies = [+ "bitflags 2.9.4",+ "cursor-icon",+ "wayland-backend",+]++[[package]]+name = "wayland-cursor"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "447ccc440a881271b19e9989f75726d60faa09b95b0200a9b7eb5cc47c3eeb29"+dependencies = [+ "rustix 1.1.2",+ "wayland-client",+ "xcursor",+]+[[package]]name = "wayland-protocols"version = "0.32.9"@@ -11722,6 +12200,19 @@ dependencies = ["wayland-scanner",]+[[package]]+name = "wayland-protocols-plasma"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a07a14257c077ab3279987c4f8bb987851bf57081b93710381daea94f2c2c032"+dependencies = [+ "bitflags 2.9.4",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]+[[package]]name = "wayland-protocols-wlr"version = "0.3.9"@@ -11754,6 +12245,7 @@ checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142"dependencies = ["dlib","log",+ "once_cell","pkg-config",]@@ -12112,7 +12604,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"dependencies = ["objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-foundation 0.3.1","raw-window-handle",@@ -12763,6 +13255,58 @@ version = "0.53.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"+[[package]]+name = "winit"+version = "0.30.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"+dependencies = [+ "ahash",+ "android-activity",+ "atomic-waker",+ "bitflags 2.9.4",+ "block2 0.5.1",+ "bytemuck",+ "calloop",+ "cfg_aliases 0.2.1",+ "concurrent-queue",+ "core-foundation 0.9.4",+ "core-graphics 0.23.2",+ "cursor-icon",+ "dpi",+ "js-sys",+ "libc",+ "memmap2",+ "ndk 0.9.0",+ "objc2 0.5.2",+ "objc2-app-kit 0.2.2",+ "objc2-foundation 0.2.2",+ "objc2-ui-kit 0.2.2",+ "orbclient",+ "percent-encoding",+ "pin-project",+ "raw-window-handle",+ "redox_syscall 0.4.1",+ "rustix 0.38.44",+ "sctk-adwaita",+ "smithay-client-toolkit",+ "smol_str",+ "tracing",+ "unicode-segmentation",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-plasma",+ "web-sys",+ "web-time",+ "windows-sys 0.52.0",+ "x11-dl",+ "x11rb",+ "xkbcommon-dl",+]+[[package]]name = "winnow"version = "0.5.40"@@ -12925,15 +13469,15 @@ dependencies = ["html5ever","http 1.3.1","javascriptcore-rs",- "jni",+ "jni 0.21.1","kuchikiki","libc","ndk 0.9.0","objc2 0.6.2",- "objc2-app-kit",+ "objc2-app-kit 0.3.1","objc2-core-foundation","objc2-foundation 0.3.1",- "objc2-ui-kit",+ "objc2-ui-kit 0.3.1","objc2-web-kit","once_cell","percent-encoding",@@ -12979,7 +13523,11 @@ version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"dependencies = [+ "as-raw-xcb-connection","gethostname",+ "libc",+ "libloading 0.8.8",+ "once_cell","rustix 1.1.2","x11rb-protocol",]@@ -13000,6 +13548,25 @@ dependencies = ["rustix 1.1.2",]+[[package]]+name = "xcursor"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b"++[[package]]+name = "xkbcommon-dl"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"+dependencies = [+ "bitflags 2.9.4",+ "dlib",+ "log",+ "once_cell",+ "xkeysym",+]+[[package]]name = "xkeysym"version = "0.2.1"diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.tomlindex 9d7f7d024..5096c73ae 100644--- a/apps/cli/Cargo.toml+++ b/apps/cli/Cargo.toml@@ -28,6 +28,9 @@ image = "0.25.2"chrono = "0.4.31"tracing.workspace = truetracing-subscriber = "0.3.19"+cpal = { workspace = true }+winit = "0.30"+softbuffer = "0.4"workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }[target.'cfg(unix)'.dependencies]diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 0782da5b3..7ee005824 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -7,6 +7,7 @@ mod project;mod record;mod recordings;mod screenshot;+mod selftest;mod session;mod targets;mod update;@@ -196,6 +197,8 @@ enum Commands {Targets(TargetsArgs),/// Report CLI environment and capture-readiness diagnosticsDoctor(FormatArgs),+ /// Run end-to-end diagnostics that verify Cap works on this machine+ Selftest(selftest::SelftestArgs),/// Print CLI version and execution contextVersion(FormatArgs),/// Inspect or manage the desktop-installed `cap` shim@@ -210,7 +213,12 @@ enum Commands {impl Commands {fn exit_after_success(&self) -> bool {- matches!(self, Self::Export(_) | Self::ExportPreview(_))+ // Selftest runs an export, so it shares export's teardown-crash+ // avoidance on Windows.+ matches!(+ self,+ Self::Export(_) | Self::ExportPreview(_) | Self::Selftest(_)+ )}}@@ -425,6 +433,12 @@ fn main() {let exit_after_success = cli.exit_after_success();+ // The self-test opens a window, which AppKit requires to live on the real+ // process main thread — so the main thread stays here to serve pattern+ // requests while the command itself runs on the runtime thread.+ let pattern_rx = matches!(cli.command, Some(Commands::Selftest(_)))+ .then(selftest::pattern::install_main_thread_runner);+// Windows export exercises deep WGPU/MediaFoundation/FFmpeg stacks. Running the CLI runtime// on an explicitly large stack is what stopped the export worker from overflowing before// the first frame; keep the sidecar and desktop runtimes in sync.@@ -439,6 +453,7 @@ fn main() {.map_err(|e| format!("Failed to build Tokio runtime: {e}"))?;let result = runtime.block_on(run(cli));+ selftest::pattern::shutdown_main_thread_runner();if exit_after_success && result.is_ok() {// Successful export/preview workers have already written their output by here.// Exiting directly avoids Windows GPU/MediaFoundation teardown crashes in the@@ -451,6 +466,10 @@ fn main() {result});+ if let Some(rx) = pattern_rx {+ selftest::pattern::serve_main_thread(rx);+ }+// Surface failures as a clean, unquoted `error: ...` line on stderr (the default// `Result`-returning main prints `Error: "debug-quoted"`, which is noisy for humans and brittle// for agents scraping stderr). clap already exits 2 for usage/parse errors before we get here.@@ -484,6 +503,7 @@ async fn run(cli: Cli) -> Result<(), String> {match command {Commands::Export(e) => e.run(json).await,Commands::ExportPreview(e) => e.run().await,+ Commands::Selftest(args) => args.run(json).await,Commands::Project(args) => args.run(json),Commands::Record(RecordArgs { command, args }) => match command {Some(RecordCommands::Start(args)) => args.run(json).await,diff --git a/apps/cli/src/selftest/measure.rs b/apps/cli/src/selftest/measure.rsnew file mode 100644index 000000000..bd4b0b0aa--- /dev/null+++ b/apps/cli/src/selftest/measure.rs@@ -0,0 +1,515 @@+//! Content-level A/V sync measurement for the self-test.+//!+//! Extracts flash onsets from a video track (mean luma over the frame+//! center with adaptive hysteresis) and beep onsets from an audio track+//! (RMS envelope with an adaptive threshold), pairs them, and computes+//! robust offset and drift statistics. Positive offset means audio is late.++use std::path::Path;++use ffmpeg::{codec, format, frame, media};+use serde::Serialize;++/// Fraction of the frame (centered) used for luma measurement, avoiding+/// menu bars, notches and window chrome at the edges.+const CENTER_CROP: f64 = 0.5;+/// Minimum spacing between onsets, guarding against double-triggers within+/// a single tone burst.+const MIN_ONSET_GAP_SECS: f64 = 0.5;++pub fn video_flash_onsets(path: &Path) -> Result<Vec<f64>, String> {+ let mut ictx =+ format::input(&path).map_err(|e| format!("open video {}: {e}", path.display()))?;+ let stream = ictx+ .streams()+ .best(media::Type::Video)+ .ok_or("no video stream")?;+ let stream_index = stream.index();+ let time_base = stream.time_base();+ let tb = f64::from(time_base.numerator()) / f64::from(time_base.denominator());++ let ctx = codec::context::Context::from_parameters(stream.parameters())+ .map_err(|e| format!("video codec params: {e}"))?;+ let mut decoder = ctx+ .decoder()+ .video()+ .map_err(|e| format!("video decoder: {e}"))?;++ let mut samples: Vec<(f64, f64)> = Vec::new();+ let mut take_frame = |decoded: &frame::Video| {+ let Some(pts) = decoded.pts() else { return };+ let t = pts as f64 * tb;+ if let Some(luma) = mean_center_luma(decoded) {+ samples.push((t, luma));+ }+ };++ let mut decoded = frame::Video::empty();+ for (s, packet) in ictx.packets() {+ if s.index() != stream_index {+ continue;+ }+ if decoder.send_packet(&packet).is_ok() {+ while decoder.receive_frame(&mut decoded).is_ok() {+ take_frame(&decoded);+ }+ }+ }+ let _ = decoder.send_eof();+ while decoder.receive_frame(&mut decoded).is_ok() {+ take_frame(&decoded);+ }++ if samples.len() < 10 {+ return Err(format!(+ "only {} video frames decoded; recording too short to analyze",+ samples.len()+ ));+ }++ // Adaptive hysteresis from the observed luma range so exact black/white+ // levels (color range, HDR tone mapping) don't matter. The high anchor is+ // the peak, not a percentile: flashes are a small duty cycle of frames.+ let mut lumas: Vec<f64> = samples.iter().map(|(_, l)| *l).collect();+ lumas.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let lo = percentile_sorted(&lumas, 0.10);+ let hi = percentile_sorted(&lumas, 0.998);+ if hi - lo < 40.0 {+ return Err(format!(+ "test pattern not visible in the recording (luma range {lo:.0}..{hi:.0}); \+ the test window may have been covered or moved"+ ));+ }+ let on = lo + 0.7 * (hi - lo);+ let off = lo + 0.3 * (hi - lo);++ let mut onsets = Vec::new();+ let mut armed = true;+ for (t, luma) in &samples {+ if *luma >= on && armed {+ onsets.push(*t);+ armed = false;+ } else if *luma <= off {+ armed = true;+ }+ }+ Ok(onsets)+}++fn mean_center_luma(frame: &frame::Video) -> Option<f64> {+ // Plane 0 is luma for all YUV formats the decoders produce. Reject+ // non-planar/packed formats rather than misreading them.+ use ffmpeg::format::Pixel;+ if !matches!(+ frame.format(),+ Pixel::YUV420P | Pixel::NV12 | Pixel::YUV422P | Pixel::YUV444P | Pixel::YUVJ420P+ ) {+ return None;+ }+ let width = frame.width() as usize;+ let height = frame.height() as usize;+ let stride = frame.stride(0);+ let data = frame.data(0);++ let x0 = (width as f64 * (0.5 - CENTER_CROP / 2.0)) as usize;+ let x1 = (width as f64 * (0.5 + CENTER_CROP / 2.0)) as usize;+ let y0 = (height as f64 * (0.5 - CENTER_CROP / 2.0)) as usize;+ let y1 = (height as f64 * (0.5 + CENTER_CROP / 2.0)) as usize;++ let mut sum = 0u64;+ let mut count = 0u64;+ let mut y = y0;+ while y < y1.min(height) {+ let row = &data[y * stride..y * stride + width];+ let mut x = x0;+ while x < x1.min(width) {+ sum += u64::from(row[x]);+ count += 1;+ x += 4;+ }+ y += 4;+ }+ (count > 0).then(|| sum as f64 / count as f64)+}++pub struct AudioOnsets {+ pub onsets: Vec<f64>,+ /// Ratio of tone peak to noise floor; low values mean the beep was not+ /// reliably captured (e.g. muted output).+ pub snr: f64,+}++pub fn audio_beep_onsets(path: &Path) -> Result<AudioOnsets, String> {+ let mut ictx =+ format::input(&path).map_err(|e| format!("open audio {}: {e}", path.display()))?;+ let stream = ictx+ .streams()+ .best(media::Type::Audio)+ .ok_or("no audio stream")?;+ let stream_index = stream.index();++ let ctx = codec::context::Context::from_parameters(stream.parameters())+ .map_err(|e| format!("audio codec params: {e}"))?;+ let mut decoder = ctx+ .decoder()+ .audio()+ .map_err(|e| format!("audio decoder: {e}"))?;++ let mut mono: Vec<f32> = Vec::new();+ let mut sample_rate = 0u32;+ let mut take_frame = |decoded: &frame::Audio| {+ sample_rate = decoded.rate();+ append_mono(decoded, &mut mono);+ };++ let mut decoded = frame::Audio::empty();+ for (s, packet) in ictx.packets() {+ if s.index() != stream_index {+ continue;+ }+ if decoder.send_packet(&packet).is_ok() {+ while decoder.receive_frame(&mut decoded).is_ok() {+ take_frame(&decoded);+ }+ }+ }+ let _ = decoder.send_eof();+ while decoder.receive_frame(&mut decoded).is_ok() {+ take_frame(&decoded);+ }++ if sample_rate == 0 || mono.len() < sample_rate as usize {+ return Err("audio track too short to analyze".to_string());+ }++ bandpass_1khz_in_place(&mut mono, sample_rate);++ // 1 ms RMS envelope.+ let chunk = (sample_rate / 1000).max(1) as usize;+ let mut env: Vec<f32> = mono+ .chunks(chunk)+ .map(|c| (c.iter().map(|s| s * s).sum::<f32>() / c.len() as f32).sqrt())+ .collect();+ let chunk_secs = chunk as f64 / f64::from(sample_rate);++ let mut sorted = env.clone();+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let noise_floor = f64::from(percentile_sorted_f32(&sorted, 0.20)).max(1e-6);+ let peak = f64::from(percentile_sorted_f32(&sorted, 0.999));+ let snr = peak / noise_floor;+ // Edge-triggered hysteresis: after bandpassing, the tone bursts dominate+ // the envelope peak while background audio (music, speech) sits well+ // below it. A rising edge through the high threshold marks an onset; the+ // detector re-arms only after the envelope falls back through the low+ // threshold, so sustained background level cannot mask or spam onsets.+ let hi = ((noise_floor * 8.0).max(peak * 0.35)) as f32;+ let lo = hi * 0.5;++ let mut onsets = Vec::new();+ let mut armed = true;+ let mut last = f64::NEG_INFINITY;+ for (i, value) in env.drain(..).enumerate() {+ let t = i as f64 * chunk_secs;+ if value >= hi && armed && t - last >= MIN_ONSET_GAP_SECS {+ onsets.push(t);+ last = t;+ armed = false;+ } else if value < lo {+ armed = true;+ }+ }++ Ok(AudioOnsets { onsets, snr })+}++/// Second-order (RBJ) bandpass centered on the 1 kHz test tone. Real+/// machines play music/speech during a self-test; narrowband filtering lets+/// the constant-frequency beep dominate the envelope regardless.+fn bandpass_1khz_in_place(samples: &mut [f32], sample_rate: u32) {+ let f0 = 1000.0f64;+ let q = 8.0f64;+ let w0 = 2.0 * std::f64::consts::PI * f0 / f64::from(sample_rate.max(2001));+ let alpha = w0.sin() / (2.0 * q);+ let cos_w0 = w0.cos();+ let a0 = 1.0 + alpha;+ let b0 = (alpha / a0) as f32;+ let b2 = (-alpha / a0) as f32;+ let a1 = (-2.0 * cos_w0 / a0) as f32;+ let a2 = ((1.0 - alpha) / a0) as f32;++ let (mut x1, mut x2, mut y1, mut y2) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);+ for sample in samples.iter_mut() {+ let x0 = *sample;+ let y0 = b0 * x0 + b2 * x2 - a1 * y1 - a2 * y2;+ x2 = x1;+ x1 = x0;+ y2 = y1;+ y1 = y0;+ *sample = y0;+ }+}++fn append_mono(decoded: &frame::Audio, out: &mut Vec<f32>) {+ use ffmpeg::format::Sample;+ use ffmpeg::format::sample::Type;+ let samples = decoded.samples();+ let channels = decoded.channels() as usize;+ if samples == 0 || channels == 0 {+ return;+ }+ match decoded.format() {+ Sample::F32(Type::Planar) => {+ let planes: Vec<&[f32]> = (0..channels.min(decoded.planes()))+ .map(|p| &decoded.plane::<f32>(p)[..samples])+ .collect();+ for i in 0..samples {+ let sum: f32 = planes.iter().map(|p| p[i]).sum();+ out.push(sum / planes.len() as f32);+ }+ }+ Sample::F32(Type::Packed) => {+ let data = &decoded.plane::<f32>(0)[..samples * channels];+ for frame in data.chunks_exact(channels) {+ out.push(frame.iter().sum::<f32>() / channels as f32);+ }+ }+ Sample::I16(Type::Planar) => {+ let planes: Vec<&[i16]> = (0..channels.min(decoded.planes()))+ .map(|p| &decoded.plane::<i16>(p)[..samples])+ .collect();+ for i in 0..samples {+ let sum: f32 = planes.iter().map(|p| f32::from(p[i])).sum();+ out.push(sum / (planes.len() as f32 * f32::from(i16::MAX)));+ }+ }+ Sample::I16(Type::Packed) => {+ let data = &decoded.plane::<i16>(0)[..samples * channels];+ for frame in data.chunks_exact(channels) {+ let sum: f32 = frame.iter().map(|s| f32::from(*s)).sum();+ out.push(sum / (channels as f32 * f32::from(i16::MAX)));+ }+ }+ _ => {+ // Unknown format; skip frame rather than misread it.+ }+ }+}++#[derive(Debug, Clone, Serialize)]+pub struct SyncMeasurement {+ pub paired_events: usize,+ pub inlier_events: usize,+ pub median_offset_ms: f64,+ pub mad_ms: f64,+ pub drift_ms_per_min: f64,+ /// Drift accumulated across the observed window (slope × span). More+ /// robust to slope noise on short runs than the per-minute rate.+ pub total_drift_ms: f64,+ pub span_secs: f64,+ pub min_offset_ms: f64,+ pub max_offset_ms: f64,+ /// (flash time, offset ms) per inlier event.+ pub events: Vec<(f64, f64)>,+}++/// Pairs flash onsets with the nearest beep onset (both on the same clock)+/// and computes robust statistics. The first event after settle is dropped:+/// window creation/compositor transitions make it unrepresentative.+pub fn measure_sync(+ flash_onsets: &[f64],+ beep_onsets: &[f64],+ min_events: usize,+) -> Result<SyncMeasurement, String> {+ if flash_onsets.len() < 2 {+ return Err(format!(+ "only {} flash events detected in the recording",+ flash_onsets.len()+ ));+ }+ if beep_onsets.is_empty() {+ return Err("no beeps detected in the recording".to_string());+ }++ let mut pairs: Vec<(f64, f64)> = Vec::new();+ for flash in flash_onsets {+ let Some(beep) = beep_onsets+ .iter()+ .min_by(|a, b| {+ (*a - flash)+ .abs()+ .partial_cmp(&(*b - flash).abs())+ .unwrap_or(std::cmp::Ordering::Equal)+ })+ .copied()+ else {+ continue;+ };+ let offset = beep - flash;+ if offset.abs() <= 0.9 {+ pairs.push((*flash, offset * 1000.0));+ }+ }+ // Drop the first event: window-creation transitions make it noisy.+ if pairs.len() > min_events {+ pairs.remove(0);+ }+ if pairs.len() < min_events {+ return Err(format!(+ "only {} usable flash/beep pairs (need {min_events}; detected {} flashes, {} beeps); \+ the test window may have been covered or the beeps too quiet",+ pairs.len(),+ flash_onsets.len(),+ beep_onsets.len()+ ));+ }++ // Anchor on the densest offset cluster: mispaired events (a flash+ // matching the wrong beep because the true one was masked) land seconds+ // away, and with enough of them the median itself becomes junk. The true+ // pairs all share one physical offset, so they form the tightest cluster.+ let cluster_center = {+ let mut best_center = 0.0;+ let mut best_count = 0usize;+ for (_, candidate) in &pairs {+ let count = pairs+ .iter()+ .filter(|(_, o)| (o - candidate).abs() <= 60.0)+ .count();+ if count > best_count {+ best_count = count;+ best_center = *candidate;+ }+ }+ best_center+ };++ let mut inliers: Vec<(f64, f64)> = pairs+ .iter()+ .filter(|(_, o)| (o - cluster_center).abs() <= 90.0)+ .copied()+ .collect();+ if inliers.len() < min_events {+ // No dominant cluster: report statistics over every pair and let the+ // caller's thresholds judge them, rather than discarding the run.+ inliers = pairs.clone();+ }++ let mut offsets: Vec<f64> = inliers.iter().map(|(_, o)| *o).collect();+ offsets.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let median = percentile_sorted(&offsets, 0.5);+ let mut deviations: Vec<f64> = offsets.iter().map(|o| (o - median).abs()).collect();+ deviations.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ let mad = percentile_sorted(&deviations, 0.5);++ // Least-squares slope of offset over time = drift.+ let n = inliers.len() as f64;+ let mean_t = inliers.iter().map(|(t, _)| t).sum::<f64>() / n;+ let mean_o = inliers.iter().map(|(_, o)| o).sum::<f64>() / n;+ let mut num = 0.0;+ let mut den = 0.0;+ for (t, o) in &inliers {+ num += (t - mean_t) * (o - mean_o);+ den += (t - mean_t) * (t - mean_t);+ }+ let slope_ms_per_sec = if den > 0.0 { num / den } else { 0.0 };++ let min = inliers+ .iter()+ .map(|(_, o)| *o)+ .fold(f64::INFINITY, f64::min);+ let max = inliers+ .iter()+ .map(|(_, o)| *o)+ .fold(f64::NEG_INFINITY, f64::max);+ let span_secs = inliers.last().map(|(t, _)| *t).unwrap_or(0.0)+ - inliers.first().map(|(t, _)| *t).unwrap_or(0.0);++ Ok(SyncMeasurement {+ paired_events: pairs.len(),+ inlier_events: inliers.len(),+ median_offset_ms: median,+ mad_ms: mad,+ drift_ms_per_min: slope_ms_per_sec * 60.0,+ total_drift_ms: slope_ms_per_sec * span_secs,+ span_secs,+ min_offset_ms: min,+ max_offset_ms: max,+ events: inliers,+ })+}++fn percentile_sorted(sorted: &[f64], q: f64) -> f64 {+ if sorted.is_empty() {+ return 0.0;+ }+ let idx = ((sorted.len() - 1) as f64 * q).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+}++fn percentile_sorted_f32(sorted: &[f32], q: f64) -> f32 {+ if sorted.is_empty() {+ return 0.0;+ }+ let idx = ((sorted.len() - 1) as f64 * q).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn measure_sync_detects_constant_offset() {+ let flashes: Vec<f64> = (1..12).map(|k| k as f64 * 2.0).collect();+ let beeps: Vec<f64> = flashes.iter().map(|f| f + 0.030).collect();+ let m = measure_sync(&flashes, &beeps, 6).unwrap();+ assert!((m.median_offset_ms - 30.0).abs() < 1.0);+ assert!(m.total_drift_ms.abs() < 1.0);+ }++ #[test]+ fn measure_sync_detects_drift() {+ // 5 ms/s of drift = 300 ms/min.+ let flashes: Vec<f64> = (1..12).map(|k| k as f64 * 2.0).collect();+ let beeps: Vec<f64> = flashes.iter().map(|f| f + 0.005 * f).collect();+ let m = measure_sync(&flashes, &beeps, 6).unwrap();+ assert!(+ (m.drift_ms_per_min - 300.0).abs() < 30.0,+ "drift {}",+ m.drift_ms_per_min+ );+ assert!(m.total_drift_ms > 50.0, "total {}", m.total_drift_ms);+ }++ #[test]+ fn measure_sync_rejects_outliers() {+ let mut flashes: Vec<f64> = (1..12).map(|k| k as f64 * 2.0).collect();+ let beeps: Vec<f64> = flashes.iter().map(|f| f + 0.020).collect();+ // A wild first event, like a window-transition artifact.+ flashes[0] -= 0.6;+ let m = measure_sync(&flashes, &beeps, 6).unwrap();+ assert!((m.median_offset_ms - 20.0).abs() < 2.0);+ assert!(m.inlier_events >= 9);+ }++ #[test]+ fn measure_sync_scattered_offsets_still_report_stats() {+ // Half the events displaced by 60ms: no clean inlier set exists, but+ // the caller still needs numbers (large MAD) to fail on, not an error.+ let flashes: Vec<f64> = (1..12).map(|k| k as f64 * 2.0).collect();+ let beeps: Vec<f64> = flashes+ .iter()+ .enumerate()+ .map(|(i, f)| f + if i % 2 == 0 { 0.010 } else { 0.070 })+ .collect();+ let m = measure_sync(&flashes, &beeps, 6).unwrap();+ assert!(m.mad_ms >= 20.0, "mad {}", m.mad_ms);+ }++ #[test]+ fn measure_sync_fails_with_too_few_events() {+ let flashes = vec![2.0, 4.0];+ let beeps = vec![2.02, 4.02];+ assert!(measure_sync(&flashes, &beeps, 6).is_err());+ }+}diff --git a/apps/cli/src/selftest/mod.rs b/apps/cli/src/selftest/mod.rsnew file mode 100644index 000000000..9df4bd0c6--- /dev/null+++ b/apps/cli/src/selftest/mod.rs@@ -0,0 +1,702 @@+//! `cap selftest` — diagnostics that verify Cap works correctly on this+//! machine, starting with an end-to-end A/V sync test: record a known+//! flash+beep pattern through the real capture pipeline, then measure the+//! flash-to-beep offset in both the raw recording and an export of it.++pub mod measure;+pub mod pattern;++use std::{+ path::{Path, PathBuf},+ time::Duration,+};++use cap_project::{RecordingMeta, RecordingMetaInner, StudioRecordingMeta};+use clap::{Args, Subcommand};+use serde::Serialize;++use measure::SyncMeasurement;+use pattern::PatternSpec;++const DEFAULT_PATTERN_SECS: u64 = 20;+const EVENT_PERIOD: Duration = Duration::from_secs(2);+const FLASH_LEN: Duration = Duration::from_millis(120);+const SETTLE: Duration = Duration::from_secs(2);+const MIN_EVENTS: usize = 6;++const PASS_OFFSET_MS: f64 = 80.0;+const PASS_TOTAL_DRIFT_MS: f64 = 20.0;+const PASS_MAD_MS: f64 = 20.0;+const WARN_OFFSET_MS: f64 = 120.0;+const WARN_TOTAL_DRIFT_MS: f64 = 40.0;+const MAX_RAW_EXPORT_DELTA_MS: f64 = 25.0;+const MIN_BEEP_SNR: f64 = 8.0;+/// Extra offset budget for the acoustic microphone path: sound flight time+/// plus input device latency.+const MIC_EXTRA_OFFSET_MS: f64 = 60.0;+/// Acoustic pickup competes with room noise; a lower SNR still yields sharp+/// onsets for a 1 kHz tone.+const MIN_MIC_SNR: f64 = 4.0;++#[derive(Args)]+pub struct SelftestArgs {+ #[command(subcommand)]+ pub command: SelftestCommands,+}++#[derive(Subcommand)]+pub enum SelftestCommands {+ /// Record a test pattern and verify audio/video sync end-to-end+ #[command(name = "av-sync")]+ AvSync(AvSyncArgs),+ /// Internal: measure flash/beep onsets in an existing recording or export+ #[command(name = "analyze", hide = true)]+ Analyze(AnalyzeArgs),+}++#[derive(Args)]+pub struct AnalyzeArgs {+ /// Video file (or file containing both tracks)+ video: PathBuf,+ /// Separate audio file (defaults to the video file's audio track)+ #[arg(long)]+ audio: Option<PathBuf>,+ /// Added to flash times (track start offset)+ #[arg(long, default_value_t = 0.0)]+ voffset: f64,+ /// Added to beep times (track start offset)+ #[arg(long, default_value_t = 0.0)]+ aoffset: f64,+}++#[derive(Args)]+pub struct AvSyncArgs {+ /// Seconds of test pattern to record (longer = more sensitive to drift)+ #[arg(long, default_value_t = DEFAULT_PATTERN_SECS)]+ duration: u64,+ /// Maximum fps to record at (defaults to the standard recording fps)+ #[arg(long)]+ fps: Option<u32>,+ /// Also record a microphone and verify its sync acoustically (the mic+ /// must be able to hear the test beeps through your speakers)+ #[arg(long)]+ mic: bool,+ /// Microphone device name to use with --mic (defaults to the default mic)+ #[arg(long)]+ mic_name: Option<String>,+ /// Skip exporting the recording (tests only the recording stage)+ #[arg(long)]+ skip_export: bool,+ /// Keep the recorded project on disk for inspection+ #[arg(long)]+ keep: bool,+}++#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)]+#[serde(rename_all = "lowercase")]+enum Verdict {+ Pass,+ Warn,+ Fail,+ Inconclusive,+}++#[derive(Serialize)]+struct Thresholds {+ pass_offset_ms: f64,+ pass_total_drift_ms: f64,+ warn_offset_ms: f64,+ warn_total_drift_ms: f64,+ max_raw_export_delta_ms: f64,+}++#[derive(Serialize)]+struct Diagnostics {+ beep_snr: Option<f64>,+ audio_output_latency_ms: Option<f64>,+ /// Median (beep DAC time − flash present time) at emission; the part of+ /// the measured offset contributed by the test rig itself.+ emission_skew_ms: Option<f64>,+ project_path: Option<String>,+}++#[derive(Serialize)]+struct AvSyncReport {+ verdict: Verdict,+ summary: String,+ recording: Option<SyncMeasurement>,+ microphone: Option<SyncMeasurement>,+ export: Option<SyncMeasurement>,+ thresholds: Thresholds,+ diagnostics: Diagnostics,+}++impl SelftestArgs {+ pub async fn run(self, json: bool) -> Result<(), String> {+ match self.command {+ SelftestCommands::AvSync(args) => run_av_sync(args, json).await,+ SelftestCommands::Analyze(args) => run_analyze(args),+ }+ }+}++fn run_analyze(args: AnalyzeArgs) -> Result<(), String> {+ let flashes: Vec<f64> = measure::video_flash_onsets(&args.video)?+ .into_iter()+ .map(|t| t + args.voffset)+ .collect();+ let audio_path = args.audio.as_ref().unwrap_or(&args.video);+ let audio = measure::audio_beep_onsets(audio_path)?;+ let beeps: Vec<f64> = audio.onsets.iter().map(|t| t + args.aoffset).collect();+ eprintln!(+ "flashes: {} beeps: {} (snr {:.1})",+ flashes.len(),+ beeps.len(),+ audio.snr+ );+ let measurement = measure::measure_sync(&flashes, &beeps, MIN_EVENTS)?;+ println!(+ "{}",+ serde_json::to_string_pretty(&measurement)+ .map_err(|e| format!("failed to serialize: {e}"))?+ );+ Ok(())+}++fn progress(json: bool, msg: &str) {+ if !json {+ eprintln!("{msg}");+ }+}++async fn run_av_sync(args: AvSyncArgs, json: bool) -> Result<(), String> {+ // ffmpeg's own stderr chatter (muxer segment writes, codec notes) drowns+ // the progress output; measurement errors are surfaced through Results.+ ffmpeg::util::log::set_level(ffmpeg::util::log::Level::Quiet);++ let pattern_secs = args.duration.clamp(10, 120);+ let events = (pattern_secs / EVENT_PERIOD.as_secs()).max(3) as u32;+ let spec = PatternSpec {+ settle: SETTLE,+ events,+ period: EVENT_PERIOD,+ flash_len: FLASH_LEN,+ };++ // Rough wall-clock estimate: settle + pattern + finalize + analysis (+ export).+ let estimate_secs = spec.total_runtime().as_secs() + 4 + if args.skip_export { 0 } else { 6 };++ progress(json, "Cap A/V sync self-test");+ progress(+ json,+ &format!(+ "This will take about {} seconds.",+ (estimate_secs as f64 / 10.0).round() as u64 * 10+ ),+ );+ progress(+ json,+ "A black window will appear with brief white flashes and short beeps.\n\+ Leave the window visible and make sure output volume is not muted.\n",+ );++ let project_path =+ std::env::temp_dir().join(format!("cap-selftest-{}.cap", uuid::Uuid::new_v4()));++ progress(+ json,+ &format!("[1/4] Recording test pattern ({pattern_secs}s)..."),+ );+ let mic_name =+ if args.mic || args.mic_name.is_some() {+ match args.mic_name.clone().or_else(|| {+ cap_recording::MicrophoneFeed::default_device().map(|(label, _, _)| label)+ }) {+ Some(label) => {+ progress(json, &format!("Including microphone: {label}"));+ Some(label)+ }+ None => return Err("no microphone available for --mic".to_string()),+ }+ } else {+ None+ };++ let handle = start_recording(&project_path, args.fps, mic_name.clone()).await?;++ // Give capture a moment to deliver first frames before the pattern starts.+ tokio::time::sleep(Duration::from_millis(500)).await;++ let pattern_result = pattern::request_pattern(spec).await;++ let report = match pattern_result {+ Ok(report) => report,+ Err(e) => {+ let _ = handle.stop().await;+ let _ = std::fs::remove_dir_all(&project_path);+ if e == "cancelled" {+ return Err("self-test cancelled".to_string());+ }+ return Err(format!("test pattern failed: {e}"));+ }+ };++ // Let the tail of the last beep land in the recording.+ tokio::time::sleep(Duration::from_secs(1)).await;++ progress(json, "[2/4] Finalizing recording...");+ let completed = handle+ .stop()+ .await+ .map_err(|e| format!("failed to stop recording: {e}"))?;+ let project_path = completed.project_path.clone();++ // Fragmented recordings need the shared remux step before their segment+ // files are directly readable (the same step the desktop app runs).+ {+ let project_path = project_path.clone();+ tokio::task::spawn_blocking(move || {+ cap_recording::recovery::RecoveryManager::remux_if_needed(&project_path)+ })+ .await+ .map_err(|e| format!("remux task join error: {e}"))?+ .map_err(|e| format!("failed to finalize recording segments: {e}"))?;+ }++ let emission_skew_ms = median_emission_skew_ms(&report);++ progress(json, "[3/4] Analyzing recording...");+ let raw = analyze_raw(&project_path);+ let mic = mic_name.is_some().then(|| analyze_mic(&project_path));++ let export = if args.skip_export {+ Ok(None)+ } else {+ progress(json, "[4/4] Exporting and verifying the export...");+ match crate::export::export_project_default(project_path.clone()).await {+ Ok(output) => analyze_export(&output).map(Some),+ Err(e) => Err(format!("export failed: {e}")),+ }+ };++ let (verdict, summary, raw_m, mic_m, export_m, snr) = evaluate(raw, mic, export);++ let keep = args.keep || verdict != Verdict::Pass;+ if keep {+ progress(+ json,+ &format!("Recorded project kept at {}", project_path.display()),+ );+ } else {+ let _ = std::fs::remove_dir_all(&project_path);+ }++ let report = AvSyncReport {+ verdict,+ summary: summary.clone(),+ recording: raw_m,+ microphone: mic_m,+ export: export_m,+ thresholds: Thresholds {+ pass_offset_ms: PASS_OFFSET_MS,+ pass_total_drift_ms: PASS_TOTAL_DRIFT_MS,+ warn_offset_ms: WARN_OFFSET_MS,+ warn_total_drift_ms: WARN_TOTAL_DRIFT_MS,+ max_raw_export_delta_ms: MAX_RAW_EXPORT_DELTA_MS,+ },+ diagnostics: Diagnostics {+ beep_snr: snr,+ audio_output_latency_ms: report.audio_latency_ms,+ emission_skew_ms,+ project_path: keep.then(|| project_path.display().to_string()),+ },+ };++ if json {+ println!(+ "{}",+ serde_json::to_string_pretty(&report)+ .map_err(|e| format!("failed to serialize report: {e}"))?+ );+ } else {+ print_human(&report);+ }++ match verdict {+ Verdict::Pass | Verdict::Warn => Ok(()),+ Verdict::Fail => Err(format!("A/V sync check failed: {summary}")),+ Verdict::Inconclusive => Err(format!("A/V sync check inconclusive: {summary}")),+ }+}++fn print_human(report: &AvSyncReport) {+ println!();+ if let Some(m) = &report.recording {+ println!(+ "Recording: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events (spread ±{:.0} ms)",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events, m.mad_ms+ );+ }+ if let Some(m) = &report.microphone {+ println!(+ "Microphone: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events (spread ±{:.0} ms)",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events, m.mad_ms+ );+ }+ if let Some(m) = &report.export {+ println!(+ "Export: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events (spread ±{:.0} ms)",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events, m.mad_ms+ );+ }+ let label = match report.verdict {+ Verdict::Pass => "PASS",+ Verdict::Warn => "WARN",+ Verdict::Fail => "FAIL",+ Verdict::Inconclusive => "INCONCLUSIVE",+ };+ println!("\nResult: {label} — {}", report.summary);+}++async fn start_recording(+ path: &Path,+ fps: Option<u32>,+ mic_name: Option<String>,+) -> Result<cap_recording::studio_recording::ActorHandle, String> {+ use cap_recording::{+ MicrophoneFeed, feeds::microphone, screen_capture::ScreenCaptureTarget, studio_recording,+ };+ use kameo::Actor as _;++ let display = scap_targets::Display::primary();+ let target = ScreenCaptureTarget::Display { id: display.id() };++ let mut builder =+ studio_recording::Actor::builder(path.to_path_buf(), target).with_system_audio(true);++ if let Some(label) = mic_name {+ let (error_tx, _error_rx) = flume::bounded(16);+ let mic_feed = MicrophoneFeed::spawn(MicrophoneFeed::new(error_tx));+ mic_feed+ .ask(microphone::SetInput {+ label: label.clone(),+ settings: None,+ })+ .await+ .map_err(|e| format!("failed to set microphone input '{label}': {e}"))?+ .await+ .map_err(|e| format!("microphone '{label}' failed to connect: {e}"))?;+ // The stream needs a moment to warm up before locking on slower devices.+ tokio::time::sleep(Duration::from_millis(100)).await;+ let lock = mic_feed+ .ask(microphone::Lock)+ .await+ .map_err(|e| format!("failed to lock microphone feed: {e}"))?;+ builder = builder.with_mic_feed(std::sync::Arc::new(lock));+ }++ let builder =+ cap_recording::RecordingDefaults::default().apply_to_studio_builder(builder, false, fps);++ #[cfg(target_os = "macos")]+ let shareable_content = cidre::sc::ShareableContent::current()+ .await+ .map_err(|e| {+ format!(+ "screen recording permission unavailable: {e}. \+ Grant Cap screen recording access in System Settings and retry."+ )+ })+ .map(cap_recording::SendableShareableContent::from)?;++ builder+ .build(+ #[cfg(target_os = "macos")]+ Some(shareable_content),+ )+ .await+ .map_err(|e| format!("failed to start recording: {e}"))+}++struct RawTracks {+ display: PathBuf,+ system_audio: PathBuf,+ display_start: f64,+ audio_start: f64,+ mic: Option<(PathBuf, f64)>,+}++fn locate_raw_tracks(project_path: &Path) -> Result<RawTracks, String> {+ let meta = RecordingMeta::load_for_project(project_path)+ .map_err(|e| format!("failed to load recording meta: {e}"))?;+ let RecordingMetaInner::Studio(studio) = &meta.inner else {+ return Err("self-test recording is not a studio recording".to_string());+ };+ let StudioRecordingMeta::MultipleSegments { inner, .. } = &**studio else {+ return Err("unexpected single-segment recording".to_string());+ };+ let segment = inner.segments.first().ok_or("recording has no segments")?;+ let audio = segment+ .system_audio+ .as_ref()+ .ok_or("recording has no system audio track")?;++ // Fragmented recordings write meta before remux, so the display path may+ // still reference the fragments directory; the remuxed file sits next to it.+ let mut display = meta.path(&segment.display.path);+ if display.is_dir() {+ display = display.with_extension("mp4");+ }+ if !display.is_file() {+ return Err(format!("display track not found at {}", display.display()));+ }++ let mic = segment+ .mic+ .as_ref()+ .map(|mic| (meta.path(&mic.path), mic.start_time.unwrap_or(0.0)));++ Ok(RawTracks {+ display,+ system_audio: meta.path(&audio.path),+ display_start: segment.display.start_time.unwrap_or(0.0),+ audio_start: audio.start_time.unwrap_or(0.0),+ mic,+ })+}++type MeasureOutcome = Result<(SyncMeasurement, f64), String>;++fn analyze_raw(project_path: &Path) -> MeasureOutcome {+ let tracks = locate_raw_tracks(project_path)?;++ let flashes: Vec<f64> = measure::video_flash_onsets(&tracks.display)?+ .into_iter()+ .map(|t| t + tracks.display_start)+ .collect();+ let audio = measure::audio_beep_onsets(&tracks.system_audio)?;+ let beeps: Vec<f64> = audio+ .onsets+ .iter()+ .map(|t| t + tracks.audio_start)+ .collect();++ if audio.snr < MIN_BEEP_SNR {+ return Err(format!(+ "test tone barely audible in the recording (SNR {:.1}); \+ check that output volume is not muted",+ audio.snr+ ));+ }++ measure::measure_sync(&flashes, &beeps, MIN_EVENTS).map(|m| (m, audio.snr))+}++/// Measures the microphone track against the display flashes. The beeps+/// reach the mic acoustically, so this validates the real input-device path+/// end to end (device rate, resampling, timestamping).+fn analyze_mic(project_path: &Path) -> MeasureOutcome {+ let tracks = locate_raw_tracks(project_path)?;+ let (mic_path, mic_start) = tracks+ .mic+ .ok_or("recording has no microphone track despite --mic")?;++ let flashes: Vec<f64> = measure::video_flash_onsets(&tracks.display)?+ .into_iter()+ .map(|t| t + tracks.display_start)+ .collect();+ let audio = measure::audio_beep_onsets(&mic_path)?;+ let beeps: Vec<f64> = audio.onsets.iter().map(|t| t + mic_start).collect();++ if audio.snr < MIN_MIC_SNR {+ return Err(format!(+ "test tone barely audible through the microphone (SNR {:.1}); \+ raise the output volume or move the mic closer to the speakers",+ audio.snr+ ));+ }++ measure::measure_sync(&flashes, &beeps, MIN_EVENTS).map(|m| (m, audio.snr))+}++fn analyze_export(output: &Path) -> MeasureOutcome {+ let flashes = measure::video_flash_onsets(output)?;+ let audio = measure::audio_beep_onsets(output)?;+ measure::measure_sync(&flashes, &audio.onsets, MIN_EVENTS).map(|m| (m, audio.snr))+}++fn median_emission_skew_ms(report: &pattern::PatternReport) -> Option<f64> {+ let mut skews: Vec<f64> = report+ .flash_presents+ .iter()+ .filter_map(|(event, flash)| {+ let (_, beep) = report.beep_outputs.iter().find(|(e, _)| e == event)?;+ Some(if beep >= flash {+ (*beep - *flash).as_secs_f64() * 1000.0+ } else {+ -((*flash - *beep).as_secs_f64() * 1000.0)+ })+ })+ .collect();+ if skews.is_empty() {+ return None;+ }+ skews.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ Some(skews[skews.len() / 2])+}++fn classify(m: &SyncMeasurement) -> Verdict {+ let offset = m.median_offset_ms.abs();+ let drift = m.total_drift_ms.abs();+ if offset <= PASS_OFFSET_MS && drift <= PASS_TOTAL_DRIFT_MS && m.mad_ms <= PASS_MAD_MS {+ Verdict::Pass+ } else if offset <= WARN_OFFSET_MS && drift <= WARN_TOTAL_DRIFT_MS {+ Verdict::Warn+ } else {+ Verdict::Fail+ }+}++#[allow(clippy::type_complexity)]+/// Classifies the acoustic microphone measurement: same drift/spread rules+/// as the digital path, with extra offset budget for sound flight time and+/// input device latency.+fn classify_mic(m: &SyncMeasurement) -> Verdict {+ let offset = m.median_offset_ms.abs();+ let drift = m.total_drift_ms.abs();+ if offset <= PASS_OFFSET_MS + MIC_EXTRA_OFFSET_MS+ && drift <= PASS_TOTAL_DRIFT_MS+ && m.mad_ms <= PASS_MAD_MS+ {+ Verdict::Pass+ } else if offset <= WARN_OFFSET_MS + MIC_EXTRA_OFFSET_MS && drift <= WARN_TOTAL_DRIFT_MS {+ Verdict::Warn+ } else {+ Verdict::Fail+ }+}++/// Merges verdicts: Fail dominates everything, otherwise the worse one wins.+fn merge_verdicts(a: Verdict, b: Verdict) -> Verdict {+ if a == Verdict::Fail || b == Verdict::Fail {+ Verdict::Fail+ } else {+ a.max(b)+ }+}++#[allow(clippy::type_complexity)]+fn evaluate(+ raw: MeasureOutcome,+ mic: Option<MeasureOutcome>,+ export: Result<Option<(SyncMeasurement, f64)>, String>,+) -> (+ Verdict,+ String,+ Option<SyncMeasurement>,+ Option<SyncMeasurement>,+ Option<SyncMeasurement>,+ Option<f64>,+) {+ let (raw_m, snr) = match raw {+ Ok((m, snr)) => (m, snr),+ Err(reason) => {+ return (Verdict::Inconclusive, reason, None, None, None, None);+ }+ };++ let export_m = match export {+ Ok(Some((m, _))) => Some(m),+ Ok(None) => None,+ Err(reason) => {+ // A recording that measures fine but cannot be exported is a hard+ // failure: the export path is part of the product.+ return (Verdict::Fail, reason, Some(raw_m), None, None, Some(snr));+ }+ };++ let mut verdict = classify(&raw_m);+ let mut reasons: Vec<String> = Vec::new();++ if verdict != Verdict::Pass {+ reasons.push(format!(+ "recording offset {:+.0} ms / drift {:+.0} ms over {:.0}s",+ raw_m.median_offset_ms, raw_m.total_drift_ms, raw_m.span_secs+ ));+ }++ let mic_m = match mic {+ None => None,+ Some(Ok((m, _))) => {+ let mic_verdict = classify_mic(&m);+ if mic_verdict != Verdict::Pass {+ reasons.push(format!(+ "microphone offset {:+.0} ms / drift {:+.0} ms over {:.0}s",+ m.median_offset_ms, m.total_drift_ms, m.span_secs+ ));+ }+ verdict = merge_verdicts(verdict, mic_verdict);+ Some(m)+ }+ Some(Err(reason)) => {+ // The mic leg was explicitly requested; not being able to measure+ // it makes the run inconclusive (unless something already failed).+ verdict = merge_verdicts(verdict, Verdict::Inconclusive);+ reasons.push(reason);+ None+ }+ };++ if let Some(export_m) = &export_m {+ let export_verdict = classify(export_m);+ if export_verdict > verdict && export_verdict == Verdict::Fail {+ reasons.push(format!(+ "export offset {:+.0} ms / drift {:+.0} ms over {:.0}s",+ export_m.median_offset_ms, export_m.total_drift_ms, export_m.span_secs+ ));+ }+ verdict = merge_verdicts(verdict, export_verdict);+ let delta = (export_m.median_offset_ms - raw_m.median_offset_ms).abs();+ if delta > MAX_RAW_EXPORT_DELTA_MS {+ verdict = Verdict::Fail;+ reasons.push(format!(+ "export changes sync by {delta:.0} ms vs the recording"+ ));+ }+ }++ let summary = match verdict {+ Verdict::Pass => format!(+ "audio/video sync is healthy (offset {:+.0} ms, drift {:+.0} ms over {:.0}s)",+ raw_m.median_offset_ms, raw_m.total_drift_ms, raw_m.span_secs+ ),+ Verdict::Warn => format!(+ "sync is within tolerance but not ideal: {}",+ reasons.join("; ")+ ),+ Verdict::Fail => format!("sync problem detected: {}", reasons.join("; ")),+ Verdict::Inconclusive => reasons.join("; "),+ };++ (verdict, summary, Some(raw_m), mic_m, export_m, Some(snr))+}++impl PartialOrd for Verdict {+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {+ Some(self.cmp(other))+ }+}++impl Ord for Verdict {+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {+ fn rank(v: &Verdict) -> u8 {+ match v {+ Verdict::Pass => 0,+ Verdict::Warn => 1,+ Verdict::Fail => 2,+ Verdict::Inconclusive => 3,+ }+ }+ rank(self).cmp(&rank(other))+ }+}diff --git a/apps/cli/src/selftest/pattern.rs b/apps/cli/src/selftest/pattern.rsnew file mode 100644index 000000000..2aee46c0a--- /dev/null+++ b/apps/cli/src/selftest/pattern.rs@@ -0,0 +1,493 @@+//! Main-thread test pattern for the A/V sync self-test.+//!+//! Renders a fullscreen black window that flashes white at a fixed period+//! while playing a 1 kHz beep through the default audio output at the same+//! scheduled instants. The window must run on the process main thread+//! (required by AppKit); the async side of the self-test requests a pattern+//! run through [`request_pattern`] and the real main thread services it via+//! [`serve_main_thread`].++use std::{+ num::NonZeroU32,+ sync::{+ Arc, Mutex, OnceLock,+ atomic::{AtomicBool, Ordering},+ mpsc,+ },+ time::{Duration, Instant},+};++use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use winit::{+ application::ApplicationHandler,+ event::{ElementState, WindowEvent},+ event_loop::{ActiveEventLoop, ControlFlow, EventLoop},+ keyboard::{Key, NamedKey},+ platform::run_on_demand::EventLoopExtRunOnDemand,+ window::{Fullscreen, Window, WindowId, WindowLevel},+};++#[derive(Clone, Copy, Debug)]+pub struct PatternSpec {+ /// Time to sit black before the first event, letting capture settle.+ pub settle: Duration,+ /// Number of flash+beep events.+ pub events: u32,+ /// Time between event onsets.+ pub period: Duration,+ /// Duration of each flash / beep.+ pub flash_len: Duration,+}++impl PatternSpec {+ pub fn total_runtime(&self) -> Duration {+ self.settle + self.period * self.events + Duration::from_millis(500)+ }+}++#[derive(Debug)]+pub struct PatternReport {+ /// Instants at which each flash was actually presented (post-present).+ pub flash_presents: Vec<(u32, Instant)>,+ /// Estimated instants at which each beep hit the output (DAC time).+ pub beep_outputs: Vec<(u32, Instant)>,+ /// Mean reported output latency of the audio stream, if available.+ pub audio_latency_ms: Option<f64>,+}++pub struct PatternRequest {+ pub spec: PatternSpec,+ pub reply: mpsc::Sender<Result<PatternReport, String>>,+}++static PATTERN_TX: OnceLock<Mutex<Option<mpsc::Sender<PatternRequest>>>> = OnceLock::new();++/// Called from `main()` before the runtime thread spawns, when the parsed+/// command is a self-test. Returns the receiver the main thread must serve.+pub fn install_main_thread_runner() -> mpsc::Receiver<PatternRequest> {+ let (tx, rx) = mpsc::channel();+ let _ = PATTERN_TX.set(Mutex::new(Some(tx)));+ rx+}++/// Called by the runtime thread once the command finishes, releasing the main+/// thread from its serve loop.+pub fn shutdown_main_thread_runner() {+ if let Some(slot) = PATTERN_TX.get() {+ slot.lock().unwrap().take();+ }+}++/// Runs pattern requests on the main thread until the sender is dropped via+/// [`shutdown_main_thread_runner`].+pub fn serve_main_thread(rx: mpsc::Receiver<PatternRequest>) {+ while let Ok(request) = rx.recv() {+ let result = run_pattern(request.spec);+ let _ = request.reply.send(result);+ }+}++/// Called from the async side; blocks the calling task until the pattern+/// window has run to completion on the main thread.+pub async fn request_pattern(spec: PatternSpec) -> Result<PatternReport, String> {+ let tx = PATTERN_TX+ .get()+ .and_then(|slot| slot.lock().unwrap().clone())+ .ok_or("self-test pattern runner is not installed on the main thread")?;+ tokio::task::spawn_blocking(move || {+ let (reply_tx, reply_rx) = mpsc::channel();+ tx.send(PatternRequest {+ spec,+ reply: reply_tx,+ })+ .map_err(|_| "main thread pattern runner is gone".to_string())?;+ reply_rx+ .recv()+ .map_err(|_| "main thread pattern runner dropped the request".to_string())?+ })+ .await+ .map_err(|e| format!("pattern task join error: {e}"))?+}++struct BeepState {+ epoch: Instant,+ period_samples: u64,+ beep_samples: u64,+ events: u32,+ sample_rate: u32,+ channels: usize,+ /// Absolute sample index of pattern epoch, fixed on the first callback.+ epoch_sample: Mutex<Option<i64>>,+ samples_written: Mutex<u64>,+ beep_outputs: Mutex<Vec<(u32, Instant)>>,+ latency_sum_ms: Mutex<(f64, u64)>,+}++impl BeepState {+ fn fill(&self, data: &mut [f32], info: &cpal::OutputCallbackInfo) {+ let now = Instant::now();+ let mut written = self.samples_written.lock().unwrap();+ let buffer_start_sample = *written as i64;++ let mut epoch_sample = self.epoch_sample.lock().unwrap();+ let epoch_sample = *epoch_sample.get_or_insert_with(|| {+ let until_epoch = if self.epoch > now {+ (self.epoch - now).as_secs_f64()+ } else {+ -(now - self.epoch).as_secs_f64()+ };+ buffer_start_sample + (until_epoch * self.sample_rate as f64) as i64+ });++ let latency = info+ .timestamp()+ .playback+ .duration_since(&info.timestamp().callback);+ if let Some(latency) = latency {+ let mut acc = self.latency_sum_ms.lock().unwrap();+ acc.0 += latency.as_secs_f64() * 1000.0;+ acc.1 += 1;+ }++ let frames = data.len() / self.channels.max(1);+ for frame_idx in 0..frames {+ let abs_sample = buffer_start_sample + frame_idx as i64;+ let rel = abs_sample - epoch_sample;+ let mut value = 0.0f32;+ if rel >= 0 {+ let event = (rel as u64) / self.period_samples;+ let within = (rel as u64) % self.period_samples;+ if event < u64::from(self.events) && within < self.beep_samples {+ // 1 kHz tone with a 2 ms fade-in/out to avoid clicks while+ // keeping the onset sharp for detection.+ let t = within as f32 / self.sample_rate as f32;+ let fade_len = 0.002 * self.sample_rate as f32;+ let fade_in = (within as f32 / fade_len).min(1.0);+ let remaining = (self.beep_samples - within) as f32;+ let fade_out = (remaining / fade_len).min(1.0);+ value =+ 0.4 * fade_in * fade_out * (t * 1000.0 * 2.0 * std::f32::consts::PI).sin();++ if within == 0 {+ let dac = now+ + latency.unwrap_or_default()+ + Duration::from_secs_f64(frame_idx as f64 / self.sample_rate as f64);+ self.beep_outputs.lock().unwrap().push((event as u32, dac));+ }+ }+ }+ for ch in 0..self.channels {+ data[frame_idx * self.channels + ch] = value;+ }+ }++ *written += frames as u64;+ }+}++fn build_beep_stream(+ epoch: Instant,+ spec: &PatternSpec,+) -> Result<(cpal::Stream, Arc<BeepState>), String> {+ let host = cpal::default_host();+ let device = host+ .default_output_device()+ .ok_or("no default audio output device; cannot run the sync test")?;+ let config = device+ .default_output_config()+ .map_err(|e| format!("failed to query audio output config: {e}"))?;++ let sample_rate = config.sample_rate().0;+ let channels = config.channels() as usize;+ let state = Arc::new(BeepState {+ epoch,+ period_samples: (spec.period.as_secs_f64() * sample_rate as f64) as u64,+ beep_samples: (spec.flash_len.as_secs_f64() * sample_rate as f64) as u64,+ events: spec.events,+ sample_rate,+ channels,+ epoch_sample: Mutex::new(None),+ samples_written: Mutex::new(0),+ beep_outputs: Mutex::new(Vec::new()),+ latency_sum_ms: Mutex::new((0.0, 0)),+ });++ let err_fn = |e| tracing::warn!("selftest audio stream error: {e}");+ let stream_config = config.config();++ let stream = match config.sample_format() {+ cpal::SampleFormat::F32 => {+ let state = state.clone();+ device+ .build_output_stream(+ &stream_config,+ move |data: &mut [f32], info: &cpal::OutputCallbackInfo| {+ state.fill(data, info);+ },+ err_fn,+ None,+ )+ .map_err(|e| format!("failed to build audio output stream: {e}"))?+ }+ cpal::SampleFormat::I16 => {+ let state = state.clone();+ let mut scratch = Vec::new();+ device+ .build_output_stream(+ &stream_config,+ move |data: &mut [i16], info: &cpal::OutputCallbackInfo| {+ scratch.clear();+ scratch.resize(data.len(), 0.0f32);+ state.fill(&mut scratch, info);+ for (dst, src) in data.iter_mut().zip(&scratch) {+ *dst = (src * f32::from(i16::MAX)) as i16;+ }+ },+ err_fn,+ None,+ )+ .map_err(|e| format!("failed to build audio output stream: {e}"))?+ }+ other => {+ return Err(format!(+ "unsupported audio output sample format for the sync test: {other:?}"+ ));+ }+ };++ Ok((stream, state))+}++struct PatternApp {+ spec: PatternSpec,+ run_start: Instant,+ epoch: Instant,+ window: Option<Arc<Window>>,+ surface: Option<softbuffer::Surface<Arc<Window>, Arc<Window>>>,+ size: (u32, u32),+ last_drawn_white: bool,+ flash_presents: Vec<(u32, Instant)>,+ aborted: Arc<AtomicBool>,+ error: Option<String>,+}++impl PatternApp {+ /// Returns whether the pattern should currently show white, and the event+ /// index if so.+ fn desired_state(&self, now: Instant) -> Option<u32> {+ if now < self.epoch {+ return None;+ }+ let rel = now - self.epoch;+ let period = self.spec.period.as_secs_f64();+ let event = (rel.as_secs_f64() / period) as u32;+ let within = rel.as_secs_f64() - f64::from(event) * period;+ (event < self.spec.events && within < self.spec.flash_len.as_secs_f64()).then_some(event)+ }++ fn next_transition(&self, now: Instant) -> Instant {+ if now < self.epoch {+ return self.epoch;+ }+ let rel = (now - self.epoch).as_secs_f64();+ let period = self.spec.period.as_secs_f64();+ let event = (rel / period) as u32;+ let within = rel - f64::from(event) * period;+ let flash = self.spec.flash_len.as_secs_f64();+ let next_rel = if within < flash {+ f64::from(event) * period + flash+ } else {+ f64::from(event + 1) * period+ };+ self.epoch + Duration::from_secs_f64(next_rel)+ }++ fn done_at(&self) -> Instant {+ self.run_start + self.spec.total_runtime()+ }++ fn draw(&mut self, event_loop: &ActiveEventLoop) {+ let now = Instant::now();+ let desired = self.desired_state(now);+ let white = desired.is_some();++ let Some(surface) = self.surface.as_mut() else {+ return;+ };+ let (w, h) = self.size;+ if w == 0 || h == 0 {+ return;+ }+ if surface+ .resize(NonZeroU32::new(w).unwrap(), NonZeroU32::new(h).unwrap())+ .is_err()+ {+ return;+ }+ let Ok(mut buffer) = surface.buffer_mut() else {+ return;+ };+ // Keep the high byte opaque: some softbuffer backends (macOS layers)+ // treat it as alpha rather than ignoring it.+ let color: u32 = if white { 0xFFFF_FFFF } else { 0xFF00_0000 };+ buffer.fill(color);+ let presented = buffer.present().is_ok();++ if presented && white && !self.last_drawn_white {+ let event = desired.unwrap_or(0);+ if self+ .flash_presents+ .last()+ .is_none_or(|(last, _)| *last != event)+ {+ self.flash_presents.push((event, Instant::now()));+ }+ }+ self.last_drawn_white = white;++ if Instant::now() >= self.done_at() {+ event_loop.exit();+ }+ }+}++impl ApplicationHandler for PatternApp {+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {+ if self.window.is_some() {+ return;+ }+ let attrs = Window::default_attributes()+ .with_title("Cap Sync Test")+ .with_fullscreen(Some(Fullscreen::Borderless(None)))+ .with_window_level(WindowLevel::AlwaysOnTop);+ let window = match event_loop.create_window(attrs) {+ Ok(w) => Arc::new(w),+ Err(e) => {+ self.error = Some(format!("failed to create test window: {e}"));+ event_loop.exit();+ return;+ }+ };+ let size = window.inner_size();+ self.size = (size.width, size.height);++ let context = match softbuffer::Context::new(window.clone()) {+ Ok(c) => c,+ Err(e) => {+ self.error = Some(format!("failed to create draw context: {e}"));+ event_loop.exit();+ return;+ }+ };+ match softbuffer::Surface::new(&context, window.clone()) {+ Ok(s) => self.surface = Some(s),+ Err(e) => {+ self.error = Some(format!("failed to create draw surface: {e}"));+ event_loop.exit();+ return;+ }+ }+ window.request_redraw();+ self.window = Some(window);+ }++ fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {+ match event {+ WindowEvent::CloseRequested => {+ self.aborted.store(true, Ordering::Release);+ event_loop.exit();+ }+ WindowEvent::KeyboardInput { event, .. } => {+ if event.state == ElementState::Pressed+ && event.logical_key == Key::Named(NamedKey::Escape)+ {+ self.aborted.store(true, Ordering::Release);+ event_loop.exit();+ }+ }+ WindowEvent::Resized(size) => {+ self.size = (size.width, size.height);+ }+ WindowEvent::RedrawRequested => {+ self.draw(event_loop);+ }+ _ => {}+ }+ }++ fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {+ let now = Instant::now();+ if now >= self.done_at() {+ event_loop.exit();+ return;+ }+ let next = self.next_transition(now).min(self.done_at());+ if let Some(window) = &self.window {+ // Redraw slightly eagerly so the flip lands at (not after) the+ // scheduled transition.+ window.request_redraw();+ }+ event_loop.set_control_flow(ControlFlow::WaitUntil(next));+ }+}++fn run_pattern(spec: PatternSpec) -> Result<PatternReport, String> {+ #[allow(unused_mut)]+ let mut builder = EventLoop::builder();+ #[cfg(target_os = "macos")]+ {+ use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};+ builder+ .with_activation_policy(ActivationPolicy::Regular)+ .with_activate_ignoring_other_apps(true);+ }+ let mut event_loop = builder+ .build()+ .map_err(|e| format!("failed to create event loop: {e}"))?;++ let run_start = Instant::now();+ let epoch = run_start + spec.settle;++ let (stream, beep_state) = build_beep_stream(epoch, &spec)?;+ stream+ .play()+ .map_err(|e| format!("failed to start audio output: {e}"))?;++ let mut app = PatternApp {+ spec,+ run_start,+ epoch,+ window: None,+ surface: None,+ size: (0, 0),+ last_drawn_white: false,+ flash_presents: Vec::new(),+ aborted: Arc::new(AtomicBool::new(false)),+ error: None,+ };++ event_loop+ .run_app_on_demand(&mut app)+ .map_err(|e| format!("event loop error: {e}"))?;++ drop(stream);++ if let Some(error) = app.error {+ return Err(error);+ }+ if app.aborted.load(Ordering::Acquire) {+ return Err("cancelled".to_string());+ }++ let latency = {+ let acc = beep_state.latency_sum_ms.lock().unwrap();+ (acc.1 > 0).then(|| acc.0 / acc.1 as f64)+ };+ let beep_outputs = beep_state.beep_outputs.lock().unwrap().clone();++ Ok(PatternReport {+ flash_presents: app.flash_presents,+ beep_outputs,+ audio_latency_ms: latency,+ })+}diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rsnew file mode 100644index 000000000..c9adb1aea--- /dev/null+++ b/crates/recording/tests/sync_matrix.rs@@ -0,0 +1,495 @@+//! Synthetic device matrix for A/V sync.+//!+//! Drives the real recording pipeline (sources -> mux loop -> encoders ->+//! containers) with synthetic video and audio across sample rates, channel+//! counts, frame rates and delivery pathologies (jitter, drops, gaps), then+//! verifies the muxed output preserves real time. No capture hardware is+//! required, so this runs identically on macOS, Windows and Linux CI.+//!+//! Frames are emitted in real time because the pipeline pins video+//! timestamps to the wall clock; each case therefore costs its content+//! duration. Keep cases short.+//!+//! Set `CAP_SYNC_MATRIX_REPORT` to write a JSON report of every case.++use std::{+ path::{Path, PathBuf},+ time::Duration,+};++use cap_media_info::{AudioInfo, Sample, Type, VideoInfo};+use cap_recording::{+ AudioFrame, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,+ ChannelVideoSourceConfig, OutputPipeline,+ ffmpeg::{+ FFmpegVideoFrame, Mp4Muxer, OggMuxer, SegmentedVideoMuxer, SegmentedVideoMuxerConfig,+ },+};+use cap_timestamp::{Timestamp, Timestamps};+use serde::Serialize;++const CONTENT_SECS: f64 = 4.0;+/// Absolute tolerance for a muxed pts vs the sent capture timestamp. Covers+/// warmup anchoring, emission jitter and encoder rounding.+const ABS_TOLERANCE_SECS: f64 = 0.20;+/// Tolerance for the relative structure (pts deltas vs sent deltas), which is+/// what actually determines sync drift.+const REL_TOLERANCE_SECS: f64 = 0.10;+/// Tolerance for decoded audio duration vs generated duration.+const AUDIO_DURATION_TOLERANCE_SECS: f64 = 0.15;++#[derive(Debug, Clone, Copy)]+enum VideoScenario {+ Steady,+ Jitter,+ Drops,+ Gap,+}++impl VideoScenario {+ fn name(self) -> &'static str {+ match self {+ Self::Steady => "steady",+ Self::Jitter => "jitter",+ Self::Drops => "drops",+ Self::Gap => "gap",+ }+ }++ /// Deterministic capture timestamps (seconds) for the scenario.+ fn timestamps(self, fps: u32) -> Vec<f64> {+ let period = 1.0 / f64::from(fps);+ let total = (CONTENT_SECS * f64::from(fps)) as u64;+ let mut out = Vec::new();+ for k in 0..total {+ let base = k as f64 * period;+ match self {+ Self::Steady => out.push(base),+ Self::Jitter => {+ // Deterministic pseudo-jitter, +-40% of the period, kept+ // monotonic (and non-negative) by construction.+ let phase = (k as f64 * 0.7368).fract() - 0.5;+ out.push((base + phase * period * 0.8).max(0.0));+ }+ Self::Drops => {+ // Drop every 4th and 7th frame: the capture stream simply+ // never delivers them.+ if k % 4 != 3 && k % 7 != 6 {+ out.push(base);+ }+ }+ Self::Gap => {+ // 1.5s of frames, a 2s static-screen gap, then the rest.+ let t = base;+ if t < 1.5 {+ out.push(t);+ } else {+ out.push(t + 2.0);+ }+ }+ }+ }+ out.sort_by(|a, b| a.partial_cmp(b).unwrap());+ out.dedup_by(|a, b| (*a - *b).abs() < period * 0.25);+ out+ }+}++#[derive(Serialize)]+struct CaseResult {+ name: String,+ pass: bool,+ detail: String,+}++fn make_video_frame(width: u32, height: u32, shade: u8) -> ffmpeg::frame::Video {+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, width, height);+ for byte in frame.data_mut(0).iter_mut() {+ *byte = shade;+ }+ frame+}++async fn run_video_case(+ fps: u32,+ scenario: VideoScenario,+ fragmented: bool,+) -> Result<String, String> {+ let temp = tempfile::tempdir().map_err(|e| format!("tempdir: {e}"))?;+ let out_path = if fragmented {+ temp.path().join("display")+ } else {+ temp.path().join("display.mp4")+ };++ let info = VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 160, 120, fps);+ let (tx, rx) = flume::bounded::<FFmpegVideoFrame>(32);+ let timestamps = Timestamps::now();++ let sent = scenario.timestamps(fps);+ let emit = {+ let sent = sent.clone();+ let base = timestamps.instant();+ tokio::spawn(async move {+ for &ts in &sent {+ tokio::time::sleep_until((base + Duration::from_secs_f64(ts)).into()).await;+ let frame = FFmpegVideoFrame {+ inner: make_video_frame(160, 120, ((ts * 40.0) as u8).wrapping_mul(3)),+ timestamp: Timestamp::Instant(base + Duration::from_secs_f64(ts)),+ };+ if tx.send_async(frame).await.is_err() {+ break;+ }+ }+ // Sender drops here, ending the stream.+ })+ };++ let builder = OutputPipeline::builder(out_path.clone())+ .with_video::<ChannelVideoSource<FFmpegVideoFrame>>(ChannelVideoSourceConfig::new(info, rx))+ .with_timestamps(timestamps);++ let pipeline = if fragmented {+ builder+ .build::<SegmentedVideoMuxer>(SegmentedVideoMuxerConfig {+ segment_duration: Duration::from_secs(2),+ ..Default::default()+ })+ .await+ } else {+ builder.build::<Mp4Muxer>(()).await+ }+ .map_err(|e| format!("pipeline build: {e}"))?;++ emit.await.map_err(|e| format!("emit join: {e}"))?;+ // Allow the tail of the stream to flush through the encoder.+ tokio::time::sleep(Duration::from_millis(500)).await;+ let finished = pipeline.stop().await.map_err(|e| format!("stop: {e}"))?;++ // Read back the muxed pts.+ let playable = if fragmented {+ concat_fmp4(&out_path, temp.path())?+ } else {+ out_path.clone()+ };+ let pts = read_video_pts(&playable)?;++ if pts.len() != sent.len() {+ return Err(format!(+ "frame count mismatch: sent {} frames, container has {}",+ sent.len(),+ pts.len()+ ));+ }++ let mut max_abs: f64 = 0.0;+ let mut max_rel: f64 = 0.0;+ for (i, (&p, &s)) in pts.iter().zip(&sent).enumerate() {+ max_abs = max_abs.max((p - s).abs());+ let rel = ((p - pts[0]) - (s - sent[0])).abs();+ max_rel = max_rel.max(rel);+ if rel > REL_TOLERANCE_SECS {+ return Err(format!(+ "frame {i}: relative pts error {rel:.3}s (pts {p:.3}s vs sent {s:.3}s)"+ ));+ }+ }+ if max_abs > ABS_TOLERANCE_SECS {+ return Err(format!(+ "absolute pts error {max_abs:.3}s exceeds tolerance"+ ));+ }++ // The span the recorder would persist must match the sent span.+ if let Some((first, last)) = finished.video_timestamp_span {+ let span = (last - first).as_secs_f64();+ let expected = sent.last().unwrap() - sent[0];+ if (span - expected).abs() > 0.25 {+ return Err(format!(+ "video_timestamp_span {span:.3}s does not match sent span {expected:.3}s"+ ));+ }+ } else {+ return Err("video_timestamp_span missing".to_string());+ }++ // Gap preservation is the regression that desynced 0.5.4.+ if matches!(scenario, VideoScenario::Gap) {+ let mut max_gap: f64 = 0.0;+ for pair in pts.windows(2) {+ max_gap = max_gap.max(pair[1] - pair[0]);+ }+ if max_gap < 1.8 {+ return Err(format!(+ "2s capture gap collapsed to {max_gap:.3}s in the container"+ ));+ }+ }++ Ok(format!(+ "{} frames, max abs err {:.0} ms, max rel err {:.0} ms",+ pts.len(),+ max_abs * 1000.0,+ max_rel * 1000.0+ ))+}++async fn run_audio_case(rate: u32, channels: u16) -> Result<String, String> {+ let temp = tempfile::tempdir().map_err(|e| format!("tempdir: {e}"))?;+ let out_path = temp.path().join("audio.ogg");++ let info = AudioInfo::new(Sample::F32(Type::Packed), rate, channels)+ .map_err(|e| format!("audio info: {e:?}"))?;+ let (tx, rx) = futures::channel::mpsc::channel::<AudioFrame>(32);+ let timestamps = Timestamps::now();++ let chunk_frames = (rate / 50).max(1) as usize; // 20ms chunks+ let total_chunks = (CONTENT_SECS * 50.0) as usize;++ let emit = {+ let base = timestamps.instant();+ let mut tx = tx;+ let info = info;+ tokio::spawn(async move {+ use futures::SinkExt;+ for k in 0..total_chunks {+ let ts = k as f64 * 0.02;+ tokio::time::sleep_until((base + Duration::from_secs_f64(ts)).into()).await;+ let mut frame = ffmpeg::frame::Audio::new(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),+ chunk_frames,+ info.channel_layout(),+ );+ frame.set_rate(rate);+ let data = frame.data_mut(0);+ for (i, sample) in bytemuck_cast_f32(data).iter_mut().enumerate() {+ let n = (k * chunk_frames + i / channels as usize) as f32;+ *sample = (n * 440.0 * 2.0 * std::f32::consts::PI / rate as f32).sin() * 0.4;+ }+ let frame = AudioFrame::new(+ frame,+ Timestamp::Instant(base + Duration::from_secs_f64(ts)),+ );+ if tx.send(frame).await.is_err() {+ break;+ }+ }+ })+ };++ let pipeline = OutputPipeline::builder(out_path.clone())+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(info, rx))+ .with_timestamps(timestamps)+ .build::<OggMuxer>(())+ .await+ .map_err(|e| format!("pipeline build: {e}"))?;++ emit.await.map_err(|e| format!("emit join: {e}"))?;+ tokio::time::sleep(Duration::from_millis(300)).await;+ pipeline.stop().await.map_err(|e| format!("stop: {e}"))?;++ let (duration, decoded_channels, energy) = read_audio_stats(&out_path)?;+ if (duration - CONTENT_SECS).abs() > AUDIO_DURATION_TOLERANCE_SECS {+ return Err(format!(+ "decoded duration {duration:.3}s vs expected {CONTENT_SECS:.3}s \+ (rate handling error: content plays at the wrong speed)"+ ));+ }+ if energy < 0.01 {+ return Err(format!(+ "decoded audio is nearly silent (rms {energy:.4}); samples were lost or zeroed"+ ));+ }++ Ok(format!(+ "duration {duration:.3}s, {decoded_channels} ch decoded, rms {energy:.3}"+ ))+}++fn bytemuck_cast_f32(data: &mut [u8]) -> &mut [f32] {+ let len = data.len() / 4;+ unsafe { std::slice::from_raw_parts_mut(data.as_mut_ptr().cast::<f32>(), len) }+}++/// Concatenates a fragmented-mp4 segment directory (init.mp4 + *.m4s) into a+/// single playable file.+fn concat_fmp4(dir: &Path, scratch: &Path) -> Result<PathBuf, String> {+ let init = dir.join("init.mp4");+ let mut bytes = std::fs::read(&init).map_err(|e| format!("read init.mp4: {e}"))?;+ let mut segments: Vec<PathBuf> = std::fs::read_dir(dir)+ .map_err(|e| format!("read segment dir: {e}"))?+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| p.extension().is_some_and(|ext| ext == "m4s"))+ .collect();+ segments.sort();+ if segments.is_empty() {+ return Err("no media segments produced".to_string());+ }+ for segment in &segments {+ bytes.extend(std::fs::read(segment).map_err(|e| format!("read segment: {e}"))?);+ }+ let out = scratch.join("concat.mp4");+ std::fs::write(&out, bytes).map_err(|e| format!("write concat: {e}"))?;+ Ok(out)+}++fn read_video_pts(path: &Path) -> Result<Vec<f64>, String> {+ let mut ictx = ffmpeg::format::input(&path).map_err(|e| format!("open {e}"))?;+ let stream = ictx+ .streams()+ .best(ffmpeg::media::Type::Video)+ .ok_or("no video stream")?;+ let index = stream.index();+ let tb = stream.time_base();+ let tb = f64::from(tb.numerator()) / f64::from(tb.denominator());+ let mut pts: Vec<f64> = ictx+ .packets()+ .filter_map(|(s, p)| (s.index() == index).then_some(p.pts()).flatten())+ .map(|p| p as f64 * tb)+ .collect();+ pts.sort_by(|a, b| a.partial_cmp(b).unwrap());+ Ok(pts)+}++fn read_audio_stats(path: &Path) -> Result<(f64, u16, f64), String> {+ let mut ictx = ffmpeg::format::input(&path).map_err(|e| format!("open {e}"))?;+ let stream = ictx+ .streams()+ .best(ffmpeg::media::Type::Audio)+ .ok_or("no audio stream")?;+ let index = stream.index();+ let ctx = ffmpeg::codec::context::Context::from_parameters(stream.parameters())+ .map_err(|e| format!("params: {e}"))?;+ let mut decoder = ctx.decoder().audio().map_err(|e| format!("decoder: {e}"))?;++ let mut samples = 0u64;+ let mut rate = 0u32;+ let mut channels = 0u16;+ let mut sum_sq = 0.0f64;+ let mut counted = 0u64;+ let mut frame = ffmpeg::frame::Audio::empty();+ for (s, packet) in ictx.packets() {+ if s.index() != index {+ continue;+ }+ if decoder.send_packet(&packet).is_ok() {+ while decoder.receive_frame(&mut frame).is_ok() {+ samples += frame.samples() as u64;+ rate = frame.rate();+ channels = frame.channels();+ if let ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar) =+ frame.format()+ {+ for &v in &frame.plane::<f32>(0)[..frame.samples()] {+ sum_sq += f64::from(v) * f64::from(v);+ counted += 1;+ }+ }+ }+ }+ }+ let _ = decoder.send_eof();+ while decoder.receive_frame(&mut frame).is_ok() {+ samples += frame.samples() as u64;+ }++ if rate == 0 {+ return Err("no audio decoded".to_string());+ }+ let rms = if counted > 0 {+ (sum_sq / counted as f64).sqrt()+ } else {+ 0.0+ };+ Ok((samples as f64 / f64::from(rate), channels, rms))+}++#[tokio::test(flavor = "multi_thread")]+async fn synthetic_device_matrix_preserves_sync() {+ let mut results: Vec<CaseResult> = Vec::new();++ let video_cases: Vec<(u32, VideoScenario, bool)> = vec![+ (15, VideoScenario::Steady, true),+ (30, VideoScenario::Steady, true),+ (60, VideoScenario::Steady, true),+ (120, VideoScenario::Steady, true),+ (30, VideoScenario::Jitter, true),+ (60, VideoScenario::Jitter, true),+ (30, VideoScenario::Drops, true),+ (60, VideoScenario::Drops, true),+ (30, VideoScenario::Gap, true),+ (60, VideoScenario::Gap, true),+ (30, VideoScenario::Steady, false),+ (30, VideoScenario::Gap, false),+ ];++ for (fps, scenario, fragmented) in video_cases {+ let name = format!(+ "video/{}fps/{}/{}",+ fps,+ scenario.name(),+ if fragmented { "fragmented" } else { "mp4" }+ );+ let outcome = run_video_case(fps, scenario, fragmented).await;+ eprintln!(+ "{name}: {}",+ match &outcome {+ Ok(d) => format!("ok ({d})"),+ Err(e) => format!("FAIL ({e})"),+ }+ );+ results.push(CaseResult {+ name,+ pass: outcome.is_ok(),+ detail: outcome.unwrap_or_else(|e| e),+ });+ }++ let audio_cases: Vec<(u32, u16)> = vec![+ (8_000, 2),+ (16_000, 2),+ (22_050, 2),+ (44_100, 2),+ (48_000, 2),+ (96_000, 2),+ (48_000, 1),+ (44_100, 1),+ (48_000, 6),+ ];++ for (rate, channels) in audio_cases {+ let name = format!("audio/{rate}hz/{channels}ch");+ let outcome = run_audio_case(rate, channels).await;+ eprintln!(+ "{name}: {}",+ match &outcome {+ Ok(d) => format!("ok ({d})"),+ Err(e) => format!("FAIL ({e})"),+ }+ );+ results.push(CaseResult {+ name,+ pass: outcome.is_ok(),+ detail: outcome.unwrap_or_else(|e| e),+ });+ }++ if let Ok(report_path) = std::env::var("CAP_SYNC_MATRIX_REPORT") {+ let json = serde_json::to_string_pretty(&results).expect("serialize report");+ std::fs::write(&report_path, json).expect("write report");+ eprintln!("report written to {report_path}");+ }++ let failures: Vec<&CaseResult> = results.iter().filter(|r| !r.pass).collect();+ assert!(+ failures.is_empty(),+ "{} of {} matrix cases failed:\n{}",+ failures.len(),+ results.len(),+ failures+ .iter()+ .map(|r| format!(" {} — {}", r.name, r.detail))+ .collect::<Vec<_>>()+ .join("\n")+ );+}