diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 5038700a..567f6233 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -25,6 +25,11 @@ jobs: packages: libboost-all-dev wireshark-dev - preset: 'server' packages: libboost-all-dev libsystemd-dev + # tracing is opt-in and rarely built; build it here so the instrumentation and the + # Perfetto SDK glue don't bitrot (WIVRN_TRACE_MONADO needs percetto, not packaged in CI) + - preset: 'server-tracing' + packages: libboost-all-dev libsystemd-dev + perfetto: true - preset: 'server-no-systemd' packages: libboost-all-dev - preset: 'server-no-system-boost' @@ -70,6 +75,18 @@ jobs: vulkan-components: Vulkan-Headers, Vulkan-Loader, Glslang, SPIRV-Reflect, SPIRV-Tools vulkan-use-cache: true + - name: Fetch Perfetto SDK + if: ${{ matrix.config.perfetto }} + # The amalgamated SDK is two files; install them where server/CMakeLists.txt looks. + env: + PERFETTO_TAG: v51.0 + run: | + sudo mkdir -p /usr/share/perfetto/sdk + for f in perfetto.h perfetto.cc; do + sudo curl -fsSL -o /usr/share/perfetto/sdk/$f \ + https://raw.githubusercontent.com/google/perfetto/${PERFETTO_TAG}/sdk/$f + done + - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type @@ -120,7 +137,7 @@ jobs: - name: Prepare run: | apt-get update - apt-get install --yes curl wget sudo jq cmake gcc g++ git pkgconf libboost-all-dev libkirigami-dev gettext libarchive-dev nlohmann-json3-dev qcoro-qt6-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev libvulkan-dev libssl-dev librsvg2-dev extra-cmake-modules qml6-module-org-kde-kirigamiaddons-formcard + apt-get install --yes curl wget sudo jq cmake ninja-build gcc g++ git pkgconf libboost-all-dev libkirigami-dev gettext libarchive-dev nlohmann-json3-dev qcoro-qt6-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev libvulkan-dev libssl-dev librsvg2-dev extra-cmake-modules qml6-module-org-kde-kirigamiaddons-formcard - uses: actions/cache@v5 with: diff --git a/.github/workflows/Format.yml b/.github/workflows/Format.yml index 40e3d849..b258169d 100644 --- a/.github/workflows/Format.yml +++ b/.github/workflows/Format.yml @@ -21,3 +21,19 @@ jobs: with: clang-format-version: '21' check-path: ${{ matrix.path }} + + python-format-check: + name: Python lint (ruff) + runs-on: ubuntu-24.04 + if: ${{ vars.APK_ONLY == '' }} + steps: + - uses: actions/checkout@v6 + # Scope set by `include` in ruff.toml. + - name: Run ruff lint check + uses: astral-sh/ruff-action@v3 + with: + args: "check" + - name: Run ruff format check + uses: astral-sh/ruff-action@v3 + with: + args: "format --check" diff --git a/.gitignore b/.gitignore index a16fdcd7..0f75582d 100644 --- a/.gitignore +++ b/.gitignore @@ -11,11 +11,13 @@ build/ build-*/ **/result +__pycache__/ *.so a.out *.pgm *.zip *.keystore +*.pftrace gradle.properties local.properties compile_commands.json diff --git a/CMakeLists.txt b/CMakeLists.txt index 2cfadaa0..8ddb7d23 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,6 +59,12 @@ option(WIVRN_USE_VAAPI "Enable vaapi (AMD/Intel) hardware encoder" ON) option(WIVRN_USE_VULKAN_ENCODE "Enable vulkan video encoder" ON) option(WIVRN_USE_X264 "Enable x264 software encoder" ON) +option(WIVRN_USE_PERFETTO "Enable Perfetto tracing via the Perfetto SDK (server only)" OFF) +option(WIVRN_TRACE_MONADO "Also instrument Monado (percetto) under the same WIVRN_TRACING switch; pulls in a second Perfetto runtime, system backend only. Requires WIVRN_USE_PERFETTO" OFF) +if(WIVRN_TRACE_MONADO AND NOT WIVRN_USE_PERFETTO) + message(FATAL_ERROR "WIVRN_TRACE_MONADO=ON requires WIVRN_USE_PERFETTO=ON") +endif() + option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" ON) set(OVR_COMPAT_SEARCH_PATH "/opt/xrizer:/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite:/opt/VapoR:/usr/local/lib/VapoR" diff --git a/CMakePresets.json b/CMakePresets.json index 45483d7c..45a30ab2 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -9,6 +9,7 @@ { "name": "base", "hidden": true, + "generator": "Ninja", "cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", "CMAKE_INTERPROCEDURAL_OPTIMIZATION": "ON", @@ -64,6 +65,24 @@ "WIVRN_BUILD_WIVRNCTL": "ON" } }, + { + "name": "server-tracing", + "displayName": "Server with Perfetto tracing", + "inherits": "server", + "binaryDir": "${sourceDir}/build-server-tracing", + "cacheVariables": { + "WIVRN_USE_PERFETTO": "ON" + } + }, + { + "name": "server-tracing-monado", + "displayName": "Server with Perfetto tracing (incl. Monado)", + "inherits": "server-tracing", + "binaryDir": "${sourceDir}/build-server-tracing-monado", + "cacheVariables": { + "WIVRN_TRACE_MONADO": "ON" + } + }, { "name": "dashboard", "displayName": "Dashboard only", diff --git a/common/utils/xdg_base_directory.cpp b/common/utils/xdg_base_directory.cpp index 20d93974..f0013080 100644 --- a/common/utils/xdg_base_directory.cpp +++ b/common/utils/xdg_base_directory.cpp @@ -54,6 +54,14 @@ std::filesystem::path xdg_data_home() return "."; } +std::filesystem::path xdg_runtime_dir() +{ + if (const char * xdg_runtime_dir = std::getenv("XDG_RUNTIME_DIR"); xdg_runtime_dir and *xdg_runtime_dir) + return xdg_runtime_dir; + + return "/tmp"; +} + std::vector xdg_config_dirs() { std::vector paths; diff --git a/common/utils/xdg_base_directory.h b/common/utils/xdg_base_directory.h index 84a2aae9..d3588930 100644 --- a/common/utils/xdg_base_directory.h +++ b/common/utils/xdg_base_directory.h @@ -25,5 +25,6 @@ std::filesystem::path xdg_config_home(); std::filesystem::path xdg_cache_home(); std::filesystem::path xdg_data_home(); +std::filesystem::path xdg_runtime_dir(); std::vector xdg_config_dirs(); std::vector xdg_data_dirs(bool include_data_home = true); diff --git a/docs/building.md b/docs/building.md index 25fed993..4ba152a8 100644 --- a/docs/building.md +++ b/docs/building.md @@ -35,6 +35,21 @@ Lighthouse driver support for use with lighthouse-tracked devices Additionally, if your environment requires absolute paths inside the OpenXR runtime manifest, you can add `-DWIVRN_OPENXR_MANIFEST_TYPE=absolute` to the build configuration. +## Profiling / tracing build + +To build the server with Perfetto tracing for local profiling, use the `server-tracing` preset (it is the `server` preset plus `WIVRN_USE_PERFETTO=ON`): + +```bash +cmake --preset server-tracing +cmake --build build-server-tracing +``` + +This requires the Perfetto amalgamated SDK installed where CMake looks for it (`/usr/share/perfetto/sdk/perfetto.{h,cc}`, override with `-DPERFETTO_SDK_DIR=`). Tracing is gated at runtime by the `WIVRN_TRACING` env var, so a tracing-enabled build has no cost until you set it. + +To also instrument Monado under the same switch, use the `server-tracing-monado` preset (adds `WIVRN_TRACE_MONADO=ON`); this requires [percetto](https://github.com/olvaffe/percetto/) to be discoverable at configure time. + +See [profiling](profiling.md) for how to run the server with tracing and capture/analyse traces. + # Dashboard The WiVRn dashboard requires Qt6, and the WiVRn server. diff --git a/docs/debugging.md b/docs/debugging.md index 419e16d8..8c19140b 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -15,9 +15,7 @@ This guide covers debugging techniques for WiVRn, including log collection, cras - [Crash Debugging](#crash-debugging) - [Server Crashes](#server-crashes) - [HMD Client Crashes](#hmd-client-crashes) -- [Performance Debugging](#performance-debugging) - - [Timing Analysis](#timing-analysis) - - [Perfetto Profiling](#perfetto-profiling) +- [Performance Profiling](#performance-profiling) - [USB Tunneling](#usb-tunneling) - [Game Debugging](#game-debugging) - [Environment Variables Reference](#environment-variables-reference) @@ -254,43 +252,12 @@ adb logcat '*:F' | grep -A 50 wivrn --- -## Performance Debugging +## Performance Profiling -### Timing Analysis - -WiVRn can record detailed timing information for analysis. - -Capture timing data: - -```bash -WIVRN_DUMP_TIMINGS=/tmp/wivrn-timings.csv wivrn-server -``` - -### Perfetto Profiling - -[Perfetto](https://perfetto.dev/) provides detailed system-wide profiling. - -#### HMD Profiling - -Enable persistent tracing on Android: - -```bash -adb shell setprop persist.traced.enable 1 -``` - -Open the [Perfetto UI](https://ui.perfetto.dev/), connect to your device, and configure tracing as needed. - -See the [Android tracing quickstart](https://perfetto.dev/docs/quickstart/android-tracing) for detailed instructions. - -#### Server Profiling - -Ensure WiVRn is built with `XRT_FEATURE_TRACING=ON` to enable [Monado tracing with Perfetto](https://monado.pages.freedesktop.org/monado/tracing-perfetto.html). - -Start with tracing enabled: - -```bash -XRT_TRACING=true wivrn-server -``` +WiVRn supports timing analysis via CSV dumps and detailed system-wide +profiling with Perfetto. See [docs/profiling.md](profiling.md) for capturing +timing data, profiling the HMD client and server, and comparing the Vulkan, +NVENC, and VAAPI encoder paths. --- @@ -363,7 +330,7 @@ The log is located at `$XDG_STATE_HOME/xrizer/xrizer.txt`, or `$HOME/.local/stat | `WIVRN_DUMP_TIMINGS` | Path to dump timing CSV (e.g., `/tmp/wivrn-timings.csv`) | | `WIVRN_LOGLEVEL` | Log level for the native client | | `WIVRN_AUTOCONNECT` | Auto-connect to the first discovered server | -| `XRT_TRACING` | Enable Perfetto tracing (`true`/`false`) | +| `WIVRN_TRACING` | Enable WiVRn Perfetto tracing: `system` / `inprocess`. Requires `WIVRN_USE_PERFETTO=ON` at build time. See [docs/profiling.md](profiling.md). | ### Vulkan diff --git a/docs/profiling.md b/docs/profiling.md new file mode 100644 index 00000000..a173fd4b --- /dev/null +++ b/docs/profiling.md @@ -0,0 +1,190 @@ +# Profiling WiVRn + +Performance analysis for WiVRn: per-frame timing CSV and [Perfetto](https://perfetto.dev/) tracing. +For general debugging see [docs/debugging.md](debugging.md). + +## Quick start + +Build with tracing (`server-tracing` preset = `server` + `WIVRN_USE_PERFETTO=ON`): +```bash +cmake --preset server-tracing +cmake --build build-server-tracing +``` + +Self-contained **in-process** trace (no daemon, no script): +```bash +WIVRN_TRACING=inprocess build-server-tracing/server/wivrn-server +``` +Connect the HMD, stream, disconnect. Each session writes a `wivrn--.pftrace` in cwd; +open it in . + +**System-backend** capture via the daemon + wrapper: +```bash +WIVRN_TRACING=system wivrn-server # one shell, with a client streaming +tools/perfetto/wivrn_capture.py # WiVRn-only; --full adds Monado + ftrace +``` + +`WIVRN_USE_PERFETTO` defaults `OFF`; even built `ON`, tracing is inert until `WIVRN_TRACING` is set. +The Perfetto amalgamated SDK must be installed where CMake looks (`/usr/share/perfetto/sdk`, override +with `-DPERFETTO_SDK_DIR=`); no automatic fetch. + +## Timing analysis (CSV) + +Per-frame timing without any Perfetto setup — same events as the `wivrn_feedback` track, one row each: +```bash +WIVRN_DUMP_TIMINGS=/tmp/wivrn-timings.csv wivrn-server +``` +CSV and Perfetto are independent; set either, neither, or both. See +[CSV ↔ Perfetto](#csv--perfetto-alignment). + +## HMD profiling + +```bash +adb shell setprop persist.traced.enable 1 +``` +Then use the [Perfetto UI](https://ui.perfetto.dev/) → connect device. See the +[Android tracing quickstart](https://perfetto.dev/docs/quickstart/android-tracing). + +## Backends — `WIVRN_TRACING` + +`WIVRN_TRACING` enables tracing and selects how it is collected. Unset/`off` = disabled; unknown +values warn and stay off. + +| Value | Behavior | +| ------------------ | -------- | +| `system` | Connect to an external `traced` daemon; an external consumer owns the session. The only mode that gives a unified system-wide capture. Use `tools/perfetto/wivrn_capture.py`. | +| `inprocess` | wivrn-server runs the service itself and writes a self-contained `.pftrace`. No daemon, no sudo. WiVRn track events only — no ftrace/system data. | +| `system+inprocess` | Both, independently → two separate traces (not merged). | + +In-process options: +- `WIVRN_TRACING_FILE` — output path. A trace is written on **each client disconnect** and at server + shutdown, so one run can produce several files. Unset → timestamped `wivrn--.pftrace` + in cwd. An explicit value expands `%t` (timestamp)/`%p` (pid) and gains a `-2`, `-3`, … suffix + rather than overwriting. Written from the per-session child, so use an absolute path if unsure; + parent dirs are created. +- `WIVRN_TRACING_BUFFER_KB` — ring buffer size in KiB (default `65536`). + +A headset must be streaming during the capture window. Confirm setup by raising Monado's log level +(default `warn` hides the lines): +```bash +XRT_LOG=info WIVRN_TRACING=system wivrn-server +# → wivrn::trace: producer socket /run/user//wivrn-perfetto-producer.sock +# → wivrn::trace: init complete +``` + +> Perfetto's default socket is root-only, so WiVRn (and the wrapper) use +> `$XDG_RUNTIME_DIR/wivrn-perfetto-{producer,consumer}.sock` (fallback `/tmp`). Override via +> `PERFETTO_PRODUCER_SOCK_NAME`. + + +## Capturing — `wivrn_capture.py` + +A wrapper around `tracebox` (downloaded on first run): starts the tracing services, waits for the +wivrn-server producer, captures, and tears down. If no producer connects within 20s it **aborts** +rather than write an empty trace — start wivrn-server with `WIVRN_TRACING=system`, stream, retry. + +```bash +tools/perfetto/wivrn_capture.py # default: WiVRn-only, no ftrace, no sudo +tools/perfetto/wivrn_capture.py --full # + every producer + broad ftrace (needs sudo) +tools/perfetto/wivrn_capture.py --full --cpu-only # full producers, ftrace stripped (no sudo) +tools/perfetto/wivrn_capture.py --duration-ms 5000 -o my.pftrace +tools/perfetto/wivrn_capture.py -c custom.pbtx # any Perfetto config +``` + +`--cpu-only` strips any `linux.ftrace` block from the config. The wrapper auto-detects ftrace in the +config and only then starts `traced_probes` + uses `sudo`. + +### Default vs `--full` + +| Aspect | default (`wivrn_trace_cfg.pbtx`) | `--full` (`wivrn_full_trace_cfg.pbtx`) | +| ------ | -------------------------------- | -------------------------------------- | +| track_event | WiVRn categories only | every category, every producer | +| ftrace | none | sched + freq + idle + IRQs + vblank | +| Buffers | 64 MiB (track_event) | 64 MiB track_event **+** 256 MiB system | +| sudo | no | yes (ftrace) | +| Use for | encoder-pipeline questions | "something outside WiVRn is doing X" | + +`--full` isolates `track_event` in its own buffer so the high-rate ftrace stream can't evict the +WiVRn/Monado slices, and defaults to a 5 s window (override with `--duration-ms`). If a trace is too +big to load, drop the `irq/*` events from a copy of the config. + +### Manual capture + +Drive Perfetto yourself against WiVRn's default socket pair: +```bash +SOCK_DIR="${XDG_RUNTIME_DIR:-/tmp}" +export PERFETTO_PRODUCER_SOCK_NAME="$SOCK_DIR/wivrn-perfetto-producer.sock" +export PERFETTO_CONSUMER_SOCK_NAME="$SOCK_DIR/wivrn-perfetto-consumer.sock" + +traced --background # add sudo + traced_probes for ftrace configs +WIVRN_TRACING=system wivrn-server # in another shell, streaming +perfetto -c tools/perfetto/wivrn_trace_cfg.pbtx --txt -o trace.pftrace +``` +For ftrace configs, run `traced`/`traced_probes` under `sudo -E` and add +`--set-socket-permissions "$USER:0660:$USER:0660"` to `traced`. + +### Summaries + +`tools/perfetto/pftrace_summary.py` prints per-slice stats, or a side-by-side diff for two traces: +```bash +tools/perfetto/pftrace_summary.py nvenc.pftrace # one trace +tools/perfetto/pftrace_summary.py nvenc.pftrace vulkan.pftrace # diff with Δmean +``` + +## Tracing Monado too + +Monado's own `u_trace` (built on percetto) can join the same session. Build with +`WIVRN_TRACE_MONADO=ON` (requires `WIVRN_USE_PERFETTO=ON`): +```bash +cmake --preset server-tracing-monado +cmake --build build-server-tracing-monado + +WIVRN_TRACING=system wivrn-server # also sets Monado's XRT_TRACING for you +tools/perfetto/wivrn_capture.py --full +``` + +- **System backend + `--full` only.** Monado's percetto can't write in-process, and the default + config allowlists only `wivrn_*` categories. +- **percetto must be available** at configure time (pkg-config, or `-DPercetto_ROOT_DIR=`); + Monado does not fetch it. Missing → `XRT_HAVE_PERCETTO specified but not available`. +- Links a second Perfetto SDK copy (percetto's); both feed one `traced`. Leave off unless you need + Monado spans. + +## Adding instrumentation + +Include `utils/wivrn_trace.h`; no `#ifdef` at call sites. + +```cpp +// CPU span (RAII; ends at scope exit) +wivrn::trace::scope s(wivrn::trace::cpu_track::encoder, stream_idx, frame_index, "my_span"); + +// CPU instant +wivrn::trace::cpu_instant(wivrn::trace::cpu_track::compositor, "my_event", 0, 0); + +// CPU begin/end pair (lifetime spans multiple calls) +wivrn::trace::cpu_begin(wivrn::trace::cpu_track::network, stream_idx, frame_idx, "Send"); +wivrn::trace::cpu_end (wivrn::trace::cpu_track::network, stream_idx, frame_idx, "Send"); + +// GPU span: bracket work with a gpu_timestamp_pool's cmd_begin/cmd_end, emit after the fence +if (auto s = pool.collect(slot)) + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::nvenc_copy, + "my_gpu_span", s->begin_ns, s->end_ns, s->frame_index, stream); +``` + +GPU begin/end come from the pool already in host-monotonic ns (via `VK_EXT_calibrated_timestamps`). +A disabled pool (no timestamp bits, or `WIVRN_TRACING` unset) returns `nullopt`. `name` must outlive +the emit (a literal is fine). Place the span at the operation's semantic start, not the function top. + +| `cpu_track` | category | track | +| ----------- | -------- | ----- | +| `encoder` | `wivrn_encoder` | WiVRn encoder | +| `compositor` | `wivrn_compositor` | WiVRn compositor | +| `network` | `wivrn_network` | WiVRn network | + +## CSV ↔ Perfetto alignment + +`WIVRN_DUMP_TIMINGS` (CSV) and the `wivrn_feedback` track read the **same** `dump_time` stream, clock +(`CLOCK_MONOTONIC`), and event names (`wake_up`, `encode_begin`, `send_end`, `display`, …) — so +`grep encode_begin` over the CSV and `name = "encode_begin"` in Perfetto select the same frames at +the same timestamps. Perfetto additionally carries the CPU/GPU spans the CSV does not. Use the CSV +for offline scripting, the trace for a visual timeline. diff --git a/patches/monado/0009-ipc-join-client-threads-before-teardown.patch b/patches/monado/0009-ipc-join-client-threads-before-teardown.patch new file mode 100644 index 00000000..d4b47614 --- /dev/null +++ b/patches/monado/0009-ipc-join-client-threads-before-teardown.patch @@ -0,0 +1,62 @@ +From a149552933bda15ffab81460f38dbe90abd0dfe0 Mon Sep 17 00:00:00 2001 +From: no name +Date: Sun, 28 Jun 2026 11:36:08 -0600 +Subject: [PATCH] ipc: join client threads before teardown + +On shutdown main_loop() returns as soon as s->running is cleared, but the +per-client threads may still be in common_shutdown() destroying their +compositor and dereferencing s->xsysd/s->xso. teardown_all() then frees +those resources concurrently, so a client thread can lock a mutex the main +thread has already destroyed (assert om->initialized in +multi_compositor_destroy). Join the client threads first. +--- + src/xrt/ipc/server/ipc_server_process.c | 28 +++++++++++++++++++++++++ + 1 file changed, 28 insertions(+) + +diff --git a/src/xrt/ipc/server/ipc_server_process.c b/src/xrt/ipc/server/ipc_server_process.c +index caa82d05d..9dfffceaa 100644 +--- a/src/xrt/ipc/server/ipc_server_process.c ++++ b/src/xrt/ipc/server/ipc_server_process.c +@@ -163,11 +163,39 @@ print_linux_end_user_started_information(enum u_logging_level log_level) + U_LOG_IFL_I(log_level, "%s", sink.buffer); + } + ++/*! ++ * Join any still-running per-client threads. ++ * ++ * On shutdown @ref main_loop returns as soon as `s->running` is cleared, but the ++ * per-client threads may still be inside common_shutdown(), which destroys each ++ * client's compositor and dereferences `s->xsysd` / `s->xso`. Waiting for them ++ * here, before teardown_all() destroys those resources, avoids a race where a ++ * client thread locks a mutex the teardown below has already freed (observed as ++ * an `om->initialized` assertion in multi_compositor_destroy). `s->running` is ++ * already false by this point, so each client loop exits within its poll timeout. ++ */ ++static void ++join_all_client_threads(struct ipc_server *s) ++{ ++ for (uint32_t i = 0; i < IPC_MAX_CLIENTS; i++) { ++ struct ipc_thread *it = &s->threads[i]; ++ if (it->state == IPC_THREAD_READY) { ++ continue; ++ } ++ os_thread_join(&it->thread); ++ os_thread_destroy(&it->thread); ++ it->state = IPC_THREAD_READY; ++ } ++} ++ + static void + teardown_all(struct ipc_server *s) + { + u_var_remove_root(s); + ++ // Client threads reference the resources destroyed below; wait them out first. ++ join_all_client_threads(s); ++ + xrt_syscomp_destroy(&s->xsysc); + + xrt_space_overseer_destroy(&s->xso); +-- +2.54.0 + diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 00000000..a15bb5cc --- /dev/null +++ b/ruff.toml @@ -0,0 +1,8 @@ +# Ruff config — https://docs.astral.sh/ruff/ +# `include` sets which files are linted; widen it to cover more paths. +include = ["tools/perfetto/**/*.py"] +line-length = 100 +target-version = "py310" + +[lint] +extend-select = ["I"] # also sort imports diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index e71c532b..bee76ba2 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -70,6 +70,18 @@ set(BUILD_TESTING OFF) set(XRT_HAVE_SYSTEM_CJSON OFF) +# Drive Monado's tracing from the same switch as WiVRn's: WIVRN_TRACE_MONADO builds Monado +# with percetto so its u_trace markers join the WIVRN_TRACING session (system backend). +# Monado does not fetch percetto; it must be discoverable (pkg-config / installed, or +# -DPercetto_ROOT_DIR=...). If it is missing, Monado's option_with_deps fails the configure +# with "XRT_HAVE_PERCETTO specified but not available". Linking percetto against WiVRn's own +# Perfetto SDK copy (to drop this requirement and the second runtime) is a planned follow-up. +if(WIVRN_TRACE_MONADO) + message(STATUS "WIVRN_TRACE_MONADO=ON: building Monado with percetto tracing (percetto must be available)") + set(XRT_FEATURE_TRACING ON) + set(XRT_HAVE_PERCETTO ON) +endif() + set(XRT_IPC_MSG_SOCK_FILENAME "wivrn/comp_ipc" CACHE STRING "Service socket filename") set(XRT_IPC_SERVICE_PID_FILENAME "wivrn.pid" CACHE STRING "Service pidfile filename") set(XRT_OXR_RUNTIME_SUFFIX "wivrn" CACHE STRING "OpenXR client library suffix") @@ -121,6 +133,8 @@ if (WIVRN_BUILD_SERVER) driver/xrt_cast.cpp utils/wivrn_vk_bundle.cpp + utils/wivrn_trace.cpp + utils/gpu_timestamp_pool.cpp ) target_compile_features(wivrn-server PRIVATE cxx_std_20) target_compile_definitions(wivrn-server PRIVATE VULKAN_HPP_NO_CONSTRUCTORS) @@ -171,6 +185,25 @@ if (WIVRN_BUILD_SERVER) target_link_libraries(wivrn-server PRIVATE PkgConfig::X264) endif() + if(WIVRN_USE_PERFETTO) + find_path(PERFETTO_SDK_DIR + NAMES perfetto.h + PATHS /usr/share/perfetto/sdk + DOC "Perfetto amalgamated SDK directory") + if(NOT PERFETTO_SDK_DIR) + message(FATAL_ERROR "WIVRN_USE_PERFETTO=ON but Perfetto SDK (perfetto.h) not found. Install perfetto-sdk.") + endif() + add_library(wivrn-perfetto-sdk STATIC ${PERFETTO_SDK_DIR}/perfetto.cc) + target_include_directories(wivrn-perfetto-sdk PUBLIC ${PERFETTO_SDK_DIR}) + target_compile_options(wivrn-perfetto-sdk PRIVATE -w) + target_link_libraries(wivrn-perfetto-sdk PUBLIC pthread dl) + target_link_libraries(wivrn-server PRIVATE wivrn-perfetto-sdk) + target_compile_definitions(wivrn-server PRIVATE WIVRN_USE_PERFETTO) + if(WIVRN_TRACE_MONADO) + target_compile_definitions(wivrn-server PRIVATE WIVRN_TRACE_MONADO) + endif() + endif() + if(WIVRN_USE_SYSTEMD) target_link_libraries(wivrn-server PRIVATE PkgConfig::SYSTEMD) endif() diff --git a/server/compositor/compositor.cpp b/server/compositor/compositor.cpp index 74d9621c..56bda3f3 100644 --- a/server/compositor/compositor.cpp +++ b/server/compositor/compositor.cpp @@ -35,6 +35,7 @@ #include "encoder/video_encoder.h" #include "inplace_vector.hpp" #include "utils/method.h" +#include "utils/wivrn_trace.h" #include "xrt/xrt_config_build.h" // IWYU pragma: keep #ifdef XRT_FEATURE_RENDERDOC @@ -628,12 +629,15 @@ void compositor::encoder_work(std::stop_token tok) if (req < 0) { encode_request.wait(req); + wivrn::trace::cpu_instant(wivrn::trace::cpu_track::compositor, "encoder_work wake", 0, 0); continue; } assert(req < images.size()); auto & image = images[req]; + wivrn::trace::scope trace_iter(wivrn::trace::cpu_track::compositor, 0, image.frame_index, "encoder_work iter"); + try { for (auto & encoder: encoders) @@ -720,6 +724,14 @@ compositor::compositor(wivrn_session & session) : log_level); vk::detail::resultCheck(vk::Result(res), "vk_init_from_given"); + // vk_init_from_given can't enable calibrated timestamps; do it here. +#ifdef VK_EXT_calibrated_timestamps + c_base->vk.has_EXT_calibrated_timestamps = vk.has_device_ext(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME); +#endif + + // Share monado's vk_bundle so gpu_timestamp_pool reuses its calibration cache. + wivrn::trace::set_calibration_source(&c_base->vk); + // vk_init_from_given assumes a graphics queue was provided c_base->vk.graphics_queue = nullptr; diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index 6de2c8eb..c97f67d3 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -28,6 +28,7 @@ #include "utils/load_icon.h" #include "utils/method.h" #include "utils/scoped_lock.h" +#include "utils/wivrn_trace.h" #include "audio/audio_setup.h" #include "wivrn_android_face_tracker.h" @@ -383,6 +384,9 @@ void wivrn_session::pause_session() audio_handle->pause(); // FIXME: pause compositor + + // Rotate this connection's trace before it pauses for reconnect. + wivrn::trace::flush_session(); } void wivrn_session::resume_session() @@ -1066,6 +1070,7 @@ void wivrn_session::set_foveated_size(uint32_t width, uint32_t height) void wivrn_session::dump_time(const std::string & event, uint64_t frame, int64_t time, uint8_t stream, const char * extra) { + trace::instant_feedback(event.c_str(), time, frame, stream); if (feedback_csv) { std::lock_guard lock(csv_mutex); diff --git a/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp b/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp index 9878ce20..70fbdb37 100644 --- a/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp +++ b/server/encoder/ffmpeg/video_encoder_ffmpeg.cpp @@ -20,6 +20,7 @@ #include "video_encoder_ffmpeg.h" #include "util/u_logging.h" +#include "utils/wivrn_trace.h" extern "C" { @@ -83,9 +84,13 @@ std::optional video_encoder_ffmpeg::encode(uint8_t s bool is_idr = idr_handler.get_type(frame_index) == default_idr_handler::frame_type::i; - push_frame(is_idr, slot); std::shared_ptr enc_pkt(av_packet_alloc(), [](AVPacket * d) { av_packet_free(&d); }); - int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get()); + int err; + { + wivrn::trace::scope trace_send_recv(wivrn::trace::cpu_track::encoder, stream_idx, frame_index, "avcodec_send+receive"); + push_frame(is_idr, slot); + err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get()); + } if (err == 0) { return data{ diff --git a/server/encoder/ffmpeg/video_encoder_va.cpp b/server/encoder/ffmpeg/video_encoder_va.cpp index cc860af3..0730e7f4 100644 --- a/server/encoder/ffmpeg/video_encoder_va.cpp +++ b/server/encoder/ffmpeg/video_encoder_va.cpp @@ -23,7 +23,9 @@ #include "encoder/encoder_settings.h" +#include "os/os_time.h" #include "util/u_logging.h" +#include "utils/wivrn_trace.h" #include "utils/wivrn_vk_bundle.h" #include @@ -430,9 +432,11 @@ video_encoder_va::video_encoder_va(wivrn::vk_bundle & vk, vk.device.bindImageMemory2(bind_info); } } + + ts_pool = gpu_timestamp_pool(vk, vk.queue.family_index, num_slots, std::format("va encoder {} pixel copy", stream_idx)); } -void video_encoder_va::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, uint8_t slot, uint64_t) +void video_encoder_va::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, uint8_t slot, uint64_t frame_index) { if (vk.device.waitForFences(*in[slot].fence, true, 1'000'000'000) == vk::Result::eTimeout) { @@ -468,6 +472,8 @@ void video_encoder_va::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, auto & cmd = in[slot].cmd; cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + ts_pool.cmd_begin(cmd, slot, frame_index, vk::PipelineStageFlagBits2::eTopOfPipe); + cmd.pipelineBarrier( vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eTransfer, @@ -534,6 +540,8 @@ void video_encoder_va::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, nullptr, im_barriers); + ts_pool.cmd_end(cmd, slot, vk::PipelineStageFlagBits2::eAllTransfer); + cmd.end(); std::unique_lock lock(vk.queue.mutex); @@ -553,6 +561,17 @@ void video_encoder_va::push_frame(bool idr, uint8_t slot) { if (vk.device.waitForFences(*in[slot].fence, true, 1'000'000'000) == vk::Result::eTimeout) throw std::runtime_error("timeout"); + + if (auto s = ts_pool.collect(slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::va_copy, + "vk_copy_luma_chroma", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } + auto & va_frame = in[slot].va_frame; va_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; int err = avcodec_send_frame(encoder_ctx.get(), va_frame.get()); diff --git a/server/encoder/ffmpeg/video_encoder_va.h b/server/encoder/ffmpeg/video_encoder_va.h index 6d06df40..d63f1195 100644 --- a/server/encoder/ffmpeg/video_encoder_va.h +++ b/server/encoder/ffmpeg/video_encoder_va.h @@ -20,6 +20,7 @@ #pragma once #include "ffmpeg_helper.h" +#include "utils/gpu_timestamp_pool.h" #include "video_encoder_ffmpeg.h" #include @@ -47,6 +48,8 @@ class video_encoder_va : public video_encoder_ffmpeg av_buffer_ptr drm_frame_ctx; std::array in; + gpu_timestamp_pool ts_pool; + public: video_encoder_va(wivrn::vk_bundle &, const wivrn::encoder_settings & settings, uint8_t stream_index); diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index fc5904b6..5862f9e2 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -24,6 +24,7 @@ #include "encoder_settings.h" #include "os/os_time.h" +#include "utils/wivrn_trace.h" #include "wivrn_config.h" #include @@ -234,6 +235,7 @@ void video_encoder::set_framerate(float framerate) void video_encoder::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo info, uint64_t frame_index) { + wivrn::trace::scope trace_present(wivrn::trace::cpu_track::encoder, stream_idx, frame_index, "present_image"); // Wait for encoder to be done present_slot = (present_slot + 1) % num_slots; state[present_slot].wait(busy); @@ -271,6 +273,7 @@ void video_encoder::encode(wivrn_session & cnx, this->cnx = &cnx; clock = cnx.get_offset(); + wivrn::trace::scope trace_encode(wivrn::trace::cpu_track::encoder, stream_idx, frame_index, "encode"); auto encode_begin = os_monotonic_get_ns(); timing_info = { .encode_begin = clock.to_headset(encode_begin), @@ -297,6 +300,13 @@ void video_encoder::encode(wivrn_session & cnx, void video_encoder::SendData(std::span data, bool end_of_frame, bool control) { std::lock_guard lock(mutex); + if (shard.shard_idx == 0) + { + // One SendData call per NAL; span the whole frame, not each call. + wivrn::trace::cpu_begin(wivrn::trace::cpu_track::network, stream_idx, shard.frame_idx, "SendData"); + cnx->dump_time("send_begin", shard.frame_idx, os_monotonic_get_ns(), stream_idx); + timing_info.send_begin = clock.to_headset(os_monotonic_get_ns()); + } if (end_of_frame) { timing_info.send_end = clock.to_headset(os_monotonic_get_ns()); @@ -305,11 +315,6 @@ void video_encoder::SendData(std::span data, bool end_of_frame, bool co } if (video_dump) video_dump.write((char *)data.data(), data.size()); - if (shard.shard_idx == 0) - { - cnx->dump_time("send_begin", shard.frame_idx, os_monotonic_get_ns(), stream_idx); - timing_info.send_begin = clock.to_headset(os_monotonic_get_ns()); - } ssize_t max_payload_size = (cnx->has_stream() and not control) ? to_headset::video_stream_data_shard::max_payload_size : std::numeric_limits::max(); @@ -341,7 +346,10 @@ void video_encoder::SendData(std::span data, bool end_of_frame, bool co begin = next; } if (end_of_frame) + { cnx->dump_time("send_end", shard.frame_idx, os_monotonic_get_ns(), stream_idx); + wivrn::trace::cpu_end(wivrn::trace::cpu_track::network, stream_idx, shard.frame_idx, "SendData"); + } } } // namespace wivrn diff --git a/server/encoder/video_encoder_nvenc.cpp b/server/encoder/video_encoder_nvenc.cpp index 1ff1830d..200c8b8e 100644 --- a/server/encoder/video_encoder_nvenc.cpp +++ b/server/encoder/video_encoder_nvenc.cpp @@ -20,7 +20,9 @@ #include "video_encoder_nvenc.h" #include "encoder_settings.h" +#include "os/os_time.h" #include "util/u_logging.h" +#include "utils/wivrn_trace.h" #include "utils/wivrn_vk_bundle.h" bool operator==(const GUID & l, const GUID & r) @@ -410,6 +412,8 @@ video_encoder_nvenc::video_encoder_nvenc( i.nvenc_resource = resource_params.registeredResource; } CU_CHECK(shared_state->cuda_fn->cuCtxPopCurrent(NULL)); + + ts_pool = gpu_timestamp_pool(vk, vk.queue.family_index, num_slots, std::format("nvenc encoder {} pixel copy", stream_idx)); } video_encoder_nvenc::~video_encoder_nvenc() @@ -418,7 +422,7 @@ video_encoder_nvenc::~video_encoder_nvenc() shared_state->fn.nvEncDestroyEncoder(session_handle); } -void video_encoder_nvenc::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, uint8_t slot, uint64_t) +void video_encoder_nvenc::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInfo, uint8_t slot, uint64_t frame_index) { if (vk.device.waitForFences(*in[slot].fence, true, 1'000'000'000) == vk::Result::eTimeout) { @@ -428,6 +432,8 @@ void video_encoder_nvenc::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInf auto & cmd = in[slot].cmd; cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + ts_pool.cmd_begin(cmd, slot, frame_index, vk::PipelineStageFlagBits2::eTopOfPipe); + cmd.copyImageToBuffer( y_cbcr, vk::ImageLayout::eGeneral, @@ -459,6 +465,7 @@ void video_encoder_nvenc::present_image(vk::Image y_cbcr, vk::SemaphoreSubmitInf .depth = 1, }, }}); + ts_pool.cmd_end(cmd, slot, vk::PipelineStageFlagBits2::eAllTransfer); cmd.end(); std::unique_lock lock(vk.queue.mutex); @@ -482,6 +489,16 @@ std::optional video_encoder_nvenc::encode(uint8_t slot, uin return {}; } + if (auto s = ts_pool.collect(slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::nvenc_copy, + "vk_copy_image_to_buffer", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } + CU_CHECK(shared_state->cuda_fn->cuCtxPushCurrent(shared_state->cuda)); auto & idr_handler = ((default_idr_handler &)*idr); @@ -557,14 +574,16 @@ std::optional video_encoder_nvenc::encode(uint8_t slot, uin frame_params.pictureType = NV_ENC_PIC_TYPE_UNKNOWN; break; } - NVENC_CHECK(shared_state->fn.nvEncEncodePicture(session_handle, &frame_params)); - NV_ENC_LOCK_BITSTREAM buf_lock_params{ .version = NV_ENC_LOCK_BITSTREAM_VER, .doNotWait = 0, .outputBitstream = outputBuffer, }; - NVENC_CHECK(shared_state->fn.nvEncLockBitstream(session_handle, &buf_lock_params)); + { + wivrn::trace::scope trace_nvenc(wivrn::trace::cpu_track::encoder, stream_idx, frame_index, "nvEncEncodePicture+Lock"); + NVENC_CHECK(shared_state->fn.nvEncEncodePicture(session_handle, &frame_params)); + NVENC_CHECK(shared_state->fn.nvEncLockBitstream(session_handle, &buf_lock_params)); + } if (buf_lock_params.pictureType == NV_ENC_PIC_TYPE_NONREF_P) idr_handler.set_non_ref(frame_index); diff --git a/server/encoder/video_encoder_nvenc.h b/server/encoder/video_encoder_nvenc.h index 13c421b4..567cbb8d 100644 --- a/server/encoder/video_encoder_nvenc.h +++ b/server/encoder/video_encoder_nvenc.h @@ -19,6 +19,7 @@ #pragma once +#include "utils/gpu_timestamp_pool.h" #include "video_encoder.h" #include "video_encoder_nvenc_shared_state.h" #include @@ -53,6 +54,8 @@ private: }; std::array in; + gpu_timestamp_pool ts_pool; + float fps; uint64_t bitrate; int bytesPerPixel = 1; diff --git a/server/encoder/video_encoder_vulkan.cpp b/server/encoder/video_encoder_vulkan.cpp index ba2ef244..336466c2 100644 --- a/server/encoder/video_encoder_vulkan.cpp +++ b/server/encoder/video_encoder_vulkan.cpp @@ -20,7 +20,9 @@ #include "encoder/encoder_settings.h" #include "inplace_vector.hpp" +#include "os/os_time.h" #include "util/u_logging.h" +#include "utils/wivrn_trace.h" #include "utils/wivrn_vk_bundle.h" #include @@ -565,6 +567,15 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca vk.name(query_pool, std::format("vulkan encoder {} query pool", stream_idx)); } + // Each pool is bound to the queue family that records its timestamps; pools + // whose corresponding code path never runs stay dormant. + ts_pool = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} encode", stream_idx)); + if (tmp_image) + ts_pool_image_copy = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} image-copy", stream_idx)); + const uint32_t host_copy_family = vk.transfer_queue ? vk.transfer_queue.family_index : encode_queue.family_index; + ts_pool_host_copy = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy", stream_idx)); + ts_pool_host_copy_overflow = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy-overflow", stream_idx)); + // command pools { video_command_pool = vk.device.createCommandPool( @@ -685,6 +696,7 @@ void wivrn::video_encoder_vulkan::present_image(vk::Image y_cbcr, vk::SemaphoreS .pImageMemoryBarriers = im_barriers.data(), }); + ts_pool_image_copy.cmd_begin(video_cmd_buf, encode_slot, frame_index, vk::PipelineStageFlagBits2::eCopy); video_cmd_buf.copyImage( y_cbcr, target_layout, @@ -726,6 +738,7 @@ void wivrn::video_encoder_vulkan::present_image(vk::Image y_cbcr, vk::SemaphoreS }, }, }); + ts_pool_image_copy.cmd_end(video_cmd_buf, encode_slot, vk::PipelineStageFlagBits2::eCopy); vk::ImageMemoryBarrier2 tmp_image_barrier{ .srcStageMask = vk::PipelineStageFlagBits2KHR::eTransfer, @@ -911,7 +924,9 @@ void wivrn::video_encoder_vulkan::present_image(vk::Image y_cbcr, vk::SemaphoreS encode_info.setReferenceSlots(ref_slot->info); video_cmd_buf.beginQuery(*query_pool, encode_slot, {}); + ts_pool.cmd_begin(video_cmd_buf, encode_slot, frame_index, vk::PipelineStageFlagBits2::eVideoEncodeKHR); video_cmd_buf.encodeVideoKHR(encode_info); + ts_pool.cmd_end(video_cmd_buf, encode_slot, vk::PipelineStageFlagBits2::eVideoEncodeKHR); video_cmd_buf.endQuery(*query_pool, encode_slot); video_cmd_buf.endVideoCodingKHR(vk::VideoEndCodingInfoKHR{}); @@ -943,12 +958,14 @@ void wivrn::video_encoder_vulkan::present_image(vk::Image y_cbcr, vk::SemaphoreS cmd.pipelineBarrier2(dep_info); } + ts_pool_host_copy.cmd_begin(cmd, encode_slot, frame_index, vk::PipelineStageFlagBits2::eCopy); cmd.copyBuffer( slot_item.output_buffer, slot_item.host_buffer, vk::BufferCopy{ .size = slot_item.copy_size, }); + ts_pool_host_copy.cmd_end(cmd, encode_slot, vk::PipelineStageFlagBits2::eCopy); cmd.end(); } else @@ -964,12 +981,14 @@ void wivrn::video_encoder_vulkan::present_image(vk::Image y_cbcr, vk::SemaphoreS .memoryBarrierCount = 1, .pMemoryBarriers = &mem_barrier, }); + ts_pool_host_copy.cmd_begin(video_cmd_buf, encode_slot, frame_index, vk::PipelineStageFlagBits2::eCopy); video_cmd_buf.copyBuffer( slot_item.output_buffer, slot_item.host_buffer, vk::BufferCopy{ .size = slot_item.copy_size, }); + ts_pool_host_copy.cmd_end(video_cmd_buf, encode_slot, vk::PipelineStageFlagBits2::eCopy); } } @@ -1043,6 +1062,34 @@ std::optional wivrn::video_encoder_vulkan::encode(ui std::cerr << "device.getQueryPoolResults: " << vk::to_string(res) << std::endl; } + if (auto s = ts_pool.collect(encode_slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::vulkan_encode, + "encodeVideoKHR", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } + if (auto s = ts_pool_image_copy.collect(encode_slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::vulkan_image_copy, + "vk_copy_image_tmp", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } + if (auto s = ts_pool_host_copy.collect(encode_slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::vulkan_host_copy, + "vk_copy_to_host", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } + // We don't copy the whole buffer, but an estimate of how much we'll need // If that wasn't enough, we have to issue a second copy command for the rest if (slot_item.host_buffer and size > slot_item.copy_size) @@ -1054,6 +1101,7 @@ std::optional wivrn::video_encoder_vulkan::encode(ui cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + ts_pool_host_copy_overflow.cmd_begin(cmd, encode_slot, frame_index, vk::PipelineStageFlagBits2::eCopy); cmd.copyBuffer( slot_item.output_buffer, slot_item.host_buffer, @@ -1062,6 +1110,7 @@ std::optional wivrn::video_encoder_vulkan::encode(ui .dstOffset = slot_item.copy_size, .size = size - slot_item.copy_size, }); + ts_pool_host_copy_overflow.cmd_end(cmd, encode_slot, vk::PipelineStageFlagBits2::eCopy); cmd.end(); @@ -1086,6 +1135,16 @@ std::optional wivrn::video_encoder_vulkan::encode(ui U_LOG_E("Timeout on stream %d", stream_idx); return {}; } + + if (auto s = ts_pool_host_copy_overflow.collect(encode_slot)) + { + wivrn::trace::gpu_slice(wivrn::trace::gpu_track::vulkan_host_copy_overflow, + "vk_copy_to_host_overflow", + s->begin_ns, + s->end_ns, + s->frame_index, + stream_idx); + } } void * mapped = slot_item.host_buffer ? slot_item.host_buffer.map() : slot_item.output_buffer.map(); diff --git a/server/encoder/video_encoder_vulkan.h b/server/encoder/video_encoder_vulkan.h index e93d0642..d888aab9 100644 --- a/server/encoder/video_encoder_vulkan.h +++ b/server/encoder/video_encoder_vulkan.h @@ -22,6 +22,7 @@ #include #include +#include "utils/gpu_timestamp_pool.h" #include "utils/wivrn_vk_bundle.h" #include "video_encoder.h" #include "vk/allocation.h" @@ -44,6 +45,11 @@ class video_encoder_vulkan : public video_encoder uint64_t sem_value = 0; vk::raii::QueryPool query_pool = nullptr; + gpu_timestamp_pool ts_pool; + // Optional per-op GPU timestamp pools; created only when their path runs. + gpu_timestamp_pool ts_pool_image_copy; + gpu_timestamp_pool ts_pool_host_copy; + gpu_timestamp_pool ts_pool_host_copy_overflow; vk::raii::CommandPool transfer_command_pool = nullptr; vk::raii::CommandPool video_command_pool = nullptr; diff --git a/server/main.cpp b/server/main.cpp index b5ca313b..33581968 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -9,6 +9,7 @@ #include "openxr/openxr.h" #include "sleep_inhibitor.h" #include "util/u_trace_marker.h" +#include "utils/wivrn_trace.h" #include "active_runtime.h" #include "avahi_publisher.h" @@ -944,8 +945,6 @@ int inner_main(int argc, char * argv[], bool show_instructions) active_runtime::cleanup_openxr(); listen_socket = create_listen_socket(); - u_trace_marker_init(); - // Initialize main loop main_loop = g_main_loop_new(nullptr, false); auto main_context = g_main_loop_get_context(main_loop); diff --git a/server/target_instance_wivrn.cpp b/server/target_instance_wivrn.cpp index e10c846c..59807d63 100644 --- a/server/target_instance_wivrn.cpp +++ b/server/target_instance_wivrn.cpp @@ -19,12 +19,12 @@ #include "target_instance_wivrn.h" #include "utils/method.h" +#include "utils/wivrn_trace.h" #include "xrt/xrt_instance.h" #include "xrt/xrt_system.h" #include "b_system.h" -#include "util/u_trace_marker.h" #include @@ -82,7 +82,7 @@ instance::instance() : .is_system_available = method_pointer<&instance::is_system_available>, .create_system = method_pointer<&instance::create_system>, .get_prober = method_pointer<&instance::get_prober>, - .destroy = [](xrt_instance * ptr) { delete (instance *)ptr; }, + .destroy = [](xrt_instance * ptr) { wivrn::trace::shutdown(); delete (instance *)ptr; }, .startup_timestamp = os_monotonic_get_ns(), } { @@ -99,7 +99,7 @@ void instance::set_ipc_server(ipc_server * server) xrt_result_t xrt_instance_create(struct xrt_instance_info * ii, struct xrt_instance ** out_xinst) { - u_trace_marker_init(); + wivrn::trace::init(); *out_xinst = new wivrn::instance(); diff --git a/server/utils/gpu_timestamp_pool.cpp b/server/utils/gpu_timestamp_pool.cpp new file mode 100644 index 00000000..4c980658 --- /dev/null +++ b/server/utils/gpu_timestamp_pool.cpp @@ -0,0 +1,102 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 WiVRn Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +// Monado's vk_helpers.h pulls in xrt_vulkan_includes.h, which sets the +// VK_USE_PLATFORM_* defines *before* gets included for the +// first time. Including it before wivrn_vk_bundle.h (which transitively pulls +// in vulkan_raii.hpp) ensures the platform-specific PFN_* surface types are +// declared and the function-pointer table in vk_helpers_h_funcs.h.inc compiles. +#ifdef WIVRN_USE_PERFETTO +#include "vk/vk_helpers.h" +#endif + +#include "gpu_timestamp_pool.h" + +#include "wivrn_trace.h" +#include "wivrn_vk_bundle.h" + +#ifdef WIVRN_USE_PERFETTO +#include +#include +#endif + +namespace wivrn +{ +// No tracing build ⇒ no timestamp consumer; keep the pool disabled. +gpu_timestamp_pool::gpu_timestamp_pool([[maybe_unused]] wivrn::vk_bundle & vk, + [[maybe_unused]] uint32_t queue_family_index, + [[maybe_unused]] uint32_t slot_count, + [[maybe_unused]] const std::string & name) +{ +#ifdef WIVRN_USE_PERFETTO + // Runtime tracing off: skip the pool instead of recording timestamps we'd drop. + if (!wivrn::trace::is_enabled()) + return; + auto qprops = vk.physical_device.getQueueFamilyProperties(); + if (queue_family_index >= qprops.size() or qprops[queue_family_index].timestampValidBits == 0) + return; + + pool = vk.device.createQueryPool(vk::QueryPoolCreateInfo{ + .queryType = vk::QueryType::eTimestamp, + .queryCount = slot_count * 2, + }); + vk.name(pool, name); + frame_indices.assign(slot_count, 0); +#endif +} + +void gpu_timestamp_pool::cmd_begin(const vk::raii::CommandBuffer & cmd, uint8_t slot, uint64_t frame_index, vk::PipelineStageFlagBits2 stage) +{ + if (not *pool) + return; + cmd.resetQueryPool(*pool, slot * 2, 2); + cmd.writeTimestamp2(stage, *pool, slot * 2); + frame_indices[slot] = frame_index; +} + +void gpu_timestamp_pool::cmd_end(const vk::raii::CommandBuffer & cmd, uint8_t slot, vk::PipelineStageFlagBits2 stage) const +{ + if (not *pool) + return; + cmd.writeTimestamp2(stage, *pool, slot * 2 + 1); +} + +std::optional gpu_timestamp_pool::collect(uint8_t slot) +{ +#ifdef WIVRN_USE_PERFETTO + if (not *pool) + return std::nullopt; + ::vk_bundle * cal = wivrn::trace::calibration_source(); + assert(cal != nullptr); + // Read both queries into a stack array, no allocation. + auto [res, times] = pool.getResult>(slot * 2, 2, sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); + if (res != vk::Result::eSuccess or times[1] < times[0]) + return std::nullopt; + if (vk_convert_timestamps_to_host_ns(cal, times.size(), times.data()) != VK_SUCCESS) + return std::nullopt; + return sample{ + .begin_ns = static_cast(times[0]), + .end_ns = static_cast(times[1]), + .frame_index = frame_indices[slot], + }; +#else + (void)slot; + return std::nullopt; +#endif +} +} // namespace wivrn diff --git a/server/utils/gpu_timestamp_pool.h b/server/utils/gpu_timestamp_pool.h new file mode 100644 index 00000000..821471f3 --- /dev/null +++ b/server/utils/gpu_timestamp_pool.h @@ -0,0 +1,59 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 WiVRn Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace wivrn +{ +struct vk_bundle; + +// A begin/end GPU timestamp pair per slot, used to measure GPU-side encode and +// copy durations for tracing. Conversion to host monotonic ns goes through +// monado's vk_convert_timestamps_to_host_ns (via wivrn::trace::calibration_source) +// so the calibration cache is shared with any future monado-side perfetto +// producer. If runtime tracing is off, the calibration source is missing, or +// the queue family doesn't support timestamps, the pool stays disabled and +// every method is a no-op. Default-constructed instances are also disabled, +// so members can be declared before being assigned. +class gpu_timestamp_pool +{ + vk::raii::QueryPool pool = nullptr; + std::vector frame_indices; + +public: + gpu_timestamp_pool() = default; + gpu_timestamp_pool(wivrn::vk_bundle & vk, uint32_t queue_family_index, uint32_t slot_count, const std::string & name); + + void cmd_begin(const vk::raii::CommandBuffer & cmd, uint8_t slot, uint64_t frame_index, vk::PipelineStageFlagBits2 stage); + void cmd_end(const vk::raii::CommandBuffer & cmd, uint8_t slot, vk::PipelineStageFlagBits2 stage) const; + + struct sample + { + int64_t begin_ns; + int64_t end_ns; + uint64_t frame_index; + }; + std::optional collect(uint8_t slot); +}; +} // namespace wivrn diff --git a/server/utils/wivrn_trace.cpp b/server/utils/wivrn_trace.cpp new file mode 100644 index 00000000..e25fdf99 --- /dev/null +++ b/server/utils/wivrn_trace.cpp @@ -0,0 +1,493 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 WiVRn Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "wivrn_trace.h" + +#include "util/u_trace_marker.h" + +#ifdef WIVRN_USE_PERFETTO + +#include "os/os_time.h" +#include "util/u_debug.h" +#include "util/u_logging.h" +#include "utils/xdg_base_directory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +PERFETTO_DEFINE_CATEGORIES( + perfetto::Category("wivrn_encoder").SetDescription("WiVRn encoder CPU spans"), + perfetto::Category("wivrn_encoder_gpu").SetDescription("WiVRn encoder GPU slices"), + perfetto::Category("wivrn_compositor").SetDescription("WiVRn compositor spans"), + perfetto::Category("wivrn_network").SetDescription("WiVRn network send spans"), + perfetto::Category("wivrn_feedback").SetDescription("WiVRn dump_time markers")); +PERFETTO_TRACK_EVENT_STATIC_STORAGE(); + +DEBUG_GET_ONCE_OPTION(wivrn_tracing, "WIVRN_TRACING", NULL) + +namespace wivrn::trace +{ +namespace +{ +bool initialized = false; +::vk_bundle * calibration = nullptr; + +perfetto::Track g_encoder_track(1); +perfetto::Track g_compositor_track(2); +perfetto::Track g_network_track(3); +perfetto::Track g_feedback_track(4); + +// WIVRN_TRACING is the single switch: it both enables tracing and selects which Perfetto +// backend(s) init() arms. +// unset/off/0/false/no - disabled +// system / 1/true/yes/on - connect to an external traced as a producer (the consumer +// owns the session); legacy boolean values map here +// inprocess - run the tracing service in this process and write the file +// system+inprocess - arm both independently +// Unknown values emit a warning and leave tracing disabled. +enum class tracing_mode +{ + off, + system, + inprocess, + both, +}; + +// In-process session state (only used when the mode includes inprocess). The session +// must outlive every emit and be stopped/flushed in shutdown() to produce a file. +std::unique_ptr g_inproc_session; + +tracing_mode parse_tracing_mode() +{ + const char * v = debug_get_option_wivrn_tracing(); + if (!v or !*v) + return tracing_mode::off; + const std::string s = v; + if (s == "off" or s == "0" or s == "false" or s == "no") + return tracing_mode::off; + if (s == "system" or s == "1" or s == "true" or s == "yes" or s == "on") + return tracing_mode::system; + if (s == "inprocess") + return tracing_mode::inprocess; + if (s == "system+inprocess" or s == "both") + return tracing_mode::both; + U_LOG_W("wivrn::trace: unknown WIVRN_TRACING '%s' (expected off|system|inprocess|system+inprocess), tracing disabled", v); + return tracing_mode::off; +} + +// Default socket is root-only; use a per-user XDG_RUNTIME_DIR path so a user-launched traced can bind. +std::string default_producer_sock_path() +{ + return (xdg_runtime_dir() / "wivrn-perfetto-producer.sock").string(); +} + +// Local-time stamp for trace filenames, evaluated per flush. +std::string now_timestamp() +{ + const std::time_t now = std::time(nullptr); + std::tm tm{}; + localtime_r(&now, &tm); + char buf[16]; + std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", &tm); + return buf; +} + +std::string expand_file_placeholders(std::string s) +{ + const std::string ts = now_timestamp(); + const std::string pid = std::to_string(getpid()); + for (size_t pos = 0; (pos = s.find('%', pos)) != std::string::npos;) + { + if (pos + 1 >= s.size()) + break; + const char c = s[pos + 1]; + const std::string * rep = nullptr; + if (c == 't') + rep = &ts; + else if (c == 'p') + rep = &pid; + if (rep) + { + s.replace(pos, 2, *rep); + pos += rep->size(); + } + else + pos += 2; // leave any other %x untouched + } + return s; +} + +// Path from WIVRN_TRACING_FILE; unset ⇒ wivrn--.pftrace in cwd. %t/%p expanded. +std::string resolve_inproc_file_path() +{ + const char * file = std::getenv("WIVRN_TRACING_FILE"); + if (!file or !*file) + return "wivrn-" + now_timestamp() + "-" + std::to_string(getpid()) + ".pftrace"; + return expand_file_placeholders(file); +} + +// Don't clobber an existing trace; suffix -2, -3, ... until free. +std::filesystem::path unique_file_path(const std::string & candidate) +{ + std::filesystem::path p = candidate; + std::error_code ec; + if (not std::filesystem::exists(p, ec)) + return p; + const auto dir = p.parent_path(); + const auto stem = p.stem().string(); + const auto ext = p.extension().string(); + for (unsigned n = 2;; ++n) + { + std::filesystem::path q = dir / (stem + "-" + std::to_string(n) + ext); + if (not std::filesystem::exists(q, ec)) + return q; + } +} + +// Flush + stop the session and write its buffer; caller re-arms or resets. +void write_inproc_session() +{ + perfetto::TrackEvent::Flush(); + g_inproc_session->StopBlocking(); + const std::vector data = g_inproc_session->ReadTraceBlocking(); + + const std::filesystem::path path = unique_file_path(resolve_inproc_file_path()); + std::error_code ec; + if (const auto parent = path.parent_path(); not parent.empty()) + std::filesystem::create_directories(parent, ec); + + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (out) + { + out.write(data.data(), static_cast(data.size())); + U_LOG_I("wivrn::trace: wrote %zu bytes to %s", data.size(), path.string().c_str()); + } + else + U_LOG_E("wivrn::trace: failed to open %s for writing", path.string().c_str()); +} + +// Arm an in-process tracing session. The output path is resolved when the buffer is written +// (on flush_session/shutdown), so each rotated trace gets its own timestamped file. +void start_inprocess_session() +{ + uint32_t buffer_kb = 65536; + if (const char * b = std::getenv("WIVRN_TRACING_BUFFER_KB"); b and *b) + { + if (const long parsed = std::strtol(b, nullptr, 10); parsed > 0) + buffer_kb = static_cast(parsed); + } + + // Enable only the WiVRn categories, mirroring the system-backend .pbtx allowlist. + // Do NOT add disabled_categories("*"): per wivrn_trace_cfg.pbtx that silences the + // allowlist too. wivrn-server defines only these categories, so this fully scopes it. + perfetto::protos::gen::TrackEventConfig te; + te.add_enabled_categories("wivrn_encoder"); + te.add_enabled_categories("wivrn_encoder_gpu"); + te.add_enabled_categories("wivrn_compositor"); + te.add_enabled_categories("wivrn_network"); + te.add_enabled_categories("wivrn_feedback"); + + perfetto::TraceConfig cfg; + cfg.add_buffers()->set_size_kb(buffer_kb); + auto * ds = cfg.add_data_sources()->mutable_config(); + ds->set_name("track_event"); + ds->set_track_event_config_raw(te.SerializeAsString()); + + g_inproc_session = perfetto::Tracing::NewTrace(perfetto::kInProcessBackend); + g_inproc_session->Setup(cfg); + g_inproc_session->StartBlocking(); + U_LOG_I("wivrn::trace: in-process session started, %u KiB buffer", buffer_kb); +} + +perfetto::Track & cpu_track_obj(cpu_track d) +{ + switch (d) + { + case cpu_track::encoder: + return g_encoder_track; + case cpu_track::compositor: + return g_compositor_track; + case cpu_track::network: + return g_network_track; + } + return g_encoder_track; +} +} // namespace + +// Bridge the WIVRN_TRACING switch onto Monado's tracing before u_trace_marker_init() caches +// XRT_TRACING. Only the system backend reaches a traced consumer, so only enable Monado then; +// setenv(..., 0) preserves an explicit user-set XRT_TRACING. No-op without WIVRN_TRACE_MONADO. +static void propagate_to_monado() +{ +#ifdef WIVRN_TRACE_MONADO + const tracing_mode mode = parse_tracing_mode(); + if (mode == tracing_mode::system or mode == tracing_mode::both) + setenv("XRT_TRACING", "true", 0); +#endif +} + +void init() +{ + if (initialized) + return; + initialized = true; + + // Monado's marker init caches XRT_TRACING, so propagate_to_monado() must run first. + // Both run regardless of WIVRN_TRACING so Monado's tracing behaves as it would normally. + propagate_to_monado(); + u_trace_marker_init(); + + const tracing_mode mode = parse_tracing_mode(); + if (mode == tracing_mode::off) + { + U_LOG_D("wivrn::trace: WIVRN_TRACING not set, perfetto tracing disabled"); + return; + } + + const bool use_system = mode == tracing_mode::system or mode == tracing_mode::both; + const bool use_inprocess = mode == tracing_mode::inprocess or mode == tracing_mode::both; + + perfetto::TracingInitArgs args; + if (use_system) + { + const auto sock = default_producer_sock_path(); + if (setenv("PERFETTO_PRODUCER_SOCK_NAME", sock.c_str(), 0) == 0) + U_LOG_I("wivrn::trace: producer socket %s", std::getenv("PERFETTO_PRODUCER_SOCK_NAME")); + args.backends |= perfetto::kSystemBackend; + } + if (use_inprocess) + args.backends |= perfetto::kInProcessBackend; + perfetto::Tracing::Initialize(args); + perfetto::TrackEvent::Register(); + + // Name the custom tracks; descriptors must be emitted after Register(). + auto set_track_name = [](perfetto::Track & trk, const char * name) { + auto desc = trk.Serialize(); + desc.set_name(name); + perfetto::TrackEvent::SetTrackDescriptor(trk, desc); + }; + set_track_name(g_encoder_track, "WiVRn encoder"); + set_track_name(g_compositor_track, "WiVRn compositor"); + set_track_name(g_network_track, "WiVRn network"); + set_track_name(g_feedback_track, "WiVRn feedback"); + + // The in-process session must be started after Register() so its data source is known. + if (use_inprocess) + start_inprocess_session(); + + U_LOG_I("wivrn::trace: init complete"); +} + +void flush_session() +{ + if (!initialized or !g_inproc_session) + return; + // Client gone but process lives; flush and re-arm for the next one. + write_inproc_session(); + g_inproc_session.reset(); + start_inprocess_session(); +} + +void shutdown() +{ + if (!initialized or !g_inproc_session) + return; + write_inproc_session(); + g_inproc_session.reset(); +} + +bool is_enabled() +{ + return initialized; +} + +void set_calibration_source(::vk_bundle * monado_vk) +{ + calibration = monado_vk; +} + +::vk_bundle * calibration_source() +{ + return calibration; +} + +void instant_feedback(const char * name, int64_t time_ns, uint64_t frame, uint8_t stream) +{ + if (!initialized) + return; + TRACE_EVENT_INSTANT("wivrn_feedback", perfetto::DynamicString(name), g_feedback_track, static_cast(time_ns), "frame", frame, "stream", static_cast(stream)); +} + +void gpu_slice(gpu_track, const char * slice_name, int64_t begin_ns, int64_t end_ns, uint64_t frame, uint8_t stream) +{ + if (!initialized) + return; + // gpu_track is unused today (all slices share the encoder track); kept for future GPU lanes. + TRACE_EVENT_BEGIN("wivrn_encoder_gpu", perfetto::DynamicString(slice_name), g_encoder_track, static_cast(begin_ns), "frame", frame, "stream", static_cast(stream)); + TRACE_EVENT_END("wivrn_encoder_gpu", g_encoder_track, static_cast(end_ns)); +} + +#define WIVRN_CPU_BEGIN(CAT, trk, name, ts, frame, stream) \ + TRACE_EVENT_BEGIN(CAT, perfetto::DynamicString(name), (trk), static_cast(ts), "frame", (frame), "stream", static_cast(stream)) + +scope::scope(cpu_track which, uint8_t stream, uint64_t frame, const char * name) : + which(which), stream(stream), frame(frame), name(name), begin_ns(0), active(false) +{ + if (!initialized) + return; + bool enabled = false; + switch (which) + { + case cpu_track::encoder: + enabled = TRACE_EVENT_CATEGORY_ENABLED("wivrn_encoder"); + break; + case cpu_track::compositor: + enabled = TRACE_EVENT_CATEGORY_ENABLED("wivrn_compositor"); + break; + case cpu_track::network: + enabled = TRACE_EVENT_CATEGORY_ENABLED("wivrn_network"); + break; + } + if (!enabled) + return; + active = true; + begin_ns = os_monotonic_get_ns(); +} + +scope::~scope() +{ + if (!active) + return; + const int64_t end_ns = os_monotonic_get_ns(); + perfetto::Track & trk = cpu_track_obj(which); + switch (which) + { + case cpu_track::encoder: + WIVRN_CPU_BEGIN("wivrn_encoder", trk, name, begin_ns, frame, stream); + TRACE_EVENT_END("wivrn_encoder", trk, static_cast(end_ns)); + break; + case cpu_track::compositor: + WIVRN_CPU_BEGIN("wivrn_compositor", trk, name, begin_ns, frame, stream); + TRACE_EVENT_END("wivrn_compositor", trk, static_cast(end_ns)); + break; + case cpu_track::network: + WIVRN_CPU_BEGIN("wivrn_network", trk, name, begin_ns, frame, stream); + TRACE_EVENT_END("wivrn_network", trk, static_cast(end_ns)); + break; + } +} + +void cpu_instant(cpu_track which, const char * name, uint64_t frame, uint8_t stream) +{ + if (!initialized) + return; + const int64_t ts = os_monotonic_get_ns(); + perfetto::Track & trk = cpu_track_obj(which); + switch (which) + { + case cpu_track::encoder: + TRACE_EVENT_INSTANT("wivrn_encoder", perfetto::DynamicString(name), trk, static_cast(ts), "frame", frame, "stream", static_cast(stream)); + break; + case cpu_track::compositor: + TRACE_EVENT_INSTANT("wivrn_compositor", perfetto::DynamicString(name), trk, static_cast(ts), "frame", frame, "stream", static_cast(stream)); + break; + case cpu_track::network: + TRACE_EVENT_INSTANT("wivrn_network", perfetto::DynamicString(name), trk, static_cast(ts), "frame", frame, "stream", static_cast(stream)); + break; + } +} + +void cpu_begin(cpu_track which, uint8_t stream, uint64_t frame, const char * name) +{ + if (!initialized) + return; + const int64_t ts = os_monotonic_get_ns(); + perfetto::Track & trk = cpu_track_obj(which); + switch (which) + { + case cpu_track::encoder: + WIVRN_CPU_BEGIN("wivrn_encoder", trk, name, ts, frame, stream); + break; + case cpu_track::compositor: + WIVRN_CPU_BEGIN("wivrn_compositor", trk, name, ts, frame, stream); + break; + case cpu_track::network: + WIVRN_CPU_BEGIN("wivrn_network", trk, name, ts, frame, stream); + break; + } +} + +void cpu_end(cpu_track which, uint8_t, uint64_t, const char *) +{ + if (!initialized) + return; + const int64_t ts = os_monotonic_get_ns(); + perfetto::Track & trk = cpu_track_obj(which); + switch (which) + { + case cpu_track::encoder: + TRACE_EVENT_END("wivrn_encoder", trk, static_cast(ts)); + break; + case cpu_track::compositor: + TRACE_EVENT_END("wivrn_compositor", trk, static_cast(ts)); + break; + case cpu_track::network: + TRACE_EVENT_END("wivrn_network", trk, static_cast(ts)); + break; + } +} +} // namespace wivrn::trace + +#else // !WIVRN_USE_PERFETTO + +namespace wivrn::trace +{ +void init() +{ + u_trace_marker_init(); +} +void flush_session() {} +void shutdown() {} +bool is_enabled() +{ + return false; +} +void set_calibration_source(::vk_bundle *) {} +::vk_bundle * calibration_source() +{ + return nullptr; +} +void instant_feedback(const char *, int64_t, uint64_t, uint8_t) {} +void gpu_slice(gpu_track, const char *, int64_t, int64_t, uint64_t, uint8_t) {} +scope::scope(cpu_track which, uint8_t stream, uint64_t frame, const char * name) : + which(which), stream(stream), frame(frame), name(name), begin_ns(0), active(false) {} +scope::~scope() {} +void cpu_instant(cpu_track, const char *, uint64_t, uint8_t) {} +void cpu_begin(cpu_track, uint8_t, uint64_t, const char *) {} +void cpu_end(cpu_track, uint8_t, uint64_t, const char *) {} +} // namespace wivrn::trace + +#endif // WIVRN_USE_PERFETTO diff --git a/server/utils/wivrn_trace.h b/server/utils/wivrn_trace.h new file mode 100644 index 00000000..3dc3093c --- /dev/null +++ b/server/utils/wivrn_trace.h @@ -0,0 +1,108 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 WiVRn Contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include + +// Perfetto tracing via the Perfetto SDK. No-op unless built with WIVRN_USE_PERFETTO. + +// Monado's vk_bundle (C struct from util/vk/vk_helpers.h); used as the +// calibration source for converting GPU timestamp-query ticks to host +// monotonic ns via vk_convert_timestamps_to_host_ns. +struct vk_bundle; + +namespace wivrn::trace +{ +// The single tracing entry point. Idempotent. Always runs Monado's u_trace_marker_init() +// (and, with WIVRN_TRACE_MONADO, bridges WIVRN_TRACING onto Monado's tracing first); Perfetto +// tracing is a no-op without WIVRN_USE_PERFETTO or WIVRN_TRACING. WIVRN_TRACING selects the +// backend (system / inprocess / system+inprocess) — see wivrn_trace.cpp for the full env-var docs. +void init(); + +// Writes the current in-process trace to its own file and re-arms a fresh session, without +// ending the process. Call when a streaming client disconnects (the session pauses, awaiting +// reconnect), so each connection leaves its own trace. No-op unless the in-process backend is +// active. +void flush_session(); + +// Stops and flushes the in-process session (writing the final trace file) if one is running; +// no-op otherwise. Must be called once at process/session teardown. +void shutdown(); + +// True iff WIVRN_TRACING is set in the environment (and WIVRN_USE_PERFETTO +// is enabled). Cached after the first read. +bool is_enabled(); + +// Set by the compositor after vk_init_from_given so query-pool ticks can be +// converted via monado's calibration cache. Single-threaded init window; +// reads happen on encoder threads after streaming starts. +void set_calibration_source(::vk_bundle * monado_vk); +::vk_bundle * calibration_source(); + +// Instant on the feedback track at an explicit monotonic timestamp. +// name is copied at emit time (perfetto::DynamicString), so it need not outlive the call. +void instant_feedback(const char * name, int64_t time_ns, uint64_t frame, uint8_t stream); + +// GPU-hardware-timestamped slice on the WiVRn encoder track. +// begin_ns/end_ns must come from GPU query pools (gpu_timestamp_pool::collect), +// already converted to host monotonic via calibrated timestamps. +enum class gpu_track +{ + vulkan_encode, + vulkan_image_copy, + vulkan_host_copy, + vulkan_host_copy_overflow, + nvenc_copy, + va_copy, +}; +void gpu_slice(gpu_track which, const char * slice_name, int64_t begin_ns, int64_t end_ns, uint64_t frame, uint8_t stream); + +enum class cpu_track +{ + encoder, + compositor, + network, +}; + +// RAII CPU span. Zero-cost when tracing is off. Construct as a local with a +// chosen variable name; the span closes at scope exit. +class scope +{ + cpu_track which; + uint8_t stream; + uint64_t frame; + const char * name; + int64_t begin_ns; + bool active; + +public: + scope(cpu_track which, uint8_t stream, uint64_t frame, const char * name); + ~scope(); + scope(const scope &) = delete; + scope & operator=(const scope &) = delete; +}; + +void cpu_instant(cpu_track which, const char * name, uint64_t frame, uint8_t stream); + +// Non-RAII begin/end pair, for spans whose lifetime crosses function calls +// (e.g. video_encoder::SendData where a frame is split across several calls). +// Only cpu_begin reads name (copied via perfetto::DynamicString); cpu_end ignores it. +void cpu_begin(cpu_track which, uint8_t stream, uint64_t frame, const char * name); +void cpu_end(cpu_track which, uint8_t stream, uint64_t frame, const char * name); +} // namespace wivrn::trace diff --git a/server/utils/wivrn_vk_bundle.cpp b/server/utils/wivrn_vk_bundle.cpp index 01f1f792..a99000b3 100644 --- a/server/utils/wivrn_vk_bundle.cpp +++ b/server/utils/wivrn_vk_bundle.cpp @@ -283,6 +283,10 @@ wivrn::vk_bundle::vk_bundle() : #endif #ifdef VK_KHR_unified_image_layouts VK_KHR_UNIFIED_IMAGE_LAYOUTS_EXTENSION_NAME, +#endif +// For perfetto GPU timestamp tracing +#ifdef VK_EXT_calibrated_timestamps + VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, #endif }; for (auto & ext: physical_device.enumerateDeviceExtensionProperties()) diff --git a/tools/perfetto/pftrace_summary.py b/tools/perfetto/pftrace_summary.py new file mode 100644 index 00000000..d567f627 --- /dev/null +++ b/tools/perfetto/pftrace_summary.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +# Perfetto pftrace summarizer — pairs BEGIN/END by trusted_packet_sequence_id. +# Single file: per-slice stats table. +# Two files: side-by-side diff table (pass in either order). + +import collections +import statistics +import sys + + +def read_varint(buf, off): + v = 0 + shift = 0 + while True: + b = buf[off] + off += 1 + v |= (b & 0x7F) << shift + if not (b & 0x80): + return v, off + shift += 7 + + +def read_tag(buf, off): + tag, off = read_varint(buf, off) + return tag >> 3, tag & 7, off + + +def skip(buf, off, wt): + if wt == 0: + _, off = read_varint(buf, off) + return off + if wt == 1: + return off + 8 + if wt == 2: + ln, off = read_varint(buf, off) + return off + ln + if wt == 5: + return off + 4 + raise ValueError(f"unknown wt {wt}") + + +def parse_track_event(buf, off, end): + name = None + ev_type = None + while off < end: + fid, wt, off = read_tag(buf, off) + if fid == 23 and wt == 2: + ln, off = read_varint(buf, off) + name = buf[off : off + ln].decode("utf-8", "replace") + off += ln + elif fid == 9 and wt == 0: + ev_type, off = read_varint(buf, off) + else: + off = skip(buf, off, wt) + return name, ev_type + + +def parse(path): + with open(path, "rb") as f: + buf = f.read() + durations = collections.defaultdict(list) + open_stack = collections.defaultdict(list) # seq_id -> [(name, ts)] + ts_min = ts_max = None + + off = 0 + n = len(buf) + while off < n: + fid, wt, off = read_tag(buf, off) + if fid != 1 or wt != 2: + off = skip(buf, off, wt) + continue + ln, off = read_varint(buf, off) + end = off + ln + ts = None + seq = None + te_name = None + te_type = None + while off < end: + f2, wt2, off = read_tag(buf, off) + if f2 == 8 and wt2 == 0: + ts, off = read_varint(buf, off) + elif f2 == 10 and wt2 == 0: + seq, off = read_varint(buf, off) + elif f2 == 11 and wt2 == 2: + ln2, off = read_varint(buf, off) + te_name, te_type = parse_track_event(buf, off, off + ln2) + off += ln2 + else: + off = skip(buf, off, wt2) + if ( + ts is not None and te_type is not None + ): # only real events, not metadata packets with ts=0 + if ts_min is None or ts < ts_min: + ts_min = ts + if ts_max is None or ts > ts_max: + ts_max = ts + if te_type is not None: + if te_type == 1 and te_name and ts is not None: + open_stack[seq].append((te_name, ts)) + elif te_type == 2 and ts is not None and open_stack[seq]: + bname, bts = open_stack[seq].pop() + durations[bname].append(ts - bts) + + span = (ts_max - ts_min) if ts_min is not None else 0 + return dict(durations), span, len(buf) + + +def _is_instant(dur_list): + return all(d == 0 for d in dur_list) + + +def _stats(dur_list, span): + srt = sorted(dur_list) + p99 = srt[int(len(srt) * 0.99)] if len(srt) > 1 else srt[0] + rate = len(dur_list) / (span / 1e9) if span else 0 + return ( + len(dur_list), + statistics.mean(dur_list) / 1e6, + statistics.median(dur_list) / 1e6, + p99 / 1e6, + max(dur_list) / 1e6, + rate, + ) + + +def summarize(path): + durations, span, size = parse(path) + print(f"\n=== {path} ===") + print(f" file size: {size:,} bytes") + print(f" trace span: {span / 1e9:.3f} s") + + rows = [] + for name, dur_list in durations.items(): + if not dur_list or _is_instant(dur_list): + continue + rows.append((name,) + _stats(dur_list, span)) + rows.sort(key=lambda r: -r[1]) + print( + f" {'slice':<32} {'n':>6} {'mean ms':>9} {'p50 ms':>8} {'p99 ms':>8} {'max ms':>8} {'rate/s':>8}" + ) + for r in rows[:30]: + print( + f" {r[0]:<32} {r[1]:>6} {r[2]:>9.3f} {r[3]:>8.3f} {r[4]:>8.3f} {r[5]:>8.3f} {r[6]:>8.1f}" + ) + + instants = [(n, _stats(d, span)) for n, d in durations.items() if d and _is_instant(d)] + if instants: + instants.sort(key=lambda x: -x[1][5]) + print(f"\n {'instant':<32} {'n':>6} {'rate/s':>8}") + for name, st in instants: + print(f" {name:<32} {st[0]:>6} {st[5]:>8.1f}") + + +def compare(path_a, path_b): + dur_a, span_a, size_a = parse(path_a) + dur_b, span_b, size_b = parse(path_b) + + label_a = path_a.rsplit("/", 1)[-1] + label_b = path_b.rsplit("/", 1)[-1] + + print(f"\n=== {label_a} vs {label_b} ===") + print( + f" A: {size_a:,} bytes {span_a / 1e9:.3f} s B: {size_b:,} bytes {span_b / 1e9:.3f} s" + ) + + all_names = sorted(set(dur_a) | set(dur_b)) + span_names = [ + n + for n in all_names + if (dur_a.get(n) and not _is_instant(dur_a[n])) + or (dur_b.get(n) and not _is_instant(dur_b[n])) + ] + + def fmt_cell(dur_list, span): + if not dur_list or _is_instant(dur_list): + return f"{'–':>5} {'–':>8} {'–':>8} {'–':>8}" + st = _stats(dur_list, span) + return f"{st[0]:>5} {st[1]:>8.3f} {st[2]:>8.3f} {st[3]:>8.3f}" + + def fmt_delta(da, db): + if not da or _is_instant(da) or not db or _is_instant(db): + return "" + ma = statistics.mean(da) / 1e6 + mb = statistics.mean(db) / 1e6 + diff = mb - ma + pct = diff / ma * 100 if ma else 0 + sign = "+" if diff >= 0 else "" + return f"{sign}{diff:.3f} ms ({sign}{pct:.0f}%)" + + col_w = 36 # n + mean + p50 + p99 + print( + f"\n {'slice':<32} {'── A: ' + label_a[:26]:<{col_w}} {'── B: ' + label_b[:26]:<{col_w}} delta" + ) + print( + f" {'':32} {'n':>5} {'mean ms':>8} {'p50 ms':>8} {'p99 ms':>8}" + f" {'n':>5} {'mean ms':>8} {'p50 ms':>8} {'p99 ms':>8}" + ) + print(" " + "-" * 110) + + # Sort by combined mean (largest first = most interesting) + def sort_key(n): + ma = statistics.mean(dur_a[n]) if dur_a.get(n) and not _is_instant(dur_a[n]) else 0 + mb = statistics.mean(dur_b[n]) if dur_b.get(n) and not _is_instant(dur_b[n]) else 0 + return -(ma + mb) + + for name in sorted(span_names, key=sort_key): + da = dur_a.get(name, []) + db = dur_b.get(name, []) + print(f" {name:<32} {fmt_cell(da, span_a)} {fmt_cell(db, span_b)} {fmt_delta(da, db)}") + + instant_names = [ + n + for n in all_names + if (dur_a.get(n) and _is_instant(dur_a[n])) or (dur_b.get(n) and _is_instant(dur_b[n])) + ] + if instant_names: + print(f"\n {'instant':<32} {'rate/s (A)':>12} {'rate/s (B)':>12}") + for name in sorted(instant_names): + da = dur_a.get(name, []) + db = dur_b.get(name, []) + ra = f"{len(da) / (span_a / 1e9):.1f}" if da and span_a else "–" + rb = f"{len(db) / (span_b / 1e9):.1f}" if db and span_b else "–" + print(f" {name:<32} {ra:>12} {rb:>12}") + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("usage: pftrace_summary.py [second.pftrace]", file=sys.stderr) + sys.exit(2) + if len(sys.argv) == 3: + compare(sys.argv[1], sys.argv[2]) + else: + for p in sys.argv[1:]: + summarize(p) + print("\n open in https://ui.perfetto.dev for the visual timeline") diff --git a/tools/perfetto/wivrn_capture.py b/tools/perfetto/wivrn_capture.py new file mode 100755 index 00000000..ee97bcc7 --- /dev/null +++ b/tools/perfetto/wivrn_capture.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 +"""One-command Perfetto capture for wivrn-server (run with WIVRN_TRACING=system). + +wivrn_capture.py # WiVRn-only (default) +wivrn_capture.py --full # full-system capture +wivrn_capture.py -c custom.pbtx # any perfetto config +wivrn_capture.py --cpu-only # strip ftrace from config +wivrn_capture.py --duration-ms 30000 -o my.pftrace +""" + +import argparse +import atexit +import os +import re +import signal +import stat +import subprocess +import sys +import tempfile +import time +import urllib.request +from datetime import datetime +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +TRACEBOX_URL = "https://get.perfetto.dev/tracebox" + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def xdg(var, default_rel): + """Resolve an XDG base directory.""" + val = os.environ.get(var) + return Path(val) if val else Path.home() / default_rel + + +def strip_ftrace_blocks(text): + """Remove any data_sources { ... } block containing name: "linux.ftrace".""" + lines = text.splitlines(keepends=True) + result = [] + in_block = False + depth = 0 + buf = [] + for line in lines: + if not in_block: + if re.match(r"^data_sources\s*\{", line): + in_block = True + depth = 1 + buf = [line] + else: + result.append(line) + else: + buf.append(line) + depth += line.count("{") - line.count("}") + if depth == 0: + if not re.search(r'name:\s*"linux\.ftrace"', "".join(buf)): + result.extend(buf) + in_block = False + buf = [] + return "".join(result) + + +def needs_ftrace(text): + return bool(re.search(r'name:\s*"linux\.ftrace"', text)) + + +def download_tracebox(url, dest): + """Download url to dest with a simple progress indicator.""" + print(f"wivrn_capture: downloading tracebox to {dest}") + try: + with urllib.request.urlopen(url) as resp: + total = int(resp.headers.get("Content-Length", 0)) + downloaded = 0 + with open(dest, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) + downloaded += len(chunk) + if total: + pct = downloaded * 100 // total + print( + f"\r {downloaded / 1e6:.1f} / {total / 1e6:.1f} MB ({pct}%)", + end="", + flush=True, + ) + else: + print(f"\r {downloaded / 1e6:.1f} MB", end="", flush=True) + print() + except Exception as e: + Path(dest).unlink(missing_ok=True) + sys.exit(f"wivrn_capture: download failed: {e}") + + +def ensure_tracebox(path): + if path.is_file() and os.access(path, os.X_OK): + return + path.parent.mkdir(parents=True, exist_ok=True) + download_tracebox(TRACEBOX_URL, path) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def pgrep(name): + """Return list of matching PIDs (as strings), or [].""" + r = subprocess.run(["pgrep", "-x", name], capture_output=True, text=True) + return r.stdout.split() if r.returncode == 0 else [] + + +def socket_listening(sock_path): + """Return True if a Unix socket at sock_path is bound and listening.""" + r = subprocess.run(["ss", "-lxH", "src", str(sock_path)], capture_output=True, text=True) + return bool(r.stdout.strip()) + + +def wait_for_producer(tracebox, env, timeout_s=20): + """True once a track_event data source registers (wivrn-server connected).""" + deadline = time.time() + timeout_s + while time.time() < deadline: + r = subprocess.run( + [str(tracebox), "perfetto", "--query"], env=env, capture_output=True, text=True + ) + if "track_event" in r.stdout: + return True + time.sleep(0.5) + return False + + +def log(msg): + print(f"wivrn_capture: {msg}") + + +def err(msg): + print(f"wivrn_capture: {msg}", file=sys.stderr) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + + +def main(): + cache_dir = xdg("XDG_CACHE_HOME", ".cache") / "wivrn" + tracebox = cache_dir / "tracebox" + sock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) + producer_sock = sock_dir / "wivrn-perfetto-producer.sock" + consumer_sock = sock_dir / "wivrn-perfetto-consumer.sock" + + parser = argparse.ArgumentParser( + prog=Path(sys.argv[0]).name, + description="One-command Perfetto capture for wivrn-server.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=f"Run: WIVRN_TRACING=system wivrn-server (socket: {producer_sock})", + ) + parser.add_argument( + "-c", + "--config", + metavar="PATH", + help="Perfetto config (default: wivrn_trace_cfg.pbtx — " + "WiVRn track_event categories only, no ftrace)", + ) + parser.add_argument( + "--full", + action="store_true", + help="Shorthand for -c wivrn_full_trace_cfg.pbtx (every category + broader ftrace)", + ) + parser.add_argument( + "-o", "--output", metavar="PATH", help="Output .pftrace path (default: wivrn-.pftrace)" + ) + parser.add_argument( + "--cpu-only", + action="store_true", + help="Strip any linux.ftrace data source from the config " + "(no traced_probes / no sudo needed)", + ) + parser.add_argument( + "--duration-ms", metavar="N", type=int, help="Override duration_ms in the config" + ) + args = parser.parse_args() + + # Resolve config. + if args.full: + cfg = SCRIPT_DIR / "wivrn_full_trace_cfg.pbtx" + elif args.config: + cfg = Path(args.config) + else: + cfg = SCRIPT_DIR / "wivrn_trace_cfg.pbtx" + + # Resolve output filename. + if args.output: + out = Path(args.output) + else: + ts = datetime.now().strftime("%Y%m%d-%H%M%S") + out = Path(f"wivrn-{ts}.pftrace") + + if not cfg.is_file(): + sys.exit(f"wivrn_capture: missing config: {cfg}") + log(f"using config {cfg}") + + ensure_tracebox(tracebox) + + # Build the runtime config (strip ftrace / override duration as needed). + cfg_text = cfg.read_text() + if args.cpu_only: + cfg_text = strip_ftrace_blocks(cfg_text) + if args.duration_ms is not None: + cfg_text = re.sub( + r"^duration_ms: \d+", f"duration_ms: {args.duration_ms}", cfg_text, flags=re.MULTILINE + ) + + run_cfg_fd, run_cfg_path = tempfile.mkstemp(suffix=".pbtx") + run_cfg = Path(run_cfg_path) + try: + os.write(run_cfg_fd, cfg_text.encode()) + finally: + os.close(run_cfg_fd) + + use_ftrace = needs_ftrace(cfg_text) + sudo = ["sudo", "-E"] if use_ftrace else [] + user = os.environ.get("USER", os.getlogin()) + + log("run a client and stream during capture, or the trace is empty") + + # Clean up stale sockets from crashed runs; traced won't reuse them. + producer_sock.unlink(missing_ok=True) + consumer_sock.unlink(missing_ok=True) + + started_traced = False + started_probes = False + + def cleanup(): + run_cfg.unlink(missing_ok=True) + if started_probes: + subprocess.run([*sudo, "pkill", "-x", "traced_probes"], capture_output=True) + if started_traced: + subprocess.run([*sudo, "pkill", "-x", "traced"], capture_output=True) + producer_sock.unlink(missing_ok=True) + consumer_sock.unlink(missing_ok=True) + + atexit.register(cleanup) + + # Route SIGTERM / SIGINT through sys.exit so atexit cleanup runs. + def _sig(signum, _frame): + sys.exit(128 + signum) + + signal.signal(signal.SIGTERM, _sig) + signal.signal(signal.SIGINT, _sig) + + # Reuse an existing traced only if it owns our sockets. + existing = pgrep("traced") + if existing: + if not socket_listening(consumer_sock): + pids = ", ".join(existing) + err(f"traced (pid {pids}) not on {consumer_sock}; kill it and re-run") + sys.exit(1) + else: + # traced reads socket paths from env vars, not CLI flags. + env = { + **os.environ, + "PERFETTO_PRODUCER_SOCK_NAME": str(producer_sock), + "PERFETTO_CONSUMER_SOCK_NAME": str(consumer_sock), + } + traced_cmd = [*sudo, str(tracebox), "traced", "--background"] + if use_ftrace: + traced_cmd += ["--set-socket-permissions", f"{user}:0660:{user}:0660"] + subprocess.run(traced_cmd, env=env, check=True) + started_traced = True + time.sleep(0.3) + + if use_ftrace and not pgrep("traced_probes"): + env = {**os.environ, "PERFETTO_PRODUCER_SOCK_NAME": str(producer_sock)} + subprocess.run([*sudo, str(tracebox), "traced_probes", "--background"], env=env, check=True) + started_probes = True + time.sleep(0.3) + + if not producer_sock.is_socket(): + err(f"traced did not bind {producer_sock}") + sys.exit(1) + + env = { + **os.environ, + "PERFETTO_PRODUCER_SOCK_NAME": str(producer_sock), + "PERFETTO_CONSUMER_SOCK_NAME": str(consumer_sock), + } + + # Wait for the producer; abort rather than capture an empty trace. + log("waiting for producer…") + if not wait_for_producer(tracebox, env): + err( + "no track_event producer after 20s — is wivrn-server running with " + "WIVRN_TRACING and a client streaming?" + ) + err("(if it just worked, restart wivrn-server — the producer doesn't reconnect)") + sys.exit(1) + + log(f"capturing → {out}") + subprocess.run( + [str(tracebox), "perfetto", "-c", str(run_cfg), "--txt", "-o", str(out)], + env=env, + check=True, + ) + + print() + trace_bytes = out.stat().st_size if out.exists() else 0 + log(f"wrote {out} ({trace_bytes} bytes)") + + if trace_bytes < 4096: + err("trace looks empty — was a client streaming during capture?") + else: + log("open in https://ui.perfetto.dev") + + +if __name__ == "__main__": + main() diff --git a/tools/perfetto/wivrn_full_trace_cfg.pbtx b/tools/perfetto/wivrn_full_trace_cfg.pbtx new file mode 100644 index 00000000..cec80f9c --- /dev/null +++ b/tools/perfetto/wivrn_full_trace_cfg.pbtx @@ -0,0 +1,78 @@ +# Full-system Perfetto config: like wivrn_trace_cfg.pbtx but unfiltered — every +# track_event category plus broad ftrace (sched, freq, GPU, IRQs, vblank). Use +# it to see WiVRn in context with the rest of the system. Bigger traces, needs +# sudo for ftrace. +# +# Capture: tools/perfetto/wivrn_capture.py --full +# Manual setup and socket details: docs/profiling.md. + +duration_ms: 5000 + +# Two buffers on purpose: in a shared ring buffer the high-volume ftrace stream +# evicts the low-volume track_event chunks by age before the trace is written, +# losing the WiVRn/Monado slices. Isolating track_event keeps it from eviction. +buffers { # buffer 0: WiVRn + Monado track_event + size_kb: 65536 + fill_policy: RING_BUFFER +} +buffers { # buffer 1: high-volume system data (ftrace + process/system info) + size_kb: 262144 + fill_policy: RING_BUFFER +} + +# Unfiltered track_event: every category from every producer is recorded. +data_sources { + config { + name: "track_event" + target_buffer: 0 + track_event_config { + enabled_categories: "*" + } + } +} + +# Broader system context than the default config: scheduling, frequency, +# OpenXR/graphics frame timing, GPU frequency/memory, and IRQs. +data_sources { + config { + name: "linux.ftrace" + target_buffer: 1 + ftrace_config { + ftrace_events: "sched/sched_switch" + ftrace_events: "sched/sched_waking" + ftrace_events: "sched/sched_process_exit" + ftrace_events: "sched/sched_process_free" + ftrace_events: "power/cpu_frequency" + ftrace_events: "power/cpu_idle" + ftrace_events: "power/gpu_frequency" + ftrace_events: "power/suspend_resume" + ftrace_events: "irq/irq_handler_entry" + ftrace_events: "irq/irq_handler_exit" + ftrace_events: "irq/softirq_entry" + ftrace_events: "irq/softirq_exit" + ftrace_events: "drm/drm_vblank_event" + atrace_categories: "gfx" + atrace_categories: "sched" + atrace_categories: "freq" + } + } +} + +# Process/thread names so threads show up labelled in the UI. +data_sources { + config { + name: "linux.process_stats" + target_buffer: 1 + process_stats_config { + scan_all_processes_on_start: true + } + } +} + +# System info: CPU count, kernel, distro. +data_sources { + config { + name: "linux.system_info" + target_buffer: 1 + } +} diff --git a/tools/perfetto/wivrn_trace_cfg.pbtx b/tools/perfetto/wivrn_trace_cfg.pbtx new file mode 100644 index 00000000..5da152e3 --- /dev/null +++ b/tools/perfetto/wivrn_trace_cfg.pbtx @@ -0,0 +1,32 @@ +# WiVRn-only Perfetto config: WiVRn track_event slices, no ftrace. Small, +# encoder-focused traces. For system context use wivrn_full_trace_cfg.pbtx +# (or --full). +# +# Capture: tools/perfetto/wivrn_capture.py +# Manual setup and socket details: docs/profiling.md. + +duration_ms: 15000 +buffers { + size_kb: 65536 + fill_policy: RING_BUFFER +} + +data_sources { + config { + name: "track_event" + target_buffer: 0 + track_event_config { + # Allowlist must match the category names in + # server/utils/wivrn_trace.cpp exactly (Perfetto does exact/glob, + # not substring matching). Listing only WiVRn categories keeps the + # trace WiVRn-only even when Monado is built with tracing. + # Do NOT add `disabled_categories: "*"`: it also silences the + # enabled allowlist, giving empty traces. + enabled_categories: "wivrn_encoder" + enabled_categories: "wivrn_encoder_gpu" + enabled_categories: "wivrn_compositor" + enabled_categories: "wivrn_network" + enabled_categories: "wivrn_feedback" + } + } +}