Flutter Impeller
khr_swapchain_impl_vk.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
6 
7 #include "fml/synchronization/semaphore.h"
18 
19 namespace impeller {
20 
21 static constexpr size_t kMaxFramesInFlight = 2u;
22 
24  vk::UniqueFence acquire;
25  vk::UniqueSemaphore render_ready;
26  vk::UniqueSemaphore present_ready;
27  std::shared_ptr<CommandBuffer> final_cmd_buffer;
28  bool is_valid = false;
29  // Whether the renderer attached an onscreen command buffer to render to.
30  bool has_onscreen = false;
31 
32  explicit KHRFrameSynchronizerVK(const vk::Device& device) {
33  auto acquire_res = device.createFenceUnique(
34  vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled});
35  auto render_res = device.createSemaphoreUnique({});
36  auto present_res = device.createSemaphoreUnique({});
37  if (acquire_res.result != vk::Result::eSuccess ||
38  render_res.result != vk::Result::eSuccess ||
39  present_res.result != vk::Result::eSuccess) {
40  VALIDATION_LOG << "Could not create synchronizer.";
41  return;
42  }
43  acquire = std::move(acquire_res.value);
44  render_ready = std::move(render_res.value);
45  present_ready = std::move(present_res.value);
46  is_valid = true;
47  }
48 
50 
51  bool WaitForFence(const vk::Device& device) {
52  if (auto result = device.waitForFences(
53  *acquire, // fence
54  true, // wait all
55  std::numeric_limits<uint64_t>::max() // timeout (ns)
56  );
57  result != vk::Result::eSuccess) {
58  VALIDATION_LOG << "Fence wait failed: " << vk::to_string(result);
59  return false;
60  }
61  if (auto result = device.resetFences(*acquire);
62  result != vk::Result::eSuccess) {
63  VALIDATION_LOG << "Could not reset fence: " << vk::to_string(result);
64  return false;
65  }
66  return true;
67  }
68 };
69 
70 static bool ContainsFormat(const std::vector<vk::SurfaceFormatKHR>& formats,
71  vk::SurfaceFormatKHR format) {
72  return std::find(formats.begin(), formats.end(), format) != formats.end();
73 }
74 
75 static std::optional<vk::SurfaceFormatKHR> ChooseSurfaceFormat(
76  const std::vector<vk::SurfaceFormatKHR>& formats,
77  PixelFormat preference) {
78  const auto colorspace = vk::ColorSpaceKHR::eSrgbNonlinear;
79  const auto vk_preference =
80  vk::SurfaceFormatKHR{ToVKImageFormat(preference), colorspace};
81  if (ContainsFormat(formats, vk_preference)) {
82  return vk_preference;
83  }
84 
85  std::vector<vk::SurfaceFormatKHR> options = {
86  {vk::Format::eB8G8R8A8Unorm, colorspace},
87  {vk::Format::eR8G8B8A8Unorm, colorspace}};
88  for (const auto& format : options) {
89  if (ContainsFormat(formats, format)) {
90  return format;
91  }
92  }
93 
94  return std::nullopt;
95 }
96 
97 static std::optional<vk::CompositeAlphaFlagBitsKHR> ChooseAlphaCompositionMode(
98  vk::CompositeAlphaFlagsKHR flags) {
99  if (flags & vk::CompositeAlphaFlagBitsKHR::eInherit) {
100  return vk::CompositeAlphaFlagBitsKHR::eInherit;
101  }
102  if (flags & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied) {
103  return vk::CompositeAlphaFlagBitsKHR::ePreMultiplied;
104  }
105  if (flags & vk::CompositeAlphaFlagBitsKHR::ePostMultiplied) {
106  return vk::CompositeAlphaFlagBitsKHR::ePostMultiplied;
107  }
108  if (flags & vk::CompositeAlphaFlagBitsKHR::eOpaque) {
109  return vk::CompositeAlphaFlagBitsKHR::eOpaque;
110  }
111 
112  return std::nullopt;
113 }
114 
115 std::shared_ptr<KHRSwapchainImplVK> KHRSwapchainImplVK::Create(
116  const std::shared_ptr<Context>& context,
117  vk::UniqueSurfaceKHR surface,
118  const ISize& size,
119  bool enable_msaa,
120  vk::SwapchainKHR old_swapchain) {
121  return std::shared_ptr<KHRSwapchainImplVK>(new KHRSwapchainImplVK(
122  context, std::move(surface), size, enable_msaa, old_swapchain));
123 }
124 
125 KHRSwapchainImplVK::KHRSwapchainImplVK(const std::shared_ptr<Context>& context,
126  vk::UniqueSurfaceKHR surface,
127  const ISize& size,
128  bool enable_msaa,
129  vk::SwapchainKHR old_swapchain) {
130  if (!context) {
131  VALIDATION_LOG << "Cannot create a swapchain without a context.";
132  return;
133  }
134 
135  auto& vk_context = ContextVK::Cast(*context);
136 
137  const auto [caps_result, surface_caps] =
138  vk_context.GetPhysicalDevice().getSurfaceCapabilitiesKHR(*surface);
139  if (caps_result != vk::Result::eSuccess) {
140  VALIDATION_LOG << "Could not get surface capabilities: "
141  << vk::to_string(caps_result);
142  return;
143  }
144 
145  auto [formats_result, formats] =
146  vk_context.GetPhysicalDevice().getSurfaceFormatsKHR(*surface);
147  if (formats_result != vk::Result::eSuccess) {
148  VALIDATION_LOG << "Could not get surface formats: "
149  << vk::to_string(formats_result);
150  return;
151  }
152 
153  const auto format = ChooseSurfaceFormat(
154  formats, vk_context.GetCapabilities()->GetDefaultColorFormat());
155  if (!format.has_value()) {
156  VALIDATION_LOG << "Swapchain has no supported formats.";
157  return;
158  }
159  vk_context.SetOffscreenFormat(ToPixelFormat(format.value().format));
160 
161  const auto composite =
162  ChooseAlphaCompositionMode(surface_caps.supportedCompositeAlpha);
163  if (!composite.has_value()) {
164  VALIDATION_LOG << "No composition mode supported.";
165  return;
166  }
167 
168  vk::SwapchainCreateInfoKHR swapchain_info;
169  swapchain_info.surface = *surface;
170  swapchain_info.imageFormat = format.value().format;
171  swapchain_info.imageColorSpace = format.value().colorSpace;
172  swapchain_info.presentMode = vk::PresentModeKHR::eFifo;
173  swapchain_info.imageExtent = vk::Extent2D{
174  std::clamp(static_cast<uint32_t>(size.width),
175  surface_caps.minImageExtent.width,
176  surface_caps.maxImageExtent.width),
177  std::clamp(static_cast<uint32_t>(size.height),
178  surface_caps.minImageExtent.height,
179  surface_caps.maxImageExtent.height),
180  };
181  swapchain_info.minImageCount =
182  std::clamp(surface_caps.minImageCount + 1u, // preferred image count
183  surface_caps.minImageCount, // min count cannot be zero
184  surface_caps.maxImageCount == 0u
185  ? surface_caps.minImageCount + 1u
186  : surface_caps.maxImageCount // max zero means no limit
187  );
188  swapchain_info.imageArrayLayers = 1u;
189  // Swapchain images are primarily used as color attachments (via resolve),
190  // blit targets, or input attachments.
191  swapchain_info.imageUsage = vk::ImageUsageFlagBits::eColorAttachment |
192  vk::ImageUsageFlagBits::eTransferDst |
193  vk::ImageUsageFlagBits::eInputAttachment;
194  swapchain_info.preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
195  swapchain_info.compositeAlpha = composite.value();
196  // If we set the clipped value to true, Vulkan expects we will never read back
197  // from the buffer. This is analogous to [CAMetalLayer framebufferOnly] in
198  // Metal.
199  swapchain_info.clipped = true;
200  // Setting queue family indices is irrelevant since the present mode is
201  // exclusive.
202  swapchain_info.imageSharingMode = vk::SharingMode::eExclusive;
203  swapchain_info.oldSwapchain = old_swapchain;
204 
205  auto [swapchain_result, swapchain] =
206  vk_context.GetDevice().createSwapchainKHRUnique(swapchain_info);
207  if (swapchain_result != vk::Result::eSuccess) {
208  VALIDATION_LOG << "Could not create swapchain: "
209  << vk::to_string(swapchain_result);
210  return;
211  }
212 
213  auto [images_result, images] =
214  vk_context.GetDevice().getSwapchainImagesKHR(*swapchain);
215  if (images_result != vk::Result::eSuccess) {
216  VALIDATION_LOG << "Could not get swapchain images.";
217  return;
218  }
219 
220  TextureDescriptor texture_desc;
221  texture_desc.usage = TextureUsage::kRenderTarget;
222  texture_desc.storage_mode = StorageMode::kDevicePrivate;
223  texture_desc.format = ToPixelFormat(swapchain_info.imageFormat);
224  texture_desc.size = ISize::MakeWH(swapchain_info.imageExtent.width,
225  swapchain_info.imageExtent.height);
226 
227  std::vector<std::shared_ptr<KHRSwapchainImageVK>> swapchain_images;
228  for (const auto& image : images) {
229  auto swapchain_image = std::make_shared<KHRSwapchainImageVK>(
230  texture_desc, // texture descriptor
231  vk_context.GetDevice(), // device
232  image // image
233  );
234  if (!swapchain_image->IsValid()) {
235  VALIDATION_LOG << "Could not create swapchain image.";
236  return;
237  }
239  vk_context.GetDevice(), swapchain_image->GetImage(),
240  "SwapchainImage" + std::to_string(swapchain_images.size()));
242  vk_context.GetDevice(), swapchain_image->GetImageView(),
243  "SwapchainImageView" + std::to_string(swapchain_images.size()));
244 
245  swapchain_images.emplace_back(swapchain_image);
246  }
247 
248  std::vector<std::unique_ptr<KHRFrameSynchronizerVK>> synchronizers;
249  for (size_t i = 0u; i < kMaxFramesInFlight; i++) {
250  auto sync =
251  std::make_unique<KHRFrameSynchronizerVK>(vk_context.GetDevice());
252  if (!sync->is_valid) {
253  VALIDATION_LOG << "Could not create frame synchronizers.";
254  return;
255  }
256  synchronizers.emplace_back(std::move(sync));
257  }
258  FML_DCHECK(!synchronizers.empty());
259 
260  context_ = context;
261  surface_ = std::move(surface);
262  surface_format_ = swapchain_info.imageFormat;
263  swapchain_ = std::move(swapchain);
264  transients_ = std::make_shared<SwapchainTransientsVK>(context, texture_desc,
265  enable_msaa);
266  images_ = std::move(swapchain_images);
267  synchronizers_ = std::move(synchronizers);
268  current_frame_ = synchronizers_.size() - 1u;
269  size_ = size;
270  enable_msaa_ = enable_msaa;
271  is_valid_ = true;
272 }
273 
276 }
277 
279  return size_;
280 }
281 
283  return is_valid_;
284 }
285 
286 void KHRSwapchainImplVK::WaitIdle() const {
287  if (auto context = context_.lock()) {
288  [[maybe_unused]] auto result =
289  ContextVK::Cast(*context).GetDevice().waitIdle();
290  }
291 }
292 
293 std::pair<vk::UniqueSurfaceKHR, vk::UniqueSwapchainKHR>
295  WaitIdle();
296  is_valid_ = false;
297  synchronizers_.clear();
298  images_.clear();
299  context_.reset();
300  return {std::move(surface_), std::move(swapchain_)};
301 }
302 
304  return surface_format_;
305 }
306 
307 std::shared_ptr<Context> KHRSwapchainImplVK::GetContext() const {
308  return context_.lock();
309 }
310 
312  auto context_strong = context_.lock();
313  if (!context_strong) {
315  }
316 
317  const auto& context = ContextVK::Cast(*context_strong);
318 
319  current_frame_ = (current_frame_ + 1u) % synchronizers_.size();
320 
321  const auto& sync = synchronizers_[current_frame_];
322 
323  //----------------------------------------------------------------------------
324  /// Wait on the host for the synchronizer fence.
325  ///
326  if (!sync->WaitForFence(context.GetDevice())) {
327  VALIDATION_LOG << "Could not wait for fence.";
329  }
330 
331  //----------------------------------------------------------------------------
332  /// Get the next image index.
333  ///
334  /// @bug Non-infinite timeouts are not supported on some older Android
335  /// devices and the only indication we get is log spam which serves to
336  /// add confusion. Just use an infinite timeout instead of being
337  /// defensive.
338  auto [acq_result, index] = context.GetDevice().acquireNextImageKHR(
339  *swapchain_, // swapchain
340  std::numeric_limits<uint64_t>::max(), // timeout (ns)
341  *sync->render_ready, // signal semaphore
342  nullptr // fence
343  );
344 
345  switch (acq_result) {
346  case vk::Result::eSuccess:
347  // Keep going.
348  break;
349  case vk::Result::eSuboptimalKHR:
350  case vk::Result::eErrorOutOfDateKHR:
351  // A recoverable error. Just say we are out of date.
352  return AcquireResult{true /* out of date */};
353  break;
354  default:
355  // An unrecoverable error.
356  VALIDATION_LOG << "Could not acquire next swapchain image: "
357  << vk::to_string(acq_result);
358  return AcquireResult{false /* out of date */};
359  }
360 
361  if (index >= images_.size()) {
362  VALIDATION_LOG << "Swapchain returned an invalid image index.";
364  }
365 
366  /// Record all subsequent cmd buffers as part of the current frame.
367  context.GetGPUTracer()->MarkFrameStart();
368 
369  auto image = images_[index % images_.size()];
370  uint32_t image_index = index;
372  transients_, // transients
373  image, // swapchain image
374  [weak_swapchain = weak_from_this(), image, image_index]() -> bool {
375  auto swapchain = weak_swapchain.lock();
376  if (!swapchain) {
377  return false;
378  }
379  return swapchain->Present(image, image_index);
380  } // swap callback
381  )};
382 }
383 
385  std::shared_ptr<CommandBuffer> cmd_buffer) {
386  const auto& sync = synchronizers_[current_frame_];
387  sync->final_cmd_buffer = std::move(cmd_buffer);
388  sync->has_onscreen = true;
389 }
390 
391 bool KHRSwapchainImplVK::Present(
392  const std::shared_ptr<KHRSwapchainImageVK>& image,
393  uint32_t index) {
394  auto context_strong = context_.lock();
395  if (!context_strong) {
396  return false;
397  }
398 
399  const auto& context = ContextVK::Cast(*context_strong);
400  const auto& sync = synchronizers_[current_frame_];
401  context.GetGPUTracer()->MarkFrameEnd();
402 
403  //----------------------------------------------------------------------------
404  /// Transition the image to color-attachment-optimal.
405  ///
406  if (!sync->has_onscreen) {
407  sync->final_cmd_buffer = context.CreateCommandBuffer();
408  }
409  sync->has_onscreen = false;
410  if (!sync->final_cmd_buffer) {
411  return false;
412  }
413 
414  auto vk_final_cmd_buffer =
415  CommandBufferVK::Cast(*sync->final_cmd_buffer).GetCommandBuffer();
416  {
417  BarrierVK barrier;
418  barrier.new_layout = vk::ImageLayout::ePresentSrcKHR;
419  barrier.cmd_buffer = vk_final_cmd_buffer;
420  barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite;
421  barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput;
422  barrier.dst_access = {};
423  barrier.dst_stage = vk::PipelineStageFlagBits::eBottomOfPipe;
424 
425  if (!image->SetLayout(barrier).ok()) {
426  return false;
427  }
428 
429  if (vk_final_cmd_buffer.end() != vk::Result::eSuccess) {
430  return false;
431  }
432  }
433 
434  //----------------------------------------------------------------------------
435  /// Signal that the presentation semaphore is ready.
436  ///
437  {
438  vk::SubmitInfo submit_info;
439  vk::PipelineStageFlags wait_stage =
440  vk::PipelineStageFlagBits::eColorAttachmentOutput;
441  submit_info.setWaitDstStageMask(wait_stage);
442  submit_info.setWaitSemaphores(*sync->render_ready);
443  submit_info.setSignalSemaphores(*sync->present_ready);
444  submit_info.setCommandBuffers(vk_final_cmd_buffer);
445  auto result =
446  context.GetGraphicsQueue()->Submit(submit_info, *sync->acquire);
447  if (result != vk::Result::eSuccess) {
448  VALIDATION_LOG << "Could not wait on render semaphore: "
449  << vk::to_string(result);
450  return false;
451  }
452  }
453 
454  //----------------------------------------------------------------------------
455  /// Present the image.
456  ///
457  uint32_t indices[] = {static_cast<uint32_t>(index)};
458 
459  vk::PresentInfoKHR present_info;
460  present_info.setSwapchains(*swapchain_);
461  present_info.setImageIndices(indices);
462  present_info.setWaitSemaphores(*sync->present_ready);
463 
464  auto result = context.GetGraphicsQueue()->Present(present_info);
465 
466  switch (result) {
467  case vk::Result::eErrorOutOfDateKHR:
468  // Caller will recreate the impl on acquisition, not submission.
469  [[fallthrough]];
470  case vk::Result::eErrorSurfaceLostKHR:
471  // Vulkan guarantees that the set of queue operations will still
472  // complete successfully.
473  [[fallthrough]];
474  case vk::Result::eSuboptimalKHR:
475  // Even though we're handling rotation changes via polling, we
476  // still need to handle the case where the swapchain signals that
477  // it's suboptimal (i.e. every frame when we are rotated given we
478  // aren't doing Vulkan pre-rotation).
479  [[fallthrough]];
480  case vk::Result::eSuccess:
481  break;
482  default:
483  VALIDATION_LOG << "Could not present queue: " << vk::to_string(result);
484  break;
485  }
486 
487  return true;
488 }
489 
490 } // namespace impeller
static ContextVK & Cast(Context &base)
Definition: backend_cast.h:13
vk::CommandBuffer GetCommandBuffer() const
Retrieve the native command buffer from this object.
bool SetDebugName(T handle, std::string_view label) const
Definition: context_vk.h:150
const vk::Device & GetDevice() const
Definition: context_vk.cc:587
An instance of a swapchain that does NOT adapt to going out of date with the underlying surface....
std::shared_ptr< Context > GetContext() const
void AddFinalCommandBuffer(std::shared_ptr< CommandBuffer > cmd_buffer)
static std::shared_ptr< KHRSwapchainImplVK > Create(const std::shared_ptr< Context > &context, vk::UniqueSurfaceKHR surface, const ISize &size, bool enable_msaa=true, vk::SwapchainKHR old_swapchain=VK_NULL_HANDLE)
std::pair< vk::UniqueSurfaceKHR, vk::UniqueSwapchainKHR > DestroySwapchain()
static std::unique_ptr< SurfaceVK > WrapSwapchainImage(const std::shared_ptr< SwapchainTransientsVK > &transients, const std::shared_ptr< TextureSourceVK > &swapchain_image, SwapCallback swap_callback)
Wrap the swapchain image in a Surface, which provides the additional configuration required for usage...
Definition: surface_vk.cc:13
static std::optional< vk::SurfaceFormatKHR > ChooseSurfaceFormat(const std::vector< vk::SurfaceFormatKHR > &formats, PixelFormat preference)
static constexpr size_t kMaxFramesInFlight
static bool ContainsFormat(const std::vector< vk::SurfaceFormatKHR > &formats, vk::SurfaceFormatKHR format)
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99
constexpr vk::Format ToVKImageFormat(PixelFormat format)
Definition: formats_vk.h:146
static std::optional< vk::CompositeAlphaFlagBitsKHR > ChooseAlphaCompositionMode(vk::CompositeAlphaFlagsKHR flags)
static PixelFormat ToPixelFormat(AHardwareBuffer_Format format)
bool WaitForFence(const vk::Device &device)
KHRFrameSynchronizerVK(const vk::Device &device)
std::shared_ptr< CommandBuffer > final_cmd_buffer
Type height
Definition: size.h:29
Type width
Definition: size.h:28
static constexpr TSize MakeWH(Type width, Type height)
Definition: size.h:43
#define VALIDATION_LOG
Definition: validation.h:91