upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorMumogg <104529023+Mumogg@users.noreply.github.com>2026-11-23 16:11:49 -0600
committerMumogg <104529023+Mumogg@users.noreply.github.com>2026-11-23 16:11:49 -0600
commit0c7ec65c0e0d1890139eda86cc92fc4f0ed830e6 (patch)
treef27b75b09e1a4de109ce36b4b9aebb0bef353a97 /runtime/src
parentc9ea50842077678228204a2be52314c4065f87d7 (diff)
local: apply #9419 (present dump) as a patch
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/present_dump.h256
-rw-r--r--runtime/src/vulkan_present.h40
2 files changed, 285 insertions, 11 deletions
diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h
new file mode 100644
index 000000000..2e594fcb5
--- /dev/null
+++ b/runtime/src/present_dump.h
@@ -0,0 +1,256 @@
1#pragma once
2
3// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals.
4#include <vulkan/vulkan.h>
5
6#include <algorithm>
7#include <array>
8#include <atomic>
9#include <charconv>
10#include <cmath>
11#include <cstdint>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <filesystem>
16#include <memory>
17#include <mutex>
18#include <span>
19#include <string>
20#include <thread>
21#include <vector>
22
23namespace leonida::present_dump {
24
25inline unsigned texel_size(VkFormat format) {
26 switch (format) {
27 case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB:
28 case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB:
29 case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4;
30 case VK_FORMAT_R16G16B16A16_SFLOAT: return 8;
31 case VK_FORMAT_R32G32B32A32_SFLOAT: return 16;
32 default: return 0;
33 }
34}
35
36inline std::uint8_t unorm8(float v) {
37 return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0;
38}
39
40inline std::uint8_t half_unorm8(std::uint16_t bits) {
41 const int exponent = bits >> 10;
42 const int fraction = bits & 1023;
43 if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0;
44 return unorm8(std::ldexp(float(1024 + fraction), exponent - 25));
45}
46
47inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) {
48 if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) {
49 std::memcpy(dst, src, size_t(width) * 4);
50 return;
51 }
52 const unsigned stride = texel_size(format);
53 for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) {
54 if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) {
55 dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3];
56 } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) {
57 std::uint16_t v[4];
58 std::memcpy(v, src, sizeof(v));
59 std::transform(v, v + 4, dst, half_unorm8);
60 } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) {
61 float v[4];
62 std::memcpy(v, src, sizeof(v));
63 std::transform(v, v + 4, dst, unorm8);
64 } else {
65 // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR.
66 // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits.
67 static const auto pq_to_sdr = [] {
68 std::array<std::uint8_t, 1024> table{};
69 for (unsigned i = 0; i < table.size(); ++i) {
70 const double p = std::pow(i / 1023.0, 1.0 / 78.84375);
71 const double linear = (10000.0 / 203.0) *
72 std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125);
73 const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055;
74 table[i] = unorm8(float(srgb));
75 }
76 return table;
77 }();
78 std::uint32_t packed;
79 std::memcpy(&packed, src, sizeof(packed));
80 for (unsigned channel = 0; channel < 3; ++channel) {
81 const unsigned bits = (packed >> (10 * channel)) & 1023;
82 dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023);
83 }
84 if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]);
85 dst[3] = std::uint8_t((packed >> 30) * 85);
86 }
87 }
88}
89
90inline std::array<std::uint8_t, 4> big_endian(std::uint32_t n) {
91 return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)};
92}
93
94inline bool chunk(std::FILE* file, const char (&type)[5], std::span<const std::uint8_t> data,
95 std::span<const std::uint8_t> prefix = {}) {
96 static constexpr auto crc_table = [] {
97 std::array<std::uint32_t, 256> table{};
98 for (unsigned i = 0; i < table.size(); ++i) {
99 unsigned c = i;
100 for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0);
101 table[i] = c;
102 }
103 return table;
104 }();
105 std::uint32_t crc = ~0u;
106 const auto write = [&](std::span<const std::uint8_t> bytes) {
107 for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8);
108 return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
109 };
110 return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 &&
111 write({reinterpret_cast<const std::uint8_t*>(type), 4}) && write(prefix) && write(data) &&
112 std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4;
113}
114
115inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) {
116 constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10};
117 std::array<std::uint8_t, 13> ihdr{};
118 const auto w = big_endian(extent.width), h = big_endian(extent.height);
119 std::copy(w.begin(), w.end(), ihdr.begin());
120 std::copy(h.begin(), h.end(), ihdr.begin() + 4);
121 ihdr[8] = 8;
122 ihdr[9] = 6; // 8-bit RGBA
123 constexpr std::uint8_t zlib_header[]{0x78, 0x01};
124 if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) ||
125 !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false;
126
127 // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies
128 // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement).
129 std::vector<std::uint8_t> row(1 + size_t(extent.width) * 4);
130 std::uint32_t a = 1, b = 0;
131 for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) {
132 rgba_row(row.data() + 1, src, extent.width, format, pq);
133 std::span<const std::uint8_t> rest(row);
134 while (!rest.empty()) {
135 auto block = rest.first(std::min<size_t>(rest.size(), 65535));
136 rest = rest.subspan(block.size());
137 const auto len = std::uint16_t(block.size());
138 const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()),
139 std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)};
140 for (auto byte : block) {
141 a = (a + byte) % 65521;
142 b = (b + a) % 65521;
143 }
144 if (!chunk(file, "IDAT", block, header)) return false;
145 }
146 }
147 return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {});
148}
149
150class PresentDump {
151public:
152 PresentDump() {
153#ifdef _WIN32
154 wchar_t* env = nullptr;
155 size_t length = 0;
156 if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) {
157 bad_value();
158 return;
159 }
160 const std::unique_ptr<wchar_t, decltype(&std::free)> owned(env, &std::free);
161#else
162 const auto* env = std::getenv("LEONIDA_PRESENT_DUMP");
163#endif
164 if (!env) return;
165 try {
166 auto value = std::filesystem::path(env).native();
167 std::uint64_t interval = 60;
168 const auto comma = value.rfind(',');
169 if (comma != value.npos) {
170 const auto n = std::filesystem::path(value.substr(comma + 1)).string();
171 const auto end = n.data() + n.size();
172 const auto parsed = std::from_chars(n.data(), end, interval);
173 if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) {
174 bad_value();
175 return;
176 }
177 value.resize(comma);
178 }
179 if (value.empty()) {
180 bad_value();
181 return;
182 }
183 dir_ = std::filesystem::absolute(value);
184 std::filesystem::create_directories(dir_);
185 interval_ = interval;
186 } catch (const std::exception&) { bad_value(); }
187 }
188
189 bool enabled() const { return interval_ != 0; }
190 bool due(std::uint64_t frames_shown) const {
191 const auto n = interval_.load();
192 return n && frames_shown % n == 0;
193 }
194 void disable(const char* why) {
195 if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why);
196 }
197 void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) {
198 try {
199 // Bound memory to one outstanding write even at N=1. Teardown joins the final writer.
200 if (writer_.joinable()) writer_.join();
201 if (!enabled()) return;
202 char name[48];
203 std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast<unsigned long long>(frame));
204 writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name,
205 bytes = std::vector<std::uint8_t>(src, src + size)] {
206 try {
207 if (publish(path, extent, format, pq, bytes.data())) {
208 const auto utf8 = path.u8string();
209 std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n",
210 static_cast<unsigned long long>(frame), reinterpret_cast<const char*>(utf8.c_str()));
211 return;
212 }
213 } catch (const std::exception&) {}
214 disable("could not write the present dump");
215 });
216 } catch (const std::exception&) { disable("could not queue the present dump"); }
217 }
218
219private:
220 static void bad_value() {
221 static std::once_flag once;
222 std::call_once(once, [] {
223 std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n");
224 });
225 }
226 static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq,
227 const std::uint8_t* src) {
228 // Never open an existing output for writing: it could be a link to a file outside the dump directory.
229 // Build a complete sibling exclusively, then replace the directory entry in a single rename.
230 auto tmp = path;
231 tmp += ".tmp";
232#ifdef _WIN32
233 std::FILE* file = nullptr;
234 _wfopen_s(&file, tmp.c_str(), L"wbx");
235#else
236 auto* file = std::fopen(tmp.c_str(), "wbx");
237#endif
238 if (!file) return false;
239 bool ok = false;
240 try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {}
241 if (std::fclose(file) != 0) ok = false;
242 std::error_code ec;
243 if (ok) {
244 std::filesystem::rename(tmp, path, ec);
245 if (!ec) return true;
246 }
247 std::filesystem::remove(tmp, ec);
248 return false;
249 }
250
251 std::filesystem::path dir_;
252 std::atomic<std::uint64_t> interval_{0};
253 std::jthread writer_; // joined before the state it uses is destroyed
254};
255
256} // namespace leonida::present_dump
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 8644346c5..2ce6f457b 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -27,6 +27,7 @@
27 27
28#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h" 29#include "vulkan_present_compose.h"
30#include "present_dump.h"
30 31
31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 32// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 33#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -583,7 +584,15 @@ private:
583 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain 584 // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain
584 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 585 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
585 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 586 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
586 ++presented_; 587 const auto shown = ++presented_;
588 if (dump_.due(shown - 1)) {
589 // Presentation is already queued and the queue/tracker locks are released. A sampled frame
590 // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker.
591 if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS)
592 dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_));
593 else
594 dump_.disable("present dump fence wait failed");
595 }
587 if (planes) ++composed_; 596 if (planes) ++composed_;
588 if (tearing) { 597 if (tearing) {
589 last_tore_ = true; 598 last_tore_ = true;
@@ -915,7 +924,7 @@ private:
915 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 924 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
916 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; 925 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
917 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; 926 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT;
918 if (capture_ && capture_buffer_) { 927 if (capture_buffer_ && (capture_ || dump_.due(presented_))) {
919 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy 928 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy
920 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. 929 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC.
921 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; 930 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
@@ -942,6 +951,10 @@ private:
942 copy.imageExtent = {extent_.width, extent_.height, 1}; 951 copy.imageExtent = {extent_.width, extent_.height, 1};
943 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, 952 fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1,
944 &copy); 953 &copy);
954 auto to_host = capture_waw;
955 to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
956 fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
957 0, nullptr, 1, &to_host, 0, nullptr);
945 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 958 layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
946 access = VK_ACCESS_TRANSFER_READ_BIT; 959 access = VK_ACCESS_TRANSFER_READ_BIT;
947 } 960 }
@@ -954,7 +967,7 @@ private:
954 release_capture(); 967 release_capture();
955 auto& vk = context_.vk; 968 auto& vk = context_.vk;
956 const VkDevice device = context_.device(); 969 const VkDevice device = context_.device();
957 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; 970 capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_);
958 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 971 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
959 info.size = capture_size_; 972 info.size = capture_size_;
960 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; 973 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
@@ -1039,7 +1052,9 @@ private:
1039 return true; 1052 return true;
1040 } 1053 }
1041 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; 1054 VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1042 if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; 1055 if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT))
1056 dump_.disable("surface does not support swapchain readback");
1057 if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
1043 if ((caps.supportedUsageFlags & usage) != usage) return false; 1058 if ((caps.supportedUsageFlags & usage) != usage) return false;
1044 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain 1059 // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain
1045 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it 1060 // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it
@@ -1183,13 +1198,14 @@ private:
1183 extent_ = extent; 1198 extent_ = extent;
1184 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; 1199 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height;
1185 hdr_active_ = chose_hdr; 1200 hdr_active_ = chose_hdr;
1186 if (capture_) { 1201 dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT;
1187 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1202 if (capture_ || dump_.enabled()) {
1188 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1203 const auto stride = present_dump::texel_size(format_);
1189 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || 1204 if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel
1190 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || 1205 if (!stride || !make_capture_buffer()) {
1191 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; 1206 dump_.disable("cannot read back this swapchain format or allocate its capture buffer");
1192 if (!four_bytes || !make_capture_buffer()) return false; 1207 if (capture_) return false;
1208 }
1193 } 1209 }
1194 vsync_ = vsync; 1210 vsync_ = vsync;
1195 swapchain_srgb_ = srgb; 1211 swapchain_srgb_ = srgb;
@@ -1300,6 +1316,8 @@ private:
1300 std::map<VkFormat, VkFormatFeatureFlags> features_; 1316 std::map<VkFormat, VkFormatFeatureFlags> features_;
1301 bool warned_srgb_ = false; 1317 bool warned_srgb_ = false;
1302 bool capture_ = false; 1318 bool capture_ = false;
1319 present_dump::PresentDump dump_;
1320 bool dump_pq_ = false;
1303 VkBuffer capture_buffer_ = VK_NULL_HANDLE; 1321 VkBuffer capture_buffer_ = VK_NULL_HANDLE;
1304 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; 1322 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE;
1305 VkDeviceSize capture_size_ = 0; 1323 VkDeviceSize capture_size_ = 0;