upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_present.h
diff options
context:
space:
mode:
authorAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 21:03:29 +0100
committerAlxcBTW <187763517+AlxcBTW@users.noreply.github.com>2026-11-22 21:03:29 +0100
commit5efe4afddd0f3da687835027e69f0e6983a7d283 (patch)
tree9eb48efe56fe8c4b3b20684238c2faba00b9dc7b /runtime/src/vulkan_present.h
parentf8007dda67f9c45757b63df5c5fd8377647da4ae (diff)
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
Merge origin/main into queue-wait-before-signal
Diffstat (limited to 'runtime/src/vulkan_present.h')
-rw-r--r--runtime/src/vulkan_present.h311
1 files changed, 296 insertions, 15 deletions
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 0bda6f853..2a2845fb2 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -15,12 +15,18 @@
15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every 15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every
16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory. 16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory.
17// 17//
18// Plane composition (PresentX with placement, a filter, HDR10 or a second plane): present_planes() runs a compute pass
19// (present_compose.comp, vulkan_present_compose.h) over up to two textures into an RGBA16F image and copies that to the
20// swapchain; with an HDR10 plane and a surface that lists an ST.2084 format the swapchain is created in it. The plain
21// blit above is unchanged.
22//
18// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original) 23// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original)
19// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE), 24// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE),
20// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a 25// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a
21// request is ignored and the frame waits for the vblank. 26// request is ignored and the frame waits for the vblank.
22 27
23#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h"
24 30
25// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
26#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -29,12 +35,14 @@
29 35
30#include <algorithm> 36#include <algorithm>
31#include <array> 37#include <array>
38#include <cmath>
32#include <cstdint> 39#include <cstdint>
33#include <cstdio> 40#include <cstdio>
34#include <cstring> 41#include <cstring>
35#include <functional> 42#include <functional>
36#include <map> 43#include <map>
37#include <deque> 44#include <deque>
45#include <memory>
38#include <mutex> 46#include <mutex>
39#include <vector> 47#include <vector>
40 48
@@ -45,6 +53,22 @@ struct PresentRect {
45 std::int32_t left, top, right, bottom; 53 std::int32_t left, top, right, bottom;
46}; 54};
47 55
56// One plane of present_planes(): a colour texture, the part of it shown, and where in the output it goes.
57struct PresentPlane {
58 ResourceId source{};
59 PresentRect source_rect{}; // texels; used when has_source_rect
60 bool has_source_rect = false;
61 float dest[4] = {0, 0, 1, 1}; // left, top, right, bottom as fractions of the output (0..1)
62 bool point_filter = false; // nearest texel; otherwise bilinear inside the source rectangle
63 bool hdr10 = false; // the texture holds ST.2084 (PQ) Rec.2020 values; otherwise G2.2 Rec.709 ones
64 bool straight_alpha = false; // plane 1 only: alpha is not premultiplied into the colour
65};
66struct PresentPlanes {
67 PresentPlane plane[2];
68 std::uint32_t count = 1;
69 float sdr_white_nits = 203.0f; // what SDR white maps to in an HDR10 output, and what HDR10 is divided by for SDR
70};
71
48namespace detail { 72namespace detail {
49inline bool is_srgb_format(VkFormat format) { 73inline bool is_srgb_format(VkFormat format) {
50 switch (format) { 74 switch (format) {
@@ -143,7 +167,9 @@ public:
143 release(swapchain_); 167 release(swapchain_);
144 swapchain_ = VK_NULL_HANDLE; 168 swapchain_ = VK_NULL_HANDLE;
145 release_capture(); 169 release_capture();
170 composer_.reset();
146 for (Frame& frame : frames_) { 171 for (Frame& frame : frames_) {
172 drop_views(frame);
147 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 173 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
148 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 174 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
149 } 175 }
@@ -203,6 +229,47 @@ public:
203 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear); 229 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear);
204 } 230 }
205 231
232 // PresentX with planes (docs section 4.5): one or two textures, each scaled from its source rectangle to its
233 // destination rectangle of the window, plane 1 blended over plane 0, composed by a compute pass into an RGBA16F image
234 // that is then copied to the swapchain image. Colour spaces are converted to the swapchain's: when a plane is HDR10 and
235 // the surface lists an HDR10 (ST.2084) format the swapchain uses it (hdr_active()), else the HDR10 planes are
236 // converted to SDR by clipping (no tone mapping). The swapchain is always UNORM here; sRGB-format sources are
237 // encoded again by the pass. Sources must be single-sample, sampled (no DENY_SHADER_RESOURCE) float/UNORM/sRGB
238 // colour textures; others are refused (VK_ERROR_FORMAT_NOT_SUPPORTED). Rectangles outside their range give
239 // VK_ERROR_UNKNOWN. vsync and `tear` as for present().
240 VkResult present_planes(const PresentPlanes& planes, bool vsync, bool tear = false) {
241 if (planes.count < 1 || planes.count > 2) return VK_ERROR_UNKNOWN;
242 if (!(planes.sdr_white_nits > 0.0f) || !std::isfinite(planes.sdr_white_nits)) return VK_ERROR_UNKNOWN;
243 for (std::uint32_t i = 0; i < planes.count; ++i) {
244 const PresentPlane& plane = planes.plane[i];
245 ResourceBinding binding;
246 {
247 std::shared_lock lock(context_.resource_mutex_);
248 const ResourceBinding* found = context_.resolve(plane.source);
249 if (!found || !found->image) return VK_ERROR_UNKNOWN;
250 binding = *found;
251 }
252 if (binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT || binding.samples > 1 || !binding.sampled || detail::blit_unsupported_format(binding.format) ||
253 !(format_features(binding.format) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
254 return VK_ERROR_FORMAT_NOT_SUPPORTED;
255 const PresentRect& r = plane.source_rect;
256 if (plane.has_source_rect && (r.left < 0 || r.top < 0 || r.left >= r.right || r.top >= r.bottom ||
257 std::uint32_t(r.right) > binding.width || std::uint32_t(r.bottom) > binding.height))
258 return VK_ERROR_UNKNOWN;
259 const float* d = plane.dest;
260 if (!(d[0] >= 0.0f && d[0] < d[2] && d[2] <= 1.0f && d[1] >= 0.0f && d[1] < d[3] && d[3] <= 1.0f))
261 return VK_ERROR_UNKNOWN; // (also false for NaN)
262 }
263 return submit(nullptr, ResourceId{}, vsync, nullptr, false, tear, &planes);
264 }
265 // The swapchain holds HDR10 (ST.2084) values: a plane asked for it and the surface has the format.
266 bool hdr_active() const { return hdr_active_; }
267 // Presents that went through the compose pass (present_planes); plain blits and blank frames are not counted.
268 std::uint64_t composed_presents() const { return composed_; }
269 // Tests, on surfaces without HDR10: compose as if the output were HDR10 but write the PQ values into the (8-bit,
270 // UNORM) swapchain, so the encoder can be checked on any GPU. Takes effect with the next present_planes().
271 void force_hdr_encoding(bool on) { force_hdr_encoding_ = on; }
272
206 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with 273 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with
207 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. 274 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames.
208 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); } 275 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); }
@@ -219,7 +286,7 @@ public:
219 if (!ok_) return false; 286 if (!ok_) return false;
220 capture_ = true; 287 capture_ = true;
221 stale_ = true; 288 stale_ = true;
222 if (!recreate(vsync_, swapchain_srgb_) || (swapchain_ && !capture_buffer_)) { 289 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
223 capture_ = false; 290 capture_ = false;
224 return false; 291 return false;
225 } 292 }
@@ -239,7 +306,8 @@ public:
239 return true; 306 return true;
240 } 307 }
241 308
242 // Shared by present() and present_blank(). `binding` null: clear instead of blit. 309<<<<<<< HEAD
310 // Shared by present(), present_blank() and present_planes().
243 // 311 //
244 // A Present is ordered behind the work the queues hold (a batch that waits for a Signal not yet submitted, 312 // A Present is ordered behind the work the queues hold (a batch that waits for a Signal not yet submitted,
245 // queue_holds.h): it would otherwise blit whatever the source texture held before that batch ran. It is not 313 // queue_holds.h): it would otherwise blit whatever the source texture held before that batch ran. It is not
@@ -250,12 +318,16 @@ public:
250 // is only ordered behind earlier presents. Waiting instead was rejected: the Signal that releases the work may 318 // is only ordered behind earlier presents. Waiting instead was rejected: the Signal that releases the work may
251 // be one the application's own thread makes after Present returns. 319 // be one the application's own thread makes after Present returns.
252 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 320 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
253 bool srgb, bool tear = false) { 321 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
254 std::lock_guard lock(present_mutex_); 322 std::lock_guard lock(present_mutex_);
255 if (deferred_.empty() && !(binding && context_.holds().any_held())) 323 // `binding` null and `planes` null: clear instead of blit; `planes`: compose them (`binding`, `source`,
256 return submit_now(binding, source, vsync, source_rect, srgb, tear); 324 // `source_rect` unused). Only a present that reads a texture waits for held work.
257 PendingPresent pending{binding != nullptr, source, vsync, source_rect != nullptr, {}, srgb, tear}; 325 if (deferred_.empty() && !((binding || planes) && context_.holds().any_held()))
326 return submit_now(binding, source, vsync, source_rect, srgb, tear, planes);
327 PendingPresent pending{binding != nullptr, source, vsync, source_rect != nullptr, {}, srgb, tear,
328 planes != nullptr, {}};
258 if (source_rect) pending.rect = *source_rect; 329 if (source_rect) pending.rect = *source_rect;
330 if (planes) pending.planes = *planes;
259 deferred_.push_back(pending); 331 deferred_.push_back(pending);
260 context_.holds().after_held(this, [this] { run_deferred(); }); 332 context_.holds().after_held(this, [this] { run_deferred(); });
261 return VK_SUCCESS; 333 return VK_SUCCESS;
@@ -270,6 +342,8 @@ private:
270 PresentRect rect; 342 PresentRect rect;
271 bool srgb; 343 bool srgb;
272 bool tear; 344 bool tear;
345 bool has_planes;
346 PresentPlanes planes;
273 }; 347 };
274 348
275 void run_deferred() { 349 void run_deferred() {
@@ -279,27 +353,37 @@ private:
279 deferred_.pop_front(); 353 deferred_.pop_front();
280 ResourceBinding binding{}; 354 ResourceBinding binding{};
281 const VkResult result = submit_now(p.has_source ? &binding : nullptr, p.source, p.vsync, 355 const VkResult result = submit_now(p.has_source ? &binding : nullptr, p.source, p.vsync,
282 p.has_rect ? &p.rect : nullptr, p.srgb, p.tear); 356 p.has_rect ? &p.rect : nullptr, p.srgb, p.tear,
357 p.has_planes ? &p.planes : nullptr);
283 if (result != VK_SUCCESS) 358 if (result != VK_SUCCESS)
284 std::fprintf(stderr, "[rt] d3d12: a Present held behind queued work failed when it was released (%d)\n", 359 std::fprintf(stderr, "[rt] d3d12: a Present held behind queued work failed when it was released (%d)\n",
285 int(result)); 360 int(result));
286 } 361 }
287 362
288 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 363 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
289 bool srgb, bool tear = false) { 364 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
290 last_tore_ = false; 365 last_tore_ = false;
291 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 366 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
292 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_) { 367 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
368 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one.
369 bool want_hdr = swapchain_hdr_req_;
370 if (planes)
371 want_hdr = (planes->plane[0].hdr10) || (planes->count > 1 && planes->plane[1].hdr10);
372 else if (binding)
373 want_hdr = false;
374 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
293 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 375 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
294 // recreate is tried again at the next present. 376 // recreate is tried again at the next present.
295 if (!recreate(vsync, srgb)) return VK_ERROR_OUT_OF_DATE_KHR; 377 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
296 } 378 }
297 if (!swapchain_) { // minimised: try again next frame 379 if (!swapchain_) { // minimised: try again next frame
298 stale_ = true; 380 stale_ = true;
299 return VK_SUCCESS; 381 return VK_SUCCESS;
300 } 382 }
301 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 383 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
302 if (binding && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) return VK_ERROR_FORMAT_NOT_SUPPORTED; 384 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT))
385 return VK_ERROR_FORMAT_NOT_SUPPORTED;
386 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED;
303 auto& vk = context_.vk; 387 auto& vk = context_.vk;
304 const VkDevice device = context_.device(); 388 const VkDevice device = context_.device();
305 Frame& frame = frames_[frame_index_ % frames_.size()]; 389 Frame& frame = frames_[frame_index_ % frames_.size()];
@@ -309,18 +393,43 @@ private:
309 std::uint32_t image = 0; 393 std::uint32_t image = 0;
310 VkResult acquired = acquire(frame.acquired, &image); 394 VkResult acquired = acquire(frame.acquired, &image);
311 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 395 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
312 if (!recreate(vsync, swapchain_srgb_)) return acquired; 396 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
313 if (!swapchain_) return VK_SUCCESS; 397 if (!swapchain_) return VK_SUCCESS;
314 acquired = acquire(frame.acquired, &image); 398 acquired = acquire(frame.acquired, &image);
315 } 399 }
316 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 400 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
317 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; 401 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true;
402 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
403 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED);
318 404
319 bool recorded = false; 405 bool recorded = false;
320 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 406 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
321 bool rollback_source = false; 407 bool rollback_source = false;
322 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED; 408 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
323 if (binding) { 409 std::array<RollbackPlane, 2> plane_rollbacks{}; // present_planes(): the same, per plane
410 if (planes) {
411 std::array<ResourceBinding, 2> current{};
412 bool found_all = true;
413 {
414 std::shared_lock resource_lock(context_.resource_mutex_);
415 for (std::uint32_t i = 0; i < planes->count; ++i) {
416 const ResourceBinding* found = context_.resolve(planes->plane[i].source);
417 if (found && found->image && found->aspects == VK_IMAGE_ASPECT_COLOR_BIT && found->sampled)
418 current[i] = *found;
419 else
420 found_all = false;
421 }
422 if (found_all) {
423 tracker_lock.lock();
424 for (std::uint32_t i = 0; i < planes->count; ++i) {
425 plane_rollbacks[i].id = planes->plane[i].source;
426 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id);
427 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0);
428 }
429 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image);
430 }
431 }
432 } else if (binding) {
324 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 433 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
325 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout 434 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
326 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map. 435 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
@@ -340,6 +449,11 @@ private:
340 const auto rollback = [&] { 449 const auto rollback = [&] {
341 if (rollback_source) 450 if (rollback_source)
342 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout); 451 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
452 if (planes)
453 for (std::uint32_t i = 0; i < planes->count; ++i)
454 if (plane_rollbacks[i].tracked)
455 context_.tracker_.set(plane_rollbacks[i].id, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
456 plane_rollbacks[i].layout);
343 }; 457 };
344 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 458 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
345 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 459 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
@@ -390,6 +504,7 @@ private:
390 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 504 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
391 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 505 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
392 ++presented_; 506 ++presented_;
507 if (planes) ++composed_;
393 if (tearing) { 508 if (tearing) {
394 last_tore_ = true; 509 last_tore_ = true;
395 ++tear_presents_; 510 ++tear_presents_;
@@ -412,6 +527,7 @@ private:
412 VkCommandBuffer commands = VK_NULL_HANDLE; 527 VkCommandBuffer commands = VK_NULL_HANDLE;
413 VkFence done = VK_NULL_HANDLE; 528 VkFence done = VK_NULL_HANDLE;
414 VkSemaphore acquired = VK_NULL_HANDLE; 529 VkSemaphore acquired = VK_NULL_HANDLE;
530 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
415 }; 531 };
416 532
417 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 533 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
@@ -510,6 +626,139 @@ private:
510 vk.vkEndCommandBuffer(commands); 626 vk.vkEndCommandBuffer(commands);
511 } 627 }
512 628
629 struct RollbackPlane {
630 ResourceId id{};
631 bool tracked = false;
632 VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
633 };
634
635 void drop_views(Frame& frame) {
636 for (VkImageView& view : frame.views)
637 if (view) context_.vk.vkDestroyImageView(context_.device(), view, nullptr);
638 frame.views = {};
639 }
640
641 // The compose pass and its target image, for the swapchain's current size.
642 bool prepare_compose() {
643 if (!composer_) {
644 VkPhysicalDeviceMemoryProperties memory{};
645 if (!vkGetPhysicalDeviceMemoryProperties_) return false;
646 vkGetPhysicalDeviceMemoryProperties_(physical_, &memory);
647 composer_ = std::make_unique<PresentComposer>(context_, memory);
648 }
649 if (!composer_->ready()) return false;
650 if (composer_->target() && composer_->extent().width == extent_.width &&
651 composer_->extent().height == extent_.height)
652 return true;
653 {
654 std::lock_guard lock(context_.submit_mutex());
655 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use
656 }
657 bool changed = false;
658 return composer_->ensure_target(extent_, changed);
659 }
660
661 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the
662 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks.
663 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current,
664 const PresentPlanes& planes, std::uint32_t image) {
665 auto& vk = context_.vk;
666 const ReplayFunctions& fn = context_.replay_;
667 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width ||
668 composer_->extent().height != extent_.height)
669 return false; // the target does not match the swapchain: nothing recorded
670 drop_views(frame);
671 for (std::uint32_t i = 0; i < planes.count; ++i) {
672 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
673 view_info.image = current[i].image;
674 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
675 view_info.format = current[i].format;
676 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
677 if (vk.vkCreateImageView(context_.device(), &view_info, nullptr, &frame.views[i]) != VK_SUCCESS) {
678 drop_views(frame);
679 return false;
680 }
681 }
682 if (planes.count == 1) frame.views[1] = VK_NULL_HANDLE; // the shader never reads it; plane 0's view is bound twice
683
684 VkCommandBuffer commands = frame.commands;
685 vk.vkResetCommandBuffer(commands, 0);
686 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
687 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
688 vk.vkBeginCommandBuffer(commands, &begin);
689
690 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
691 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
692 const bool same = planes.count > 1 && planes.plane[1].source == planes.plane[0].source;
693 std::array<LayoutPieces, 2> pieces;
694 std::array<VkImageLayout, 2> read_layout{};
695 // Each distinct source: its PRESENT (common) layout, then readable by the compute pass. A never-written back buffer
696 // is zero-filled first, as any committed resource is.
697 for (std::uint32_t i = 0; i < planes.count; ++i) {
698 read_layout[i] = image_layout(current[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
699 if (i == 1 && same) continue;
700 const VkImageLayout common = image_layout(current[i], VK_IMAGE_LAYOUT_GENERAL);
701 pieces[i] = detail::current(&context_.tracker_, planes.plane[i].source, range, common);
702 detail::initialize(fn, commands, current[i], planes.plane[i].source, pieces[i], common, &context_.tracker_);
703 for (const auto& piece : pieces[i])
704 detail::image_barrier(fn, commands, current[i], piece.range, piece.layout, read_layout[i],
705 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
706 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
707 }
708
709 // The pass: destinations in output pixels, sources in texels.
710 PresentComposePush push{};
711 const float out_w = float(extent_.width), out_h = float(extent_.height);
712 std::uint32_t* flags[2] = {&push.flags0, &push.flags1};
713 float* dest[2] = {push.dest0, push.dest1};
714 float* src[2] = {push.src0, push.src1};
715 for (std::uint32_t i = 0; i < planes.count; ++i) {
716 const PresentPlane& plane = planes.plane[i];
717 dest[i][0] = plane.dest[0] * out_w;
718 dest[i][1] = plane.dest[1] * out_h;
719 dest[i][2] = plane.dest[2] * out_w;
720 dest[i][3] = plane.dest[3] * out_h;
721 const PresentRect whole{0, 0, std::int32_t(current[i].width), std::int32_t(current[i].height)};
722 const PresentRect& r = plane.has_source_rect ? plane.source_rect : whole;
723 src[i][0] = float(r.left);
724 src[i][1] = float(r.top);
725 src[i][2] = float(r.right);
726 src[i][3] = float(r.bottom);
727 *flags[i] = (plane.point_filter ? compose_flag::point : 0u) |
728 (detail::is_srgb_format(current[i].format) ? compose_flag::srgb_source : 0u) |
729 (plane.hdr10 ? compose_flag::hdr10 : 0u) | (plane.straight_alpha ? compose_flag::straight_alpha : 0u);
730 }
731 push.plane_count = planes.count;
732 push.out_hdr = (hdr_active_ || force_hdr_encoding_) ? 1u : 0u;
733 push.sdr_white = planes.sdr_white_nits;
734 push.width = extent_.width;
735 push.height = extent_.height;
736 composer_->record(commands, slot, frame.views[0], read_layout[0], frame.views[1] ? frame.views[1] : frame.views[0],
737 read_layout[1] ? read_layout[1] : read_layout[0], push);
738
739 // The swapchain image, written by a copy of the composed image (same size: no scaling).
740 ResourceBinding target = target_of(image);
741 detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0,
742 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
743 VkImageBlit blit{};
744 blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
745 blit.srcOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
746 blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
747 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
748 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image],
749 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
750 finish_image(commands, image);
751 for (std::uint32_t i = 0; i < planes.count; ++i) {
752 if (i == 1 && same) continue;
753 for (const auto& piece : pieces[i])
754 detail::image_barrier(fn, commands, current[i], piece.range, read_layout[i], piece.layout,
755 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, any,
756 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
757 }
758 vk.vkEndCommandBuffer(commands);
759 return true;
760 }
761
513 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format. 762 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format.
514 VkFormatFeatureFlags format_features(VkFormat format) { 763 VkFormatFeatureFlags format_features(VkFormat format) {
515 const auto it = features_.find(format); 764 const auto it = features_.find(format);
@@ -643,7 +892,7 @@ private:
643 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no 892 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no
644 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and 893 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and
645 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. 894 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again.
646 bool recreate(bool vsync, bool srgb) { 895 bool recreate(bool vsync, bool srgb, bool hdr = false) {
647 auto& vk = context_.vk; 896 auto& vk = context_.vk;
648 const VkDevice device = context_.device(); 897 const VkDevice device = context_.device();
649 { 898 {
@@ -673,6 +922,8 @@ private:
673 swapchain_ = VK_NULL_HANDLE; 922 swapchain_ = VK_NULL_HANDLE;
674 vsync_ = vsync; 923 vsync_ = vsync;
675 swapchain_srgb_ = srgb; 924 swapchain_srgb_ = srgb;
925 swapchain_hdr_req_ = hdr;
926 hdr_active_ = false;
676 stale_ = false; 927 stale_ = false;
677 return true; 928 return true;
678 } 929 }
@@ -691,8 +942,28 @@ private:
691 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them. 942 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them.
692 VkSurfaceFormatKHR chosen = formats[0]; 943 VkSurfaceFormatKHR chosen = formats[0];
693 bool found = false; 944 bool found = false;
945 bool chose_hdr = false;
946 if (hdr) {
947 // A plane in HDR10 (PQ, Rec.2020): the surface's ST.2084 format, which needs VK_EXT_swapchain_colorspace on
948 // the instance. Without it the composition converts to SDR.
949 for (const VkFormat wanted : {VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32}) {
950 for (const auto& f : formats)
951 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) {
952 chosen = f;
953 found = chose_hdr = true;
954 break;
955 }
956 if (found) break;
957 }
958 if (!found && !warned_hdr_) {
959 warned_hdr_ = true;
960 std::fprintf(stderr, "[rt] present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to "
961 "SDR by clipping\n");
962 }
963 }
694 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} 964 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB}
695 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) { 965 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) {
966 if (chose_hdr) break;
696 for (const auto& f : formats) 967 for (const auto& f : formats)
697 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { 968 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
698 chosen = f; 969 chosen = f;
@@ -787,14 +1058,18 @@ private:
787 ready_ = std::move(ready); 1058 ready_ = std::move(ready);
788 format_ = chosen.format; 1059 format_ = chosen.format;
789 extent_ = extent; 1060 extent_ = extent;
1061 hdr_active_ = chose_hdr;
790 if (capture_) { 1062 if (capture_) {
791 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1063 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
792 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1064 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
793 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB; 1065 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB ||
1066 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 ||
1067 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
794 if (!four_bytes || !make_capture_buffer()) return false; 1068 if (!four_bytes || !make_capture_buffer()) return false;
795 } 1069 }
796 vsync_ = vsync; 1070 vsync_ = vsync;
797 swapchain_srgb_ = srgb; 1071 swapchain_srgb_ = srgb;
1072 swapchain_hdr_req_ = hdr;
798 stale_ = false; 1073 stale_ = false;
799 return true; 1074 return true;
800 } 1075 }
@@ -886,6 +1161,12 @@ private:
886 bool stale_ = false; 1161 bool stale_ = false;
887 bool ok_ = false; 1162 bool ok_ = false;
888 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 1163 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
1164 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_)
1165 bool hdr_active_ = false;
1166 std::uint64_t composed_ = 0;
1167 bool force_hdr_encoding_ = false;
1168 bool warned_hdr_ = false;
1169 std::unique_ptr<PresentComposer> composer_;
889 std::function<bool()> abort_; 1170 std::function<bool()> abort_;
890 std::function<VkExtent2D()> extent_fn_; 1171 std::function<VkExtent2D()> extent_fn_;
891 std::map<VkFormat, VkFormatFeatureFlags> features_; 1172 std::map<VkFormat, VkFormatFeatureFlags> features_;