upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/present_dump.h
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/present_dump.h
parentc9ea50842077678228204a2be52314c4065f87d7 (diff)
local: apply #9419 (present dump) as a patch
Diffstat (limited to 'runtime/src/present_dump.h')
-rw-r--r--runtime/src/present_dump.h256
1 files changed, 256 insertions, 0 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