Add WiVRn-native Perfetto via Perfetto SDK

Optional server profiling built on the Perfetto SDK. Adds CPU spans
(compositor, encoder, network), GPU encode/copy slices from Vulkan timestamp
queries (Vulkan/NVENC/VAAPI), and headset feedback markers from dump_time.

WIVRN_TRACING enables tracing and selects the backend (system, inprocess, or
both); WIVRN_USE_PERFETTO gates it at build time and compiles it out otherwise.
WIVRN_TRACE_MONADO additionally drives Monado's percetto tracing from the same
switch so WiVRn and Monado land on one timeline.

Tooling: server-tracing[-monado] presets and a CI build, two Perfetto configs
(WiVRn-only and full-system), a wivrn_capture.py capture wrapper, a pftrace
summary script, and docs/profiling.md.
This commit is contained in:
Jonathan Steffan
2026-07-01 21:04:08 +02:00
committed by xytovl
parent b11655fdee
commit b9c8a54d92
34 changed files with 1968 additions and 58 deletions
+33
View File
@@ -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()
+12
View File
@@ -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;
+5
View File
@@ -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);
@@ -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<wivrn::video_encoder::data> 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<AVPacket> 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{
+20 -1
View File
@@ -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 <drm_fourcc.h>
@@ -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());
+3
View File
@@ -20,6 +20,7 @@
#pragma once
#include "ffmpeg_helper.h"
#include "utils/gpu_timestamp_pool.h"
#include "video_encoder_ffmpeg.h"
#include <array>
@@ -47,6 +48,8 @@ class video_encoder_va : public video_encoder_ffmpeg
av_buffer_ptr drm_frame_ctx;
std::array<in_t, num_slots> in;
gpu_timestamp_pool ts_pool;
public:
video_encoder_va(wivrn::vk_bundle &, const wivrn::encoder_settings & settings, uint8_t stream_index);
+13 -5
View File
@@ -24,6 +24,7 @@
#include "encoder_settings.h"
#include "os/os_time.h"
#include "utils/wivrn_trace.h"
#include "wivrn_config.h"
#include <string>
@@ -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<uint8_t> 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<uint8_t> 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<uint32_t>::max();
@@ -341,7 +346,10 @@ void video_encoder::SendData(std::span<uint8_t> 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
+23 -4
View File
@@ -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::data> 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::data> 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);
+3
View File
@@ -19,6 +19,7 @@
#pragma once
#include "utils/gpu_timestamp_pool.h"
#include "video_encoder.h"
#include "video_encoder_nvenc_shared_state.h"
#include <array>
@@ -53,6 +54,8 @@ private:
};
std::array<in_t, num_slots> in;
gpu_timestamp_pool ts_pool;
float fps;
uint64_t bitrate;
int bytesPerPixel = 1;
+59
View File
@@ -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 <iostream>
@@ -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::data> 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::data> 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::data> 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::data> 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();
+6
View File
@@ -22,6 +22,7 @@
#include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#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;
+1 -2
View File
@@ -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);
+3 -3
View File
@@ -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 <assert.h>
@@ -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();
+102
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
// Monado's vk_helpers.h pulls in xrt_vulkan_includes.h, which sets the
// VK_USE_PLATFORM_* defines *before* <vulkan/vulkan.h> 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 <array>
#include <cassert>
#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::sample> 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<std::array<uint64_t, 2>>(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<int64_t>(times[0]),
.end_ns = static_cast<int64_t>(times[1]),
.frame_index = frame_indices[slot],
};
#else
(void)slot;
return std::nullopt;
#endif
}
} // namespace wivrn
+59
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
#include <vulkan/vulkan_raii.hpp>
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<uint64_t> 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<sample> collect(uint8_t slot);
};
} // namespace wivrn
+493
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
#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 <cstdint>
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <memory>
#include <perfetto.h>
#include <string>
#include <unistd.h>
#include <vector>
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<perfetto::TracingSession> 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-<ts>-<pid>.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<char> 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<std::streamsize>(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<uint32_t>(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<uint64_t>(time_ns), "frame", frame, "stream", static_cast<uint32_t>(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<uint64_t>(begin_ns), "frame", frame, "stream", static_cast<uint32_t>(stream));
TRACE_EVENT_END("wivrn_encoder_gpu", g_encoder_track, static_cast<uint64_t>(end_ns));
}
#define WIVRN_CPU_BEGIN(CAT, trk, name, ts, frame, stream) \
TRACE_EVENT_BEGIN(CAT, perfetto::DynamicString(name), (trk), static_cast<uint64_t>(ts), "frame", (frame), "stream", static_cast<uint32_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(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<uint64_t>(ts), "frame", frame, "stream", static_cast<uint32_t>(stream));
break;
case cpu_track::compositor:
TRACE_EVENT_INSTANT("wivrn_compositor", perfetto::DynamicString(name), trk, static_cast<uint64_t>(ts), "frame", frame, "stream", static_cast<uint32_t>(stream));
break;
case cpu_track::network:
TRACE_EVENT_INSTANT("wivrn_network", perfetto::DynamicString(name), trk, static_cast<uint64_t>(ts), "frame", frame, "stream", static_cast<uint32_t>(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<uint64_t>(ts));
break;
case cpu_track::compositor:
TRACE_EVENT_END("wivrn_compositor", trk, static_cast<uint64_t>(ts));
break;
case cpu_track::network:
TRACE_EVENT_END("wivrn_network", trk, static_cast<uint64_t>(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
+108
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstdint>
// 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
+4
View File
@@ -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())