diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn b/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn index 0a7702f36a..6de8fff0b1 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn @@ -15,6 +15,7 @@ impeller_component("vulkan_unittests") { "fence_waiter_vk_unittests.cc", "pass_bindings_cache_unittests.cc", "resource_manager_vk_unittests.cc", + "test/gpu_tracer_unittests.cc", "test/mock_vulkan.cc", "test/mock_vulkan.h", "test/mock_vulkan_unittests.cc", diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc index 8f973bd0fa..d963d8519f 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.cc @@ -7,6 +7,7 @@ #include "flutter/fml/closure.h" #include "impeller/renderer/backend/vulkan/context_vk.h" #include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" namespace impeller { @@ -133,21 +134,25 @@ std::shared_ptr CommandEncoderFactoryVK::Create() { context_vk.SetDebugName(tracked_objects->GetCommandBuffer(), label_.value()); } + context->GetGPUTracer()->RecordCmdBufferStart( + tracked_objects->GetCommandBuffer()); - return std::make_shared(context_vk.GetDeviceHolder(), - tracked_objects, queue, - context_vk.GetFenceWaiter()); + return std::make_shared( + context_vk.GetDeviceHolder(), tracked_objects, queue, + context_vk.GetFenceWaiter(), context->GetGPUTracer()); } CommandEncoderVK::CommandEncoderVK( std::weak_ptr device_holder, std::shared_ptr tracked_objects, const std::shared_ptr& queue, - std::shared_ptr fence_waiter) + std::shared_ptr fence_waiter, + const std::shared_ptr& gpu_tracer) : device_holder_(std::move(device_holder)), tracked_objects_(std::move(tracked_objects)), queue_(queue), - fence_waiter_(std::move(fence_waiter)) {} + fence_waiter_(std::move(fence_waiter)), + gpu_tracer_(gpu_tracer) {} CommandEncoderVK::~CommandEncoderVK() = default; @@ -178,18 +183,23 @@ bool CommandEncoderVK::Submit(SubmitCallback callback) { auto command_buffer = GetCommandBuffer(); + auto end_frame = gpu_tracer_->RecordCmdBufferEnd(command_buffer); + auto status = command_buffer.end(); if (status != vk::Result::eSuccess) { + gpu_tracer_->OnFenceComplete(end_frame, false); VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(status); return false; } std::shared_ptr strong_device = device_holder_.lock(); if (!strong_device) { + gpu_tracer_->OnFenceComplete(end_frame, false); VALIDATION_LOG << "Device lost."; return false; } auto [fence_result, fence] = strong_device->GetDevice().createFenceUnique({}); if (fence_result != vk::Result::eSuccess) { + gpu_tracer_->OnFenceComplete(end_frame, false); VALIDATION_LOG << "Failed to create fence: " << vk::to_string(fence_result); return false; } @@ -199,6 +209,7 @@ bool CommandEncoderVK::Submit(SubmitCallback callback) { submit_info.setCommandBuffers(buffers); status = queue_->Submit(submit_info, *fence); if (status != vk::Result::eSuccess) { + gpu_tracer_->OnFenceComplete(end_frame, false); VALIDATION_LOG << "Failed to submit queue: " << vk::to_string(status); return false; } @@ -206,9 +217,14 @@ bool CommandEncoderVK::Submit(SubmitCallback callback) { // Submit will proceed, call callback with true when it is done and do not // call when `reset` is collected. fail_callback = false; + auto gpu_tracer = gpu_tracer_; return fence_waiter_->AddFence( std::move(fence), - [callback, tracked_objects = std::move(tracked_objects_)] { + [callback, tracked_objects = std::move(tracked_objects_), gpu_tracer, + end_frame] { + if (end_frame.has_value()) { + gpu_tracer->OnFenceComplete(end_frame, true); + } if (callback) { callback(true); } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h index 5402a6ad3c..5a1e7d9d72 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk.h @@ -29,7 +29,8 @@ class FenceWaiterVK; class CommandEncoderFactoryVK { public: - CommandEncoderFactoryVK(const std::weak_ptr& context); + explicit CommandEncoderFactoryVK( + const std::weak_ptr& context); std::shared_ptr Create(); @@ -50,7 +51,8 @@ class CommandEncoderVK { CommandEncoderVK(std::weak_ptr device_holder, std::shared_ptr tracked_objects, const std::shared_ptr& queue, - std::shared_ptr fence_waiter); + std::shared_ptr fence_waiter, + const std::shared_ptr& gpu_tracer); ~CommandEncoderVK(); @@ -89,6 +91,7 @@ class CommandEncoderVK { std::shared_ptr tracked_objects_; std::shared_ptr queue_; const std::shared_ptr fence_waiter_; + std::shared_ptr gpu_tracer_; bool is_valid_ = true; void Reset(); diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc index 028b92ffb1..8204f5965e 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc @@ -433,7 +433,7 @@ void ContextVK::Setup(Settings settings) { // Create the GPU Tracer later because it depends on state from // the ContextVK. - gpu_tracer_ = std::make_shared(weak_from_this()); + gpu_tracer_ = std::make_shared(GetDeviceHolder()); //---------------------------------------------------------------------------- /// Label all the relevant objects. This happens after setup so that the diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc index 0b7da21de9..1d16f90661 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc @@ -4,128 +4,170 @@ #include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include #include +#include "fml/logging.h" #include "fml/trace_event.h" #include "impeller/base/validation.h" -#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" -#include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include "impeller/renderer/backend/vulkan/context_vk.h" -#include "impeller/renderer/command_buffer.h" +#include "vulkan/vulkan.hpp" namespace impeller { -static constexpr uint32_t kPoolSize = 32u; +static constexpr uint32_t kPoolSize = 64u; -GPUTracerVK::GPUTracerVK(const std::weak_ptr& context) - : context_(context) { - auto strong_context = context_.lock(); - if (!strong_context) { - return; - } - timestamp_period_ = strong_context->GetPhysicalDevice() +GPUTracerVK::GPUTracerVK(const std::shared_ptr& device_holder) + : device_holder_(device_holder) { + timestamp_period_ = device_holder_->GetPhysicalDevice() .getProperties() .limits.timestampPeriod; if (timestamp_period_ <= 0) { // The device does not support timestamp queries. return; } - vk::QueryPoolCreateInfo info; - info.queryCount = kPoolSize; - info.queryType = vk::QueryType::eTimestamp; - - auto [status, pool] = strong_context->GetDevice().createQueryPoolUnique(info); - if (status != vk::Result::eSuccess) { - VALIDATION_LOG << "Failed to create query pool."; - return; - } - query_pool_ = std::move(pool); // Disable tracing in release mode. #ifdef IMPELLER_DEBUG - valid_ = true; + enabled_ = true; #endif } -void GPUTracerVK::RecordStartFrameTime() { - if (!valid_) { - return; - } - auto strong_context = context_.lock(); - if (!strong_context) { - return; - } - auto buffer = strong_context->CreateCommandBuffer(); - auto vk_trace_cmd_buffer = - CommandBufferVK::Cast(*buffer).GetEncoder()->GetCommandBuffer(); - // The two commands below are executed in order, such that writeTimeStamp is - // guaranteed to occur after resetQueryPool has finished. The validation - // layer seem particularly strict, and efforts to reset the entire pool - // were met with validation errors (though seemingly correct measurements). - // To work around this, the tracer only resets the query that will be - // used next. - vk_trace_cmd_buffer.resetQueryPool(query_pool_.get(), current_index_, 1); - vk_trace_cmd_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, - query_pool_.get(), current_index_); - - if (!buffer->SubmitCommands()) { - VALIDATION_LOG << "GPUTracerVK: Failed to record start time."; - } - - // The logic in RecordEndFrameTime requires us to have recorded a pair of - // tracing events. If this method failed for any reason we need to be sure we - // don't attempt to record and read back a second value, or we will get values - // that span multiple frames. - started_frame_ = true; +bool GPUTracerVK::IsEnabled() const { + return enabled_; } -void GPUTracerVK::RecordEndFrameTime() { - if (!valid_ || !started_frame_) { - return; - } - auto strong_context = context_.lock(); - if (!strong_context) { +void GPUTracerVK::MarkFrameStart() { + FML_DCHECK(!in_frame_); + in_frame_ = true; + raster_thread_id_ = std::this_thread::get_id(); +} + +void GPUTracerVK::MarkFrameEnd() { + if (!enabled_) { return; } - started_frame_ = false; - auto last_query = current_index_; - current_index_ += 1; + Lock lock(trace_state_mutex_); + current_state_ = (current_state_ + 1) % 16; - auto buffer = strong_context->CreateCommandBuffer(); - auto vk_trace_cmd_buffer = - CommandBufferVK::Cast(*buffer).GetEncoder()->GetCommandBuffer(); - vk_trace_cmd_buffer.resetQueryPool(query_pool_.get(), current_index_, 1); - vk_trace_cmd_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, - query_pool_.get(), current_index_); + auto& state = trace_states_[current_state_]; + // If there are still pending buffers on the trace state we're switching to, + // that means that a cmd buffer we were relying on to signal this likely + // never finished. This shouldn't happen unless there is a bug in the + // encoder logic. We set it to zero anyway to prevent a validation error + // from becoming a memory leak. + FML_DCHECK(state.pending_buffers == 0u); - // On completion of the second time stamp recording, we read back this value - // and the previous value. The difference is approximately the frame time. - const auto device_holder = strong_context->GetDeviceHolder(); - auto submitted = buffer->SubmitCommands( - [&, last_query, device_holder](CommandBuffer::Status status) { - if (status != CommandBuffer::Status::kCompleted) { - return; - } - uint64_t bits[2] = {0, 0}; - auto result = device_holder->GetDevice().getQueryPoolResults( - query_pool_.get(), last_query, 2, sizeof(bits), &bits, - sizeof(int64_t), vk::QueryResultFlagBits::e64); + state.pending_buffers = 0; + state.current_index = 0; + state.contains_failure = false; + in_frame_ = false; +} - if (result != vk::Result::eSuccess) { - return; - } - // This value should probably be available in some form besides a - // timeline event but that is a job for a future Jonah. - auto gpu_ms = (((bits[1] - bits[0]) * timestamp_period_) / 1000000); - FML_TRACE_COUNTER("flutter", "GPUTracer", - reinterpret_cast(this), // Trace Counter ID - "FrameTimeMS", gpu_ms); - }); - if (!submitted) { - VALIDATION_LOG << "GPUTracerVK failed to record frame end time."; +void GPUTracerVK::RecordCmdBufferStart(const vk::CommandBuffer& buffer) { + if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || + !in_frame_) { + return; + } + Lock lock(trace_state_mutex_); + auto& state = trace_states_[current_state_]; + + // Initialize the query pool for the first query on each frame. + if (state.pending_buffers == 0) { + vk::QueryPoolCreateInfo info; + info.queryCount = kPoolSize; + info.queryType = vk::QueryType::eTimestamp; + + auto [status, pool] = + device_holder_->GetDevice().createQueryPoolUnique(info); + if (status != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create query pool."; + return; + } + trace_states_[current_state_].query_pool = std::move(pool); + buffer.resetQueryPool(trace_states_[current_state_].query_pool.get(), 0, + kPoolSize); } - if (current_index_ == kPoolSize - 1) { - current_index_ = 0u; + // We size the query pool to kPoolSize, but Flutter applications can create an + // unbounded amount of work per frame. If we encounter this, stop recording + // cmds. + if (state.current_index >= kPoolSize) { + return; + } + + buffer.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, + trace_states_[current_state_].query_pool.get(), + state.current_index); + state.pending_buffers += 1; + state.current_index += 1; +} + +std::optional GPUTracerVK::RecordCmdBufferEnd( + const vk::CommandBuffer& buffer) { + if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || + !in_frame_) { + return std::nullopt; + } + Lock lock(trace_state_mutex_); + GPUTraceState& state = trace_states_[current_state_]; + + if (state.current_index >= kPoolSize) { + return current_state_; + } + + buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, + state.query_pool.get(), state.current_index); + + state.current_index += 1; + return current_state_; +} + +void GPUTracerVK::OnFenceComplete(std::optional maybe_frame_index, + bool success) { + if (!enabled_ || !maybe_frame_index.has_value()) { + return; + } + auto frame_index = maybe_frame_index.value(); + Lock lock(trace_state_mutex_); + GPUTraceState& state = trace_states_[frame_index]; + if (state.pending_buffers == 0) { + return; + } + state.contains_failure = !success; + state.pending_buffers -= 1; + + if (state.pending_buffers == 0 && !state.contains_failure) { + auto buffer_count = state.current_index; + std::vector bits(buffer_count); + + auto result = device_holder_->GetDevice().getQueryPoolResults( + state.query_pool.get(), 0, state.current_index, + buffer_count * sizeof(uint64_t), bits.data(), sizeof(uint64_t), + vk::QueryResultFlagBits::e64); + // This may return VK_NOT_READY if the query couldn't be completed, or if + // there are queries still pending. From local testing, this happens + // occassionally on very expensive frames. Its unclear if we can do anything + // about this, because by design this should only signal after all cmd + // buffers have signaled. Adding VK_QUERY_RESULT_WAIT_BIT to the flags + // passed to getQueryPoolResults seems like it would fix this, but actually + // seems to result in more stuck query errors. Better to just drop them and + // move on. + if (result != vk::Result::eSuccess) { + return; + } + + uint64_t smallest_timestamp = std::numeric_limits::max(); + uint64_t largest_timestamp = 0; + for (auto i = 0u; i < bits.size(); i++) { + smallest_timestamp = std::min(smallest_timestamp, bits[i]); + largest_timestamp = std::max(largest_timestamp, bits[i]); + } + auto gpu_ms = + (((largest_timestamp - smallest_timestamp) * timestamp_period_) / + 1000000); + FML_TRACE_COUNTER("flutter", "GPUTracer", + reinterpret_cast(this), // Trace Counter ID + "FrameTimeMS", gpu_ms); } } diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h b/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h index 8913bf3ffd..238bf618f1 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h @@ -3,8 +3,11 @@ // found in the LICENSE file. #include +#include #include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder.h" +#include "vulkan/vulkan_handles.hpp" namespace impeller { @@ -12,29 +15,70 @@ namespace impeller { /// execution time. class GPUTracerVK { public: - explicit GPUTracerVK(const std::weak_ptr& context); + explicit GPUTracerVK(const std::shared_ptr& device_holder); ~GPUTracerVK() = default; - /// @brief Record the approximate start time of the GPU workload for the - /// current frame. - void RecordStartFrameTime(); + /// @brief Record a timestamp query into the provided cmd buffer to record + /// start time. + void RecordCmdBufferStart(const vk::CommandBuffer& buffer); - /// @brief Record the approximate end time of the GPU workload for the current - /// frame. - void RecordEndFrameTime(); + /// @brief Record a timestamp query into the provided cmd buffer to record end + /// time. + /// + /// Returns the index that should be passed to [OnFenceComplete]. + std::optional RecordCmdBufferEnd(const vk::CommandBuffer& buffer); + + /// @brief Signal that the cmd buffer is completed. + /// + /// If [frame_index] is std::nullopt, this frame recording is ignored. + void OnFenceComplete(std::optional frame_index, bool success); + + /// @brief Signal the start of a frame workload. + /// + /// Any cmd buffers that are created after this call and before + /// [MarkFrameEnd] will be attributed to the current frame. + void MarkFrameStart(); + + /// @brief Signal the end of a frame workload. + void MarkFrameEnd(); + + // visible for testing. + bool IsEnabled() const; private: - void ResetQueryPool(size_t pool); + const std::shared_ptr device_holder_; - const std::weak_ptr context_; - vk::UniqueQueryPool query_pool_ = {}; + struct GPUTraceState { + size_t current_index = 0; + size_t pending_buffers = 0; + // If a cmd buffer submission fails for any reason, this field is used + // to indicate that the query pool results may be incomplete and this + // frame should be discarded. + bool contains_failure = false; + vk::UniqueQueryPool query_pool; + }; + + mutable Mutex trace_state_mutex_; + GPUTraceState trace_states_[16] IPLR_GUARDED_BY(trace_state_mutex_); + size_t current_state_ IPLR_GUARDED_BY(trace_state_mutex_) = 0u; - size_t current_index_ = 0u; // The number of nanoseconds for each timestamp unit. float timestamp_period_ = 1; - bool started_frame_ = false; - bool valid_ = false; + + // If in_frame_ is not true, then this cmd buffer was started as a part of + // some non-frame workload like image decoding. We should not record this as + // part of the frame workload, as the gap between this non-frame and a + // frameworkload may be substantial. For example, support the engine creates a + // cmd buffer to perform an image upload at timestamp 0 and then 30 ms later + // actually renders a frame. Without the in_frame_ guard, the GPU frame time + // would include this 30ms gap during which the engine was idle. + bool in_frame_ = false; + + // Track the raster thread id to avoid recording mipmap/image cmd buffers + // that are not guaranteed to start/end according to frame boundaries. + std::thread::id raster_thread_id_; + bool enabled_ = false; }; } // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc index 351ac2a1c9..7d0f982345 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain_impl_vk.cc @@ -379,9 +379,6 @@ SwapchainImplVK::AcquireResult SwapchainImplVK::AcquireNextDrawable() { nullptr // fence ); - /// Record the approximate start of the GPU workload. - context.GetGPUTracer()->RecordStartFrameTime(); - switch (acq_result) { case vk::Result::eSuccess: // Keep going. @@ -403,6 +400,9 @@ SwapchainImplVK::AcquireResult SwapchainImplVK::AcquireNextDrawable() { return {}; } + /// Record all subsequent cmd buffers as part of the current frame. + context.GetGPUTracer()->MarkFrameStart(); + auto image = images_[index % images_.size()]; uint32_t image_index = index; return AcquireResult{SurfaceVK::WrapSwapchainImage( @@ -428,6 +428,10 @@ bool SwapchainImplVK::Present(const std::shared_ptr& image, const auto& context = ContextVK::Cast(*context_strong); const auto& sync = synchronizers_[current_frame_]; + /// Record the approximate end of the GPU workload. This is intentionally + /// done before creating the final cmd buffer as that is not tracked. + context.GetGPUTracer()->MarkFrameEnd(); + //---------------------------------------------------------------------------- /// Transition the image to color-attachment-optimal. /// @@ -457,9 +461,6 @@ bool SwapchainImplVK::Present(const std::shared_ptr& image, } } - /// Record the approximate end of the GPU workload. - context.GetGPUTracer()->RecordEndFrameTime(); - //---------------------------------------------------------------------------- /// Signal that the presentation semaphore is ready. /// diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc new file mode 100644 index 0000000000..d20e41a68a --- /dev/null +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc @@ -0,0 +1,111 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer//backend/vulkan/command_encoder_vk.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +namespace impeller { +namespace testing { + +#ifdef IMPELLER_DEBUG +TEST(GPUTracerVK, CanTraceCmdBuffer) { + auto const context = MockVulkanContextBuilder().Build(); + + auto tracer = std::make_shared(context->GetDeviceHolder()); + + ASSERT_TRUE(tracer->IsEnabled()); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto vk_cmd_buffer = CommandBufferVK::Cast(cmd_buffer.get()); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + tracer->MarkFrameStart(); + tracer->RecordCmdBufferStart(vk_cmd_buffer->GetEncoder()->GetCommandBuffer()); + auto frame_id = tracer->RecordCmdBufferEnd( + vk_cmd_buffer->GetEncoder()->GetCommandBuffer()); + tracer->MarkFrameEnd(); + + ASSERT_EQ(frame_id, 0u); + auto called = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") != + called->end()); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") == called->end()); + + tracer->OnFenceComplete(frame_id, true); + + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") != called->end()); +} + +TEST(GPUTracerVK, DoesNotTraceOutsideOfFrameWorkload) { + auto const context = MockVulkanContextBuilder().Build(); + + auto tracer = std::make_shared(context->GetDeviceHolder()); + + ASSERT_TRUE(tracer->IsEnabled()); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto vk_cmd_buffer = CommandBufferVK::Cast(cmd_buffer.get()); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + tracer->RecordCmdBufferStart(vk_cmd_buffer->GetEncoder()->GetCommandBuffer()); + auto frame_id = tracer->RecordCmdBufferEnd( + vk_cmd_buffer->GetEncoder()->GetCommandBuffer()); + + ASSERT_TRUE(!frame_id.has_value()); + auto called = GetMockVulkanFunctions(context->GetDevice()); + + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") == + called->end()); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") == called->end()); + + tracer->OnFenceComplete(frame_id, true); + + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") == + called->end()); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") == called->end()); +} + +TEST(GPUTracerVK, DoesNotTraceOtherTheads) { + auto const context = MockVulkanContextBuilder().Build(); + + auto tracer = std::make_shared(context->GetDeviceHolder()); + + ASSERT_TRUE(tracer->IsEnabled()); + + tracer->MarkFrameStart(); + + // Record the cmd buffer on another thread to simulate a mipmap cmd buffer. + std::thread image_upload_thread([&context]() { + auto cmd_buffer = context->CreateCommandBuffer(); + auto vk_cmd_buffer = CommandBufferVK::Cast(cmd_buffer.get()); + auto blit_pass = cmd_buffer->CreateBlitPass(); + if (!cmd_buffer->SubmitCommands()) { + VALIDATION_LOG << "Failed to submit commands"; + } + }); + + image_upload_thread.join(); + + auto called = GetMockVulkanFunctions(context->GetDevice()); + + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") == + called->end()); +} + +#endif // IMPELLER_DEBUG + +} // namespace testing +} // namespace impeller diff --git a/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc b/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc index 1140078386..bee4d53e67 100644 --- a/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc +++ b/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc @@ -10,6 +10,8 @@ #include "fml/thread_local.h" #include "impeller/base/thread_safety.h" #include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep. +#include "third_party/swiftshader/include/vulkan/vulkan_core.h" +#include "vulkan/vulkan_core.h" namespace impeller { namespace testing { @@ -23,6 +25,8 @@ struct MockCommandBuffer { std::shared_ptr> called_functions_; }; +struct MockQueryPool {}; + struct MockCommandPool {}; class MockDevice final { @@ -153,6 +157,7 @@ void vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, static_cast(VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT); pProperties->limits.maxImageDimension2D = 4096; + pProperties->limits.timestampPeriod = 1; } void vkGetPhysicalDeviceQueueFamilyProperties( @@ -495,6 +500,40 @@ VkResult vkSetDebugUtilsObjectNameEXT( return VK_SUCCESS; } +VkResult vkCreateQueryPool(VkDevice device, + const VkQueryPoolCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkQueryPool* pQueryPool) { + *pQueryPool = reinterpret_cast(new MockQueryPool()); + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateQueryPool"); + return VK_SUCCESS; +} + +VkResult vkGetQueryPoolResults(VkDevice device, + VkQueryPool queryPool, + uint32_t firstQuery, + uint32_t queryCount, + size_t dataSize, + void* pData, + VkDeviceSize stride, + VkQueryResultFlags flags) { + MockDevice* mock_device = reinterpret_cast(device); + if (dataSize == sizeof(uint32_t)) { + uint32_t* data = static_cast(pData); + for (auto i = firstQuery; i < queryCount; i++) { + data[0] = i; + } + } else if (dataSize == sizeof(int64_t)) { + uint64_t* data = static_cast(pData); + for (auto i = firstQuery; i < queryCount; i++) { + data[0] = i; + } + } + mock_device->AddCalledFunction("vkGetQueryPoolResults"); + return VK_SUCCESS; +} + PFN_vkVoidFunction GetMockVulkanProcAddress(VkInstance instance, const char* pName) { if (strcmp("vkEnumerateInstanceExtensionProperties", pName) == 0) { @@ -595,6 +634,10 @@ PFN_vkVoidFunction GetMockVulkanProcAddress(VkInstance instance, return (PFN_vkVoidFunction)vkCreateDebugUtilsMessengerEXT; } else if (strcmp("vkSetDebugUtilsObjectNameEXT", pName) == 0) { return (PFN_vkVoidFunction)vkSetDebugUtilsObjectNameEXT; + } else if (strcmp("vkCreateQueryPool", pName) == 0) { + return (PFN_vkVoidFunction)vkCreateQueryPool; + } else if (strcmp("vkGetQueryPoolResults", pName) == 0) { + return (PFN_vkVoidFunction)vkGetQueryPoolResults; } return noop; }