diff options
| author | NotRexed <therealnothingfn@gmail.com> | 2026-11-27 17:58:38 -0500 |
|---|---|---|
| committer | NotRexed <therealnothingfn@gmail.com> | 2026-11-27 17:58:38 -0500 |
| commit | 00131bb85ee294179e5179b00a2c68f4ea3610b5 (patch) | |
| tree | 11854f35d928e964919b81746360146c3657ce07 /runtime/src | |
| parent | eac96d744c3a899fa6e326e296f387fe11e05eab (diff) | |
main keeps its own runtime, tools and tests; the branch's variants stay on port/d3d12-nvidia
After the merge the tree held this branch's older states of files main maintains. Run against main's code,
tests/test_acphal_abi.py and 11 of the 15 translator tests that differed failed, and the C++ runtime would have
been built from two generations of its sources. So that the merge cannot break what main builds and tests:
- runtime/ is main's, file for file (68 files only this branch had are not carried over);
- every file under tools/, tests/ and docs/ that both sides have is main's (80 files);
- ten translator tests only this branch has, which test rules main's translator does not have, and their
fixtures are left out.
What main gains: d3d12/ (the Rust D3D12 runtime), its launchers and helpers (Launcher.bat, scripts/play*.ps1,
play-linux.sh, port_ctl.py, smooth-motion.ps1, fetch_vkd3d_proton.py, sync_victory.py), mods/example_lua, eleven
notes under docs/, seven tools and the tests that pass with main's code, the README's sections and credits, and
the "Runtime traps" section of AGENTS.md. Everything left out here is on the branch port/d3d12-nvidia.
Checked: compileall; make_game.py --help; check_no_game_data.py over every file this adds to main; the
line-ending, docs-encoding, CI-registration and docs tests; each test file that differs from main, on its own.
Not run: the whole translator suite, the C++ build, cargo over d3d12/ after the merge (d3d12/ is byte for byte the
branch's), CI.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
28 files changed, 1 insertions, 5740 deletions
diff --git a/runtime/src/aspect_fit.h b/runtime/src/aspect_fit.h deleted file mode 100644 index feef6c6a2..000000000 --- a/runtime/src/aspect_fit.h +++ /dev/null | |||
| @@ -1,222 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // Ultrawide support (docs/ultrawide.md): the aspect the user asks for, the wider display mode the title is told about, | ||
| 4 | // and where a frame goes in a window of another shape. Pure arithmetic, no Windows or Vulkan headers; | ||
| 5 | // test/aspect_fit_test.cpp checks it. | ||
| 6 | // | ||
| 7 | // LEONIDA_ASPECT=W:H (or a decimal, or `auto` for the primary monitor's shape): the console output's display mode | ||
| 8 | // (shims/xbox_display.cpp) and the title's window (shims/title_window.cpp) are widened to that aspect, keeping their | ||
| 9 | // height. Unset, empty, `off` or `none`: nothing changes. A ratio at or below the mode's own aspect changes nothing. | ||
| 10 | // LEONIDA_PRESENT_SCALE=fit|stretch: how a frame is put in a window of another shape (src/vulkan_present.h). `fit` | ||
| 11 | // keeps the frame's aspect: it is centred, as large as fits, with black bars beside it (pillarbox) or above and below | ||
| 12 | // (letterbox). `stretch` fills the window whatever the shapes, as before. Default: `fit` when LEONIDA_ASPECT asks for | ||
| 13 | // an aspect, else `stretch`. | ||
| 14 | |||
| 15 | #include "display_mode.h" | ||
| 16 | |||
| 17 | #include <cmath> | ||
| 18 | #include <cstdint> | ||
| 19 | #include <string_view> | ||
| 20 | |||
| 21 | namespace leonida::aspect { | ||
| 22 | |||
| 23 | // The ratios LEONIDA_ASPECT takes: square up to four times as wide as high (32:9 is 3.56). | ||
| 24 | inline constexpr double kMinRatio = 1.0; | ||
| 25 | inline constexpr double kMaxRatio = 4.0; | ||
| 26 | |||
| 27 | enum class Kind { none, ratio, automatic }; | ||
| 28 | |||
| 29 | struct Request { | ||
| 30 | Kind kind = Kind::none; | ||
| 31 | double ratio = 0.0; // width over height, for Kind::ratio | ||
| 32 | }; | ||
| 33 | |||
| 34 | namespace detail { | ||
| 35 | inline std::string_view trim(std::string_view s) { | ||
| 36 | while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1); | ||
| 37 | while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n')) s.remove_suffix(1); | ||
| 38 | return s; | ||
| 39 | } | ||
| 40 | inline bool same_word(std::string_view a, std::string_view b) { | ||
| 41 | if (a.size() != b.size()) return false; | ||
| 42 | for (std::size_t i = 0; i < a.size(); ++i) { | ||
| 43 | char c = a[i]; | ||
| 44 | if (c >= 'A' && c <= 'Z') c = char(c - 'A' + 'a'); | ||
| 45 | if (c != b[i]) return false; | ||
| 46 | } | ||
| 47 | return true; | ||
| 48 | } | ||
| 49 | // A decimal number without sign or exponent ("21", "2.39", ".5"), locale-independent. False for anything else. | ||
| 50 | inline bool number(std::string_view s, double* out) { | ||
| 51 | s = trim(s); | ||
| 52 | if (s.empty() || s.size() > 12) return false; | ||
| 53 | double value = 0.0, scale = 1.0; | ||
| 54 | bool dot = false, digits = false; | ||
| 55 | for (const char c : s) { | ||
| 56 | if (c == '.') { | ||
| 57 | if (dot) return false; | ||
| 58 | dot = true; | ||
| 59 | } else if (c >= '0' && c <= '9') { | ||
| 60 | digits = true; | ||
| 61 | if (dot) { | ||
| 62 | scale /= 10.0; | ||
| 63 | value += scale * double(c - '0'); | ||
| 64 | } else { | ||
| 65 | value = value * 10.0 + double(c - '0'); | ||
| 66 | } | ||
| 67 | } else { | ||
| 68 | return false; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | if (!digits) return false; | ||
| 72 | *out = value; | ||
| 73 | return true; | ||
| 74 | } | ||
| 75 | inline std::uint32_t round_even(double v) { return std::uint32_t(std::lround(v / 2.0)) * 2u; } | ||
| 76 | } // namespace detail | ||
| 77 | |||
| 78 | // LEONIDA_ASPECT's text: empty, `off` or `none` (any case) is Kind::none; `auto` is Kind::automatic; `W:H` or `W/H` | ||
| 79 | // (decimals allowed on either side) or a single decimal is Kind::ratio when the ratio is in kMinRatio..kMaxRatio. | ||
| 80 | // False, with `*out` untouched, for anything else. | ||
| 81 | inline bool parse_request(std::string_view text, Request* out) { | ||
| 82 | text = detail::trim(text); | ||
| 83 | Request r; | ||
| 84 | if (text.empty() || detail::same_word(text, "off") || detail::same_word(text, "none")) { | ||
| 85 | r.kind = Kind::none; | ||
| 86 | } else if (detail::same_word(text, "auto")) { | ||
| 87 | r.kind = Kind::automatic; | ||
| 88 | } else { | ||
| 89 | const std::size_t colon = text.find_first_of(":/"); | ||
| 90 | double ratio = 0.0; | ||
| 91 | if (colon == std::string_view::npos) { | ||
| 92 | if (!detail::number(text, &ratio)) return false; | ||
| 93 | } else { | ||
| 94 | double w = 0.0, h = 0.0; | ||
| 95 | if (!detail::number(text.substr(0, colon), &w) || !detail::number(text.substr(colon + 1), &h) || !(h > 0.0)) | ||
| 96 | return false; | ||
| 97 | ratio = w / h; | ||
| 98 | } | ||
| 99 | if (!(ratio >= kMinRatio && ratio <= kMaxRatio)) return false; | ||
| 100 | r.kind = Kind::ratio; | ||
| 101 | r.ratio = ratio; | ||
| 102 | } | ||
| 103 | if (out) *out = r; | ||
| 104 | return true; | ||
| 105 | } | ||
| 106 | |||
| 107 | // The ratio a request stands for: the monitor's `monitor_width` / `monitor_height` for Kind::automatic (0 when that is | ||
| 108 | // not known or outside kMinRatio..kMaxRatio), 0 for Kind::none. | ||
| 109 | inline double resolve(const Request& request, std::uint32_t monitor_width = 0, std::uint32_t monitor_height = 0) { | ||
| 110 | if (request.kind == Kind::ratio) return request.ratio; | ||
| 111 | if (request.kind == Kind::automatic && monitor_width && monitor_height) { | ||
| 112 | const double ratio = double(monitor_width) / double(monitor_height); | ||
| 113 | return ratio >= kMinRatio && ratio <= kMaxRatio ? ratio : 0.0; | ||
| 114 | } | ||
| 115 | return 0.0; | ||
| 116 | } | ||
| 117 | |||
| 118 | struct Size { | ||
| 119 | std::uint32_t width = 0, height = 0; | ||
| 120 | }; | ||
| 121 | |||
| 122 | // `size` made `ratio` wide by widening it (the height kept, the width rounded to an even number). Unchanged when the | ||
| 123 | // ratio is not wider than the size already is, or for an empty size. | ||
| 124 | inline Size widen(Size size, double ratio) { | ||
| 125 | if (!size.width || !size.height || !(ratio > 0.0) || !std::isfinite(ratio)) return size; | ||
| 126 | const double width = double(size.height) * ratio; | ||
| 127 | if (width < double(size.width) + 1.0) return size; | ||
| 128 | size.width = detail::round_even(width); | ||
| 129 | return size; | ||
| 130 | } | ||
| 131 | |||
| 132 | // The display mode the console output reports with LEONIDA_ASPECT: `mode` widened to `ratio` (widen above), kept inside | ||
| 133 | // parse_display_mode's range: a width above 7680 is 7680, with the height made smaller to keep the ratio. | ||
| 134 | inline DisplayMode widen_display_mode(DisplayMode mode, double ratio) { | ||
| 135 | const Size wide = widen({mode.width, mode.height}, ratio); | ||
| 136 | if (wide.width == mode.width) return mode; | ||
| 137 | mode.width = wide.width; | ||
| 138 | if (mode.width > 7680) { | ||
| 139 | mode.width = 7680; | ||
| 140 | mode.height = detail::round_even(7680.0 / ratio); | ||
| 141 | if (mode.height < 360) mode.height = 360; | ||
| 142 | } | ||
| 143 | return mode; | ||
| 144 | } | ||
| 145 | |||
| 146 | enum class Scaling { stretch, fit }; | ||
| 147 | |||
| 148 | // LEONIDA_PRESENT_SCALE's text: `fit` or `stretch` (any case). False, with `*out` untouched, for anything else. | ||
| 149 | inline bool parse_scaling(std::string_view text, Scaling* out) { | ||
| 150 | text = detail::trim(text); | ||
| 151 | Scaling s; | ||
| 152 | if (detail::same_word(text, "fit")) s = Scaling::fit; | ||
| 153 | else if (detail::same_word(text, "stretch")) s = Scaling::stretch; | ||
| 154 | else return false; | ||
| 155 | if (out) *out = s; | ||
| 156 | return true; | ||
| 157 | } | ||
| 158 | |||
| 159 | // The scaling from the two variables' values (null: unset): LEONIDA_PRESENT_SCALE when it parses, else `fit` when | ||
| 160 | // LEONIDA_ASPECT asks for an aspect (a ratio or `auto`), else `stretch`. | ||
| 161 | inline Scaling scaling_from(const char* present_scale, const char* aspect_text) { | ||
| 162 | Scaling s = Scaling::stretch; | ||
| 163 | if (present_scale && parse_scaling(present_scale, &s)) return s; | ||
| 164 | Request request; | ||
| 165 | if (aspect_text && parse_request(aspect_text, &request) && request.kind != Kind::none) return Scaling::fit; | ||
| 166 | return Scaling::stretch; | ||
| 167 | } | ||
| 168 | |||
| 169 | // A rectangle of the output in pixels: left/top inclusive, right/bottom exclusive. | ||
| 170 | struct Box { | ||
| 171 | std::int32_t left = 0, top = 0, right = 0, bottom = 0; | ||
| 172 | std::int32_t width() const { return right - left; } | ||
| 173 | std::int32_t height() const { return bottom - top; } | ||
| 174 | }; | ||
| 175 | |||
| 176 | inline bool is_whole(const Box& box, std::uint32_t out_width, std::uint32_t out_height) { | ||
| 177 | return box.left == 0 && box.top == 0 && box.right == std::int32_t(out_width) && box.bottom == std::int32_t(out_height); | ||
| 178 | } | ||
| 179 | |||
| 180 | // Where content of aspect `content` (width over height) goes in an output of `out_width` x `out_height` with | ||
| 181 | // Scaling::fit: centred, as large as fits, so the bars are beside it when the content is narrower (pillarbox) and | ||
| 182 | // above and below when it is wider (letterbox). The whole output when the two shapes differ by less than a pixel, and | ||
| 183 | // for an empty output or a content aspect that is not a positive finite number. | ||
| 184 | inline Box fit_box(double content, std::uint32_t out_width, std::uint32_t out_height) { | ||
| 185 | const Box whole{0, 0, std::int32_t(out_width), std::int32_t(out_height)}; | ||
| 186 | if (!out_width || !out_height || !(content > 0.0) || !std::isfinite(content)) return whole; | ||
| 187 | const double ow = double(out_width), oh = double(out_height); | ||
| 188 | if (content < ow / oh) { // narrower: pillarbox | ||
| 189 | const double width = oh * content; | ||
| 190 | if (ow - width < 1.0) return whole; | ||
| 191 | std::int32_t w = std::int32_t(std::lround(width)); | ||
| 192 | if (w < 1) w = 1; | ||
| 193 | const std::int32_t left = (std::int32_t(out_width) - w) / 2; | ||
| 194 | return {left, 0, left + w, std::int32_t(out_height)}; | ||
| 195 | } | ||
| 196 | const double height = ow / content; // wider (or the same): letterbox | ||
| 197 | if (oh - height < 1.0) return whole; | ||
| 198 | std::int32_t h = std::int32_t(std::lround(height)); | ||
| 199 | if (h < 1) h = 1; | ||
| 200 | const std::int32_t top = (std::int32_t(out_height) - h) / 2; | ||
| 201 | return {0, top, std::int32_t(out_width), top + h}; | ||
| 202 | } | ||
| 203 | |||
| 204 | // The aspect of the output a plane was composed for: a source of `source_width` x `source_height` texels shown | ||
| 205 | // undistorted in `dest` (left, top, right, bottom as fractions of that output) makes it | ||
| 206 | // (source_width / source_height) * (dest height / dest width). 0 for an empty source or destination. | ||
| 207 | inline double content_aspect(double source_width, double source_height, const float dest[4]) { | ||
| 208 | const double dw = double(dest[2]) - double(dest[0]), dh = double(dest[3]) - double(dest[1]); | ||
| 209 | if (!(source_width > 0.0) || !(source_height > 0.0) || !(dw > 0.0) || !(dh > 0.0)) return 0.0; | ||
| 210 | return source_width / source_height * dh / dw; | ||
| 211 | } | ||
| 212 | |||
| 213 | // `dest` (fractions of the title's output) in output pixels once that output is `box`. | ||
| 214 | inline void place(const float dest[4], const Box& box, float out[4]) { | ||
| 215 | const float w = float(box.width()), h = float(box.height()); | ||
| 216 | out[0] = float(box.left) + dest[0] * w; | ||
| 217 | out[1] = float(box.top) + dest[1] * h; | ||
| 218 | out[2] = float(box.left) + dest[2] * w; | ||
| 219 | out[3] = float(box.top) + dest[3] * h; | ||
| 220 | } | ||
| 221 | |||
| 222 | } // namespace leonida::aspect | ||
diff --git a/runtime/src/bcpack_decode.h b/runtime/src/bcpack_decode.h deleted file mode 100644 index 37175caa4..000000000 --- a/runtime/src/bcpack_decode.h +++ /dev/null | |||
| @@ -1,19 +0,0 @@ | |||
| 1 | // The BCPack entry point DirectStorage calls (shims/dstorage_xs.cpp, ported from VIctory's | ||
| 2 | // crates/victory-hle/src/modules/dstorage.rs). Defined in bcpack.cpp, a port of VIctory's victory-formats BCPack | ||
| 3 | // decoder (GPL-3.0-or-later, Marvisak and contributors, DexNom fork); Leonida is GPL-3.0-or-later too. | ||
| 4 | // bcpack_decode_stub.cpp defines it too, always false, for dstorage_xs_test only (see runtime/CMakeLists.txt). | ||
| 5 | // | ||
| 6 | // BCPack is the Xbox Series' packed form of BCn texture blocks, which the console's DirectStorage hardware unpacks | ||
| 7 | // while it reads. | ||
| 8 | // format: the BC number of the request (DSTORAGE_BCPACK_MODE, options bits 1-4): 1 and 3-7; BC2 is not supported. | ||
| 9 | // dst_size: the decoded size, a whole number of blocks. Bytes after the last one the stream needs are ignored. | ||
| 10 | // Returns false when the format tables are missing or refused (see bcpack.h), for an unsupported format, a bad size | ||
| 11 | // or a stream that ends early or is corrupt; `dst` may then hold some blocks already, and the request completes with | ||
| 12 | // HRESULT_FROM_WIN32(ERROR_INVALID_DATA). Thread-safe. | ||
| 13 | #pragma once | ||
| 14 | |||
| 15 | #include <cstddef> | ||
| 16 | #include <cstdint> | ||
| 17 | |||
| 18 | bool leonida_bcpack_decode(std::uint32_t format, const std::uint8_t* src, std::size_t src_size, std::uint8_t* dst, | ||
| 19 | std::size_t dst_size); | ||
diff --git a/runtime/src/bcpack_decode_stub.cpp b/runtime/src/bcpack_decode_stub.cpp deleted file mode 100644 index 57bd7cd54..000000000 --- a/runtime/src/bcpack_decode_stub.cpp +++ /dev/null | |||
| @@ -1,12 +0,0 @@ | |||
| 1 | // No BCPack decoder yet: the stand-in for leonida_bcpack_decode (bcpack_decode.h) until the decoder is ported. Part of | ||
| 2 | // the port of VIctory's crates/victory-hle/src/modules/dstorage.rs (GPL-3.0-or-later; Marvisak and contributors, | ||
| 3 | // DexNom fork); Leonida is GPL-3.0-or-later too. | ||
| 4 | // | ||
| 5 | // Every call fails, so a DirectStorage request with a BCPack stage completes with an error status, which the shim logs | ||
| 6 | // once per BC format, instead of leaving whatever the destination held. The decoder's own file takes this one's place | ||
| 7 | // in the gta6rt target. | ||
| 8 | #include "bcpack_decode.h" | ||
| 9 | |||
| 10 | bool leonida_bcpack_decode(std::uint32_t, const std::uint8_t*, std::size_t, std::uint8_t*, std::size_t) { | ||
| 11 | return false; | ||
| 12 | } | ||
diff --git a/runtime/src/console_insn.cpp b/runtime/src/console_insn.cpp deleted file mode 100644 index e8f079fc6..000000000 --- a/runtime/src/console_insn.cpp +++ /dev/null | |||
| @@ -1,334 +0,0 @@ | |||
| 1 | // The console-only instruction emulation of console_insn.h: the decoder (portable) and the vectored handler that | ||
| 2 | // uses it (Win32). Behaviour ported from VIctory victory-loader src/console_insn.rs (GPL-3.0-or-later); see the header | ||
| 3 | // for what is VIctory's and where the encodings come from. | ||
| 4 | #include "console_insn.h" | ||
| 5 | |||
| 6 | #include <atomic> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | |||
| 10 | #if defined(_WIN32) | ||
| 11 | #include <windows.h> | ||
| 12 | |||
| 13 | #include "../shims/shims.h" | ||
| 14 | #endif | ||
| 15 | |||
| 16 | namespace rt::console_insn { | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | // The ModRM operand's length (ModRM, SIB and displacement) at `b`, 0 when the bytes run out. | ||
| 21 | size_t modrm_length(const uint8_t* b, size_t size) { | ||
| 22 | if (size < 1) return 0; | ||
| 23 | const uint8_t mod = b[0] >> 6, rm = b[0] & 7; | ||
| 24 | if (mod == 3) return 1; | ||
| 25 | size_t length = 1; | ||
| 26 | uint8_t base = rm; | ||
| 27 | if (rm == 4) { | ||
| 28 | if (size < 2) return 0; | ||
| 29 | base = b[1] & 7; | ||
| 30 | ++length; | ||
| 31 | } | ||
| 32 | if (mod == 1) length += 1; | ||
| 33 | else if (mod == 2 || (mod == 0 && base == 5)) length += 4; // mod 0 base 5: disp32 (RIP-relative without a SIB) | ||
| 34 | return length <= size ? length : 0; | ||
| 35 | } | ||
| 36 | |||
| 37 | } // namespace | ||
| 38 | |||
| 39 | Decoded decode(const uint8_t* code, size_t size) { | ||
| 40 | Decoded none; | ||
| 41 | if (!code) return none; | ||
| 42 | size_t i = 0; | ||
| 43 | bool p66 = false, p67 = false; | ||
| 44 | uint8_t rep = 0; // the last of F2 / F3: the one that selects the instruction | ||
| 45 | uint8_t rex = 0; // a REX counts only right before the opcode; a legacy prefix after it cancels it | ||
| 46 | for (; i < size && i < 15; ++i) { | ||
| 47 | const uint8_t b = code[i]; | ||
| 48 | if (b >= 0x40 && b <= 0x4F) { | ||
| 49 | rex = b; | ||
| 50 | continue; | ||
| 51 | } | ||
| 52 | if (b == 0x66) p66 = true; | ||
| 53 | else if (b == 0x67) p67 = true; | ||
| 54 | else if (b == 0xF2 || b == 0xF3) rep = b; | ||
| 55 | else if (b != 0x26 && b != 0x2E && b != 0x36 && b != 0x3E && b != 0x64 && b != 0x65) break; | ||
| 56 | rex = 0; | ||
| 57 | } | ||
| 58 | if (i + 2 > size || code[i] != 0x0F) return none; | ||
| 59 | const uint8_t op = code[i + 1]; | ||
| 60 | const bool rex_r = (rex & 4) != 0, rex_b = (rex & 1) != 0; | ||
| 61 | |||
| 62 | if (op == 0x0B) return {Kind::Ud2, static_cast<uint8_t>(i + 2)}; | ||
| 63 | if (i + 3 > size) return none; | ||
| 64 | const uint8_t m = code[i + 2]; | ||
| 65 | const uint8_t mod = m >> 6, reg = (m >> 3) & 7, rm = m & 7; | ||
| 66 | |||
| 67 | switch (op) { | ||
| 68 | case 0x01: | ||
| 69 | if (m == 0xFC) { | ||
| 70 | // clzero; add rax, 40h (48 83 C0 40); cmp rax, r64 (48|4C 39 /r, r/m = rax); jb -12 (72 F4), the jb | ||
| 71 | // landing on the clzero. Not after a 67: that CLZERO is at EAX, and it is stepped alone. | ||
| 72 | const uint8_t* l = code + i; | ||
| 73 | if (!p67 && size >= i + 12 && l[3] == 0x48 && l[4] == 0x83 && l[5] == 0xC0 && l[6] == 0x40 && | ||
| 74 | (l[7] == 0x48 || l[7] == 0x4C) && l[8] == 0x39 && (l[9] >> 6) == 3 && (l[9] & 7) == 0 && | ||
| 75 | l[10] == 0x72 && l[11] == 0xF4) { | ||
| 76 | Decoded d{Kind::ClzeroLoop, static_cast<uint8_t>(i + 12)}; | ||
| 77 | d.reg = static_cast<uint8_t>(((l[9] >> 3) & 7) | (l[7] == 0x4C ? 8 : 0)); | ||
| 78 | return d; | ||
| 79 | } | ||
| 80 | Decoded d{Kind::Clzero, static_cast<uint8_t>(i + 3)}; | ||
| 81 | d.address32 = p67; | ||
| 82 | return d; | ||
| 83 | } | ||
| 84 | if (m == 0xFD) return {Kind::Rdpru, static_cast<uint8_t>(i + 3)}; | ||
| 85 | if (m == 0xFA) return {Kind::Monitorx, static_cast<uint8_t>(i + 3)}; | ||
| 86 | if (m == 0xFB) return {Kind::Mwaitx, static_cast<uint8_t>(i + 3)}; | ||
| 87 | return none; | ||
| 88 | case 0xAE: { | ||
| 89 | // 66 0F AE /6 with a memory operand; without the 66 it is XSAVEOPT, with F3 another instruction. | ||
| 90 | if (!p66 || rep || reg != 6 || mod == 3) return none; | ||
| 91 | const size_t operand = modrm_length(code + i + 2, size - (i + 2)); | ||
| 92 | if (!operand) return none; | ||
| 93 | return {Kind::Clwb, static_cast<uint8_t>(i + 2 + operand)}; | ||
| 94 | } | ||
| 95 | case 0xC7: { | ||
| 96 | if (rep != 0xF3 || reg != 7 || mod != 3) return none; | ||
| 97 | Decoded d{Kind::Rdpid, static_cast<uint8_t>(i + 3)}; | ||
| 98 | d.reg = static_cast<uint8_t>(rm | (rex_b ? 8 : 0)); | ||
| 99 | return d; | ||
| 100 | } | ||
| 101 | case 0x78: | ||
| 102 | case 0x79: { | ||
| 103 | // SSE4a, register operands only. F2 selects INSERTQ, F3 nothing; 66 without either selects EXTRQ. | ||
| 104 | if (mod != 3) return none; | ||
| 105 | const bool insert = rep == 0xF2; | ||
| 106 | if (!insert && !(rep == 0 && p66)) return none; | ||
| 107 | const uint8_t xreg = static_cast<uint8_t>(reg | (rex_r ? 8 : 0)); | ||
| 108 | const uint8_t xrm = static_cast<uint8_t>(rm | (rex_b ? 8 : 0)); | ||
| 109 | Decoded d{insert ? Kind::Insertq : Kind::Extrq}; | ||
| 110 | if (op == 0x78) { | ||
| 111 | if (i + 5 > size) return none; | ||
| 112 | if (!insert && reg != 0) return none; // EXTRQ xmm, imm8, imm8 is /0 | ||
| 113 | d.reg = insert ? xreg : xrm; | ||
| 114 | d.src = xrm; | ||
| 115 | d.field_length = code[i + 3] & 63; | ||
| 116 | d.field_index = code[i + 4] & 63; | ||
| 117 | d.length = static_cast<uint8_t>(i + 5); | ||
| 118 | } else { | ||
| 119 | d.reg = xreg; | ||
| 120 | d.src = xrm; | ||
| 121 | d.from_register = true; | ||
| 122 | d.length = static_cast<uint8_t>(i + 3); | ||
| 123 | } | ||
| 124 | return d; | ||
| 125 | } | ||
| 126 | default: | ||
| 127 | return none; | ||
| 128 | } | ||
| 129 | } | ||
| 130 | |||
| 131 | namespace { | ||
| 132 | unsigned field_bits(unsigned length) { return (length & 63) ? (length & 63) : 64; } | ||
| 133 | uint64_t low_ones(unsigned bits) { return bits >= 64 ? ~0ull : (1ull << bits) - 1; } | ||
| 134 | } // namespace | ||
| 135 | |||
| 136 | uint64_t extrq(uint64_t value, unsigned field_length, unsigned field_index) { | ||
| 137 | const unsigned bits = field_bits(field_length), index = field_index & 63; | ||
| 138 | return (value >> index) & low_ones(bits); | ||
| 139 | } | ||
| 140 | |||
| 141 | uint64_t insertq(uint64_t dst, uint64_t src, unsigned field_length, unsigned field_index) { | ||
| 142 | const unsigned bits = field_bits(field_length), index = field_index & 63; | ||
| 143 | const uint64_t mask = low_ones(bits) << index; // the bits of the field that fall inside the quadword | ||
| 144 | return (dst & ~mask) | ((src << index) & mask); | ||
| 145 | } | ||
| 146 | |||
| 147 | namespace { | ||
| 148 | std::atomic<uint64_t> g_emulated{0}; | ||
| 149 | } | ||
| 150 | uint64_t emulated_count() { return g_emulated.load(std::memory_order_relaxed); } | ||
| 151 | |||
| 152 | #if defined(_WIN32) | ||
| 153 | |||
| 154 | namespace { | ||
| 155 | |||
| 156 | // Where the committed, writable memory `at` lies in ends, at most `end`; 0 when `at` is not in such memory. | ||
| 157 | uintptr_t writable_until(uintptr_t at, uintptr_t end) { | ||
| 158 | MEMORY_BASIC_INFORMATION mbi{}; | ||
| 159 | if (!VirtualQuery(reinterpret_cast<void*>(at), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return 0; | ||
| 160 | if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return 0; | ||
| 161 | if (!(mbi.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY))) return 0; | ||
| 162 | const uintptr_t region_end = reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize; | ||
| 163 | return region_end < end ? region_end : end; | ||
| 164 | } | ||
| 165 | |||
| 166 | DWORD64* gpr(CONTEXT* c, unsigned index) { | ||
| 167 | DWORD64* const regs[16] = {&c->Rax, &c->Rcx, &c->Rdx, &c->Rbx, &c->Rsp, &c->Rbp, &c->Rsi, &c->Rdi, | ||
| 168 | &c->R8, &c->R9, &c->R10, &c->R11, &c->R12, &c->R13, &c->R14, &c->R15}; | ||
| 169 | return regs[index & 15]; | ||
| 170 | } | ||
| 171 | |||
| 172 | const char* name(Kind k) { | ||
| 173 | switch (k) { | ||
| 174 | case Kind::Clwb: return "CLWB"; | ||
| 175 | case Kind::Clzero: return "CLZERO"; | ||
| 176 | case Kind::ClzeroLoop: return "a CLZERO loop"; | ||
| 177 | case Kind::Rdpru: return "RDPRU"; | ||
| 178 | case Kind::Monitorx: return "MONITORX"; | ||
| 179 | case Kind::Mwaitx: return "MWAITX"; | ||
| 180 | case Kind::Rdpid: return "RDPID"; | ||
| 181 | case Kind::Extrq: return "EXTRQ"; | ||
| 182 | case Kind::Insertq: return "INSERTQ"; | ||
| 183 | default: return "?"; | ||
| 184 | } | ||
| 185 | } | ||
| 186 | |||
| 187 | } // namespace | ||
| 188 | |||
| 189 | bool emulate(CONTEXT* ctx, const uint8_t* code, size_t size) { | ||
| 190 | const Decoded d = decode(code, size); | ||
| 191 | if (d.kind == Kind::None || d.kind == Kind::Ud2) return false; | ||
| 192 | |||
| 193 | static std::atomic<bool> s_logged[16]; | ||
| 194 | if (!s_logged[static_cast<unsigned>(d.kind) & 15].exchange(true)) | ||
| 195 | std::fprintf(stderr, "[rt] cpu: %s is a console CPU instruction this CPU lacks: emulated (logged once)\n", | ||
| 196 | name(d.kind)); | ||
| 197 | |||
| 198 | switch (d.kind) { | ||
| 199 | case Kind::Clwb: { | ||
| 200 | // Nothing to write back on a PC: the instruction becomes NOPs, so it never faults again. | ||
| 201 | DWORD old = 0; | ||
| 202 | void* at = reinterpret_cast<void*>(ctx->Rip); | ||
| 203 | if (VirtualProtect(at, d.length, PAGE_EXECUTE_READWRITE, &old)) { | ||
| 204 | std::memset(at, 0x90, d.length); | ||
| 205 | VirtualProtect(at, d.length, old, &old); | ||
| 206 | FlushInstructionCache(GetCurrentProcess(), at, d.length); | ||
| 207 | } | ||
| 208 | break; | ||
| 209 | } | ||
| 210 | case Kind::Monitorx: | ||
| 211 | break; | ||
| 212 | case Kind::Mwaitx: | ||
| 213 | YieldProcessor(); | ||
| 214 | break; | ||
| 215 | case Kind::Clzero: { | ||
| 216 | const uintptr_t line = static_cast<uintptr_t>(d.address32 ? (ctx->Rax & 0xFFFFFFFFull) : ctx->Rax) & ~uintptr_t{63}; | ||
| 217 | if (writable_until(line, line + 64) != line + 64) return false; // the real instruction faults there too | ||
| 218 | std::memset(reinterpret_cast<void*>(line), 0, 64); | ||
| 219 | break; | ||
| 220 | } | ||
| 221 | case Kind::ClzeroLoop: { | ||
| 222 | // The loop's effect: every line from rAX's up to the first rAX + 64k at or past the end is zeroed, and rAX | ||
| 223 | // is left there with the jb not taken (CF clear; ZF as the last compare set it). | ||
| 224 | const uint64_t start = ctx->Rax, end = *gpr(ctx, d.reg); | ||
| 225 | if (end <= start || end - start >= (uint64_t{2} << 30)) { | ||
| 226 | // One line and once round, as the CPU would take it. | ||
| 227 | const uintptr_t line = static_cast<uintptr_t>(start) & ~uintptr_t{63}; | ||
| 228 | if (writable_until(line, line + 64) != line + 64) return false; | ||
| 229 | std::memset(reinterpret_cast<void*>(line), 0, 64); | ||
| 230 | ctx->Rax = start + 64; | ||
| 231 | ctx->Rip += (d.length - 12) + 7; // past clzero and add: the cmp and jb run as code | ||
| 232 | g_emulated.fetch_add(1, std::memory_order_relaxed); | ||
| 233 | return true; | ||
| 234 | } | ||
| 235 | const uint64_t final_rax = start + ((end - start + 63) / 64) * 64; | ||
| 236 | const uintptr_t from = static_cast<uintptr_t>(start) & ~uintptr_t{63}; | ||
| 237 | const uintptr_t to = static_cast<uintptr_t>((final_rax - 64) & ~uint64_t{63}) + 64; | ||
| 238 | uintptr_t at = from; | ||
| 239 | while (at < to) { | ||
| 240 | const uintptr_t until = writable_until(at, to); | ||
| 241 | if (!until) break; | ||
| 242 | std::memset(reinterpret_cast<void*>(at), 0, until - at); | ||
| 243 | at = until; | ||
| 244 | } | ||
| 245 | if (at == from) return false; | ||
| 246 | if (at < to) { | ||
| 247 | // What follows is not writable: the loop resumes at that line (the same instruction again), where the | ||
| 248 | // real one faults too. rAX keeps its offset in the line. | ||
| 249 | ctx->Rax = at + (start & 63); | ||
| 250 | g_emulated.fetch_add(1, std::memory_order_relaxed); | ||
| 251 | return true; | ||
| 252 | } | ||
| 253 | ctx->Rax = final_rax; | ||
| 254 | constexpr DWORD kCarry = 0x1, kZero = 0x40; | ||
| 255 | ctx->EFlags = (ctx->EFlags & ~(kCarry | kZero)) | (final_rax == end ? kZero : 0); | ||
| 256 | break; | ||
| 257 | } | ||
| 258 | case Kind::Rdpru: { | ||
| 259 | LARGE_INTEGER counter{}; | ||
| 260 | QueryPerformanceCounter(&counter); | ||
| 261 | const uint64_t v = (ctx->Rcx & 0xFFFFFFFFull) <= 1 ? static_cast<uint64_t>(counter.QuadPart) : 0; | ||
| 262 | ctx->Rax = v & 0xFFFFFFFFull; | ||
| 263 | ctx->Rdx = v >> 32; | ||
| 264 | break; | ||
| 265 | } | ||
| 266 | case Kind::Rdpid: | ||
| 267 | *gpr(ctx, d.reg) = GetCurrentProcessorNumber(); | ||
| 268 | break; | ||
| 269 | case Kind::Extrq: { | ||
| 270 | M128A* x = ctx->FltSave.XmmRegisters; | ||
| 271 | unsigned length = d.field_length, index = d.field_index; | ||
| 272 | if (d.from_register) { | ||
| 273 | const uint64_t control = x[d.src & 15].Low; | ||
| 274 | length = control & 63; | ||
| 275 | index = (control >> 8) & 63; | ||
| 276 | } | ||
| 277 | x[d.reg & 15].Low = extrq(x[d.reg & 15].Low, length, index); | ||
| 278 | x[d.reg & 15].High = 0; | ||
| 279 | break; | ||
| 280 | } | ||
| 281 | case Kind::Insertq: { | ||
| 282 | M128A* x = ctx->FltSave.XmmRegisters; | ||
| 283 | const M128A source = x[d.src & 15]; | ||
| 284 | unsigned length = d.field_length, index = d.field_index; | ||
| 285 | if (d.from_register) { | ||
| 286 | const uint64_t control = static_cast<uint64_t>(source.High); | ||
| 287 | length = control & 63; | ||
| 288 | index = (control >> 8) & 63; | ||
| 289 | } | ||
| 290 | x[d.reg & 15].Low = insertq(x[d.reg & 15].Low, source.Low, length, index); | ||
| 291 | x[d.reg & 15].High = 0; | ||
| 292 | break; | ||
| 293 | } | ||
| 294 | default: | ||
| 295 | return false; | ||
| 296 | } | ||
| 297 | ctx->Rip += d.length; | ||
| 298 | g_emulated.fetch_add(1, std::memory_order_relaxed); | ||
| 299 | return true; | ||
| 300 | } | ||
| 301 | |||
| 302 | namespace { | ||
| 303 | |||
| 304 | LONG CALLBACK illegal_instruction(EXCEPTION_POINTERS* info) { | ||
| 305 | if (!info || !info->ExceptionRecord || !info->ContextRecord || | ||
| 306 | info->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) | ||
| 307 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 308 | const uintptr_t rip = static_cast<uintptr_t>(info->ContextRecord->Rip); | ||
| 309 | uint64_t base = 0; | ||
| 310 | if (!rt::shims::mapped_image_base(rip, base)) return EXCEPTION_CONTINUE_SEARCH; // only the title's code | ||
| 311 | MEMORY_BASIC_INFORMATION mbi{}; | ||
| 312 | if (!VirtualQuery(reinterpret_cast<void*>(rip), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT || | ||
| 313 | (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS))) | ||
| 314 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 315 | const uintptr_t region_end = reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize; | ||
| 316 | const size_t readable = region_end - rip < 16 ? region_end - rip : 16; | ||
| 317 | return emulate(info->ContextRecord, reinterpret_cast<const uint8_t*>(rip), readable) ? EXCEPTION_CONTINUE_EXECUTION | ||
| 318 | : EXCEPTION_CONTINUE_SEARCH; | ||
| 319 | } | ||
| 320 | |||
| 321 | } // namespace | ||
| 322 | |||
| 323 | void install() { | ||
| 324 | static const bool installed = AddVectoredExceptionHandler(1, &illegal_instruction) != nullptr; | ||
| 325 | (void)installed; | ||
| 326 | } | ||
| 327 | |||
| 328 | #else | ||
| 329 | |||
| 330 | void install() {} | ||
| 331 | |||
| 332 | #endif | ||
| 333 | |||
| 334 | } // namespace rt::console_insn | ||
diff --git a/runtime/src/console_insn.h b/runtime/src/console_insn.h deleted file mode 100644 index f6916b48c..000000000 --- a/runtime/src/console_insn.h +++ /dev/null | |||
| @@ -1,73 +0,0 @@ | |||
| 1 | // Instructions the console's CPU (Zen 2) has and a PC's CPU may lack. A title compiled for the console runs them as | ||
| 2 | // they are; on an Intel CPU (CLZERO, RDPRU, MONITORX/MWAITX and SSE4a's EXTRQ/INSERTQ are AMD's, CLWB and RDPID are | ||
| 3 | // missing before Ice Lake / Alder Lake) each raises STATUS_ILLEGAL_INSTRUCTION, and the retail title zeroes memory | ||
| 4 | // with a CLZERO loop from its first frames. The vectored handler in console_insn.cpp decodes the faulting | ||
| 5 | // instruction here, emulates it and steps over it. | ||
| 6 | // | ||
| 7 | // Which instructions to emulate and how is VIctory's (victory-loader src/console_insn.rs, GPL-3.0-or-later), | ||
| 8 | // measured on the same title: CLWB is a no-op (a PC's memory is coherent) and is patched to NOPs, MONITORX/MWAITX | ||
| 9 | // are a skipped wait, RDPRU reads a counter, RDPID the processor number, a whole `clzero; add rax,40h; cmp rax,reg; | ||
| 10 | // jb` loop is done at once, and the high quadword of an EXTRQ/INSERTQ destination is zeroed (as a Zen 5 does; AMD | ||
| 11 | // leaves it undefined). This decoder is written from the encodings in AMD's Architecture Programmer's Manual | ||
| 12 | // (volume 3 for CLZERO, RDPRU, MONITORX, MWAITX, CLWB, RDPID; volume 4 for EXTRQ and INSERTQ), not translated from | ||
| 13 | // VIctory's, whose decoder is XCL's (GPL-2.0-only); the prefix rules VIctory measured on a Zen 5 (the last of F2/F3 | ||
| 14 | // decides, 66 only without either, a REX counts only right before the opcode) are followed as facts. | ||
| 15 | // | ||
| 16 | // Portable: no Win32 here. The handler and its memory checks are the Win32 boundary. | ||
| 17 | #pragma once | ||
| 18 | |||
| 19 | #include <cstddef> | ||
| 20 | #include <cstdint> | ||
| 21 | |||
| 22 | #if defined(_WIN32) | ||
| 23 | struct _CONTEXT; // <windows.h>'s CONTEXT | ||
| 24 | #endif | ||
| 25 | |||
| 26 | namespace rt::console_insn { | ||
| 27 | |||
| 28 | enum class Kind : uint8_t { | ||
| 29 | None, // not one of ours: the exception goes on to the title's handlers and the crash report | ||
| 30 | Ud2, // the title's own trap, never emulated | ||
| 31 | Clwb, // 66 0F AE /6 (memory operand): write back a cache line | ||
| 32 | Clzero, // 0F 01 FC: zero the 64-byte line at rAX (EAX with a 67 prefix) | ||
| 33 | ClzeroLoop, // clzero; add rax,40h; cmp rax,<reg>; jb back to the clzero: zero [rax, reg) | ||
| 34 | Rdpru, // 0F 01 FD: ECX 0 MPERF, 1 APERF into EDX:EAX | ||
| 35 | Monitorx, // 0F 01 FA | ||
| 36 | Mwaitx, // 0F 01 FB | ||
| 37 | Rdpid, // F3 0F C7 /7 (register operand): TSC_AUX, the processor number | ||
| 38 | Extrq, // 66 0F 78 /0 ib ib, or 66 0F 79 /r | ||
| 39 | Insertq, // F2 0F 78 /r ib ib, or F2 0F 79 /r | ||
| 40 | }; | ||
| 41 | |||
| 42 | struct Decoded { | ||
| 43 | Kind kind = Kind::None; | ||
| 44 | uint8_t length = 0; // bytes to step over (for ClzeroLoop the whole loop) | ||
| 45 | uint8_t reg = 0; // Rdpid's destination, ClzeroLoop's end register (CONTEXT order: rax, rcx, rdx, rbx, rsp, | ||
| 46 | // rbp, rsi, rdi, r8-r15); Extrq/Insertq's destination XMM register | ||
| 47 | uint8_t src = 0; // Extrq (register form) / Insertq: the source XMM register | ||
| 48 | bool from_register = false; // Extrq/Insertq: length and index come from the source register, not immediates | ||
| 49 | uint8_t field_length = 0; // immediate forms: the field's length (0 means 64) and index, low 6 bits each | ||
| 50 | uint8_t field_index = 0; | ||
| 51 | bool address32 = false; // Clzero: a 67 prefix, the line is at EAX | ||
| 52 | }; | ||
| 53 | |||
| 54 | // The console-only instruction at the start of `code` (up to `size` readable bytes), or Kind::None. | ||
| 55 | Decoded decode(const uint8_t* code, size_t size); | ||
| 56 | |||
| 57 | // SSE4a on a low quadword. A field length of 0 is 64; a field past bit 63 gives what the shifts give. | ||
| 58 | uint64_t extrq(uint64_t value, unsigned field_length, unsigned field_index); | ||
| 59 | uint64_t insertq(uint64_t dst, uint64_t src, unsigned field_length, unsigned field_index); | ||
| 60 | |||
| 61 | // Installs the vectored handler (Windows; a no-op elsewhere). Emulates only in images the loader mapped. Once. | ||
| 62 | void install(); | ||
| 63 | |||
| 64 | // How many instructions the handler has emulated, for the log and tests. | ||
| 65 | uint64_t emulated_count(); | ||
| 66 | |||
| 67 | #if defined(_WIN32) | ||
| 68 | // The handler's work on a faulting thread's context, with `size` readable code bytes at its RIP (`code`): true when | ||
| 69 | // the instruction was emulated (RIP is past it, or at it again for a CLZERO loop stopped by memory it cannot write). | ||
| 70 | bool emulate(::_CONTEXT* ctx, const uint8_t* code, size_t size); | ||
| 71 | #endif | ||
| 72 | |||
| 73 | } // namespace rt::console_insn | ||
diff --git a/runtime/src/debug_magenta_spv.h b/runtime/src/debug_magenta_spv.h deleted file mode 100644 index 826f82e2c..000000000 --- a/runtime/src/debug_magenta_spv.h +++ /dev/null | |||
| @@ -1,71 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // A pixel shader that writes solid magenta to colour outputs 0-3: LEONIDA_DEBUG_SOLID_PS=1 swaps it in for every | ||
| 4 | // translated pixel shader, to tell a geometry or target problem (still black) from a shader-input one (magenta). | ||
| 5 | // Built from this GLSL with glslangValidator -V --vn kMagentaFragment: | ||
| 6 | // #version 450 | ||
| 7 | // layout(location = 0..3) out vec4 c0..c3; | ||
| 8 | // void main() { c0 = vec4(1.0, 0.0, 1.0, 1.0); c1 = c0; c2 = c0; c3 = c0; } | ||
| 9 | #include <cstdint> | ||
| 10 | |||
| 11 | namespace leonida { | ||
| 12 | |||
| 13 | inline constexpr std::uint32_t kMagentaFragment[] = { | ||
| 14 | 0x07230203,0x00010000,0x0008000b,0x00000013,0x00000000,0x00020011,0x00000001,0x0006000b, | ||
| 15 | 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, | ||
| 16 | 0x0009000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x0000000f, | ||
| 17 | 0x00000011,0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005, | ||
| 18 | 0x00000004,0x6e69616d,0x00000000,0x00030005,0x00000009,0x00003063,0x00030005,0x0000000d, | ||
| 19 | 0x00003163,0x00030005,0x0000000f,0x00003263,0x00030005,0x00000011,0x00003363,0x00040047, | ||
| 20 | 0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,0x00000001,0x00040047, | ||
| 21 | 0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000011,0x0000001e,0x00000003,0x00020013, | ||
| 22 | 0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017, | ||
| 23 | 0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003b, | ||
| 24 | 0x00000008,0x00000009,0x00000003,0x0004002b,0x00000006,0x0000000a,0x3f800000,0x0004002b, | ||
| 25 | 0x00000006,0x0000000b,0x00000000,0x0007002c,0x00000007,0x0000000c,0x0000000a,0x0000000b, | ||
| 26 | 0x0000000a,0x0000000a,0x0004003b,0x00000008,0x0000000d,0x00000003,0x0004003b,0x00000008, | ||
| 27 | 0x0000000f,0x00000003,0x0004003b,0x00000008,0x00000011,0x00000003,0x00050036,0x00000002, | ||
| 28 | 0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0003003e,0x00000009,0x0000000c, | ||
| 29 | 0x0004003d,0x00000007,0x0000000e,0x00000009,0x0003003e,0x0000000d,0x0000000e,0x0004003d, | ||
| 30 | 0x00000007,0x00000010,0x00000009,0x0003003e,0x0000000f,0x00000010,0x0004003d,0x00000007, | ||
| 31 | 0x00000012,0x00000009,0x0003003e,0x00000011,0x00000012,0x000100fd,0x00010038 | ||
| 32 | }; | ||
| 33 | |||
| 34 | // LEONIDA_DEBUG_SOLID_VS=1: a vertex shader that draws one full-screen triangle from gl_VertexIndex (positions only). | ||
| 35 | inline constexpr std::uint32_t kFullscreenVertex[] = { | ||
| 36 | 0x07230203,0x00010000,0x0008000b,0x00000027,0x00000000,0x00020011,0x00000001,0x0006000b, | ||
| 37 | 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, | ||
| 38 | 0x0007000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000a,0x00000015,0x00030003, | ||
| 39 | 0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005,0x00000008, | ||
| 40 | 0x00000069,0x00060005,0x0000000a,0x565f6c67,0x65747265,0x646e4978,0x00007865,0x00060005, | ||
| 41 | 0x00000013,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000013,0x00000000, | ||
| 42 | 0x505f6c67,0x7469736f,0x006e6f69,0x00070006,0x00000013,0x00000001,0x505f6c67,0x746e696f, | ||
| 43 | 0x657a6953,0x00000000,0x00070006,0x00000013,0x00000002,0x435f6c67,0x4470696c,0x61747369, | ||
| 44 | 0x0065636e,0x00070006,0x00000013,0x00000003,0x435f6c67,0x446c6c75,0x61747369,0x0065636e, | ||
| 45 | 0x00030005,0x00000015,0x00000000,0x00040047,0x0000000a,0x0000000b,0x0000002a,0x00030047, | ||
| 46 | 0x00000013,0x00000002,0x00050048,0x00000013,0x00000000,0x0000000b,0x00000000,0x00050048, | ||
| 47 | 0x00000013,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000013,0x00000002,0x0000000b, | ||
| 48 | 0x00000003,0x00050048,0x00000013,0x00000003,0x0000000b,0x00000004,0x00020013,0x00000002, | ||
| 49 | 0x00030021,0x00000003,0x00000002,0x00040015,0x00000006,0x00000020,0x00000001,0x00040020, | ||
| 50 | 0x00000007,0x00000007,0x00000006,0x00040020,0x00000009,0x00000001,0x00000006,0x0004003b, | ||
| 51 | 0x00000009,0x0000000a,0x00000001,0x0004002b,0x00000006,0x0000000c,0x00000003,0x00030016, | ||
| 52 | 0x0000000e,0x00000020,0x00040017,0x0000000f,0x0000000e,0x00000004,0x00040015,0x00000010, | ||
| 53 | 0x00000020,0x00000000,0x0004002b,0x00000010,0x00000011,0x00000001,0x0004001c,0x00000012, | ||
| 54 | 0x0000000e,0x00000011,0x0006001e,0x00000013,0x0000000f,0x0000000e,0x00000012,0x00000012, | ||
| 55 | 0x00040020,0x00000014,0x00000003,0x00000013,0x0004003b,0x00000014,0x00000015,0x00000003, | ||
| 56 | 0x0004002b,0x00000006,0x00000016,0x00000000,0x0004002b,0x00000006,0x00000018,0x00000001, | ||
| 57 | 0x00020014,0x00000019,0x0004002b,0x0000000e,0x0000001b,0x40400000,0x0004002b,0x0000000e, | ||
| 58 | 0x0000001c,0xbf800000,0x0004002b,0x00000006,0x0000001f,0x00000002,0x0004002b,0x0000000e, | ||
| 59 | 0x00000022,0x3f000000,0x0004002b,0x0000000e,0x00000023,0x3f800000,0x00040020,0x00000025, | ||
| 60 | 0x00000003,0x0000000f,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, | ||
| 61 | 0x00000005,0x0004003b,0x00000007,0x00000008,0x00000007,0x0004003d,0x00000006,0x0000000b, | ||
| 62 | 0x0000000a,0x0005008b,0x00000006,0x0000000d,0x0000000b,0x0000000c,0x0003003e,0x00000008, | ||
| 63 | 0x0000000d,0x0004003d,0x00000006,0x00000017,0x00000008,0x000500aa,0x00000019,0x0000001a, | ||
| 64 | 0x00000017,0x00000018,0x000600a9,0x0000000e,0x0000001d,0x0000001a,0x0000001b,0x0000001c, | ||
| 65 | 0x0004003d,0x00000006,0x0000001e,0x00000008,0x000500aa,0x00000019,0x00000020,0x0000001e, | ||
| 66 | 0x0000001f,0x000600a9,0x0000000e,0x00000021,0x00000020,0x0000001b,0x0000001c,0x00070050, | ||
| 67 | 0x0000000f,0x00000024,0x0000001d,0x00000021,0x00000022,0x00000023,0x00050041,0x00000025, | ||
| 68 | 0x00000026,0x00000015,0x00000016,0x0003003e,0x00000026,0x00000024,0x000100fd,0x00010038 | ||
| 69 | }; | ||
| 70 | |||
| 71 | } // namespace leonida | ||
diff --git a/runtime/src/display_mode.h b/runtime/src/display_mode.h deleted file mode 100644 index 7d622cbc4..000000000 --- a/runtime/src/display_mode.h +++ /dev/null | |||
| @@ -1,55 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // The display mode the console reports to the title: LEONIDA_DISPLAY_MODE=WxH, default 3840x2160. | ||
| 4 | // | ||
| 5 | // Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; | ||
| 6 | // victory/crates/victory-gpu/src/dxgi.rs:222-240 `display_size`, VICTORY_DISPLAY_MODE): a console reports the | ||
| 7 | // television it is plugged into (a Series X on a 1080p set lists a 1080p mode). VIctory accepts W in 640..7680 and H in | ||
| 8 | // 360..4320 and otherwise reports 3840x2160; so does this. It does not follow the host monitor either (V: "not yet the | ||
| 9 | // host display's own size by default"). The title reads the mode but does not size its frames by it: what does is | ||
| 10 | // display_profile.h. No Windows headers; present_window_parts_test checks the parser. | ||
| 11 | |||
| 12 | #include <cstdint> | ||
| 13 | #include <string_view> | ||
| 14 | |||
| 15 | namespace leonida { | ||
| 16 | |||
| 17 | struct DisplayMode { | ||
| 18 | std::uint32_t width = 3840; | ||
| 19 | std::uint32_t height = 2160; | ||
| 20 | std::uint32_t refresh_hz = 60; // V dxgi.rs `modes`: one mode at 60 Hz | ||
| 21 | }; | ||
| 22 | |||
| 23 | // "WxH" (an `x` or `X` between, spaces around the numbers allowed), W in 640..7680 and H in 360..4320. False, with | ||
| 24 | // `*out` untouched, for anything else. | ||
| 25 | inline bool parse_display_mode(std::string_view text, DisplayMode* out) { | ||
| 26 | const auto trim = [](std::string_view s) { | ||
| 27 | while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1); | ||
| 28 | while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n')) | ||
| 29 | s.remove_suffix(1); | ||
| 30 | return s; | ||
| 31 | }; | ||
| 32 | const auto number = [](std::string_view s, std::uint32_t* value) { | ||
| 33 | if (s.empty() || s.size() > 5) return false; | ||
| 34 | std::uint32_t v = 0; | ||
| 35 | for (const char c : s) { | ||
| 36 | if (c < '0' || c > '9') return false; | ||
| 37 | v = v * 10 + std::uint32_t(c - '0'); | ||
| 38 | } | ||
| 39 | *value = v; | ||
| 40 | return true; | ||
| 41 | }; | ||
| 42 | text = trim(text); | ||
| 43 | const std::size_t x = text.find_first_of("xX"); | ||
| 44 | if (x == std::string_view::npos) return false; | ||
| 45 | std::uint32_t width = 0, height = 0; | ||
| 46 | if (!number(trim(text.substr(0, x)), &width) || !number(trim(text.substr(x + 1)), &height)) return false; | ||
| 47 | if (width < 640 || width > 7680 || height < 360 || height > 4320) return false; | ||
| 48 | if (out) { | ||
| 49 | out->width = width; | ||
| 50 | out->height = height; | ||
| 51 | } | ||
| 52 | return true; | ||
| 53 | } | ||
| 54 | |||
| 55 | } // namespace leonida | ||
diff --git a/runtime/src/display_profile.h b/runtime/src/display_profile.h deleted file mode 100644 index b8d9abf47..000000000 --- a/runtime/src/display_profile.h +++ /dev/null | |||
| @@ -1,170 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // The size the title outputs and renders at: LEONIDA_DISPLAY_MODE=WxH (and LEONIDA_RENDER_SCALE), applied to the mapped | ||
| 4 | // executable before any of its code runs. | ||
| 5 | // | ||
| 6 | // Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; upstream commit ab34a8b21, | ||
| 7 | // apps/victory/src/native_1440p.rs `prepare`). The title does not size its frames by the display mode DXGI reports | ||
| 8 | // (shims/xbox_display.h answers that too): the Series X SDR mode is a constant in the executable, 3840x2160 at 60 Hz, | ||
| 9 | // and the title builds its window, its two scanout buffers and its frontend from it. Its scene is rendered at 2/3 of | ||
| 10 | // that and scaled up temporally (2560x1440 into 3840x2160). VIctory's native 1440p profile changes four places of the | ||
| 11 | // retail executable, each checked against its stock bytes first: | ||
| 12 | // - the SDR mode (W, H, 60, 1); | ||
| 13 | // - the size reserved for the two scanout buffers (`mov ecx, imm32`): two 64 KiB-aligned RGBA8 surfaces in the | ||
| 14 | // 64 KiB D_X swizzle, rounded up to 2 MiB, "matching the title's allocation check" (V). The stock value, | ||
| 15 | // 0x04000000, is what this gives for 3840x2160, which scanout_pool_bytes checks; | ||
| 16 | // - the temporal scene scale (a float, stock 2/3): the render size over the output size; | ||
| 17 | // - the Settings screen's viewport load, which reads a separate 3840x2160 pair: pointed at the SDR mode instead. | ||
| 18 | // VIctory checks the build by the BLAKE3 hash of the file as well; here every patch is checked against the bytes it | ||
| 19 | // replaces, all before any is written, so another build is left alone (and says so). | ||
| 20 | // | ||
| 21 | // VIctory applies it for 2560x1440 output, rendered at 2560x1440 (scale 1) or 1920x1080 (VICTORY_RENDER_1080P, scale | ||
| 22 | // 0.75); so does this, with LEONIDA_RENDER_SCALE (0.25..1, default 1) for the scale. Other outputs are refused: with | ||
| 23 | // the SDR mode set to 1920x1080 the 1.0.2.1 title still makes a 2560x1440 window and 2560x1440 scanout buffers | ||
| 24 | // (measured under gta6rt --run), which a reservation sized for 1920x1080 would not hold. 3840x2160 (the default) | ||
| 25 | // changes nothing. | ||
| 26 | |||
| 27 | #include "display_mode.h" | ||
| 28 | |||
| 29 | #include <algorithm> | ||
| 30 | #include <array> | ||
| 31 | #include <cstdint> | ||
| 32 | #include <cstring> | ||
| 33 | #include <string> | ||
| 34 | #include <vector> | ||
| 35 | |||
| 36 | #ifdef _WIN32 | ||
| 37 | #ifndef NOMINMAX | ||
| 38 | #define NOMINMAX // std::min and std::max, not the macros | ||
| 39 | #endif | ||
| 40 | #include <windows.h> | ||
| 41 | #endif | ||
| 42 | |||
| 43 | namespace leonida::display_profile { | ||
| 44 | |||
| 45 | // RVAs in the 1.0.2.1 retail executable (V native_1440p.rs). | ||
| 46 | inline constexpr std::uint32_t kSdrModeRva = 0x0615c100; | ||
| 47 | inline constexpr std::uint32_t kScanoutReservationRva = 0x0247ad4a; | ||
| 48 | inline constexpr std::uint32_t kSceneScaleRva = 0x028f1e7e; | ||
| 49 | inline constexpr std::uint32_t kSettingsViewportLoadRva = 0x058048d4; | ||
| 50 | |||
| 51 | // Two scanout surfaces of `width` x `height` RGBA8 in the 64 KiB D_X swizzle (128x128 texels a 64 KiB block), each | ||
| 52 | // 64 KiB aligned, together rounded up to 2 MiB. | ||
| 53 | inline std::uint32_t scanout_pool_bytes(std::uint32_t width, std::uint32_t height) { | ||
| 54 | const std::uint64_t blocks = std::uint64_t((width + 127) / 128) * ((height + 127) / 128); | ||
| 55 | const std::uint64_t surface = blocks * 65536; // already a multiple of 64 KiB | ||
| 56 | const std::uint64_t two_mib = std::uint64_t(2) << 20; | ||
| 57 | return std::uint32_t((surface * 2 + two_mib - 1) / two_mib * two_mib); | ||
| 58 | } | ||
| 59 | |||
| 60 | struct Patch { | ||
| 61 | std::uint32_t rva = 0; | ||
| 62 | std::vector<std::uint8_t> stock; // what must be there | ||
| 63 | std::vector<std::uint8_t> bytes; // what goes there | ||
| 64 | const char* what = ""; | ||
| 65 | }; | ||
| 66 | |||
| 67 | struct Plan { | ||
| 68 | DisplayMode output; | ||
| 69 | std::uint32_t render_width = 0, render_height = 0; | ||
| 70 | float scale = 2.0f / 3.0f; | ||
| 71 | std::uint32_t pool = 0; | ||
| 72 | std::vector<Patch> patches; // empty: the stock 3840x2160 profile, or a refused one (`refused` says why) | ||
| 73 | const char* refused = nullptr; | ||
| 74 | }; | ||
| 75 | |||
| 76 | namespace detail { | ||
| 77 | inline void put32(std::vector<std::uint8_t>& out, std::uint32_t v) { | ||
| 78 | for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); | ||
| 79 | } | ||
| 80 | inline void put_float(std::vector<std::uint8_t>& out, float f) { | ||
| 81 | std::uint32_t v = 0; | ||
| 82 | std::memcpy(&v, &f, sizeof v); | ||
| 83 | put32(out, v); | ||
| 84 | } | ||
| 85 | } // namespace detail | ||
| 86 | |||
| 87 | // The patches for an output of `mode` rendered at `render_scale` of it (0: 1). | ||
| 88 | inline Plan plan(const DisplayMode& mode, float render_scale = 0.0f) { | ||
| 89 | Plan p; | ||
| 90 | p.output = mode; | ||
| 91 | const DisplayMode stock; | ||
| 92 | if (mode.width == stock.width && mode.height == stock.height) { | ||
| 93 | p.render_width = 2560; | ||
| 94 | p.render_height = 1440; | ||
| 95 | p.pool = scanout_pool_bytes(stock.width, stock.height); | ||
| 96 | if (render_scale > 0.0f) p.refused = "a render scale is only applied with a 2560x1440 output"; | ||
| 97 | return p; | ||
| 98 | } | ||
| 99 | if (mode.width != 2560 || mode.height != 1440) { | ||
| 100 | p.refused = "only 2560x1440 is an output the title takes (VIctory's profile)"; | ||
| 101 | return p; | ||
| 102 | } | ||
| 103 | p.scale = render_scale > 0.0f ? render_scale : 1.0f; | ||
| 104 | p.render_width = std::uint32_t(float(mode.width) * p.scale); | ||
| 105 | p.render_height = std::uint32_t(float(mode.height) * p.scale); | ||
| 106 | p.pool = scanout_pool_bytes(mode.width, mode.height); | ||
| 107 | |||
| 108 | Patch sdr{kSdrModeRva, {}, {}, "SDR mode"}; | ||
| 109 | for (const std::uint32_t v : {stock.width, stock.height, 60u, 1u}) detail::put32(sdr.stock, v); | ||
| 110 | for (const std::uint32_t v : {mode.width, mode.height, 60u, 1u}) detail::put32(sdr.bytes, v); | ||
| 111 | Patch pool{kScanoutReservationRva, {0xb9}, {0xb9}, "scanout reservation"}; | ||
| 112 | detail::put32(pool.stock, scanout_pool_bytes(stock.width, stock.height)); | ||
| 113 | detail::put32(pool.bytes, p.pool); | ||
| 114 | Patch scale{kSceneScaleRva, {}, {}, "temporal scene scale"}; | ||
| 115 | detail::put_float(scale.stock, 2.0f / 3.0f); | ||
| 116 | detail::put_float(scale.bytes, p.scale); | ||
| 117 | // vmovsd xmm1, qword [rip + disp32]: the Settings viewport's 3840x2160 pair, then the SDR mode's. | ||
| 118 | Patch viewport{kSettingsViewportLoadRva, {0xc5, 0xfb, 0x10, 0x0d, 0x10, 0xf0, 0x13, 0x05}, {0xc5, 0xfb, 0x10, 0x0d}, | ||
| 119 | "Settings viewport load"}; | ||
| 120 | detail::put32(viewport.bytes, std::uint32_t(std::int32_t(kSdrModeRva) - std::int32_t(kSettingsViewportLoadRva + 8))); | ||
| 121 | p.patches = {sdr, pool, scale, viewport}; | ||
| 122 | return p; | ||
| 123 | } | ||
| 124 | |||
| 125 | // True when every patch's stock bytes are in the image, read through `at(rva, length)` (a pointer to that many bytes | ||
| 126 | // of the image, or null past it); else false with `*error` set. | ||
| 127 | template <class Access> | ||
| 128 | bool check(Access&& at, const Plan& p, std::string* error) { | ||
| 129 | for (const Patch& patch : p.patches) { | ||
| 130 | const std::uint8_t* there = at(patch.rva, patch.stock.size()); | ||
| 131 | if (!there || std::memcmp(there, patch.stock.data(), patch.stock.size()) != 0) { | ||
| 132 | if (error) *error = std::string("the ") + patch.what + " is not the 1.0.2.1 executable's"; | ||
| 133 | return false; | ||
| 134 | } | ||
| 135 | } | ||
| 136 | return true; | ||
| 137 | } | ||
| 138 | |||
| 139 | // check(), then every patch written through `at`. Nothing is written when the check fails. | ||
| 140 | template <class Access> | ||
| 141 | bool apply(Access&& at, const Plan& p, std::string* error) { | ||
| 142 | if (!check(at, p, error)) return false; | ||
| 143 | for (const Patch& patch : p.patches) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); | ||
| 144 | return true; | ||
| 145 | } | ||
| 146 | |||
| 147 | #ifdef _WIN32 | ||
| 148 | // apply() on a mapped image of `size` bytes at `base`, each write made writable for its length and its protection put | ||
| 149 | // back after. | ||
| 150 | inline bool apply_to_image(std::uint8_t* base, std::uint32_t size, const Plan& p, std::string* error) { | ||
| 151 | const auto at = [&](std::uint32_t rva, std::size_t length) -> std::uint8_t* { | ||
| 152 | return std::uint64_t(rva) + length <= size ? base + rva : nullptr; | ||
| 153 | }; | ||
| 154 | if (!check(at, p, error)) return false; | ||
| 155 | for (const Patch& patch : p.patches) { | ||
| 156 | std::uint8_t* where = at(patch.rva, patch.bytes.size()); | ||
| 157 | DWORD old = 0; | ||
| 158 | if (!VirtualProtect(where, patch.bytes.size(), PAGE_EXECUTE_READWRITE, &old)) { | ||
| 159 | if (error) *error = std::string("the ") + patch.what + " could not be made writable"; | ||
| 160 | return false; | ||
| 161 | } | ||
| 162 | std::memcpy(where, patch.bytes.data(), patch.bytes.size()); | ||
| 163 | VirtualProtect(where, patch.bytes.size(), old, &old); | ||
| 164 | FlushInstructionCache(GetCurrentProcess(), where, patch.bytes.size()); | ||
| 165 | } | ||
| 166 | return true; | ||
| 167 | } | ||
| 168 | #endif | ||
| 169 | |||
| 170 | } // namespace leonida::display_profile | ||
diff --git a/runtime/src/frame_meter.h b/runtime/src/frame_meter.h deleted file mode 100644 index cc6620b34..000000000 --- a/runtime/src/frame_meter.h +++ /dev/null | |||
| @@ -1,97 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // The frame rate in the title's window caption: "Leonida | <fps> fps <ms> ms/frame", refreshed once a second. | ||
| 4 | // | ||
| 5 | // Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; | ||
| 6 | // victory/crates/victory-gpu/src/host.rs `Meter::frame` and the "victory-caption" thread): the present path only | ||
| 7 | // counts the frame, and a thread of the runtime's own sets the caption, so presenting never waits for the window's | ||
| 8 | // thread. VIctory computes its figures at the first present a second after the last report; here the caption thread | ||
| 9 | // samples once a second and measures the frames between the newest present before its previous sample and the newest | ||
| 10 | // present now, so a figure always spans whole frames. A second without a frame keeps the previous figures until the | ||
| 11 | // frame being waited for has taken longer than they say, and then shows that wait ("0 fps 2400.0 ms/frame"), where | ||
| 12 | // VIctory's caption would stand still. No Windows headers: frame_meter_test drives it with made-up times. | ||
| 13 | |||
| 14 | #include <atomic> | ||
| 15 | #include <cstdint> | ||
| 16 | #include <cstdio> | ||
| 17 | #include <string> | ||
| 18 | |||
| 19 | namespace leonida { | ||
| 20 | |||
| 21 | class FrameMeter { | ||
| 22 | public: | ||
| 23 | // A frame was presented at `now_ns` (one monotonic clock, nanoseconds). Any thread; lock-free. | ||
| 24 | void presented(std::uint64_t now_ns) { | ||
| 25 | std::uint64_t none = 0; | ||
| 26 | first_ns_.compare_exchange_strong(none, now_ns, std::memory_order_relaxed); | ||
| 27 | last_ns_.store(now_ns, std::memory_order_relaxed); | ||
| 28 | count_.fetch_add(1, std::memory_order_release); | ||
| 29 | } | ||
| 30 | struct Reading { | ||
| 31 | std::uint64_t count = 0; // frames presented so far | ||
| 32 | std::uint64_t first_ns = 0; // when the first was | ||
| 33 | std::uint64_t last_ns = 0; // when the newest was | ||
| 34 | }; | ||
| 35 | Reading read() const { | ||
| 36 | Reading r; | ||
| 37 | r.count = count_.load(std::memory_order_acquire); | ||
| 38 | r.first_ns = first_ns_.load(std::memory_order_relaxed); | ||
| 39 | r.last_ns = last_ns_.load(std::memory_order_relaxed); | ||
| 40 | return r; | ||
| 41 | } | ||
| 42 | |||
| 43 | private: | ||
| 44 | std::atomic<std::uint64_t> count_{0}; | ||
| 45 | std::atomic<std::uint64_t> first_ns_{0}; | ||
| 46 | std::atomic<std::uint64_t> last_ns_{0}; | ||
| 47 | }; | ||
| 48 | |||
| 49 | struct FrameFigures { | ||
| 50 | double fps = 0.0; | ||
| 51 | double ms = 0.0; // per frame | ||
| 52 | }; | ||
| 53 | |||
| 54 | // One sampling thread's view of a FrameMeter (see the top comment). | ||
| 55 | class FrameRateSampler { | ||
| 56 | public: | ||
| 57 | // False while there is no figure yet: no frame, or one frame that has not been waited on for a second. | ||
| 58 | bool sample(const FrameMeter::Reading& r, std::uint64_t now_ns, FrameFigures* out) { | ||
| 59 | if (r.count == 0) return false; | ||
| 60 | if (count_ == 0) { // the first sample that sees a frame: measure from the first one | ||
| 61 | count_ = 1; | ||
| 62 | last_ns_ = r.first_ns; | ||
| 63 | } | ||
| 64 | if (r.count > count_ && r.last_ns > last_ns_) { | ||
| 65 | const double frames = double(r.count - count_); | ||
| 66 | const double span_ns = double(r.last_ns - last_ns_); | ||
| 67 | figures_ = {frames * 1e9 / span_ns, span_ns / 1e6 / frames}; | ||
| 68 | have_ = true; | ||
| 69 | count_ = r.count; | ||
| 70 | last_ns_ = r.last_ns; | ||
| 71 | } else if (now_ns > r.last_ns) { | ||
| 72 | // No new frame: the one being waited for, once it has taken longer than the last figures say. | ||
| 73 | const double waited_ms = double(now_ns - r.last_ns) / 1e6; | ||
| 74 | if ((have_ && waited_ms > figures_.ms) || (!have_ && waited_ms >= 1000.0)) { | ||
| 75 | figures_ = {1000.0 / waited_ms, waited_ms}; | ||
| 76 | have_ = true; | ||
| 77 | } | ||
| 78 | } | ||
| 79 | if (have_ && out) *out = figures_; | ||
| 80 | return have_; | ||
| 81 | } | ||
| 82 | |||
| 83 | private: | ||
| 84 | std::uint64_t count_ = 0; | ||
| 85 | std::uint64_t last_ns_ = 0; | ||
| 86 | FrameFigures figures_{}; | ||
| 87 | bool have_ = false; | ||
| 88 | }; | ||
| 89 | |||
| 90 | // "Leonida | 60 fps 16.7 ms/frame" (V host.rs: `{fps:.0} fps {ms:.1} ms/frame`). | ||
| 91 | inline std::string caption_text(const FrameFigures& f) { | ||
| 92 | char text[96]; | ||
| 93 | std::snprintf(text, sizeof text, "Leonida | %.0f fps %.1f ms/frame", f.fps, f.ms); | ||
| 94 | return text; | ||
| 95 | } | ||
| 96 | |||
| 97 | } // namespace leonida | ||
diff --git a/runtime/src/frame_step.h b/runtime/src/frame_step.h deleted file mode 100644 index 690eee018..000000000 --- a/runtime/src/frame_step.h +++ /dev/null | |||
| @@ -1,184 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // The title's time step from the measured frame time at any frame rate: LEONIDA_TIME_STEP (default `measured`; | ||
| 4 | // `stock` keeps the title's own step), applied to the mapped executable before any of its code runs. | ||
| 5 | // | ||
| 6 | // How the 1.0.2.1 title makes its step (measured by static analysis and under VIctory; RVAs below, in the style of | ||
| 7 | // display_profile.h): once a frame its timer takes the frame's real time from QueryPerformanceCounter (the previous | ||
| 8 | // count's difference times 1 / QueryPerformanceFrequency) and gives every one of its time sets (game time, game time | ||
| 9 | // not paused, camera, ...: a millisecond count, a frame count and the step in seconds) a step made from it: | ||
| 10 | // | ||
| 11 | // step = max(nominal, min(1/15 s, measured)) * time scale (re-clamped to [min step, 1/15 s] when scaled) | ||
| 12 | // | ||
| 13 | // `nominal` is one frame at the frame rate the title aims for (its settings' frame-rate cap, else the display's refresh | ||
| 14 | // over the vsync interval, else 30): 1/30 s. The cap is a 1/15 s constant. So the step is real only between 15 and 30 frames a second: above | ||
| 15 | // 30 every frame still steps 1/30 s and the world runs fps/30 times too fast (the doubled speed seen on the console when | ||
| 16 | // a glitch doubles the frame rate), below 15 every frame steps 1/15 s and the world runs at fps/15 of real time | ||
| 17 | // (0.13 at VIctory's 2 fps). The nominal floor is taken while a switch of the timer is set, which the retail build's | ||
| 18 | // init sets (the same switch picks where in the frame the timer runs); without it the floor is the timer's own minimum | ||
| 19 | // step, 1/3000 s, which its init writes. | ||
| 20 | // | ||
| 21 | // The patch moves two loads in each of the timer's two step computations (the time sets' and the camera's), keeping | ||
| 22 | // the code: the floor reads the timer's minimum step instead of the nominal frame time, and the cap reads the timer's | ||
| 23 | // own 1.0 constant instead of 1/15 s. The step is then the measured frame time between 1/3000 s and 1 s: real time | ||
| 24 | // from 1 to 3000 frames a second. Each load is checked against its stock bytes, and the two targets against theirs, | ||
| 25 | // before anything is written; another build is left alone (and says so). Frames longer than 1 s (a loading hitch) | ||
| 26 | // still step 1 s. The approach is BlueShell's for the same class of bug (the measured frame time at the engine's step, | ||
| 27 | // its commit 1a429f6); the check-then-patch shape is display_profile.h's. | ||
| 28 | // | ||
| 29 | // Measured under VIctory, the same four loads written into the running title (game time against the title's own | ||
| 30 | // unclipped real-time set and the wall clock): stock, 30 fps menus 1.00, a 42 fps loading screen 1.54, the world at | ||
| 31 | // 1.5 fps 0.15; patched, 30 fps 1.00, 70 fps 1.00, the world at 1.6 fps 1.00 over every frame under 1 s. | ||
| 32 | // | ||
| 33 | // Not changed: what counts frames instead of reading the step. The game time's frame count (the u32 after its | ||
| 34 | // millisecond count) has about 690 readers, nearly all "once a frame" or "N frames since" bookkeeping; a few turn | ||
| 35 | // frames into time and stay frame-paced at any rate, e.g. a blend over 15 frames (+0x8eee32: frames since times the | ||
| 36 | // 1/15 constant, at most 1) and a check of frames since times the current step against 0.5 s (+0x244b584). | ||
| 37 | |||
| 38 | #include <cstdint> | ||
| 39 | #include <cstring> | ||
| 40 | #include <string> | ||
| 41 | #include <vector> | ||
| 42 | |||
| 43 | #ifdef _WIN32 | ||
| 44 | #ifndef NOMINMAX | ||
| 45 | #define NOMINMAX | ||
| 46 | #endif | ||
| 47 | #include <windows.h> | ||
| 48 | #endif | ||
| 49 | |||
| 50 | namespace leonida::frame_step { | ||
| 51 | |||
| 52 | // RVAs in the 1.0.2.1 retail executable. Each load is `vmovss xmmN, dword [rip + disp32]` (C5 FA 10 modrm disp32), | ||
| 53 | // 8 bytes long. | ||
| 54 | inline constexpr std::uint32_t kTimeSetCapLoadRva = 0x02226045; // xmm3 = 1/15 s | ||
| 55 | inline constexpr std::uint32_t kTimeSetFloorLoadRva = 0x0222605a; // xmm4 = nominal frame time | ||
| 56 | inline constexpr std::uint32_t kCameraCapLoadRva = 0x02226833; // xmm0 = 1/15 s | ||
| 57 | inline constexpr std::uint32_t kCameraFloorLoadRva = 0x02226854; // xmm1 = nominal frame time | ||
| 58 | // What they read: the 1/15 s constant (.rdata), the nominal frame time (.data, 1/30 until the settings set it). | ||
| 59 | inline constexpr std::uint32_t kStockCapRva = 0x06159ec0; | ||
| 60 | inline constexpr std::uint32_t kNominalRva = 0x06849844; | ||
| 61 | // What they read after the patch: the timer's 1.0 constant (.rdata) and its minimum step (.data: 1/30 in the file, | ||
| 62 | // 1/3000 s once the timer's init has run, before its first step). | ||
| 63 | inline constexpr std::uint32_t kOneRva = 0x05fc6ed8; | ||
| 64 | inline constexpr std::uint32_t kMinStepRva = 0x06847660; | ||
| 65 | |||
| 66 | inline constexpr std::uint32_t kLoadLength = 8; | ||
| 67 | |||
| 68 | struct Patch { | ||
| 69 | std::uint32_t rva = 0; | ||
| 70 | std::vector<std::uint8_t> stock; // what must be there | ||
| 71 | std::vector<std::uint8_t> bytes; // what goes there (empty: only checked) | ||
| 72 | const char* what = ""; | ||
| 73 | }; | ||
| 74 | |||
| 75 | namespace detail { | ||
| 76 | inline void put32(std::vector<std::uint8_t>& out, std::uint32_t v) { | ||
| 77 | for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); | ||
| 78 | } | ||
| 79 | inline std::vector<std::uint8_t> float_bytes(float f) { | ||
| 80 | std::uint32_t v = 0; | ||
| 81 | std::memcpy(&v, &f, sizeof v); | ||
| 82 | std::vector<std::uint8_t> out; | ||
| 83 | put32(out, v); | ||
| 84 | return out; | ||
| 85 | } | ||
| 86 | // `vmovss xmm<reg>, dword [rip + disp32]` at `at`, reading `target`. | ||
| 87 | inline std::vector<std::uint8_t> load(std::uint32_t at, std::uint8_t reg, std::uint32_t target) { | ||
| 88 | std::vector<std::uint8_t> out{0xc5, 0xfa, 0x10, std::uint8_t(0x05 | (reg << 3))}; | ||
| 89 | put32(out, std::uint32_t(std::int32_t(target) - std::int32_t(at + kLoadLength))); | ||
| 90 | return out; | ||
| 91 | } | ||
| 92 | } // namespace detail | ||
| 93 | |||
| 94 | // The patches, in the order they are checked: the two targets' values (checked only), then the four loads. | ||
| 95 | inline std::vector<Patch> plan() { | ||
| 96 | using detail::load; | ||
| 97 | std::vector<Patch> p; | ||
| 98 | p.push_back({kOneRva, detail::float_bytes(1.0f), {}, "timer's 1.0 constant"}); | ||
| 99 | p.push_back({kMinStepRva, detail::float_bytes(1.0f / 30.0f), {}, "timer's minimum step"}); | ||
| 100 | p.push_back({kTimeSetCapLoadRva, load(kTimeSetCapLoadRva, 3, kStockCapRva), load(kTimeSetCapLoadRva, 3, kOneRva), | ||
| 101 | "time sets' step cap"}); | ||
| 102 | p.push_back({kTimeSetFloorLoadRva, load(kTimeSetFloorLoadRva, 4, kNominalRva), | ||
| 103 | load(kTimeSetFloorLoadRva, 4, kMinStepRva), "time sets' step floor"}); | ||
| 104 | p.push_back({kCameraCapLoadRva, load(kCameraCapLoadRva, 0, kStockCapRva), load(kCameraCapLoadRva, 0, kOneRva), | ||
| 105 | "camera step cap"}); | ||
| 106 | p.push_back({kCameraFloorLoadRva, load(kCameraFloorLoadRva, 1, kNominalRva), | ||
| 107 | load(kCameraFloorLoadRva, 1, kMinStepRva), "camera step floor"}); | ||
| 108 | return p; | ||
| 109 | } | ||
| 110 | |||
| 111 | // LEONIDA_TIME_STEP: unset, empty or `measured` (any case): patch; `stock`, `0` or `off`: the title's own step. | ||
| 112 | // Anything else is refused (`*known` false) and patches as the default does. | ||
| 113 | inline bool wanted(const char* value, bool* known = nullptr) { | ||
| 114 | if (known) *known = true; | ||
| 115 | if (!value || !*value) return true; | ||
| 116 | std::string v(value); | ||
| 117 | for (char& c : v) c = char(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c); | ||
| 118 | if (v == "measured" || v == "1" || v == "on") return true; | ||
| 119 | if (v == "stock" || v == "0" || v == "off") return false; | ||
| 120 | if (known) *known = false; | ||
| 121 | return true; | ||
| 122 | } | ||
| 123 | |||
| 124 | // True when every patch's stock bytes are in the image, read through `at(rva, length)` (a pointer to that many bytes | ||
| 125 | // of the image, or null past it); else false with `*error` set. | ||
| 126 | template <class Access> | ||
| 127 | bool check(Access&& at, const std::vector<Patch>& patches, std::string* error) { | ||
| 128 | for (const Patch& patch : patches) { | ||
| 129 | const std::uint8_t* there = at(patch.rva, patch.stock.size()); | ||
| 130 | if (!there || std::memcmp(there, patch.stock.data(), patch.stock.size()) != 0) { | ||
| 131 | if (error) *error = std::string("the ") + patch.what + " is not the 1.0.2.1 executable's"; | ||
| 132 | return false; | ||
| 133 | } | ||
| 134 | } | ||
| 135 | return true; | ||
| 136 | } | ||
| 137 | |||
| 138 | // check(), then every patch with bytes written through `at`. Nothing is written when the check fails. | ||
| 139 | template <class Access> | ||
| 140 | bool apply(Access&& at, const std::vector<Patch>& patches, std::string* error) { | ||
| 141 | if (!check(at, patches, error)) return false; | ||
| 142 | for (const Patch& patch : patches) | ||
| 143 | if (!patch.bytes.empty()) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); | ||
| 144 | return true; | ||
| 145 | } | ||
| 146 | |||
| 147 | #ifdef _WIN32 | ||
| 148 | // apply() on a mapped image of `size` bytes at `base`: every place is made writable first (or nothing is written), then | ||
| 149 | // all are written, then the protections are put back in reverse order (two loads share a page: the second | ||
| 150 | // VirtualProtect saw the first one's writable protection) and the instruction cache flushed. All the loads or none: a | ||
| 151 | // floor without the cap (or the other way round) would still not be real time. | ||
| 152 | inline bool apply_to_image(std::uint8_t* base, std::uint32_t size, const std::vector<Patch>& patches, | ||
| 153 | std::string* error) { | ||
| 154 | const auto at = [&](std::uint32_t rva, std::size_t length) -> std::uint8_t* { | ||
| 155 | return std::uint64_t(rva) + length <= size ? base + rva : nullptr; | ||
| 156 | }; | ||
| 157 | if (!check(at, patches, error)) return false; | ||
| 158 | std::vector<DWORD> old(patches.size(), 0); | ||
| 159 | for (std::size_t i = 0; i < patches.size(); ++i) { | ||
| 160 | const Patch& patch = patches[i]; | ||
| 161 | if (patch.bytes.empty()) continue; | ||
| 162 | if (!VirtualProtect(at(patch.rva, patch.bytes.size()), patch.bytes.size(), PAGE_EXECUTE_READWRITE, &old[i])) { | ||
| 163 | for (std::size_t j = i; j-- > 0;) | ||
| 164 | if (!patches[j].bytes.empty()) | ||
| 165 | VirtualProtect(at(patches[j].rva, patches[j].bytes.size()), patches[j].bytes.size(), old[j], &old[j]); | ||
| 166 | if (error) *error = std::string("the ") + patch.what + " could not be made writable"; | ||
| 167 | return false; | ||
| 168 | } | ||
| 169 | } | ||
| 170 | for (const Patch& patch : patches) | ||
| 171 | if (!patch.bytes.empty()) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); | ||
| 172 | for (std::size_t i = patches.size(); i-- > 0;) { | ||
| 173 | const Patch& patch = patches[i]; | ||
| 174 | if (patch.bytes.empty()) continue; | ||
| 175 | std::uint8_t* where = at(patch.rva, patch.bytes.size()); | ||
| 176 | DWORD ignored = 0; | ||
| 177 | VirtualProtect(where, patch.bytes.size(), old[i], &ignored); | ||
| 178 | FlushInstructionCache(GetCurrentProcess(), where, patch.bytes.size()); | ||
| 179 | } | ||
| 180 | return true; | ||
| 181 | } | ||
| 182 | #endif | ||
| 183 | |||
| 184 | } // namespace leonida::frame_step | ||
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b35ffc934..acfa590f8 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -762,21 +762,4 @@ inline bool decode(const BufferWords& words, Buffer& out) { | |||
| 762 | return true; | 762 | return true; |
| 763 | } | 763 | } |
| 764 | 764 | ||
| 765 | // The V# of a constant-buffer view: `size` bytes at `address` as records of one float4 (16 bytes), checked by index. | ||
| 766 | // The title's console-compiled shaders index a constant buffer's float4 rows with `buffer_load_dwordx4 ... idxen` | ||
| 767 | // and the row number as the index (a Scaleform batch vertex shader reads row 4 * batch + k of its constant buffer | ||
| 768 | // that way), which only reaches row k with a 16-byte stride: a raw view (stride 0) gives every row the first one. | ||
| 769 | // Scalar loads still see `size` bytes (s_buffer_load is bounded at NUM_RECORDS * STRIDE), offset loads (offen, | ||
| 770 | // index 0) reach the whole buffer, and index loads stop at the last row (OOB_SELECT structured, index only). D3D12 | ||
| 771 | // sizes constant buffers in 256-byte units; a size that is not a multiple of 16 keeps its last partial row. | ||
| 772 | inline Buffer constant_buffer_descriptor(std::uint64_t address, std::uint32_t size) { | ||
| 773 | Buffer buffer{}; | ||
| 774 | buffer.address = address; | ||
| 775 | buffer.stride = 16; | ||
| 776 | buffer.num_records = size / 16 + (size % 16 ? 1 : 0); | ||
| 777 | buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT | ||
| 778 | buffer.oob_select = OobSelect::structured; | ||
| 779 | return buffer; | ||
| 780 | } | ||
| 781 | |||
| 782 | } // namespace leonida::gfx10 | 765 | } // namespace leonida::gfx10 |
diff --git a/runtime/src/gfx10_tiling.h b/runtime/src/gfx10_tiling.h index 71dcd4343..d869d1102 100644 --- a/runtime/src/gfx10_tiling.h +++ b/runtime/src/gfx10_tiling.h | |||
| @@ -1,15 +1,11 @@ | |||
| 1 | #pragma once | 1 | #pragma once |
| 2 | 2 | ||
| 3 | #include <algorithm> | ||
| 4 | #include <array> | ||
| 5 | #include <bit> | 3 | #include <bit> |
| 6 | #include <cstddef> | 4 | #include <cstddef> |
| 7 | #include <cstdint> | 5 | #include <cstdint> |
| 8 | #include <cstring> | 6 | #include <cstring> |
| 9 | #include <limits> | 7 | #include <limits> |
| 10 | #include <span> | 8 | #include <span> |
| 11 | #include <utility> | ||
| 12 | #include <vector> | ||
| 13 | 9 | ||
| 14 | namespace leonida::gfx10 { | 10 | namespace leonida::gfx10 { |
| 15 | 11 | ||
| @@ -159,618 +155,4 @@ private: | |||
| 159 | std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0; | 155 | std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0; |
| 160 | }; | 156 | }; |
| 161 | 157 | ||
| 162 | // ---- Whole textures: mips, mip tails, array slices, 3D, depth/stencil planes ---------------------------------------- | ||
| 163 | // | ||
| 164 | // Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork), victory-formats texture.rs, which | ||
| 165 | // follows AMD's address library (addrlib, as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement | ||
| 166 | // and mip tails from gfx10addrlib.cpp and addrlib2.cpp, the 256-byte micro tile patterns from gfx10SwizzlePattern.h, | ||
| 167 | // the RB+ tables as on RDNA2). addrlib carries this notice: | ||
| 168 | // | ||
| 169 | // Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. | ||
| 170 | // SPDX-License-Identifier: MIT | ||
| 171 | // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated | ||
| 172 | // documentation files (the "Software"), to deal in the Software without restriction, including without limitation | ||
| 173 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and | ||
| 174 | // to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above | ||
| 175 | // copyright notice and this permission notice shall be included in all copies or substantial portions of the | ||
| 176 | // Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. | ||
| 177 | // | ||
| 178 | // Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth slab | ||
| 179 | // of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) at | ||
| 180 | // offset 0, mip 0 last. Addressable: linear, and the S and D modes without pipe/bank XOR (256 B, 4 KiB, 64 KiB, thin | ||
| 181 | // and thick); SW_64KB_R_X for one-mip, one-slice, one-sample 2D textures of 2-, 4- or 8-byte elements (Series X or S | ||
| 182 | // pipe tables). Other XOR modes and MSAA layouts are sized but have no address equation (addressable() is false). | ||
| 183 | |||
| 184 | // A swizzle mode by its hardware number (addrlib's ADDR_SW_* order). | ||
| 185 | namespace swizzle { | ||
| 186 | inline constexpr std::uint32_t linear = 0, sw_256b_s = 1, sw_256b_d = 2, sw_4kb_s = 5, sw_4kb_d = 6, sw_64kb_s = 9, | ||
| 187 | sw_64kb_d = 10, sw_64kb_s_t = 17, sw_64kb_d_t = 18, sw_4kb_s_x = 21, sw_4kb_d_x = 22, | ||
| 188 | sw_4kb_r_x = 23, sw_64kb_z_x = 24, sw_64kb_s_x = 25, sw_64kb_d_x = 26, | ||
| 189 | sw_64kb_r_x = 27; | ||
| 190 | // log2 of the block size in bytes (0 for linear), or -1 for a mode GFX10 does not have. | ||
| 191 | constexpr int block_log2(std::uint32_t mode) { | ||
| 192 | switch (mode) { | ||
| 193 | case 0: return 0; | ||
| 194 | case 1: case 2: return 8; | ||
| 195 | case 5: case 6: case 21: case 22: case 23: return 12; | ||
| 196 | case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; | ||
| 197 | default: return -1; | ||
| 198 | } | ||
| 199 | } | ||
| 200 | constexpr bool standard(std::uint32_t mode) { return mode == 1 || mode == 5 || mode == 9 || mode == 17 || mode == 21 || mode == 25; } | ||
| 201 | constexpr bool display(std::uint32_t mode) { return mode == 2 || mode == 6 || mode == 10 || mode == 18 || mode == 22 || mode == 26; } | ||
| 202 | constexpr bool z_order(std::uint32_t mode) { return mode == 24; } | ||
| 203 | // Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. | ||
| 204 | constexpr bool xor_mode(std::uint32_t mode) { return mode >= 16; } | ||
| 205 | } // namespace swizzle | ||
| 206 | |||
| 207 | enum class Dimension : std::uint8_t { tex1d, tex2d, tex3d }; | ||
| 208 | |||
| 209 | // One plane of a texture. | ||
| 210 | struct LayoutDesc { | ||
| 211 | Dimension dimension = Dimension::tex2d; | ||
| 212 | std::uint32_t width = 1, height = 1; // texels | ||
| 213 | std::uint32_t depth = 1; // depth of a 3D texture, else the array size | ||
| 214 | std::uint32_t mips = 1; | ||
| 215 | std::uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 | ||
| 216 | std::uint32_t block = 1; // texels per element side: 1, or 4 for block compression | ||
| 217 | std::uint32_t samples = 1; | ||
| 218 | std::uint32_t swizzle = swizzle::linear; | ||
| 219 | }; | ||
| 220 | |||
| 221 | // Where one mip lives inside a slice. | ||
| 222 | struct MipLayout { | ||
| 223 | std::uint32_t width = 0, height = 0, depth = 0; // elements (depth 1 unless the texture is 3D) | ||
| 224 | // Padded size in elements: whole blocks, or the tail's share of one. | ||
| 225 | std::uint32_t pitch = 0, rows = 0, depth_pitch = 0; | ||
| 226 | std::uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) | ||
| 227 | // In the mip tail: byte offset inside the tail block and the element position the mip starts at. | ||
| 228 | bool in_tail = false; | ||
| 229 | std::uint32_t tail_offset = 0, tail_x = 0, tail_y = 0; | ||
| 230 | }; | ||
| 231 | |||
| 232 | class TextureLayout { | ||
| 233 | public: | ||
| 234 | // False for a description that makes no texture (zero or oversized extent, a bad element size, a mode this | ||
| 235 | // dimension cannot use, too many mips). `series_s` picks the Series S pipe tables of SW_64KB_R_X. | ||
| 236 | static bool make(const LayoutDesc& d, bool series_s, TextureLayout& out) { | ||
| 237 | const int block_log2 = swizzle::block_log2(d.swizzle); | ||
| 238 | const auto in = [](std::uint32_t v) { return v >= 1 && v <= kMaxExtent; }; | ||
| 239 | const bool valid = | ||
| 240 | block_log2 >= 0 && in(d.width) && in(d.height) && in(d.depth) && d.mips >= 1 && d.mips <= kMaxMips && | ||
| 241 | std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && (d.block == 1 || d.block == 4) && | ||
| 242 | std::has_single_bit(d.samples) && d.samples <= 8 && | ||
| 243 | (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && | ||
| 244 | (d.dimension != Dimension::tex1d || d.height == 1) && | ||
| 245 | (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || d.swizzle == 17 || | ||
| 246 | d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); | ||
| 247 | if (!valid) return false; | ||
| 248 | TextureLayout layout; | ||
| 249 | if (block_log2 == 0) layout.linear(d); | ||
| 250 | else layout.tiled(d, std::uint32_t(block_log2), series_s); | ||
| 251 | out = std::move(layout); | ||
| 252 | return true; | ||
| 253 | } | ||
| 254 | |||
| 255 | const LayoutDesc& desc() const { return desc_; } | ||
| 256 | // Block dimensions in elements (linear: the pitch alignment, 1, 1). | ||
| 257 | const std::array<std::uint32_t, 3>& block() const { return block_; } | ||
| 258 | bool thick() const { return thick_; } // 3D blocks span block()[2] depth slices (GFX10 3D S and D modes) | ||
| 259 | // Array slices, depth slabs of block()[2] slices (thick), or depth slices (thin and linear 3D). | ||
| 260 | std::uint32_t slices() const { return slices_; } | ||
| 261 | std::uint64_t slice_size() const { return slice_size_; } // bytes of one slice: its whole mip chain | ||
| 262 | std::uint64_t size() const { return size_; } | ||
| 263 | std::uint64_t alignment() const { return alignment_; } | ||
| 264 | std::uint32_t first_tail_mip() const { return first_tail_mip_; } // mips().size() without a tail | ||
| 265 | const std::vector<MipLayout>& mips() const { return mips_; } | ||
| 266 | |||
| 267 | // Whether offsets and copies have a known address equation. | ||
| 268 | bool addressable() const { return desc_.swizzle == swizzle::linear || !pattern_[0].empty(); } | ||
| 269 | |||
| 270 | // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`; false outside the mip or for a | ||
| 271 | // layout that is not addressable. | ||
| 272 | bool offset(std::uint32_t mip, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t& out) const { | ||
| 273 | if (mip >= mips_.size() || !addressable()) return false; | ||
| 274 | const MipLayout& m = mips_[mip]; | ||
| 275 | const std::uint32_t depth = desc_.dimension == Dimension::tex3d ? m.depth : slices_; | ||
| 276 | if (x >= m.width || y >= m.height || z >= depth) return false; | ||
| 277 | const auto [slice, inner] = split(z); | ||
| 278 | const std::uint64_t base = std::uint64_t(slice) * slice_size_ + m.offset; | ||
| 279 | if (desc_.swizzle == swizzle::linear) { | ||
| 280 | out = base + (std::uint64_t(y) * m.pitch + x) * desc_.element_bytes; | ||
| 281 | } else if (desc_.swizzle == swizzle::sw_64kb_r_x) { | ||
| 282 | out = render_xor_offset(m, x, y); | ||
| 283 | } else { | ||
| 284 | out = base + row(m, y, inner) + column(m, x); | ||
| 285 | } | ||
| 286 | return true; | ||
| 287 | } | ||
| 288 | |||
| 289 | // The bytes from the texture's start that mip `first` and the smaller ones take: the smaller a mip, the nearer | ||
| 290 | // the start it lies (a title that streams textures has memory for the smaller mips only). All of the layout | ||
| 291 | // where slices follow each other. | ||
| 292 | std::uint64_t bytes_from(std::uint32_t first) const { | ||
| 293 | if (first == 0 || slices_ != 1 || thick_ || desc_.dimension == Dimension::tex3d || desc_.samples != 1 || | ||
| 294 | first >= desc_.mips) | ||
| 295 | return size_; | ||
| 296 | std::uint64_t most = 0; | ||
| 297 | for (std::size_t i = first; i < mips_.size(); ++i) { | ||
| 298 | const MipLayout& m = mips_[i]; | ||
| 299 | most = std::max(most, m.in_tail ? alignment_ | ||
| 300 | : m.offset + std::uint64_t(m.pitch) * m.rows * desc_.element_bytes); | ||
| 301 | } | ||
| 302 | return std::min(most ? most : size_, size_); | ||
| 303 | } | ||
| 304 | |||
| 305 | // One subresource out of tiled memory (the whole texture, size() bytes, or bytes_from(mip)) into linear rows: mip | ||
| 306 | // `mip` of array slice `slice` (3D: every depth slice of the mip, `slice` 0). Rows are `row_pitch` bytes apart, | ||
| 307 | // depth slices `depth_pitch`. False, with nothing written past what was copied, for a bad mip or slice, a layout | ||
| 308 | // that is not addressable, or buffers too small. | ||
| 309 | bool detile(std::span<const std::byte> tiled, std::uint32_t mip, std::uint32_t slice, std::span<std::byte> linear, | ||
| 310 | std::size_t row_pitch, std::size_t depth_pitch) const { | ||
| 311 | return walk(tiled.size(), mip, slice, linear.size(), row_pitch, depth_pitch, | ||
| 312 | [&](std::size_t t, std::size_t l, std::size_t n) { std::memcpy(linear.data() + l, tiled.data() + t, n); }); | ||
| 313 | } | ||
| 314 | |||
| 315 | // The reverse of detile: linear rows into tiled memory. | ||
| 316 | bool tile(std::span<std::byte> tiled, std::uint32_t mip, std::uint32_t slice, std::span<const std::byte> linear, | ||
| 317 | std::size_t row_pitch, std::size_t depth_pitch) const { | ||
| 318 | return walk(tiled.size(), mip, slice, linear.size(), row_pitch, depth_pitch, | ||
| 319 | [&](std::size_t t, std::size_t l, std::size_t n) { std::memcpy(tiled.data() + t, linear.data() + l, n); }); | ||
| 320 | } | ||
| 321 | |||
| 322 | private: | ||
| 323 | static constexpr std::uint32_t kMaxMips = 16; | ||
| 324 | // GFX10's image descriptors hold at most 16384 texels per side; the bound also keeps every size computed here in | ||
| 325 | // range for values a title passes unchecked. | ||
| 326 | static constexpr std::uint32_t kMaxExtent = 1u << 14; | ||
| 327 | |||
| 328 | static constexpr std::uint32_t div_ceil(std::uint32_t a, std::uint32_t b) { return (a + b - 1) / b; } | ||
| 329 | static constexpr std::uint32_t round_up(std::uint32_t a, std::uint32_t b) { return div_ceil(a, b) * b; } | ||
| 330 | // Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), | ||
| 331 | // then round up to whole elements. | ||
| 332 | static constexpr std::uint32_t dim(std::uint32_t texels, std::uint32_t mip, std::uint32_t block) { | ||
| 333 | return div_ceil(std::max(texels >> mip, 1u), block); | ||
| 334 | } | ||
| 335 | // Elements along one side for placement (padding, tail, offsets): addrlib halves mip 0's elements rounding up, | ||
| 336 | // which can be one more than dim() for odd sizes. | ||
| 337 | static constexpr std::uint32_t padded_dim(std::uint32_t texels, std::uint32_t mip, std::uint32_t block) { | ||
| 338 | return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); | ||
| 339 | } | ||
| 340 | |||
| 341 | // 256-byte micro tile patterns by log2 of the element size: for each address bit, the element coordinate bit it | ||
| 342 | // takes, "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes), from addrlib's | ||
| 343 | // GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS; larger blocks add Y, X (thin) or Y, X, Z | ||
| 344 | // (thick) in turn. | ||
| 345 | static constexpr const char* kMicro[3][5] = { | ||
| 346 | {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, | ||
| 347 | {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, | ||
| 348 | {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, | ||
| 349 | }; | ||
| 350 | static constexpr std::uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; | ||
| 351 | static constexpr std::uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; | ||
| 352 | static constexpr std::uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; | ||
| 353 | |||
| 354 | // For each axis, the address bit each coordinate bit lands on. | ||
| 355 | static std::array<std::vector<std::uint32_t>, 3> pattern(int kind, std::uint32_t element_log2, | ||
| 356 | std::uint32_t block_log2) { | ||
| 357 | std::array<std::vector<std::uint32_t>, 3> axes; | ||
| 358 | const char* micro = kMicro[kind][element_log2]; | ||
| 359 | for (std::uint32_t bit = 0; bit < 8; ++bit) { | ||
| 360 | const char axis = micro[2 * bit]; | ||
| 361 | const int to = axis == 'x' ? 0 : axis == 'y' ? 1 : axis == 'z' ? 2 : -1; | ||
| 362 | if (to < 0) continue; | ||
| 363 | const std::size_t index = std::size_t(micro[2 * bit + 1] - '0'); | ||
| 364 | if (axes[to].size() <= index) axes[to].resize(index + 1, 0); | ||
| 365 | axes[to][index] = bit; | ||
| 366 | } | ||
| 367 | static constexpr int thin[2] = {1, 0}, thick_order[3] = {1, 0, 2}; | ||
| 368 | for (std::uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) | ||
| 369 | axes[kind == 2 ? thick_order[i % 3] : thin[i % 2]].push_back(bit); | ||
| 370 | return axes; | ||
| 371 | } | ||
| 372 | |||
| 373 | // Byte offsets inside a block for coordinates 0..2^bits of one axis. | ||
| 374 | static std::vector<std::uint32_t> spread(const std::vector<std::uint32_t>& bits) { | ||
| 375 | std::vector<std::uint32_t> out(std::size_t(1) << bits.size()); | ||
| 376 | for (std::uint32_t c = 0; c < out.size(); ++c) | ||
| 377 | for (std::size_t i = 0; i < bits.size(); ++i) out[c] |= ((c >> i) & 1u) << bits[i]; | ||
| 378 | return out; | ||
| 379 | } | ||
| 380 | |||
| 381 | // AMD GFX10_SW_64K_R_X_1xaa_RBPLUS with no additional base pipe XOR: the in-block byte offset each coordinate bit | ||
| 382 | // toggles. 32 pipes / 8 packers on Series X, 8 / 4 on Series S. | ||
| 383 | static std::array<std::vector<std::uint32_t>, 3> render_xor_pattern(bool series_s, std::uint32_t element_bytes) { | ||
| 384 | std::vector<std::uint16_t> x, y; | ||
| 385 | if (!series_s && element_bytes == 2) { | ||
| 386 | x = {2, 4, 8, 0x80, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; | ||
| 387 | y = {0x10, 0x20, 0x40, 0x2000, 0x300, 0x400, 0x4800, 0x8100, 0x1000}; | ||
| 388 | } else if (!series_s && element_bytes == 4) { | ||
| 389 | x = {4, 8, 0x40, 0x2000, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; | ||
| 390 | y = {0x10, 0x20, 0x80, 0x4000, 0x300, 0x400, 0x8800, 0x100, 0x1000}; | ||
| 391 | } else if (!series_s && element_bytes == 8) { | ||
| 392 | x = {8, 0x20, 0x40, 0x4000, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; | ||
| 393 | y = {0x10, 0x80, 0x2000, 0x8000, 0x300, 0x400, 0x800, 0x100, 0x1000}; | ||
| 394 | } else if (series_s && element_bytes == 2) { | ||
| 395 | x = {2, 4, 8, 0x80, 0x200, 0x1400, 0x2100, 0x8000, 0x4000}; | ||
| 396 | y = {0x10, 0x20, 0x40, 0x800, 0x300, 0x400, 0x4100, 0x8000, 0x2000}; | ||
| 397 | } else if (series_s && element_bytes == 4) { | ||
| 398 | x = {4, 8, 0x40, 0x800, 0x200, 0x2400, 0x4100, 0x8000}; | ||
| 399 | y = {0x10, 0x20, 0x80, 0x1000, 0x300, 0x400, 0x8100, 0x4000, 0x2000}; | ||
| 400 | } else if (series_s && element_bytes == 8) { | ||
| 401 | x = {8, 0x20, 0x40, 0x1000, 0x200, 0x4400, 0x8100, 0x2000}; | ||
| 402 | y = {0x10, 0x80, 0x800, 0x2000, 0x300, 0x400, 0x8100, 0x4000}; | ||
| 403 | } else { | ||
| 404 | return {}; | ||
| 405 | } | ||
| 406 | const auto contributions = [](const std::vector<std::uint16_t>& basis) { | ||
| 407 | std::vector<std::uint32_t> offsets(std::size_t(1) << basis.size(), 0); | ||
| 408 | for (std::size_t bit = 0; bit < basis.size(); ++bit) { | ||
| 409 | const std::size_t n = std::size_t(1) << bit; | ||
| 410 | for (std::size_t i = 0; i < n; ++i) offsets[n + i] = offsets[i] ^ basis[bit]; | ||
| 411 | } | ||
| 412 | return offsets; | ||
| 413 | }; | ||
| 414 | return {contributions(x), contributions(y), {}}; | ||
| 415 | } | ||
| 416 | |||
| 417 | // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices | ||
| 418 | // each hold the chain. | ||
| 419 | void linear(const LayoutDesc& d) { | ||
| 420 | desc_ = d; | ||
| 421 | const std::uint64_t bpe = d.element_bytes; | ||
| 422 | const std::uint32_t align = 256 / d.element_bytes; | ||
| 423 | const bool three_d = d.dimension == Dimension::tex3d; | ||
| 424 | std::uint64_t offset = 0; | ||
| 425 | mips_.resize(d.mips); | ||
| 426 | for (std::uint32_t i = d.mips; i-- > 0;) { | ||
| 427 | MipLayout& m = mips_[i]; | ||
| 428 | const std::uint32_t h = padded_dim(d.height, i, d.block); | ||
| 429 | m.pitch = round_up(padded_dim(d.width, i, d.block), align); | ||
| 430 | m.width = dim(d.width, i, d.block); | ||
| 431 | m.height = dim(d.height, i, d.block); | ||
| 432 | m.depth = three_d ? dim(d.depth, i, 1) : 1; | ||
| 433 | m.rows = h; | ||
| 434 | m.depth_pitch = three_d ? d.depth : 1; | ||
| 435 | m.offset = offset; | ||
| 436 | offset += std::uint64_t(m.pitch) * h * bpe; | ||
| 437 | } | ||
| 438 | block_ = {align, 1, 1}; | ||
| 439 | thick_ = false; | ||
| 440 | slices_ = d.depth; | ||
| 441 | slice_size_ = offset; | ||
| 442 | size_ = offset * d.depth; | ||
| 443 | alignment_ = 256; | ||
| 444 | first_tail_mip_ = d.mips; | ||
| 445 | } | ||
| 446 | |||
| 447 | void tiled(const LayoutDesc& d, std::uint32_t block_log2, bool series_s) { | ||
| 448 | desc_ = d; | ||
| 449 | const std::uint32_t element_log2 = std::uint32_t(std::countr_zero(d.element_bytes)); | ||
| 450 | const std::uint64_t bpe = d.element_bytes; | ||
| 451 | const std::uint64_t block_bytes = std::uint64_t(1) << block_log2; | ||
| 452 | const bool three_d = d.dimension == Dimension::tex3d; | ||
| 453 | thick_ = three_d && (swizzle::standard(d.swizzle) || swizzle::display(d.swizzle)); | ||
| 454 | if (thick_) { // ComputeThickBlockDimension | ||
| 455 | const std::uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; | ||
| 456 | const auto& b = kBlock1k_3d[element_log2]; | ||
| 457 | block_ = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1 : 0))}; | ||
| 458 | } else { // ComputeThinBlockDimension | ||
| 459 | const std::uint32_t samples_log2 = std::uint32_t(std::countr_zero(d.samples)); | ||
| 460 | const std::uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; | ||
| 461 | const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; | ||
| 462 | const std::uint32_t w = (elements_log2 + (wide ? 1 : 0)) / 2; | ||
| 463 | block_ = {1u << w, 1u << (elements_log2 - w), 1}; | ||
| 464 | } | ||
| 465 | std::uint32_t slices = round_up(d.depth, block_[2]); | ||
| 466 | const auto mip_depth = [&](std::uint32_t i) { return thick_ ? padded_dim(d.depth, i, 1) : 1u; }; | ||
| 467 | const auto depth_of = [&](std::uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; | ||
| 468 | first_tail_mip_ = d.mips; | ||
| 469 | std::uint64_t slice_size = 0; | ||
| 470 | if (d.mips == 1) { | ||
| 471 | MipLayout m; | ||
| 472 | m.width = dim(d.width, 0, d.block); | ||
| 473 | m.height = dim(d.height, 0, d.block); | ||
| 474 | m.depth = depth_of(0); | ||
| 475 | m.pitch = round_up(m.width, block_[0]); | ||
| 476 | m.rows = round_up(m.height, block_[1]); | ||
| 477 | m.depth_pitch = three_d ? slices : 1; | ||
| 478 | mips_.push_back(m); | ||
| 479 | slice_size = std::uint64_t(m.pitch) * m.rows * bpe * d.samples; | ||
| 480 | } else { | ||
| 481 | // GetMipTailDim: the largest mip the tail takes. | ||
| 482 | std::array<std::uint32_t, 3> tail_max = block_; | ||
| 483 | if (thick_) { | ||
| 484 | switch (block_log2 % 3) { | ||
| 485 | case 0: tail_max[1] >>= 1; break; | ||
| 486 | case 1: tail_max[0] >>= 1; break; | ||
| 487 | default: tail_max[2] >>= 1; break; | ||
| 488 | } | ||
| 489 | } else { | ||
| 490 | tail_max[0] >>= 1; | ||
| 491 | } | ||
| 492 | // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). | ||
| 493 | const std::uint32_t effective = thick_ ? block_log2 - (block_log2 - 8) / 3 : block_log2; | ||
| 494 | const std::uint32_t max_in_tail = effective == 8 ? 0 | ||
| 495 | : effective >= 9 && effective <= 11 ? 1 + (1u << (effective - 9)) | ||
| 496 | : effective - 4; | ||
| 497 | // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. | ||
| 498 | std::array<std::uint32_t, 3> fixed = tail_max; | ||
| 499 | if (swizzle::z_order(d.swizzle) && element_log2 <= 1) { | ||
| 500 | fixed[0] /= kBlock256_2d[element_log2][0] / kBlock256_2d[2][0]; | ||
| 501 | fixed[1] /= kBlock256_2d[element_log2][1] / kBlock256_2d[2][1]; | ||
| 502 | } | ||
| 503 | std::vector<std::uint64_t> sizes; | ||
| 504 | for (std::uint32_t i = 0; i < d.mips; ++i) { | ||
| 505 | const std::uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); | ||
| 506 | if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { | ||
| 507 | first_tail_mip_ = i; | ||
| 508 | slice_size += block_bytes / block_[2]; | ||
| 509 | break; | ||
| 510 | } | ||
| 511 | MipLayout m; | ||
| 512 | m.pitch = round_up(w, block_[0]); | ||
| 513 | m.rows = round_up(h, block_[1]); | ||
| 514 | const std::uint32_t depth = round_up(mip_depth(i), block_[2]); | ||
| 515 | const std::uint64_t one = std::uint64_t(m.pitch) * m.rows * bpe; | ||
| 516 | slice_size += one; | ||
| 517 | sizes.push_back(one * block_[2]); | ||
| 518 | m.width = dim(d.width, i, d.block); | ||
| 519 | m.height = dim(d.height, i, d.block); | ||
| 520 | m.depth = depth_of(i); | ||
| 521 | m.depth_pitch = three_d ? depth : 1; | ||
| 522 | mips_.push_back(m); | ||
| 523 | } | ||
| 524 | // Standard mips from the smallest up, after the tail block. | ||
| 525 | std::uint64_t offset = first_tail_mip_ < d.mips ? block_bytes : 0; | ||
| 526 | for (std::uint32_t i = first_tail_mip_; i-- > 0;) { | ||
| 527 | mips_[i].offset = offset; | ||
| 528 | offset += sizes[i]; | ||
| 529 | } | ||
| 530 | const std::uint32_t micro_w = thick_ ? kBlock256_3d[element_log2][0] : kBlock256_2d[element_log2][0]; | ||
| 531 | const std::uint32_t micro_h = thick_ ? kBlock256_3d[element_log2][1] : kBlock256_2d[element_log2][1]; | ||
| 532 | std::uint32_t pitch = tail_max[0], rows = tail_max[1]; | ||
| 533 | for (std::uint32_t i = first_tail_mip_; i < d.mips; ++i) { | ||
| 534 | const std::uint32_t m = max_in_tail - 1 - (i - first_tail_mip_); | ||
| 535 | const std::uint32_t tail_offset = m > 6 ? 16u << m : m << 8; | ||
| 536 | // Address bits 8.. of the offset, odd ones x, even ones y. | ||
| 537 | const auto bits = [&](std::uint32_t from) { | ||
| 538 | std::uint32_t v = 0; | ||
| 539 | for (std::uint32_t b = 0; b < 6; ++b) v |= ((tail_offset >> (from + 2 * b)) & 1u) << b; | ||
| 540 | return v; | ||
| 541 | }; | ||
| 542 | std::uint32_t x = bits(9), y = bits(8); | ||
| 543 | if (block_log2 & 1) { | ||
| 544 | std::swap(x, y); | ||
| 545 | if (element_log2 & 1) { | ||
| 546 | y = (y << 1) | (x & 1); | ||
| 547 | x >>= 1; | ||
| 548 | } | ||
| 549 | } | ||
| 550 | MipLayout mip; | ||
| 551 | mip.width = dim(d.width, i, d.block); | ||
| 552 | mip.height = dim(d.height, i, d.block); | ||
| 553 | mip.depth = depth_of(i); | ||
| 554 | mip.pitch = pitch; | ||
| 555 | mip.rows = rows; | ||
| 556 | mip.depth_pitch = thick_ ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; | ||
| 557 | mip.in_tail = true; | ||
| 558 | mip.tail_offset = tail_offset; | ||
| 559 | mip.tail_x = x * micro_w; | ||
| 560 | mip.tail_y = y * micro_h; | ||
| 561 | mips_.push_back(mip); | ||
| 562 | pitch = std::max(pitch >> 1, micro_w); | ||
| 563 | rows = std::max(rows >> 1, micro_h); | ||
| 564 | } | ||
| 565 | } | ||
| 566 | // Thick layouts store each depth slab's chain together. | ||
| 567 | slice_size_ = slice_size * (thick_ ? block_[2] : 1); | ||
| 568 | slices_ = slices / block_[2]; | ||
| 569 | size_ = slice_size_ * slices_; | ||
| 570 | alignment_ = block_bytes; | ||
| 571 | if (!swizzle::xor_mode(d.swizzle) && d.samples == 1) { | ||
| 572 | const int kind = thick_ ? 2 : swizzle::display(d.swizzle) ? 1 : 0; | ||
| 573 | const auto bits = pattern(kind, element_log2, block_log2); | ||
| 574 | for (int axis = 0; axis < 3; ++axis) pattern_[axis] = spread(bits[axis]); | ||
| 575 | } else if (d.swizzle == swizzle::sw_64kb_r_x && d.dimension == Dimension::tex2d && d.depth == 1 && | ||
| 576 | d.mips == 1 && d.samples == 1 && d.block == 1) { | ||
| 577 | pattern_ = render_xor_pattern(series_s, d.element_bytes); | ||
| 578 | } | ||
| 579 | } | ||
| 580 | |||
| 581 | // The slice and the depth inside it for `z` (an array slice or a 3D depth slice). | ||
| 582 | std::pair<std::uint32_t, std::uint32_t> split(std::uint32_t z) const { | ||
| 583 | return thick_ ? std::pair{z / block_[2], z % block_[2]} : std::pair{z, 0u}; | ||
| 584 | } | ||
| 585 | |||
| 586 | std::uint64_t render_xor_offset(const MipLayout& m, std::uint32_t x, std::uint32_t y) const { | ||
| 587 | const std::uint64_t block = std::uint64_t(y / block_[1]) * (m.pitch / block_[0]) + x / block_[0]; | ||
| 588 | const auto& ox = pattern_[0]; | ||
| 589 | const auto& oy = pattern_[1]; | ||
| 590 | return block * alignment_ + (ox[x & (ox.size() - 1)] ^ oy[y & (oy.size() - 1)]); | ||
| 591 | } | ||
| 592 | |||
| 593 | // The part of an address that depends on the row (and the depth in a thick block). In the tail the pattern of the | ||
| 594 | // shifted position gives the mip's offset inside the tail block. | ||
| 595 | std::uint64_t row(const MipLayout& m, std::uint32_t y, std::uint32_t z) const { | ||
| 596 | const unsigned log2 = unsigned(std::countr_zero(alignment_)); | ||
| 597 | y += m.in_tail ? m.tail_y : 0; | ||
| 598 | const std::uint64_t blocks = std::uint64_t(y / block_[1]) * (m.pitch / block_[0]); | ||
| 599 | return (blocks << log2) + (pattern_[1][y % block_[1]] | pattern_[2][z]); | ||
| 600 | } | ||
| 601 | |||
| 602 | // The part of an address that depends on the column. | ||
| 603 | std::uint64_t column(const MipLayout& m, std::uint32_t x) const { | ||
| 604 | x += m.in_tail ? m.tail_x : 0; | ||
| 605 | return (std::uint64_t(x / block_[0]) << std::countr_zero(alignment_)) + pattern_[0][x % block_[0]]; | ||
| 606 | } | ||
| 607 | |||
| 608 | // Visits contiguous runs as (tiled byte offset, linear byte offset, length). | ||
| 609 | template<class Copy> | ||
| 610 | bool walk(std::size_t tiled_len, std::uint32_t mip, std::uint32_t slice, std::size_t linear_len, | ||
| 611 | std::size_t row_pitch, std::size_t depth_pitch, Copy&& copy) const { | ||
| 612 | if (mip >= mips_.size()) return false; | ||
| 613 | const MipLayout& m = mips_[mip]; | ||
| 614 | std::uint32_t first = slice; | ||
| 615 | if (desc_.dimension == Dimension::tex3d) { | ||
| 616 | if (slice != 0) return false; | ||
| 617 | first = 0; | ||
| 618 | } | ||
| 619 | if (first >= slices_ || !addressable()) return false; | ||
| 620 | const std::size_t n = desc_.element_bytes; | ||
| 621 | const std::size_t bytes = std::size_t(m.width) * n; | ||
| 622 | constexpr std::size_t max = std::numeric_limits<std::size_t>::max(); | ||
| 623 | const std::size_t dz = m.depth - 1, dy = m.height - 1; | ||
| 624 | if ((dz && depth_pitch > max / dz) || (dy && row_pitch > max / dy)) return false; | ||
| 625 | const std::size_t a = dz * depth_pitch, b = dy * row_pitch; | ||
| 626 | if (a > max - b || a + b > max - bytes) return false; | ||
| 627 | const std::size_t need = a + b + bytes; | ||
| 628 | if (tiled_len < bytes_from(mip) || linear_len < need || row_pitch < bytes) return false; | ||
| 629 | if (desc_.swizzle == swizzle::sw_64kb_r_x) { | ||
| 630 | // The low four address bits are column and element bits only, so every element size has 16-byte runs. | ||
| 631 | for (std::uint32_t y = 0; y < m.height; ++y) | ||
| 632 | for (std::uint32_t x = 0; x < m.width; x += std::uint32_t(16 / n)) { | ||
| 633 | const std::size_t lx = std::size_t(x) * n; | ||
| 634 | copy(std::size_t(render_xor_offset(m, x, y)), std::size_t(y) * row_pitch + lx, | ||
| 635 | std::min<std::size_t>(16, bytes - lx)); | ||
| 636 | } | ||
| 637 | return true; | ||
| 638 | } | ||
| 639 | const bool is_linear = desc_.swizzle == swizzle::linear; | ||
| 640 | // The row and depth contribute one common base to every column, so the same runs repeat on every row. | ||
| 641 | std::vector<std::array<std::size_t, 3>> runs; // (tiled, linear, length) within a row | ||
| 642 | if (!is_linear) { | ||
| 643 | std::size_t first_linear = 0, first_tiled = std::size_t(column(m, 0)); | ||
| 644 | for (std::uint32_t x = 1; x < m.width; ++x) { | ||
| 645 | const std::size_t at_tiled = std::size_t(column(m, x)), at_linear = std::size_t(x) * n; | ||
| 646 | if (at_tiled != first_tiled + (at_linear - first_linear)) { | ||
| 647 | runs.push_back({first_tiled, first_linear, at_linear - first_linear}); | ||
| 648 | first_tiled = at_tiled; | ||
| 649 | first_linear = at_linear; | ||
| 650 | } | ||
| 651 | } | ||
| 652 | runs.push_back({first_tiled, first_linear, bytes - first_linear}); | ||
| 653 | } | ||
| 654 | for (std::uint32_t z = 0; z < m.depth; ++z) { | ||
| 655 | const auto [s, inner] = split(first + z); | ||
| 656 | const std::uint64_t base = std::uint64_t(s) * slice_size_ + m.offset; | ||
| 657 | for (std::uint32_t y = 0; y < m.height; ++y) { | ||
| 658 | const std::size_t linear_row = std::size_t(z) * depth_pitch + std::size_t(y) * row_pitch; | ||
| 659 | if (is_linear) { | ||
| 660 | copy(std::size_t(base + std::uint64_t(y) * m.pitch * n), linear_row, bytes); | ||
| 661 | } else { | ||
| 662 | const std::size_t tiled_row = std::size_t(base + row(m, y, inner)); | ||
| 663 | for (const auto& run : runs) copy(tiled_row + run[0], linear_row + run[1], run[2]); | ||
| 664 | } | ||
| 665 | } | ||
| 666 | } | ||
| 667 | return true; | ||
| 668 | } | ||
| 669 | |||
| 670 | LayoutDesc desc_{}; | ||
| 671 | std::array<std::uint32_t, 3> block_{}; | ||
| 672 | bool thick_ = false; | ||
| 673 | std::uint32_t slices_ = 0; | ||
| 674 | std::uint64_t slice_size_ = 0, size_ = 0, alignment_ = 0; | ||
| 675 | std::uint32_t first_tail_mip_ = 0; | ||
| 676 | std::vector<MipLayout> mips_; | ||
| 677 | // Byte offsets inside a block of each element coordinate, per axis; empty for linear and unaddressable modes. | ||
| 678 | std::array<std::vector<std::uint32_t>, 3> pattern_; | ||
| 679 | }; | ||
| 680 | |||
| 681 | // What a DXGI format stores per element on the console: bytes, texels per element side (4 for block compression), and | ||
| 682 | // whether its stencil is a second plane (the GPU keeps depth and stencil apart). False for 96-bit, 1-bit, packed 4:2:2 | ||
| 683 | // and video formats (VIctory texture.rs format(): not laid out there either). | ||
| 684 | struct ElementFormat { | ||
| 685 | std::uint32_t bytes = 0, block = 1; | ||
| 686 | bool stencil = false; | ||
| 687 | }; | ||
| 688 | constexpr bool element_format(std::uint32_t dxgi, ElementFormat& out) { | ||
| 689 | const auto in = [&](std::uint32_t a, std::uint32_t b) { return dxgi >= a && dxgi <= b; }; | ||
| 690 | if (in(1, 4)) out = {16, 1, false}; | ||
| 691 | else if (in(9, 18)) out = {8, 1, false}; | ||
| 692 | else if (in(19, 22) || in(44, 47)) out = {4, 1, true}; | ||
| 693 | else if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) out = {4, 1, false}; | ||
| 694 | else if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) out = {2, 1, false}; | ||
| 695 | else if (in(118, 120)) out = {2, 1, true}; | ||
| 696 | else if (in(60, 65)) out = {1, 1, false}; | ||
| 697 | else if (in(70, 72) || in(79, 81)) out = {8, 4, false}; | ||
| 698 | else if (in(73, 78) || in(82, 84) || in(94, 99)) out = {16, 4, false}; | ||
| 699 | else return false; | ||
| 700 | return true; | ||
| 701 | } | ||
| 702 | |||
| 703 | // A texture as the console allocates it: every data plane (depth, then stencil), one after the other. | ||
| 704 | // shortcut (as VIctory's): no compression metadata planes (HTILE, CMASK, FMASK, DCC). | ||
| 705 | struct ConsoleTextureDesc { | ||
| 706 | Dimension dimension = Dimension::tex2d; | ||
| 707 | std::uint32_t width = 1, height = 1, depth_or_array = 1; | ||
| 708 | std::uint32_t mips = 1; // 0: the full chain | ||
| 709 | std::uint32_t format = 0; // DXGI format number | ||
| 710 | std::uint32_t samples = 1; | ||
| 711 | std::uint32_t swizzle = swizzle::linear; | ||
| 712 | }; | ||
| 713 | |||
| 714 | struct TexturePlane { | ||
| 715 | std::uint64_t offset = 0; // from the start of the texture | ||
| 716 | bool stencil = false; | ||
| 717 | TextureLayout layout; | ||
| 718 | }; | ||
| 719 | |||
| 720 | struct ConsoleTexture { | ||
| 721 | std::vector<TexturePlane> planes; | ||
| 722 | std::uint64_t size = 0, alignment = 1; | ||
| 723 | |||
| 724 | static bool make(const ConsoleTextureDesc& d, bool series_s, ConsoleTexture& out) { | ||
| 725 | ElementFormat f; | ||
| 726 | if (!element_format(d.format, f)) return false; | ||
| 727 | const std::uint32_t depth3d = d.dimension == Dimension::tex3d ? d.depth_or_array : 1; | ||
| 728 | const std::uint32_t mips = | ||
| 729 | d.mips ? d.mips : std::uint32_t(std::bit_width(std::max({d.width, d.height, depth3d, 1u}))); | ||
| 730 | LayoutDesc plane{d.dimension, d.width, d.height, d.depth_or_array, mips, f.bytes, f.block, | ||
| 731 | std::max(d.samples, 1u), d.swizzle}; | ||
| 732 | ConsoleTexture t; | ||
| 733 | TexturePlane first; | ||
| 734 | if (!TextureLayout::make(plane, series_s, first.layout)) return false; | ||
| 735 | t.planes.push_back(std::move(first)); | ||
| 736 | if (f.stencil) { | ||
| 737 | plane.element_bytes = 1; | ||
| 738 | TexturePlane second; | ||
| 739 | if (!TextureLayout::make(plane, series_s, second.layout)) return false; | ||
| 740 | const std::uint64_t a = second.layout.alignment(); | ||
| 741 | second.offset = (t.planes[0].layout.size() + a - 1) / a * a; | ||
| 742 | second.stencil = true; | ||
| 743 | t.planes.push_back(std::move(second)); | ||
| 744 | } | ||
| 745 | t.size = t.planes.back().offset + t.planes.back().layout.size(); | ||
| 746 | for (const TexturePlane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment()); | ||
| 747 | out = std::move(t); | ||
| 748 | return true; | ||
| 749 | } | ||
| 750 | }; | ||
| 751 | |||
| 752 | // The mode the console's layout library (xg_xs.dll XGSuggestSwizzleMode) picks for a texture: linear for 1D, the XOR | ||
| 753 | // depth and render modes for depth and render targets, else SW_4KB_S (.ttpf textures without a mode of their own use | ||
| 754 | // it). VIctory victory-hle xg.rs suggested(), which marks it a shortcut: the rule of the library's older optimal-mode | ||
| 755 | // function (any size, 2D, 3D and cubes alike); XGSuggestSwizzleMode itself is newer than every copy VIctory could | ||
| 756 | // check, so revisit if streamed textures come out scrambled. The layer reads layout word 0 with the same rule. | ||
| 757 | constexpr std::uint32_t suggested_swizzle(Dimension dimension, bool depth_stencil, bool render_target) { | ||
| 758 | return dimension == Dimension::tex1d ? swizzle::linear | ||
| 759 | : depth_stencil ? swizzle::sw_64kb_z_x | ||
| 760 | : render_target ? swizzle::sw_64kb_r_x | ||
| 761 | : swizzle::sw_4kb_s; | ||
| 762 | } | ||
| 763 | |||
| 764 | // The swizzle mode a console D3D12_RESOURCE_DESC::Layout word names (VIctory xg.rs texture(), victory-gpu | ||
| 765 | // resource.rs texture_layout): 0x100 | the mode, 1 row major (linear), 0 the library's pick (suggested_swizzle). False | ||
| 766 | // for any other word. | ||
| 767 | constexpr bool swizzle_from_layout_word(std::uint32_t word, Dimension dimension, bool depth_stencil, | ||
| 768 | bool render_target, std::uint32_t& mode) { | ||
| 769 | if (word == 0) mode = suggested_swizzle(dimension, depth_stencil, render_target); | ||
| 770 | else if (word == 1) mode = swizzle::linear; | ||
| 771 | else if ((word & ~0xffu) == 0x100) mode = word & 0xff; | ||
| 772 | else return false; | ||
| 773 | return true; | ||
| 774 | } | ||
| 775 | |||
| 776 | } // namespace leonida::gfx10 | 158 | } // namespace leonida::gfx10 |
diff --git a/runtime/src/host_cpu.h b/runtime/src/host_cpu.h index 5f36581aa..b9dd143db 100644 --- a/runtime/src/host_cpu.h +++ b/runtime/src/host_cpu.h | |||
| @@ -1,8 +1,7 @@ | |||
| 1 | // Host CPU preflight for --init and --run: the game executes AVX instructions from its TLS callbacks on, so a host | 1 | // Host CPU preflight for --init and --run: the game executes AVX instructions from its TLS callbacks on, so a host |
| 2 | // whose CPU or OS lacks AVX (a QEMU qemu64 guest, for one) dies there with a bare EXCEPTION_ILLEGAL_INSTRUCTION | 2 | // whose CPU or OS lacks AVX (a QEMU qemu64 guest, for one) dies there with a bare EXCEPTION_ILLEGAL_INSTRUCTION |
| 3 | // (0xC000001D) that reads like a loader bug. This checks AVX only, which is what was measured; it claims nothing | 3 | // (0xC000001D) that reads like a loader bug. This checks AVX only, which is what was measured; it claims nothing |
| 4 | // about AVX2, FMA or BMI2. No emulation here: the console-only instructions (CLZERO, SSE4a, ...) are emulated by | 4 | // about AVX2, FMA or BMI2. No emulation here: that is RT-500's scope. Rosetta on macOS runs AVX code but leaves |
| 5 | // console_insn.h's handler. Rosetta on macOS runs AVX code but leaves | ||
| 6 | // AVX out of CPUID unless ROSETTA_ADVERTISE_AVX=1 is set, so the check fails there until that variable is set. | 5 | // AVX out of CPUID unless ROSETTA_ADVERTISE_AVX=1 is set, so the check fails there until that variable is set. |
| 7 | #pragma once | 6 | #pragma once |
| 8 | 7 | ||
diff --git a/runtime/src/opus_packet.h b/runtime/src/opus_packet.h deleted file mode 100644 index d4e9ea243..000000000 --- a/runtime/src/opus_packet.h +++ /dev/null | |||
| @@ -1,128 +0,0 @@ | |||
| 1 | // Opus packet framing (RFC 6716, section 3): how many samples a packet decodes to, and whether its framing is valid. | ||
| 2 | // | ||
| 3 | // Leonida has no Opus decoder yet. VIctory's xapu.dll (crates/victory-hle/src/modules/apu.rs, GPL-3.0-or-later, by | ||
| 4 | // Marvisak and contributors, DexNom fork) decodes with the opus-pure crate (BSD-3-Clause), which is not in this | ||
| 5 | // repository; the xapu shim ported from it uses this parser instead, so a packet gives the sample count and the | ||
| 6 | // errors a decoder would report, and silence for its samples. The checks are libopus's opus_packet_parse for a packet | ||
| 7 | // that is not self-delimited (the requirements R1-R7 of RFC 6716 section 3.4); the sample count is what opus_decode | ||
| 8 | // returns for such a packet at 48 kHz. Written for Leonida from the RFC; GPL-3.0-or-later. Pure C++: no OS headers. | ||
| 9 | #pragma once | ||
| 10 | |||
| 11 | #include <cstddef> | ||
| 12 | #include <cstdint> | ||
| 13 | |||
| 14 | namespace rt::opus { | ||
| 15 | |||
| 16 | inline constexpr int kBufferTooSmall = -2; // OPUS_BUFFER_TOO_SMALL | ||
| 17 | inline constexpr int kInvalidPacket = -4; // OPUS_INVALID_PACKET | ||
| 18 | inline constexpr int kMaxFrameBytes = 1275; | ||
| 19 | inline constexpr int kMaxPacketSamples = 5760; // 120 ms at 48 kHz | ||
| 20 | |||
| 21 | // Samples per channel at 48 kHz in each frame of a packet with this TOC byte (configuration, bits 7-3; section 3.1). | ||
| 22 | constexpr int samples_per_frame(uint8_t toc) { | ||
| 23 | if (toc & 0x80) return (48000 << ((toc >> 3) & 3)) / 400; // CELT-only: 2.5, 5, 10, 20 ms | ||
| 24 | if ((toc & 0x60) == 0x60) return (toc & 0x08) ? 960 : 480; // hybrid: 10, 20 ms | ||
| 25 | const int size = (toc >> 3) & 3; // SILK-only: 10, 20, 40, 60 ms | ||
| 26 | return size == 3 ? 2880 : (48000 << size) / 100; | ||
| 27 | } | ||
| 28 | |||
| 29 | namespace detail { | ||
| 30 | |||
| 31 | // A frame length (section 3.2.1): one byte below 252, else two. Returns the bytes used, -1 (and size -1) without them. | ||
| 32 | inline int parse_size(const uint8_t* data, ptrdiff_t len, int* size) { | ||
| 33 | if (len < 1) { | ||
| 34 | *size = -1; | ||
| 35 | return -1; | ||
| 36 | } | ||
| 37 | if (data[0] < 252) { | ||
| 38 | *size = data[0]; | ||
| 39 | return 1; | ||
| 40 | } | ||
| 41 | if (len < 2) { | ||
| 42 | *size = -1; | ||
| 43 | return -1; | ||
| 44 | } | ||
| 45 | *size = 4 * data[1] + data[0]; | ||
| 46 | return 2; | ||
| 47 | } | ||
| 48 | |||
| 49 | } // namespace detail | ||
| 50 | |||
| 51 | // The number of frames in the packet (frame count codes 0-3, section 3.2), or kInvalidPacket for one RFC 6716 does | ||
| 52 | // not allow. | ||
| 53 | inline int frame_count(const uint8_t* data, size_t length) { | ||
| 54 | if (!data || length == 0) return kInvalidPacket; | ||
| 55 | const uint8_t toc = data[0]; | ||
| 56 | const int framesize = samples_per_frame(toc); | ||
| 57 | const uint8_t* p = data + 1; | ||
| 58 | ptrdiff_t len = static_cast<ptrdiff_t>(length) - 1; | ||
| 59 | ptrdiff_t last_size = len; | ||
| 60 | int count = 0; | ||
| 61 | switch (toc & 3) { | ||
| 62 | case 0: // one frame | ||
| 63 | count = 1; | ||
| 64 | break; | ||
| 65 | case 1: // two frames of the same size | ||
| 66 | count = 2; | ||
| 67 | if (len & 1) return kInvalidPacket; | ||
| 68 | last_size = len / 2; | ||
| 69 | break; | ||
| 70 | case 2: { // two frames, the first's size given | ||
| 71 | count = 2; | ||
| 72 | int size = 0; | ||
| 73 | const int bytes = detail::parse_size(p, len, &size); | ||
| 74 | len -= bytes; | ||
| 75 | if (size < 0 || size > len) return kInvalidPacket; | ||
| 76 | p += bytes; | ||
| 77 | last_size = len - size; | ||
| 78 | break; | ||
| 79 | } | ||
| 80 | default: { // a frame count byte: 1 to 48 frames, CBR or VBR, optional padding | ||
| 81 | if (len < 1) return kInvalidPacket; | ||
| 82 | const uint8_t ch = *p++; | ||
| 83 | --len; | ||
| 84 | count = ch & 0x3f; | ||
| 85 | if (count <= 0 || framesize * count > kMaxPacketSamples) return kInvalidPacket; | ||
| 86 | if (ch & 0x40) { | ||
| 87 | int pad = 0; | ||
| 88 | do { | ||
| 89 | if (len <= 0) return kInvalidPacket; | ||
| 90 | pad = *p++; | ||
| 91 | --len; | ||
| 92 | len -= pad == 255 ? 254 : pad; | ||
| 93 | } while (pad == 255); | ||
| 94 | } | ||
| 95 | if (len < 0) return kInvalidPacket; | ||
| 96 | if (ch & 0x80) { // VBR: every frame's size but the last | ||
| 97 | last_size = len; | ||
| 98 | for (int i = 0; i < count - 1; ++i) { | ||
| 99 | int size = 0; | ||
| 100 | const int bytes = detail::parse_size(p, len, &size); | ||
| 101 | len -= bytes; | ||
| 102 | if (size < 0 || size > len) return kInvalidPacket; | ||
| 103 | p += bytes; | ||
| 104 | last_size -= bytes + size; | ||
| 105 | } | ||
| 106 | if (last_size < 0) return kInvalidPacket; | ||
| 107 | } else { // CBR | ||
| 108 | last_size = len / count; | ||
| 109 | if (last_size * count != len) return kInvalidPacket; | ||
| 110 | } | ||
| 111 | break; | ||
| 112 | } | ||
| 113 | } | ||
| 114 | // The last frame's size (all of them, CBR) is not coded and may exceed what a frame can hold. | ||
| 115 | if (last_size > kMaxFrameBytes) return kInvalidPacket; | ||
| 116 | return count; | ||
| 117 | } | ||
| 118 | |||
| 119 | // Samples per channel at 48 kHz that decoding the packet gives, as opus_decode returns it: its frames times the | ||
| 120 | // samples per frame, kInvalidPacket for a malformed packet, kBufferTooSmall when that is more than `max_samples`. | ||
| 121 | inline int packet_samples(const uint8_t* data, size_t length, int max_samples = kMaxPacketSamples) { | ||
| 122 | const int count = frame_count(data, length); | ||
| 123 | if (count < 0) return count; | ||
| 124 | const int samples = count * samples_per_frame(data[0]); | ||
| 125 | return samples > max_samples ? kBufferTooSmall : samples; | ||
| 126 | } | ||
| 127 | |||
| 128 | } // namespace rt::opus | ||
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 54440459d..fc73f37f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -1341,10 +1341,6 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo | |||
| 1341 | return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); | 1341 | return static_cast<Loader*>(ctx)->load_runtime_module_w(basename, flags, handled); |
| 1342 | } | 1342 | } |
| 1343 | 1343 | ||
| 1344 | bool bundled_module_path(void* ctx, void* module, std::wstring& path) { | ||
| 1345 | return static_cast<Loader*>(ctx)->module_path(module, path); | ||
| 1346 | } | ||
| 1347 | |||
| 1348 | const shims::BundledModuleOps kBundledOps{ | 1344 | const shims::BundledModuleOps kBundledOps{ |
| 1349 | &bundled_find_loaded, | 1345 | &bundled_find_loaded, |
| 1350 | &bundled_load, | 1346 | &bundled_load, |
| @@ -1352,7 +1348,6 @@ const shims::BundledModuleOps kBundledOps{ | |||
| 1352 | &bundled_owns_handle, | 1348 | &bundled_owns_handle, |
| 1353 | &bundled_find_loaded_w, | 1349 | &bundled_find_loaded_w, |
| 1354 | &bundled_load_w, | 1350 | &bundled_load_w, |
| 1355 | &bundled_module_path, | ||
| 1356 | }; | 1351 | }; |
| 1357 | 1352 | ||
| 1358 | // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). | 1353 | // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). |
| @@ -1600,19 +1595,6 @@ bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) | |||
| 1600 | return false; | 1595 | return false; |
| 1601 | } | 1596 | } |
| 1602 | 1597 | ||
| 1603 | bool Loader::module_path(void* module_handle, std::wstring& path) const { | ||
| 1604 | if (!module_handle) return false; | ||
| 1605 | std::lock_guard lock(mutex_); | ||
| 1606 | for (const Module* m : order_) | ||
| 1607 | if (m->base == module_handle) { | ||
| 1608 | std::error_code ec; | ||
| 1609 | const std::filesystem::path absolute = std::filesystem::absolute(m->path, ec); | ||
| 1610 | path = (ec ? m->path : absolute).wstring(); | ||
| 1611 | return true; | ||
| 1612 | } | ||
| 1613 | return false; | ||
| 1614 | } | ||
| 1615 | |||
| 1616 | bool Loader::owns_module_handle(void* module_handle) const { | 1598 | bool Loader::owns_module_handle(void* module_handle) const { |
| 1617 | if (!module_handle) return false; | 1599 | if (!module_handle) return false; |
| 1618 | std::lock_guard lock(mutex_); | 1600 | std::lock_guard lock(mutex_); |
diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 542808f88..f75426e41 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h | |||
| @@ -137,8 +137,6 @@ public: | |||
| 137 | void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); | 137 | void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); |
| 138 | void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); | 138 | void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); |
| 139 | bool owns_module_handle(void* module_handle) const; | 139 | bool owns_module_handle(void* module_handle) const; |
| 140 | // The file a mapped module was mapped from, by its handle (base); false for any other handle. | ||
| 141 | bool module_path(void* module_handle, std::wstring& path) const; | ||
| 142 | 140 | ||
| 143 | private: | 141 | private: |
| 144 | void initialise(Module& m); | 142 | void initialise(Module& m); |
diff --git a/runtime/src/pipeline_queue.h b/runtime/src/pipeline_queue.h deleted file mode 100644 index 299b2a096..000000000 --- a/runtime/src/pipeline_queue.h +++ /dev/null | |||
| @@ -1,749 +0,0 @@ | |||
| 1 | // Pipelines made by worker threads instead of the thread that creates or first binds them, a per-frame budget for | ||
| 2 | // waiting on them at the bind, and the list of pipelines earlier runs bound, started early. | ||
| 3 | // | ||
| 4 | // Ported from VIctory (victory/crates/victory-gpu/src/pipeline/make.rs and pipeline/library.rs; GPL-3.0-or-later, | ||
| 5 | // Marvisak and contributors, DexNom fork). The title creates some 60,000 pipelines in its first 20 s and draws with a | ||
| 6 | // few dozen of them (pipeline.rs:6-11); its first world frame wants over 1,200 new ones, and made on the recording | ||
| 7 | // threads that frame took more than 30 s, past the title's GPU watchdog (make.rs:1-8, 181-185). So, as there: | ||
| 8 | // - A pipeline state records what its pipeline is made from and returns; a Job makes the pipeline on a worker. | ||
| 9 | // - Creation starts a pipeline an earlier run bound (EarlyList, library.rs:10-13 and make.rs `early`); any other | ||
| 10 | // pipeline is started by its first bind (make.rs `ready`). Requests go first, then early depth-only pipelines, | ||
| 11 | // then the other early ones (make.rs Queue). | ||
| 12 | // - A bind waits for its pipeline while the frame's budget lasts (make.rs `wait`): per frame and kind (graphics, | ||
| 13 | // compute), a window of waiting time the binding threads share (FrameWait), never for a pipeline the driver has | ||
| 14 | // held for long (held_too_long). A draw or dispatch whose pipeline is not made then is dropped and counted | ||
| 15 | // (pipeline.rs `note_drop`), and the counts are logged once a second. | ||
| 16 | // Also as there: its 12 s default budget per frame and kind (LEONIDA_PIPELINE_WAIT_MS) and its loading allowance | ||
| 17 | // (make.rs:193-223, waits of up to 4 s / 12 s per frame while a world loads, LEONIDA_PIPELINE_GATE_S). | ||
| 18 | // Leonida's own rule: on a device of no title (the PC interface, the tests) a bind waits for its pipeline however long | ||
| 19 | // it takes until the console frame clock begins a frame (device slot 80, frame.rs:120-184), so nothing is dropped | ||
| 20 | // there: D3D12 has a PSO usable once it is created. The title's device is bounded from its creation (title_running). | ||
| 21 | // | ||
| 22 | // The worker threads are the process's and are never stopped; the builder is never destroyed (a static destructor | ||
| 23 | // at exit would run under them). Nothing here is thread_local (AGENTS.md, "Runtime traps"). | ||
| 24 | #pragma once | ||
| 25 | |||
| 26 | #include <algorithm> | ||
| 27 | #include <atomic> | ||
| 28 | #include <chrono> | ||
| 29 | #include <condition_variable> | ||
| 30 | #include <cstdint> | ||
| 31 | #include <cstdio> | ||
| 32 | #include <cstdlib> | ||
| 33 | #include <deque> | ||
| 34 | #include <exception> | ||
| 35 | #include <filesystem> | ||
| 36 | #include <fstream> | ||
| 37 | #include <functional> | ||
| 38 | #include <memory> | ||
| 39 | #include <mutex> | ||
| 40 | #include <string> | ||
| 41 | #include <system_error> | ||
| 42 | #include <thread> | ||
| 43 | #include <unordered_set> | ||
| 44 | #include <vector> | ||
| 45 | |||
| 46 | #ifdef _WIN32 | ||
| 47 | #ifndef NOMINMAX | ||
| 48 | #define NOMINMAX | ||
| 49 | #endif | ||
| 50 | #include <windows.h> | ||
| 51 | #endif | ||
| 52 | |||
| 53 | namespace leonida::pipelines { | ||
| 54 | |||
| 55 | using Clock = std::chrono::steady_clock; | ||
| 56 | |||
| 57 | // ---- Frames --------------------------------------------------------------------------------------------------- | ||
| 58 | |||
| 59 | // Frames the console frame clock has begun (origin waits that hand out a token, frame.rs:163-171). 0: none yet. | ||
| 60 | inline std::atomic<std::uint64_t>& frame_counter() { | ||
| 61 | static std::atomic<std::uint64_t> frames{0}; | ||
| 62 | return frames; | ||
| 63 | } | ||
| 64 | inline std::uint64_t current_frame() { return frame_counter().load(std::memory_order_relaxed); } | ||
| 65 | inline std::uint64_t begin_frame() { return frame_counter().fetch_add(1, std::memory_order_relaxed) + 1; } | ||
| 66 | |||
| 67 | // A title is running: D3D12XboxCreateDevice made its device in the console layout. From then on a bind's wait is | ||
| 68 | // bounded even before the frame clock's first frame, which is VIctory's frame 0 (make.rs `wait` with frame::current() | ||
| 69 | // 0): the title creates and uses pipelines while it sets up, and a 30 s watchdog of its own ends a main thread that | ||
| 70 | // stops for that long (the first CreateComputePipelineState stalled ~28 s on the synchronous compile). | ||
| 71 | inline std::atomic<bool>& title_running() { | ||
| 72 | static std::atomic<bool> running{false}; | ||
| 73 | return running; | ||
| 74 | } | ||
| 75 | // Whether binds wait within a frame's budget (else as long as the build takes: the PC interface, the tests). | ||
| 76 | inline bool waits_bounded() { return title_running().load(std::memory_order_relaxed) || current_frame() > 0; } | ||
| 77 | |||
| 78 | // ---- Settings ------------------------------------------------------------------------------------------------- | ||
| 79 | |||
| 80 | // How the threads that wait in one frame share its budget (make.rs:290-332, VICTORY_PIPELINE_WAIT_SHARED; here | ||
| 81 | // LEONIDA_PIPELINE_WAIT_SHARED): a window of waiting time by default, `reserve` or `0` as VIctory had them before. | ||
| 82 | enum class Sharing { window, reserve, per_thread }; | ||
| 83 | |||
| 84 | inline Sharing sharing_from(const char* value) { | ||
| 85 | if (!value) return Sharing::window; | ||
| 86 | std::string v(value); | ||
| 87 | const auto first = v.find_first_not_of(" \t"); | ||
| 88 | v = first == std::string::npos ? std::string() : v.substr(first, v.find_last_not_of(" \t") - first + 1); | ||
| 89 | if (v == "0") return Sharing::per_thread; | ||
| 90 | if (v == "reserve") return Sharing::reserve; | ||
| 91 | return Sharing::window; | ||
| 92 | } | ||
| 93 | |||
| 94 | // VIctory's default (make.rs:170-182, decision 0007): the picture before frame rate. A frame waits for pipelines still | ||
| 95 | // being made rather than drop their draws and dispatches, up to 12 s for each kind, the threads together; both kinds' | ||
| 96 | // windows one after the other stay under the title's 30 s hang watchdog (kMaxWaitMs). Until 2026-11-26 this was | ||
| 97 | // 500 ms, and the world load dropped the passes the title dispatches once (VIctory: walls, floors and faces missing). | ||
| 98 | inline constexpr std::int64_t kDefaultWaitMs = 12000; | ||
| 99 | |||
| 100 | // While a world loads (make.rs:184-223): a frame whose budget is shorter may still wait up to 4 s for a graphics and | ||
| 101 | // 12 s for a compute pipeline, until LEONIDA_PIPELINE_GATE_S (120) seconds of such waiting are spent for that kind. | ||
| 102 | inline constexpr std::int64_t kLoadingFrameMs = 4000; | ||
| 103 | inline constexpr std::int64_t kLoadingFrameComputeMs = 12000; | ||
| 104 | |||
| 105 | inline long long env_number(const char* name, long long fallback) { | ||
| 106 | char text[32] = {}; | ||
| 107 | #ifdef _WIN32 | ||
| 108 | std::size_t length = 0; | ||
| 109 | if (getenv_s(&length, text, sizeof(text), name) != 0 || length <= 1) return fallback; | ||
| 110 | #else | ||
| 111 | const char* value = std::getenv(name); | ||
| 112 | if (!value || !*value) return fallback; | ||
| 113 | std::snprintf(text, sizeof(text), "%s", value); | ||
| 114 | #endif | ||
| 115 | char* end = nullptr; | ||
| 116 | const long long n = std::strtoll(text, &end, 10); | ||
| 117 | return end == text || n < 0 ? fallback : n; | ||
| 118 | } | ||
| 119 | |||
| 120 | // The most LEONIDA_PIPELINE_WAIT_MS may ask for. The title's hang watchdog (a thread that wakes once a second) ends the | ||
| 121 | // process when the main loop has not stamped its progress for 30 checks in a row: a deliberate write to address 0, | ||
| 122 | // which the runtime's log shows as an access violation writing 0x0. Both waits of a frame (graphics and compute) and | ||
| 123 | // the frame's own work must fit in that, so the two together stay under 24 s (VIctory's bound, make.rs:183-187). Measured: a run with the budget at 600 s | ||
| 124 | // stopped drawing at 180 s (its frames waited on pipelines made on 4 threads, one of them 10.3 s) and the title wrote | ||
| 125 | // to 0 at 211 s. | ||
| 126 | inline constexpr std::int64_t kMaxWaitMs = 12000; | ||
| 127 | static_assert(2 * kMaxWaitMs < 30000 && kLoadingFrameComputeMs <= kMaxWaitMs); | ||
| 128 | |||
| 129 | // The budget the variable asks for, kept under kMaxWaitMs. | ||
| 130 | inline std::int64_t wait_budget_from_env(std::int64_t asked) { | ||
| 131 | if (asked <= kMaxWaitMs) return asked; | ||
| 132 | std::fprintf(stderr, | ||
| 133 | "[rt] d3d12: pipelines: LEONIDA_PIPELINE_WAIT_MS %lld is past the title's 30 s hang watchdog; " | ||
| 134 | "%lld ms is used\n", | ||
| 135 | static_cast<long long>(asked), static_cast<long long>(kMaxWaitMs)); | ||
| 136 | return kMaxWaitMs; | ||
| 137 | } | ||
| 138 | |||
| 139 | // LEONIDA_PIPELINE_WAIT_MS: the waiting a frame allows per kind of pipeline, over all threads (make.rs:154-179), at | ||
| 140 | // most kMaxWaitMs. 0 waits for nothing once frames have begun. Read once; set_wait_budget overrides it (tests). | ||
| 141 | inline std::atomic<std::int64_t>& wait_budget_ms() { | ||
| 142 | static std::atomic<std::int64_t> ms{wait_budget_from_env(env_number("LEONIDA_PIPELINE_WAIT_MS", kDefaultWaitMs))}; | ||
| 143 | return ms; | ||
| 144 | } | ||
| 145 | inline Clock::duration wait_budget() { return std::chrono::milliseconds(wait_budget_ms().load(std::memory_order_relaxed)); } | ||
| 146 | inline void set_wait_budget(std::chrono::milliseconds budget) { wait_budget_ms().store(budget.count()); } | ||
| 147 | |||
| 148 | inline Sharing shared_budget() { | ||
| 149 | #ifdef _WIN32 | ||
| 150 | char text[16] = {}; | ||
| 151 | std::size_t length = 0; | ||
| 152 | static const Sharing sharing = | ||
| 153 | getenv_s(&length, text, sizeof(text), "LEONIDA_PIPELINE_WAIT_SHARED") == 0 && length > 1 ? sharing_from(text) | ||
| 154 | : Sharing::window; | ||
| 155 | #else | ||
| 156 | static const Sharing sharing = sharing_from(std::getenv("LEONIDA_PIPELINE_WAIT_SHARED")); | ||
| 157 | #endif | ||
| 158 | return sharing; | ||
| 159 | } | ||
| 160 | |||
| 161 | // LEONIDA_PIPELINE_WORKERS: build threads (make.rs:528-561: half the logical processors, 2 to 8). 0 builds each | ||
| 162 | // pipeline on the thread that starts it, as before. | ||
| 163 | inline unsigned worker_count() { | ||
| 164 | const unsigned hardware = std::max(1u, std::thread::hardware_concurrency()); | ||
| 165 | const long long fallback = std::clamp(hardware / 2, 2u, 8u); | ||
| 166 | return unsigned(std::min<long long>(env_number("LEONIDA_PIPELINE_WORKERS", fallback), 64)); | ||
| 167 | } | ||
| 168 | |||
| 169 | // ---- One frame's waiting (make.rs:334-394) --------------------------------------------------------------------- | ||
| 170 | |||
| 171 | struct FrameWait { | ||
| 172 | std::uint64_t frame = UINT64_MAX; | ||
| 173 | // The waiting counted against the budget so far (the window: time in which some thread waited, up to `since`). | ||
| 174 | Clock::duration spent{}; | ||
| 175 | // The window: threads waiting now, and since when one has been. | ||
| 176 | std::uint32_t waiting = 0; | ||
| 177 | bool open = false; | ||
| 178 | Clock::time_point since{}; | ||
| 179 | |||
| 180 | // A thread is to wait in `frame` at `now`: how long it may. | ||
| 181 | Clock::duration begin(Sharing sharing, std::uint64_t at_frame, Clock::duration budget, Clock::time_point now) { | ||
| 182 | if (frame != at_frame) *this = FrameWait{at_frame}; | ||
| 183 | if (sharing == Sharing::window) { | ||
| 184 | const Clock::duration opened = open ? now - since : Clock::duration::zero(); | ||
| 185 | const Clock::duration left = std::max(Clock::duration::zero(), budget - (spent + opened)); | ||
| 186 | if (left > Clock::duration::zero()) { | ||
| 187 | if (waiting == 0) { | ||
| 188 | since = now; | ||
| 189 | open = true; | ||
| 190 | } | ||
| 191 | ++waiting; | ||
| 192 | } | ||
| 193 | return left; | ||
| 194 | } | ||
| 195 | const Clock::duration left = std::max(Clock::duration::zero(), budget - spent); | ||
| 196 | if (sharing == Sharing::reserve) spent += left; | ||
| 197 | return left; | ||
| 198 | } | ||
| 199 | |||
| 200 | // The thread `begin` gave `left` (more than nothing) in `at_frame` has waited `waited` and stops at `now`. A frame | ||
| 201 | // that began meanwhile has its own budget. | ||
| 202 | void end(Sharing sharing, std::uint64_t at_frame, Clock::duration left, Clock::duration waited, | ||
| 203 | Clock::time_point now) { | ||
| 204 | if (frame != at_frame) return; | ||
| 205 | switch (sharing) { | ||
| 206 | case Sharing::window: | ||
| 207 | if (waiting) --waiting; | ||
| 208 | if (waiting == 0 && open) { | ||
| 209 | spent += now - since; | ||
| 210 | open = false; | ||
| 211 | } | ||
| 212 | break; | ||
| 213 | case Sharing::reserve: spent = std::max(Clock::duration::zero(), spent - (left - waited)); break; | ||
| 214 | case Sharing::per_thread: spent += waited; break; | ||
| 215 | } | ||
| 216 | } | ||
| 217 | }; | ||
| 218 | |||
| 219 | // Whether the driver has held a pipeline longer than most take, so no frame waits for it (make.rs:225-234): 10 s for | ||
| 220 | // a compute pipeline, 3 s for others, while the frame budget is shorter than that. | ||
| 221 | inline bool held_too_long(Clock::duration held, bool compute, Clock::duration base) { | ||
| 222 | const Clock::duration most = std::chrono::seconds(compute ? 10 : 3); | ||
| 223 | return base < most && held > most; | ||
| 224 | } | ||
| 225 | |||
| 226 | // LEONIDA_PIPELINE_GATE_S (120): the most a run waits past the frame budget for each kind while a world loads, all | ||
| 227 | // frames together (make.rs:198-211); 0 waits as the budget alone. | ||
| 228 | // Read once; set_loading_allowance overrides it (tests that measure the frame budget alone set 0). | ||
| 229 | inline std::atomic<std::int64_t>& loading_allowance_s() { | ||
| 230 | static std::atomic<std::int64_t> seconds{env_number("LEONIDA_PIPELINE_GATE_S", 120)}; | ||
| 231 | return seconds; | ||
| 232 | } | ||
| 233 | inline Clock::duration loading_allowance() { | ||
| 234 | return std::chrono::seconds(loading_allowance_s().load(std::memory_order_relaxed)); | ||
| 235 | } | ||
| 236 | inline void set_loading_allowance(std::chrono::seconds total) { loading_allowance_s().store(total.count()); } | ||
| 237 | |||
| 238 | // A frame's budget for a pipeline of one kind (make.rs:213-219): the frame budget, or while the run's allowance for | ||
| 239 | // that kind lasts (`spent` of it gone) up to kLoadingFrameMs or kLoadingFrameComputeMs. | ||
| 240 | inline Clock::duration frame_budget(Clock::duration base, bool compute, Clock::duration allowance, | ||
| 241 | Clock::duration spent) { | ||
| 242 | const Clock::duration loading = std::chrono::milliseconds(compute ? kLoadingFrameComputeMs : kLoadingFrameMs); | ||
| 243 | const Clock::duration rest = std::max(Clock::duration::zero(), allowance - spent); | ||
| 244 | return std::max(base, std::min(loading, rest)); | ||
| 245 | } | ||
| 246 | |||
| 247 | // ---- A pipeline to make ---------------------------------------------------------------------------------------- | ||
| 248 | |||
| 249 | inline constexpr std::uint8_t kNotQueued = 0, kEarly = 1, kRequested = 2, kMaking = 3; | ||
| 250 | |||
| 251 | class Builder; | ||
| 252 | |||
| 253 | // What a pipeline state's Vulkan pipeline is made from (a function the state sets once), and whether it is made. | ||
| 254 | class Job { | ||
| 255 | public: | ||
| 256 | Job(bool compute, bool depth_only) : compute_(compute), depth_only_(depth_only) {} | ||
| 257 | Job(const Job&) = delete; | ||
| 258 | Job& operator=(const Job&) = delete; | ||
| 259 | |||
| 260 | // The pipeline is made: what the draws and dispatches recorded with it check. | ||
| 261 | bool ready() const { return made_.load(std::memory_order_acquire); } | ||
| 262 | // The build ran, and made the pipeline or did not (refused). | ||
| 263 | bool finished() const { return finished_.load(std::memory_order_acquire); } | ||
| 264 | bool compute() const { return compute_; } | ||
| 265 | bool depth_only() const { return depth_only_; } | ||
| 266 | std::uint8_t queue_state() const { return queue_.load(std::memory_order_relaxed); } | ||
| 267 | |||
| 268 | // Set once, before the job is started. `work` returns whether it made the pipeline. | ||
| 269 | void set_work(std::function<bool()> work) { work_ = std::move(work); } | ||
| 270 | |||
| 271 | // The pipeline state is going away: a queued build is not run, and a running one is waited for. | ||
| 272 | void retire() { | ||
| 273 | std::unique_lock lock(mutex_); | ||
| 274 | retired_ = true; | ||
| 275 | done_.wait(lock, [&] { return !running_; }); | ||
| 276 | work_ = nullptr; | ||
| 277 | } | ||
| 278 | |||
| 279 | // Makes it on this thread unless a worker has it, then waits for that worker (make.rs `now`); whether it is made. | ||
| 280 | // The builder's counts leave such a build out. | ||
| 281 | bool run_now() { | ||
| 282 | run(); | ||
| 283 | wait_finished(); | ||
| 284 | return ready(); | ||
| 285 | } | ||
| 286 | |||
| 287 | // Waits however long the build takes (a retired job that never ran ends the wait too). | ||
| 288 | void wait_finished() { | ||
| 289 | std::unique_lock lock(mutex_); | ||
| 290 | done_.wait(lock, [&] { return finished_.load(std::memory_order_relaxed) || (retired_ && !running_); }); | ||
| 291 | } | ||
| 292 | bool wait_finished_for(Clock::duration limit) { | ||
| 293 | std::unique_lock lock(mutex_); | ||
| 294 | return done_.wait_for(lock, limit, [&] { return finished_.load(std::memory_order_relaxed); }); | ||
| 295 | } | ||
| 296 | |||
| 297 | // How long a worker has been at it; zero when none has begun. | ||
| 298 | Clock::duration held() const { | ||
| 299 | const std::int64_t begun = begun_.load(std::memory_order_relaxed); | ||
| 300 | if (!begun || finished()) return Clock::duration::zero(); | ||
| 301 | return Clock::now().time_since_epoch() - Clock::duration(begun); | ||
| 302 | } | ||
| 303 | |||
| 304 | // How long the build took (zero before it finished). | ||
| 305 | Clock::duration took() const { return Clock::duration(took_.load(std::memory_order_relaxed)); } | ||
| 306 | |||
| 307 | private: | ||
| 308 | friend class Builder; | ||
| 309 | |||
| 310 | // Runs the build unless it ran or the job was retired; whether it ran here. | ||
| 311 | bool run() { | ||
| 312 | { | ||
| 313 | std::lock_guard lock(mutex_); | ||
| 314 | if (retired_ || claimed_) return false; | ||
| 315 | claimed_ = true; | ||
| 316 | running_ = true; | ||
| 317 | } | ||
| 318 | const Clock::time_point begun = Clock::now(); | ||
| 319 | begun_.store(begun.time_since_epoch().count(), std::memory_order_relaxed); | ||
| 320 | bool made = false; | ||
| 321 | try { | ||
| 322 | made = work_ && work_(); | ||
| 323 | } catch (...) { | ||
| 324 | made = false; // nothing may leave a worker | ||
| 325 | } | ||
| 326 | took_.store((Clock::now() - begun).count(), std::memory_order_relaxed); | ||
| 327 | std::lock_guard lock(mutex_); | ||
| 328 | running_ = false; | ||
| 329 | made_.store(made, std::memory_order_release); | ||
| 330 | finished_.store(true, std::memory_order_release); | ||
| 331 | done_.notify_all(); | ||
| 332 | return true; | ||
| 333 | } | ||
| 334 | |||
| 335 | const bool compute_; | ||
| 336 | const bool depth_only_; | ||
| 337 | std::atomic<std::uint8_t> queue_{kNotQueued}; | ||
| 338 | std::atomic<bool> made_{false}; | ||
| 339 | std::atomic<bool> finished_{false}; | ||
| 340 | std::atomic<Clock::rep> begun_{0}; | ||
| 341 | std::atomic<Clock::rep> took_{0}; | ||
| 342 | std::mutex mutex_; | ||
| 343 | std::condition_variable done_; | ||
| 344 | bool retired_ = false; | ||
| 345 | bool claimed_ = false; | ||
| 346 | bool running_ = false; | ||
| 347 | std::function<bool()> work_; | ||
| 348 | }; | ||
| 349 | |||
| 350 | // ---- Drops (pipeline.rs:461-564) --------------------------------------------------------------------------------- | ||
| 351 | |||
| 352 | struct DropCounts { | ||
| 353 | std::uint64_t draws = 0; // a draw whose pipeline was still being made | ||
| 354 | std::uint64_t dispatches = 0; // a dispatch whose pipeline was still being made | ||
| 355 | std::uint64_t refused = 0; // either, whose pipeline could not be made | ||
| 356 | }; | ||
| 357 | |||
| 358 | class Drops { | ||
| 359 | public: | ||
| 360 | static Drops& get() { | ||
| 361 | static Drops* drops = new Drops(); // never destroyed: see the file's notes | ||
| 362 | return *drops; | ||
| 363 | } | ||
| 364 | |||
| 365 | // A draw or dispatch recorded with `job` (not ready) is dropped. Logged once a second, with what was dropped | ||
| 366 | // since the last line. | ||
| 367 | void note(const Job& job, bool dispatch, std::uint64_t waiting) { | ||
| 368 | if (job.finished()) refused_.fetch_add(1, std::memory_order_relaxed); | ||
| 369 | else (dispatch ? dispatches_ : draws_).fetch_add(1, std::memory_order_relaxed); | ||
| 370 | const std::int64_t now = std::chrono::duration_cast<std::chrono::milliseconds>( | ||
| 371 | Clock::now().time_since_epoch()).count(); | ||
| 372 | std::int64_t last = last_ms_.load(std::memory_order_relaxed); | ||
| 373 | if (now - last < 1000 || !last_ms_.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; | ||
| 374 | const DropCounts total = counts(); | ||
| 375 | std::lock_guard lock(log_mutex_); | ||
| 376 | std::fprintf(stderr, | ||
| 377 | "[rt] d3d12: pipelines: %llu draws and %llu dispatches dropped while their pipelines are made, " | ||
| 378 | "%llu whose pipelines could not be made (since the last line; %llu pipelines waiting to be " | ||
| 379 | "made)\n", | ||
| 380 | static_cast<unsigned long long>(total.draws - logged_.draws), | ||
| 381 | static_cast<unsigned long long>(total.dispatches - logged_.dispatches), | ||
| 382 | static_cast<unsigned long long>(total.refused - logged_.refused), | ||
| 383 | static_cast<unsigned long long>(waiting)); | ||
| 384 | logged_ = total; | ||
| 385 | } | ||
| 386 | |||
| 387 | DropCounts counts() const { | ||
| 388 | return {draws_.load(std::memory_order_relaxed), dispatches_.load(std::memory_order_relaxed), | ||
| 389 | refused_.load(std::memory_order_relaxed)}; | ||
| 390 | } | ||
| 391 | |||
| 392 | private: | ||
| 393 | std::atomic<std::uint64_t> draws_{0}, dispatches_{0}, refused_{0}; | ||
| 394 | std::atomic<std::int64_t> last_ms_{0}; | ||
| 395 | std::mutex log_mutex_; | ||
| 396 | DropCounts logged_; | ||
| 397 | }; | ||
| 398 | |||
| 399 | // ---- Pipelines earlier runs bound (library.rs:10-13, 431-438, 567-714) ------------------------------------------- | ||
| 400 | |||
| 401 | // Keys (known at creation: a hash of the description) of the pipelines this and earlier runs bound, one per line in | ||
| 402 | // `early-pipelines.txt` beside the pipeline cache. A run starts those at creation. The file keeps what earlier runs | ||
| 403 | // listed (library.rs:613-616), at most kMax keys; it is written whole to a temporary file and renamed over the list, | ||
| 404 | // so a reader never sees a part (library.rs:676-682). | ||
| 405 | class EarlyList { | ||
| 406 | public: | ||
| 407 | static constexpr std::size_t kMax = 8192; // library.rs:437 | ||
| 408 | static constexpr std::chrono::seconds kSaveEvery{20}; // library.rs:571 | ||
| 409 | |||
| 410 | static EarlyList& get() { | ||
| 411 | static EarlyList* list = new EarlyList(); // never destroyed: see the file's notes | ||
| 412 | return *list; | ||
| 413 | } | ||
| 414 | |||
| 415 | // Where the list is kept (empty: nowhere). `always`: written whatever runs (a path the user or a test named); | ||
| 416 | // otherwise only for a title (waits_bounded), so the PC-interface tests leave no file beside their executables. | ||
| 417 | // The first call wins, unless `replace`. | ||
| 418 | void configure(const std::filesystem::path& file, bool always, bool replace = false) { | ||
| 419 | std::lock_guard lock(mutex_); | ||
| 420 | if (configured_ && !replace) return; | ||
| 421 | configured_ = true; | ||
| 422 | file_ = file; | ||
| 423 | always_ = always; | ||
| 424 | loaded_ = false; | ||
| 425 | keys_.clear(); | ||
| 426 | changed_ = false; | ||
| 427 | last_save_ = Clock::time_point{}; | ||
| 428 | } | ||
| 429 | |||
| 430 | // Whether a pipeline with `key` was bound in this or an earlier run (library.rs:702-705). | ||
| 431 | bool wanted(const std::string& key) { | ||
| 432 | std::lock_guard lock(mutex_); | ||
| 433 | load_locked(); | ||
| 434 | return keys_.count(key) != 0; | ||
| 435 | } | ||
| 436 | |||
| 437 | // A bind asked for the pipeline with `key` (library.rs:707-714). | ||
| 438 | void note_used(const std::string& key) { | ||
| 439 | if (key.empty()) return; | ||
| 440 | std::lock_guard lock(mutex_); | ||
| 441 | load_locked(); | ||
| 442 | if (keys_.size() < kMax && keys_.insert(key).second) changed_ = true; | ||
| 443 | } | ||
| 444 | |||
| 445 | // Writes the list if it changed since the last save and kSaveEvery has passed (or `now`); whether it wrote. One save | ||
| 446 | // at a time, start to rename: a call returns after any save under way has put its file in place. | ||
| 447 | bool save(bool now) { | ||
| 448 | std::lock_guard saving(save_mutex_); | ||
| 449 | std::vector<std::string> keys; | ||
| 450 | std::filesystem::path file; | ||
| 451 | { | ||
| 452 | std::lock_guard lock(mutex_); | ||
| 453 | if (!changed_ || file_.empty() || (!always_ && !waits_bounded())) return false; | ||
| 454 | const Clock::time_point at = Clock::now(); | ||
| 455 | if (!now && last_save_ != Clock::time_point{} && at - last_save_ < kSaveEvery) return false; | ||
| 456 | last_save_ = at; | ||
| 457 | changed_ = false; | ||
| 458 | keys.assign(keys_.begin(), keys_.end()); | ||
| 459 | file = file_; | ||
| 460 | } | ||
| 461 | std::sort(keys.begin(), keys.end()); | ||
| 462 | std::string text; | ||
| 463 | for (const std::string& key : keys) text += key + "\n"; | ||
| 464 | std::error_code ec; | ||
| 465 | std::filesystem::path tmp = file; | ||
| 466 | tmp += ".tmp"; | ||
| 467 | { | ||
| 468 | std::ofstream out(tmp, std::ios::binary | std::ios::trunc); | ||
| 469 | out.write(text.data(), std::streamsize(text.size())); | ||
| 470 | if (!out) { | ||
| 471 | std::fprintf(stderr, "[rt] d3d12: pipelines: the early list could not be written\n"); | ||
| 472 | std::lock_guard lock(mutex_); | ||
| 473 | changed_ = true; | ||
| 474 | return false; | ||
| 475 | } | ||
| 476 | } | ||
| 477 | std::filesystem::rename(tmp, file, ec); | ||
| 478 | if (ec) { | ||
| 479 | std::filesystem::remove(tmp, ec); | ||
| 480 | std::lock_guard lock(mutex_); | ||
| 481 | changed_ = true; | ||
| 482 | return false; | ||
| 483 | } | ||
| 484 | saves_.fetch_add(1, std::memory_order_relaxed); | ||
| 485 | return true; | ||
| 486 | } | ||
| 487 | |||
| 488 | std::size_t size() { | ||
| 489 | std::lock_guard lock(mutex_); | ||
| 490 | load_locked(); | ||
| 491 | return keys_.size(); | ||
| 492 | } | ||
| 493 | std::uint64_t saves() const { return saves_.load(std::memory_order_relaxed); } | ||
| 494 | |||
| 495 | // Reads the file again, as the next run would (tests). | ||
| 496 | void reload() { | ||
| 497 | std::lock_guard lock(mutex_); | ||
| 498 | loaded_ = false; | ||
| 499 | keys_.clear(); | ||
| 500 | changed_ = false; | ||
| 501 | load_locked(); | ||
| 502 | } | ||
| 503 | |||
| 504 | private: | ||
| 505 | void load_locked() { | ||
| 506 | if (loaded_) return; | ||
| 507 | loaded_ = true; | ||
| 508 | if (file_.empty()) return; | ||
| 509 | std::ifstream in(file_, std::ios::binary); | ||
| 510 | std::string line; | ||
| 511 | while (in && std::getline(in, line) && keys_.size() < kMax) { | ||
| 512 | if (!line.empty() && line.back() == '\r') line.pop_back(); | ||
| 513 | if (!line.empty()) keys_.insert(line); | ||
| 514 | } | ||
| 515 | if (!keys_.empty()) | ||
| 516 | std::fprintf(stderr, "[rt] d3d12: pipelines: %zu pipelines earlier runs bound are started at creation\n", | ||
| 517 | keys_.size()); | ||
| 518 | } | ||
| 519 | |||
| 520 | std::mutex mutex_; | ||
| 521 | std::mutex save_mutex_; // held through a whole save; taken before mutex_ | ||
| 522 | std::filesystem::path file_; | ||
| 523 | bool configured_ = false; | ||
| 524 | bool always_ = false; | ||
| 525 | bool loaded_ = false; | ||
| 526 | bool changed_ = false; | ||
| 527 | Clock::time_point last_save_{}; | ||
| 528 | std::unordered_set<std::string> keys_; | ||
| 529 | std::atomic<std::uint64_t> saves_{0}; | ||
| 530 | }; | ||
| 531 | |||
| 532 | // ---- The builder (make.rs:440-580) --------------------------------------------------------------------------------- | ||
| 533 | |||
| 534 | struct BuilderStats { | ||
| 535 | std::uint64_t made = 0; // pipelines made | ||
| 536 | std::uint64_t refused = 0; // builds that made none | ||
| 537 | std::uint64_t started_early = 0; // started at creation from the early list | ||
| 538 | std::uint64_t waiting = 0; // queued and not made yet | ||
| 539 | std::uint64_t waited_us = 0; // waiting at binds in all | ||
| 540 | }; | ||
| 541 | |||
| 542 | class Builder { | ||
| 543 | public: | ||
| 544 | static Builder& get() { | ||
| 545 | static Builder* builder = new Builder(); // never destroyed: see the file's notes | ||
| 546 | return *builder; | ||
| 547 | } | ||
| 548 | |||
| 549 | // Starts `job` (kEarly at creation, kRequested at a bind), or promotes one queued early (make.rs `start`). | ||
| 550 | void start(const std::shared_ptr<Job>& job, std::uint8_t priority) { | ||
| 551 | if (job->queue_.load(std::memory_order_relaxed) >= priority) return; | ||
| 552 | if (!workers()) { | ||
| 553 | if (job->queue_.exchange(kMaking, std::memory_order_relaxed) == kNotQueued && job->run()) count(*job); | ||
| 554 | return; | ||
| 555 | } | ||
| 556 | std::lock_guard lock(mutex_); | ||
| 557 | const std::uint8_t previous = job->queue_.load(std::memory_order_relaxed); | ||
| 558 | if (previous >= priority) return; | ||
| 559 | job->queue_.store(priority, std::memory_order_relaxed); | ||
| 560 | if (priority == kRequested) requested_.push_back(job); | ||
| 561 | else if (job->depth_only()) early_depth_.push_back(job); // shadow maps and depth prepasses feed later draws | ||
| 562 | else early_.push_back(job); | ||
| 563 | if (previous == kNotQueued) { | ||
| 564 | if (priority == kEarly) started_early_.fetch_add(1, std::memory_order_relaxed); | ||
| 565 | peak_ = std::max(peak_, ++waiting_); | ||
| 566 | } | ||
| 567 | available_.notify_one(); | ||
| 568 | } | ||
| 569 | |||
| 570 | // At a bind of a pipeline `start` was given: waits for it while the current frame's budget lasts (make.rs `wait`), | ||
| 571 | // or without a limit where waits are not bounded (waits_bounded). Whether it is made. | ||
| 572 | bool wait(Job& job) { | ||
| 573 | if (job.finished()) return job.ready(); | ||
| 574 | const std::uint64_t frame = current_frame(); | ||
| 575 | const Clock::time_point started = Clock::now(); | ||
| 576 | if (!waits_bounded()) { | ||
| 577 | job.wait_finished(); | ||
| 578 | add_wait(Clock::now() - started); | ||
| 579 | return job.ready(); | ||
| 580 | } | ||
| 581 | const Clock::duration base = wait_budget(); | ||
| 582 | if (base <= Clock::duration::zero() || held_too_long(job.held(), job.compute(), base)) return job.ready(); | ||
| 583 | const Sharing sharing = shared_budget(); | ||
| 584 | const int kind = job.compute() ? 1 : 0; | ||
| 585 | FrameWait& frame_wait = frames_[kind]; | ||
| 586 | Clock::duration left; | ||
| 587 | { | ||
| 588 | std::lock_guard lock(frames_mutex_); | ||
| 589 | const Clock::duration budget = frame_budget(base, kind == 1, loading_allowance(), loading_spent_[kind]); | ||
| 590 | left = frame_wait.begin(sharing, frame, budget, started); | ||
| 591 | } | ||
| 592 | if (left <= Clock::duration::zero()) return job.ready(); | ||
| 593 | { | ||
| 594 | std::unique_lock lock(job.mutex_); | ||
| 595 | while (!job.finished_.load(std::memory_order_relaxed) && !job.retired_ && | ||
| 596 | !held_too_long(job.held(), job.compute(), base)) { | ||
| 597 | const Clock::duration rest = left - (Clock::now() - started); | ||
| 598 | if (rest <= Clock::duration::zero()) break; | ||
| 599 | // Woken now and then to see whether it has become a slow one. | ||
| 600 | job.done_.wait_for(lock, std::min<Clock::duration>(rest, std::chrono::milliseconds(250))); | ||
| 601 | } | ||
| 602 | } | ||
| 603 | const Clock::time_point ended = Clock::now(); | ||
| 604 | const Clock::duration waited = std::min(ended - started, left); | ||
| 605 | { | ||
| 606 | std::lock_guard lock(frames_mutex_); | ||
| 607 | frame_wait.end(sharing, frame, left, waited, ended); | ||
| 608 | // What the frame budget alone would not have allowed counts against the loading allowance. | ||
| 609 | if (waited > base) loading_spent_[kind] += waited - base; | ||
| 610 | } | ||
| 611 | add_wait(waited); | ||
| 612 | return job.ready(); | ||
| 613 | } | ||
| 614 | |||
| 615 | BuilderStats stats() const { | ||
| 616 | std::lock_guard lock(mutex_); | ||
| 617 | return {made_.load(std::memory_order_relaxed), refused_.load(std::memory_order_relaxed), | ||
| 618 | started_early_.load(std::memory_order_relaxed), waiting_, | ||
| 619 | waited_us_.load(std::memory_order_relaxed)}; | ||
| 620 | } | ||
| 621 | std::uint64_t waiting() const { | ||
| 622 | std::lock_guard lock(mutex_); | ||
| 623 | return waiting_; | ||
| 624 | } | ||
| 625 | |||
| 626 | // Tests: while held, workers take no job (queued ones wait), so a test can see draws dropped deterministically. | ||
| 627 | void hold(bool held) { | ||
| 628 | std::lock_guard lock(mutex_); | ||
| 629 | held_ = held; | ||
| 630 | if (!held_) available_.notify_all(); | ||
| 631 | } | ||
| 632 | |||
| 633 | private: | ||
| 634 | Builder() = default; | ||
| 635 | |||
| 636 | void add_wait(Clock::duration waited) { | ||
| 637 | waited_us_.fetch_add(std::uint64_t(std::chrono::duration_cast<std::chrono::microseconds>(waited).count()), | ||
| 638 | std::memory_order_relaxed); | ||
| 639 | } | ||
| 640 | |||
| 641 | void count(const Job& job) { | ||
| 642 | (job.ready() ? made_ : refused_).fetch_add(1, std::memory_order_relaxed); | ||
| 643 | const auto took = job.took(); | ||
| 644 | if (took > std::chrono::seconds(10)) | ||
| 645 | std::fprintf(stderr, "[rt] d3d12: pipelines: one %s pipeline took %.1f s to make\n", | ||
| 646 | job.compute() ? "compute" : "graphics", std::chrono::duration<double>(took).count()); | ||
| 647 | } | ||
| 648 | |||
| 649 | // Starts the workers on first use; false when none could be started (or LEONIDA_PIPELINE_WORKERS=0). | ||
| 650 | bool workers() { | ||
| 651 | std::call_once(workers_once_, [this] { | ||
| 652 | const unsigned count = worker_count(); | ||
| 653 | unsigned started = 0; | ||
| 654 | for (unsigned i = 0; i < count; ++i) { | ||
| 655 | try { | ||
| 656 | std::thread([this, i] { loop(i); }).detach(); | ||
| 657 | ++started; | ||
| 658 | } catch (const std::exception&) { | ||
| 659 | break; | ||
| 660 | } | ||
| 661 | } | ||
| 662 | running_ = started > 0; | ||
| 663 | std::fprintf(stderr, | ||
| 664 | "[rt] d3d12: pipelines: made on %u threads; a bind waits up to %lld ms per frame and kind " | ||
| 665 | "(LEONIDA_PIPELINE_WAIT_MS) once the frame clock runs\n", | ||
| 666 | started, static_cast<long long>(wait_budget_ms().load())); | ||
| 667 | }); | ||
| 668 | return running_; | ||
| 669 | } | ||
| 670 | |||
| 671 | void loop(unsigned index) { | ||
| 672 | (void)index; | ||
| 673 | #ifdef _WIN32 | ||
| 674 | // Below the title's own threads (loading, recording), as make.rs:538-543. | ||
| 675 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); | ||
| 676 | #endif | ||
| 677 | for (;;) { | ||
| 678 | std::shared_ptr<Job> job = next(); | ||
| 679 | if (job->run()) count(*job); | ||
| 680 | job.reset(); | ||
| 681 | bool drained = false; | ||
| 682 | std::uint64_t peak = 0; | ||
| 683 | { | ||
| 684 | std::lock_guard lock(mutex_); | ||
| 685 | if (waiting_) --waiting_; | ||
| 686 | if (waiting_ == 0) { | ||
| 687 | drained = true; | ||
| 688 | peak = peak_; | ||
| 689 | peak_ = 0; | ||
| 690 | } | ||
| 691 | } | ||
| 692 | if (drained && peak >= 10) { | ||
| 693 | const BuilderStats s = stats(); | ||
| 694 | std::fprintf(stderr, | ||
| 695 | "[rt] d3d12: pipelines: all made (%llu made, %llu could not be made, %llu started early; " | ||
| 696 | "%.1f s waited for at binds in all)\n", | ||
| 697 | static_cast<unsigned long long>(s.made), static_cast<unsigned long long>(s.refused), | ||
| 698 | static_cast<unsigned long long>(s.started_early), double(s.waited_us) / 1e6); | ||
| 699 | } | ||
| 700 | EarlyList::get().save(drained); | ||
| 701 | } | ||
| 702 | } | ||
| 703 | |||
| 704 | std::shared_ptr<Job> next() { | ||
| 705 | std::unique_lock lock(mutex_); | ||
| 706 | for (;;) { | ||
| 707 | if (!held_) { | ||
| 708 | if (std::shared_ptr<Job> job = pop()) return job; | ||
| 709 | } | ||
| 710 | available_.wait(lock); | ||
| 711 | } | ||
| 712 | } | ||
| 713 | |||
| 714 | std::shared_ptr<Job> pop() { | ||
| 715 | std::shared_ptr<Job> job; | ||
| 716 | if (!requested_.empty()) { | ||
| 717 | job = std::move(requested_.front()); | ||
| 718 | requested_.pop_front(); | ||
| 719 | } else { | ||
| 720 | // An early entry can have been promoted and claimed already. | ||
| 721 | for (auto* queue : {&early_depth_, &early_}) { | ||
| 722 | while (!job && !queue->empty()) { | ||
| 723 | std::shared_ptr<Job> front = std::move(queue->front()); | ||
| 724 | queue->pop_front(); | ||
| 725 | if (front->queue_.load(std::memory_order_relaxed) == kEarly) job = std::move(front); | ||
| 726 | } | ||
| 727 | if (job) break; | ||
| 728 | } | ||
| 729 | if (!job) return nullptr; | ||
| 730 | } | ||
| 731 | job->queue_.store(kMaking, std::memory_order_relaxed); | ||
| 732 | return job; | ||
| 733 | } | ||
| 734 | |||
| 735 | mutable std::mutex mutex_; | ||
| 736 | std::condition_variable available_; | ||
| 737 | std::deque<std::shared_ptr<Job>> requested_, early_depth_, early_; | ||
| 738 | std::uint64_t waiting_ = 0; | ||
| 739 | std::uint64_t peak_ = 0; | ||
| 740 | bool held_ = false; | ||
| 741 | std::once_flag workers_once_; | ||
| 742 | bool running_ = false; | ||
| 743 | std::atomic<std::uint64_t> made_{0}, refused_{0}, started_early_{0}, waited_us_{0}; | ||
| 744 | std::mutex frames_mutex_; | ||
| 745 | FrameWait frames_[2]; // graphics, compute | ||
| 746 | Clock::duration loading_spent_[2]{}; // waiting past the frame budget, per kind (loading_allowance) | ||
| 747 | }; | ||
| 748 | |||
| 749 | } // namespace leonida::pipelines | ||
diff --git a/runtime/src/png_write.h b/runtime/src/png_write.h deleted file mode 100644 index bf9e9e06e..000000000 --- a/runtime/src/png_write.h +++ /dev/null | |||
| @@ -1,257 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // PNG files for the presented-frame screenshots (shims/xbox_window.cpp, LEONIDA_CAPTURE_DIR): 8-bit RGB, one IDAT | ||
| 4 | // chunk, a zlib stream (RFC 1950) of one deflate block (RFC 1951) with the fixed Huffman codes and greedy LZ77 | ||
| 5 | // matches over a 32 KiB window. Each row gets the PNG filter (None, Sub, Up or Paeth) whose output has the smallest sum | ||
| 6 | // of absolute values, the usual heuristic. No third-party code and no Windows headers; the round trip is checked | ||
| 7 | // against leonida::zlib_inflate (src/shader_library.h) by png_write_test. | ||
| 8 | // | ||
| 9 | // VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; victory/crates/victory-gpu/src/capture.rs | ||
| 10 | // `save_as`, `chunk`, `crc32`) writes its frames as 8-bit RGB PNGs with the same chunk layout and CRC; it compresses | ||
| 11 | // with zlib-rs and halves the frame. This writer keeps the full size (a check reads the presented pixels) and carries | ||
| 12 | // its own deflate. | ||
| 13 | |||
| 14 | #include <algorithm> | ||
| 15 | #include <array> | ||
| 16 | #include <cstddef> | ||
| 17 | #include <cstdint> | ||
| 18 | #include <cstdlib> | ||
| 19 | #include <span> | ||
| 20 | #include <vector> | ||
| 21 | |||
| 22 | namespace leonida::png { | ||
| 23 | |||
| 24 | // CRC-32 (ISO 3309, the one PNG chunks carry), continued from `crc` (0 to start). | ||
| 25 | inline std::uint32_t crc32(std::span<const std::uint8_t> bytes, std::uint32_t crc = 0) { | ||
| 26 | static const std::array<std::uint32_t, 256> table = [] { | ||
| 27 | std::array<std::uint32_t, 256> t{}; | ||
| 28 | for (std::uint32_t n = 0; n < 256; ++n) { | ||
| 29 | std::uint32_t c = n; | ||
| 30 | for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1; | ||
| 31 | t[n] = c; | ||
| 32 | } | ||
| 33 | return t; | ||
| 34 | }(); | ||
| 35 | crc = ~crc; | ||
| 36 | for (const std::uint8_t b : bytes) crc = table[(crc ^ b) & 0xff] ^ (crc >> 8); | ||
| 37 | return ~crc; | ||
| 38 | } | ||
| 39 | |||
| 40 | inline std::uint32_t adler32(std::span<const std::uint8_t> bytes) { | ||
| 41 | std::uint32_t a = 1, b = 0; | ||
| 42 | std::size_t at = 0; | ||
| 43 | while (at < bytes.size()) { | ||
| 44 | const std::size_t run = std::min<std::size_t>(bytes.size() - at, 5552); // no overflow before the modulo | ||
| 45 | for (std::size_t i = 0; i < run; ++i) { | ||
| 46 | a += bytes[at + i]; | ||
| 47 | b += a; | ||
| 48 | } | ||
| 49 | a %= 65521u; | ||
| 50 | b %= 65521u; | ||
| 51 | at += run; | ||
| 52 | } | ||
| 53 | return (b << 16) | a; | ||
| 54 | } | ||
| 55 | |||
| 56 | namespace detail { | ||
| 57 | |||
| 58 | class BitWriter { | ||
| 59 | public: | ||
| 60 | explicit BitWriter(std::vector<std::uint8_t>& out) : out_(out) {} | ||
| 61 | // `count` bits of `value`, least significant first (deflate's order for everything but Huffman codes). | ||
| 62 | void bits(std::uint32_t value, unsigned count) { | ||
| 63 | held_ |= std::uint64_t(value) << used_; | ||
| 64 | used_ += count; | ||
| 65 | while (used_ >= 8) { | ||
| 66 | out_.push_back(std::uint8_t(held_)); | ||
| 67 | held_ >>= 8; | ||
| 68 | used_ -= 8; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | // A Huffman code of `length` bits, most significant bit first. | ||
| 72 | void code(std::uint32_t code, unsigned length) { | ||
| 73 | std::uint32_t reversed = 0; | ||
| 74 | for (unsigned i = 0; i < length; ++i) reversed |= ((code >> i) & 1u) << (length - 1 - i); | ||
| 75 | bits(reversed, length); | ||
| 76 | } | ||
| 77 | void flush() { | ||
| 78 | if (used_) out_.push_back(std::uint8_t(held_)); | ||
| 79 | held_ = 0; | ||
| 80 | used_ = 0; | ||
| 81 | } | ||
| 82 | |||
| 83 | private: | ||
| 84 | std::vector<std::uint8_t>& out_; | ||
| 85 | std::uint64_t held_ = 0; | ||
| 86 | unsigned used_ = 0; | ||
| 87 | }; | ||
| 88 | |||
| 89 | // The fixed literal/length code (RFC 1951 3.2.6). | ||
| 90 | inline void literal(BitWriter& w, unsigned symbol) { | ||
| 91 | if (symbol < 144) w.code(0x30 + symbol, 8); | ||
| 92 | else if (symbol < 256) w.code(0x190 + (symbol - 144), 9); | ||
| 93 | else if (symbol < 280) w.code(symbol - 256, 7); | ||
| 94 | else w.code(0xc0 + (symbol - 280), 8); | ||
| 95 | } | ||
| 96 | |||
| 97 | inline constexpr std::uint16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, | ||
| 98 | 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; | ||
| 99 | inline constexpr std::uint8_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, | ||
| 100 | 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; | ||
| 101 | inline constexpr std::uint16_t distance_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, | ||
| 102 | 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, | ||
| 103 | 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; | ||
| 104 | inline constexpr std::uint8_t distance_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, | ||
| 105 | 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; | ||
| 106 | |||
| 107 | inline void match(BitWriter& w, unsigned length, unsigned distance) { | ||
| 108 | unsigned l = 28; | ||
| 109 | while (length_base[l] > length) --l; | ||
| 110 | literal(w, 257 + l); | ||
| 111 | if (length_extra[l]) w.bits(length - length_base[l], length_extra[l]); | ||
| 112 | unsigned d = 29; | ||
| 113 | while (distance_base[d] > distance) --d; | ||
| 114 | w.code(d, 5); | ||
| 115 | if (distance_extra[d]) w.bits(distance - distance_base[d], distance_extra[d]); | ||
| 116 | } | ||
| 117 | |||
| 118 | } // namespace detail | ||
| 119 | |||
| 120 | // Raw deflate data (one final block, fixed Huffman codes) for `in`, appended to `out`. `chain` is how many earlier | ||
| 121 | // positions with the same three bytes are tried for a match (more: smaller and slower). | ||
| 122 | inline void deflate_fixed(std::span<const std::uint8_t> in, std::vector<std::uint8_t>& out, unsigned chain = 16) { | ||
| 123 | constexpr std::size_t window = 32768, min_match = 3, max_match = 258; | ||
| 124 | constexpr unsigned hash_bits = 15; | ||
| 125 | detail::BitWriter w(out); | ||
| 126 | w.bits(1, 1); // BFINAL | ||
| 127 | w.bits(1, 2); // BTYPE 01: fixed Huffman codes | ||
| 128 | std::vector<std::uint32_t> head(std::size_t(1) << hash_bits, 0); // position + 1 of the newest with this hash | ||
| 129 | std::vector<std::uint32_t> previous(window, 0); // the one before it, by position % window | ||
| 130 | const std::size_t n = in.size(); | ||
| 131 | const auto hash = [&](std::size_t at) { | ||
| 132 | const std::uint32_t v = std::uint32_t(in[at]) | std::uint32_t(in[at + 1]) << 8 | std::uint32_t(in[at + 2]) << 16; | ||
| 133 | return (v * 2654435761u) >> (32 - hash_bits); | ||
| 134 | }; | ||
| 135 | const auto insert = [&](std::size_t at) { | ||
| 136 | const std::uint32_t h = hash(at); | ||
| 137 | previous[at % window] = head[h]; | ||
| 138 | head[h] = std::uint32_t(at + 1); | ||
| 139 | }; | ||
| 140 | std::size_t at = 0; | ||
| 141 | while (at < n) { | ||
| 142 | std::size_t best_length = 0, best_distance = 0; | ||
| 143 | if (at + min_match <= n) { | ||
| 144 | const std::size_t limit = std::min(max_match, n - at); | ||
| 145 | std::uint32_t candidate = head[hash(at)]; | ||
| 146 | for (unsigned tries = 0; candidate && tries < chain; ++tries) { | ||
| 147 | const std::size_t from = candidate - 1; | ||
| 148 | if (at - from > window - 1) break; // deflate's distances stop at 32768; keep one back for safety | ||
| 149 | if (in[from + best_length] == in[at + best_length]) { | ||
| 150 | std::size_t length = 0; | ||
| 151 | while (length < limit && in[from + length] == in[at + length]) ++length; | ||
| 152 | if (length > best_length) { | ||
| 153 | best_length = length; | ||
| 154 | best_distance = at - from; | ||
| 155 | if (length == limit) break; | ||
| 156 | } | ||
| 157 | } | ||
| 158 | const std::uint32_t next = previous[from % window]; | ||
| 159 | if (next >= candidate) break; // the slot was reused by a newer position: the chain ends here | ||
| 160 | candidate = next; | ||
| 161 | } | ||
| 162 | } | ||
| 163 | if (best_length >= min_match) { | ||
| 164 | detail::match(w, unsigned(best_length), unsigned(best_distance)); | ||
| 165 | for (std::size_t i = 0; i < best_length; ++i) | ||
| 166 | if (at + i + min_match <= n) insert(at + i); | ||
| 167 | at += best_length; | ||
| 168 | } else { | ||
| 169 | detail::literal(w, in[at]); | ||
| 170 | if (at + min_match <= n) insert(at); | ||
| 171 | ++at; | ||
| 172 | } | ||
| 173 | } | ||
| 174 | detail::literal(w, 256); // end of block | ||
| 175 | w.flush(); | ||
| 176 | } | ||
| 177 | |||
| 178 | // A zlib stream (RFC 1950) of `in`. | ||
| 179 | inline std::vector<std::uint8_t> zlib_compress(std::span<const std::uint8_t> in) { | ||
| 180 | std::vector<std::uint8_t> out{0x78, 0x01}; // deflate, 32 KiB window, no dictionary; (0x7801 % 31) == 0 | ||
| 181 | out.reserve(in.size() / 2 + 64); | ||
| 182 | deflate_fixed(in, out); | ||
| 183 | const std::uint32_t adler = adler32(in); | ||
| 184 | for (int shift = 24; shift >= 0; shift -= 8) out.push_back(std::uint8_t(adler >> shift)); | ||
| 185 | return out; | ||
| 186 | } | ||
| 187 | |||
| 188 | namespace detail { | ||
| 189 | |||
| 190 | inline std::uint8_t paeth(std::uint8_t a, std::uint8_t b, std::uint8_t c) { | ||
| 191 | const int p = int(a) + int(b) - int(c); | ||
| 192 | const int pa = std::abs(p - int(a)), pb = std::abs(p - int(b)), pc = std::abs(p - int(c)); | ||
| 193 | return pa <= pb && pa <= pc ? a : pb <= pc ? b : c; | ||
| 194 | } | ||
| 195 | |||
| 196 | inline void put_chunk(std::vector<std::uint8_t>& png, const char (&kind)[5], std::span<const std::uint8_t> data) { | ||
| 197 | const std::uint32_t length = std::uint32_t(data.size()); | ||
| 198 | for (int shift = 24; shift >= 0; shift -= 8) png.push_back(std::uint8_t(length >> shift)); | ||
| 199 | const std::size_t start = png.size(); | ||
| 200 | png.insert(png.end(), kind, kind + 4); | ||
| 201 | png.insert(png.end(), data.begin(), data.end()); | ||
| 202 | const std::uint32_t crc = crc32(std::span<const std::uint8_t>(png.data() + start, png.size() - start)); | ||
| 203 | for (int shift = 24; shift >= 0; shift -= 8) png.push_back(std::uint8_t(crc >> shift)); | ||
| 204 | } | ||
| 205 | |||
| 206 | } // namespace detail | ||
| 207 | |||
| 208 | // A PNG of 8-bit RGB pixels: `height` rows of `width * 3` bytes, `pitch` bytes apart. Empty for a zero size. | ||
| 209 | inline std::vector<std::uint8_t> encode_rgb8(std::uint32_t width, std::uint32_t height, const std::uint8_t* rgb, | ||
| 210 | std::size_t pitch) { | ||
| 211 | if (!width || !height || !rgb) return {}; | ||
| 212 | const std::size_t row = std::size_t(width) * 3; | ||
| 213 | std::vector<std::uint8_t> filtered; | ||
| 214 | filtered.reserve((row + 1) * height); | ||
| 215 | std::array<std::vector<std::uint8_t>, 4> candidates; // None, Sub, Up and Paeth (Average is not tried) | ||
| 216 | for (auto& c : candidates) c.resize(row); | ||
| 217 | for (std::uint32_t y = 0; y < height; ++y) { | ||
| 218 | const std::uint8_t* line = rgb + std::size_t(y) * pitch; | ||
| 219 | const std::uint8_t* above = y ? rgb + std::size_t(y - 1) * pitch : nullptr; | ||
| 220 | for (std::size_t i = 0; i < row; ++i) { | ||
| 221 | const std::uint8_t left = i >= 3 ? line[i - 3] : 0; | ||
| 222 | const std::uint8_t up = above ? above[i] : 0; | ||
| 223 | const std::uint8_t corner = above && i >= 3 ? above[i - 3] : 0; | ||
| 224 | candidates[0][i] = line[i]; | ||
| 225 | candidates[1][i] = std::uint8_t(line[i] - left); | ||
| 226 | candidates[2][i] = std::uint8_t(line[i] - up); | ||
| 227 | candidates[3][i] = std::uint8_t(line[i] - detail::paeth(left, up, corner)); | ||
| 228 | } | ||
| 229 | static constexpr std::uint8_t type[4] = {0, 1, 2, 4}; | ||
| 230 | std::size_t best = 0; | ||
| 231 | std::uint64_t best_sum = ~std::uint64_t(0); | ||
| 232 | for (std::size_t c = 0; c < 4; ++c) { | ||
| 233 | std::uint64_t sum = 0; | ||
| 234 | for (const std::uint8_t v : candidates[c]) sum += v < 128 ? v : 256 - v; | ||
| 235 | if (sum < best_sum) { | ||
| 236 | best_sum = sum; | ||
| 237 | best = c; | ||
| 238 | } | ||
| 239 | } | ||
| 240 | filtered.push_back(type[best]); | ||
| 241 | filtered.insert(filtered.end(), candidates[best].begin(), candidates[best].end()); | ||
| 242 | } | ||
| 243 | std::vector<std::uint8_t> png{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}; | ||
| 244 | std::uint8_t header[13] = {}; | ||
| 245 | for (int i = 0; i < 4; ++i) { | ||
| 246 | header[i] = std::uint8_t(width >> (24 - 8 * i)); | ||
| 247 | header[4 + i] = std::uint8_t(height >> (24 - 8 * i)); | ||
| 248 | } | ||
| 249 | header[8] = 8; // bits per channel | ||
| 250 | header[9] = 2; // colour type 2: RGB | ||
| 251 | detail::put_chunk(png, "IHDR", header); | ||
| 252 | detail::put_chunk(png, "IDAT", zlib_compress(filtered)); | ||
| 253 | detail::put_chunk(png, "IEND", {}); | ||
| 254 | return png; | ||
| 255 | } | ||
| 256 | |||
| 257 | } // namespace leonida::png | ||
diff --git a/runtime/src/rect_list_gs.cpp b/runtime/src/rect_list_gs.cpp deleted file mode 100644 index 9394aa0b1..000000000 --- a/runtime/src/rect_list_gs.cpp +++ /dev/null | |||
| @@ -1,691 +0,0 @@ | |||
| 1 | // The rectangle-list geometry stage (rect_list_gs.h). Ported from VIctory (GPL-3.0-or-later, Marvisak and | ||
| 2 | // contributors, DexNom fork; victory/crates/victory-shader/src/emit/rect.rs); Leonida is GPL-3.0-or-later too. | ||
| 3 | #include "rect_list_gs.h" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <array> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | #include <map> | ||
| 10 | #include <mutex> | ||
| 11 | #include <set> | ||
| 12 | #include <unordered_map> | ||
| 13 | #include <utility> | ||
| 14 | |||
| 15 | namespace leonida::rect_list { | ||
| 16 | namespace { | ||
| 17 | |||
| 18 | constexpr std::uint32_t kMagic = 0x07230203u; | ||
| 19 | constexpr std::uint32_t kMaxScalarsPerVertex = 128; // maxGeometryOutputComponents on the GPUs the layer targets | ||
| 20 | constexpr std::uint32_t kMaxScalars = 1024; // maxGeometryTotalOutputComponents' required minimum | ||
| 21 | |||
| 22 | namespace op { | ||
| 23 | enum : std::uint32_t { | ||
| 24 | memory_model = 14, entry_point = 15, execution_mode = 16, capability = 17, type_void = 19, type_bool = 20, | ||
| 25 | type_int = 21, type_float = 22, type_vector = 23, type_array = 28, type_struct = 30, type_pointer = 32, | ||
| 26 | type_function = 33, constant = 43, function = 54, function_end = 56, variable = 59, load = 61, store = 62, | ||
| 27 | access_chain = 65, decorate = 71, member_decorate = 72, composite_construct = 80, composite_extract = 81, | ||
| 28 | bitcast = 124, f_add = 129, f_sub = 131, logical_or = 166, logical_and = 167, logical_not = 168, select = 169, | ||
| 29 | i_equal = 170, f_ord_equal = 180, f_ord_greater_than = 186, emit_vertex = 218, end_primitive = 219, label = 248, | ||
| 30 | return_ = 253, | ||
| 31 | }; | ||
| 32 | } // namespace op | ||
| 33 | enum : std::uint32_t { cap_shader = 1, cap_geometry = 2, cap_clip_distance = 32, cap_cull_distance = 33 }; | ||
| 34 | enum : std::uint32_t { model_vertex = 0, model_geometry = 3 }; | ||
| 35 | enum : std::uint32_t { | ||
| 36 | mode_invocations = 0, mode_triangles = 22, mode_output_vertices = 26, mode_output_triangle_strip = 29, | ||
| 37 | }; | ||
| 38 | enum : std::uint32_t { storage_input = 1, storage_output = 3 }; | ||
| 39 | enum : std::uint32_t { deco_block = 2, deco_builtin = 11, deco_location = 30, deco_component = 31 }; | ||
| 40 | enum : std::uint32_t { | ||
| 41 | builtin_position = 0, builtin_point_size = 1, builtin_clip_distance = 3, builtin_cull_distance = 4, | ||
| 42 | builtin_primitive_id = 7, builtin_layer = 9, builtin_viewport_index = 10, | ||
| 43 | }; | ||
| 44 | |||
| 45 | const char* builtin_name(std::uint32_t b) { | ||
| 46 | switch (b) { | ||
| 47 | case builtin_position: return "Position"; | ||
| 48 | case builtin_point_size: return "PointSize"; | ||
| 49 | case builtin_clip_distance: return "ClipDistance"; | ||
| 50 | case builtin_cull_distance: return "CullDistance"; | ||
| 51 | case builtin_layer: return "Layer"; | ||
| 52 | case builtin_viewport_index: return "ViewportIndex"; | ||
| 53 | default: return nullptr; | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | // ---- Reading the vertex shader's interface ---- | ||
| 58 | |||
| 59 | struct Type { | ||
| 60 | std::uint32_t op = 0; | ||
| 61 | std::uint32_t a = 0, b = 0; // float: width; int: width, signedness; vector: component, count; | ||
| 62 | // array: element, length id; pointer: storage, pointee | ||
| 63 | std::vector<std::uint32_t> members; // struct | ||
| 64 | }; | ||
| 65 | |||
| 66 | struct Decorations { | ||
| 67 | std::uint32_t builtin = Output::kNoBuiltin; | ||
| 68 | bool has_location = false; | ||
| 69 | std::uint32_t location = 0, component = 0; | ||
| 70 | }; | ||
| 71 | |||
| 72 | class Interface { | ||
| 73 | public: | ||
| 74 | bool read(const std::vector<std::uint32_t>& w, std::string& why) { | ||
| 75 | if (w.size() < 5 || w[0] != kMagic) return fail(why, "not a SPIR-V module"); | ||
| 76 | bool entry = false; | ||
| 77 | for (std::size_t at = 5; at < w.size();) { | ||
| 78 | const std::uint32_t count = w[at] >> 16, code = w[at] & 0xffffu; | ||
| 79 | if (!count || at + count > w.size()) return fail(why, "a truncated instruction"); | ||
| 80 | const std::uint32_t* o = &w[at + 1]; // operands | ||
| 81 | const std::uint32_t n = count - 1; | ||
| 82 | switch (code) { | ||
| 83 | case op::capability: | ||
| 84 | if (n >= 1 && o[0] == cap_clip_distance) clip_capability = true; | ||
| 85 | if (n >= 1 && o[0] == cap_cull_distance) cull_capability = true; | ||
| 86 | break; | ||
| 87 | case op::entry_point: | ||
| 88 | if (n >= 2 && o[0] == model_vertex && !entry) { | ||
| 89 | entry = true; | ||
| 90 | std::uint32_t i = 2; | ||
| 91 | while (i < n) { // the name: a nul-terminated string | ||
| 92 | const std::uint32_t word = o[i++]; | ||
| 93 | if (!(word & 0xff000000u) || !(word & 0xff0000u) || !(word & 0xff00u) || !(word & 0xffu)) break; | ||
| 94 | } | ||
| 95 | interface.assign(o + i, o + n); | ||
| 96 | } | ||
| 97 | break; | ||
| 98 | case op::decorate: | ||
| 99 | if (n >= 3 && o[1] == deco_builtin) decorations[o[0]].builtin = o[2]; | ||
| 100 | if (n >= 3 && o[1] == deco_location) { | ||
| 101 | decorations[o[0]].has_location = true; | ||
| 102 | decorations[o[0]].location = o[2]; | ||
| 103 | } | ||
| 104 | if (n >= 3 && o[1] == deco_component) decorations[o[0]].component = o[2]; | ||
| 105 | break; | ||
| 106 | case op::member_decorate: | ||
| 107 | if (n >= 4 && o[2] == deco_builtin) member_builtins[o[0]][o[1]] = o[3]; | ||
| 108 | if (n >= 3 && (o[2] == deco_location || o[2] == deco_component)) located_members.insert(o[0]); | ||
| 109 | break; | ||
| 110 | case op::type_float: | ||
| 111 | if (n >= 2) types[o[0]] = {code, o[1], 0, {}}; | ||
| 112 | break; | ||
| 113 | case op::type_int: | ||
| 114 | if (n >= 3) types[o[0]] = {code, o[1], o[2], {}}; | ||
| 115 | break; | ||
| 116 | case op::type_vector: | ||
| 117 | case op::type_array: | ||
| 118 | case op::type_pointer: | ||
| 119 | if (n >= 3) types[o[0]] = {code, o[1], o[2], {}}; | ||
| 120 | break; | ||
| 121 | case op::type_struct: | ||
| 122 | if (n >= 1) types[o[0]] = {code, 0, 0, std::vector<std::uint32_t>(o + 1, o + n)}; | ||
| 123 | break; | ||
| 124 | case op::constant: | ||
| 125 | if (n >= 3) constants[o[1]] = o[2]; | ||
| 126 | break; | ||
| 127 | case op::variable: | ||
| 128 | if (n >= 3) variables[o[1]] = {o[0], o[2]}; | ||
| 129 | break; | ||
| 130 | default: break; | ||
| 131 | } | ||
| 132 | at += count; | ||
| 133 | } | ||
| 134 | if (!entry) return fail(why, "no vertex entry point"); | ||
| 135 | return true; | ||
| 136 | } | ||
| 137 | |||
| 138 | // A 32-bit scalar or vector: its kind and size. | ||
| 139 | bool scalar_or_vector(std::uint32_t id, Kind& kind, std::uint32_t& count) const { | ||
| 140 | const Type* t = find(id); | ||
| 141 | count = 1; | ||
| 142 | if (t && t->op == op::type_vector) { | ||
| 143 | count = t->b; | ||
| 144 | t = find(t->a); | ||
| 145 | if (count < 2 || count > 4) return false; | ||
| 146 | } | ||
| 147 | if (!t || t->a != 32) return false; | ||
| 148 | if (t->op == op::type_float) kind = Kind::f32; | ||
| 149 | else if (t->op == op::type_int) kind = t->b ? Kind::i32 : Kind::u32; | ||
| 150 | else return false; | ||
| 151 | return true; | ||
| 152 | } | ||
| 153 | // An array of 32-bit floats with a constant length. | ||
| 154 | bool float_array(std::uint32_t id, std::uint32_t& length) const { | ||
| 155 | const Type* t = find(id); | ||
| 156 | if (!t || t->op != op::type_array) return false; | ||
| 157 | Kind kind; | ||
| 158 | std::uint32_t count; | ||
| 159 | const auto c = constants.find(t->b); | ||
| 160 | if (!scalar_or_vector(t->a, kind, count) || kind != Kind::f32 || count != 1 || c == constants.end()) | ||
| 161 | return false; | ||
| 162 | length = c->second; | ||
| 163 | return length >= 1 && length <= 8; | ||
| 164 | } | ||
| 165 | const Type* find(std::uint32_t id) const { | ||
| 166 | const auto t = types.find(id); | ||
| 167 | return t == types.end() ? nullptr : &t->second; | ||
| 168 | } | ||
| 169 | |||
| 170 | bool clip_capability = false, cull_capability = false; | ||
| 171 | std::vector<std::uint32_t> interface; | ||
| 172 | std::unordered_map<std::uint32_t, Decorations> decorations; | ||
| 173 | std::unordered_map<std::uint32_t, std::map<std::uint32_t, std::uint32_t>> member_builtins; // struct -> member -> b | ||
| 174 | std::set<std::uint32_t> located_members; | ||
| 175 | std::unordered_map<std::uint32_t, Type> types; | ||
| 176 | std::unordered_map<std::uint32_t, std::uint32_t> constants; // id -> first word | ||
| 177 | std::unordered_map<std::uint32_t, std::pair<std::uint32_t, std::uint32_t>> variables; // id -> type, storage | ||
| 178 | |||
| 179 | private: | ||
| 180 | static bool fail(std::string& why, const char* what) { | ||
| 181 | why = what; | ||
| 182 | return false; | ||
| 183 | } | ||
| 184 | }; | ||
| 185 | |||
| 186 | // A built-in output of the vertex shader (alone or a block member) as the stage declares it. | ||
| 187 | bool builtin_output(const Interface& in, std::uint32_t builtin, std::uint32_t type, Output& out, std::string& why) { | ||
| 188 | out = {}; | ||
| 189 | out.builtin = builtin; | ||
| 190 | const char* name = builtin_name(builtin); | ||
| 191 | if (builtin == builtin_layer || builtin == builtin_viewport_index) { | ||
| 192 | why = std::string("the vertex shader writes ") + name + ", which a geometry stage cannot read"; | ||
| 193 | return false; | ||
| 194 | } | ||
| 195 | if (!name) { | ||
| 196 | why = "the vertex shader writes built-in " + std::to_string(builtin); | ||
| 197 | return false; | ||
| 198 | } | ||
| 199 | Kind kind; | ||
| 200 | std::uint32_t count = 0; | ||
| 201 | const bool not_array = builtin == builtin_position || builtin == builtin_point_size; | ||
| 202 | const bool ok = not_array ? in.scalar_or_vector(type, kind, count) && kind == Kind::f32 && | ||
| 203 | count == (builtin == builtin_position ? 4u : 1u) | ||
| 204 | : in.float_array(type, out.array); | ||
| 205 | if (!ok) { | ||
| 206 | why = std::string("the vertex shader's ") + name + " has an unexpected type"; | ||
| 207 | return false; | ||
| 208 | } | ||
| 209 | out.count = builtin == builtin_position ? 4 : 1; | ||
| 210 | return true; | ||
| 211 | } | ||
| 212 | |||
| 213 | // ---- Writing the geometry shader ---- | ||
| 214 | |||
| 215 | class Builder { | ||
| 216 | public: | ||
| 217 | std::uint32_t id() { return next_++; } | ||
| 218 | static void put(std::vector<std::uint32_t>& to, std::uint32_t code, std::initializer_list<std::uint32_t> operands) { | ||
| 219 | to.push_back(std::uint32_t(operands.size() + 1) << 16 | code); | ||
| 220 | to.insert(to.end(), operands.begin(), operands.end()); | ||
| 221 | } | ||
| 222 | static void put(std::vector<std::uint32_t>& to, std::uint32_t code, const std::vector<std::uint32_t>& operands) { | ||
| 223 | to.push_back(std::uint32_t(operands.size() + 1) << 16 | code); | ||
| 224 | to.insert(to.end(), operands.begin(), operands.end()); | ||
| 225 | } | ||
| 226 | // A type or constant declared once: `operands` follow its result id. | ||
| 227 | std::uint32_t global(std::uint32_t code, std::vector<std::uint32_t> operands, bool result_type_first = false) { | ||
| 228 | const auto key = std::make_pair(code, operands); | ||
| 229 | if (const auto found = declared_.find(key); found != declared_.end()) return found->second; | ||
| 230 | const std::uint32_t result = id(); | ||
| 231 | operands.insert(operands.begin() + (result_type_first ? 1 : 0), result); | ||
| 232 | put(globals, code, operands); | ||
| 233 | declared_.emplace(key, result); | ||
| 234 | return result; | ||
| 235 | } | ||
| 236 | // A value instruction in the function: `type`, a fresh result id, then `operands`. | ||
| 237 | std::uint32_t value(std::uint32_t code, std::uint32_t type, std::initializer_list<std::uint32_t> operands) { | ||
| 238 | const std::uint32_t result = id(); | ||
| 239 | std::vector<std::uint32_t> all{type, result}; | ||
| 240 | all.insert(all.end(), operands.begin(), operands.end()); | ||
| 241 | put(body, code, all); | ||
| 242 | return result; | ||
| 243 | } | ||
| 244 | std::uint32_t value(std::uint32_t code, std::uint32_t type, const std::vector<std::uint32_t>& operands) { | ||
| 245 | const std::uint32_t result = id(); | ||
| 246 | std::vector<std::uint32_t> all{type, result}; | ||
| 247 | all.insert(all.end(), operands.begin(), operands.end()); | ||
| 248 | put(body, code, all); | ||
| 249 | return result; | ||
| 250 | } | ||
| 251 | |||
| 252 | std::uint32_t t_void() { return global(op::type_void, {}); } | ||
| 253 | std::uint32_t t_bool() { return global(op::type_bool, {}); } | ||
| 254 | std::uint32_t t_f32() { return global(op::type_float, {32}); } | ||
| 255 | std::uint32_t t_i32() { return global(op::type_int, {32, 1}); } | ||
| 256 | std::uint32_t t_u32() { return global(op::type_int, {32, 0}); } | ||
| 257 | std::uint32_t t_scalar(Kind k) { return k == Kind::f32 ? t_f32() : k == Kind::i32 ? t_i32() : t_u32(); } | ||
| 258 | std::uint32_t t_vector(std::uint32_t scalar, std::uint32_t count) { | ||
| 259 | return count == 1 ? scalar : global(op::type_vector, {scalar, count}); | ||
| 260 | } | ||
| 261 | std::uint32_t t_array(std::uint32_t element, std::uint32_t length) { | ||
| 262 | return global(op::type_array, {element, c_u32(length)}); | ||
| 263 | } | ||
| 264 | std::uint32_t t_pointer(std::uint32_t storage, std::uint32_t pointee) { | ||
| 265 | return global(op::type_pointer, {storage, pointee}); | ||
| 266 | } | ||
| 267 | std::uint32_t c_u32(std::uint32_t v) { return global(op::constant, {t_u32(), v}, true); } | ||
| 268 | std::uint32_t c_i32(std::uint32_t v) { return global(op::constant, {t_i32(), v}, true); } | ||
| 269 | std::uint32_t c_f32(float f) { | ||
| 270 | std::uint32_t bits; | ||
| 271 | std::memcpy(&bits, &f, 4); | ||
| 272 | return global(op::constant, {t_f32(), bits}, true); | ||
| 273 | } | ||
| 274 | // A struct type is declared every time: the input and output blocks are two types, as glslang has them. | ||
| 275 | std::uint32_t t_struct(const std::vector<std::uint32_t>& members) { | ||
| 276 | const std::uint32_t result = id(); | ||
| 277 | std::vector<std::uint32_t> operands{result}; | ||
| 278 | operands.insert(operands.end(), members.begin(), members.end()); | ||
| 279 | put(globals, op::type_struct, operands); | ||
| 280 | return result; | ||
| 281 | } | ||
| 282 | std::uint32_t variable(std::uint32_t pointer, std::uint32_t storage) { | ||
| 283 | const std::uint32_t result = id(); | ||
| 284 | put(globals, op::variable, {pointer, result, storage}); | ||
| 285 | interface.push_back(result); | ||
| 286 | return result; | ||
| 287 | } | ||
| 288 | |||
| 289 | std::uint32_t bound() const { return next_; } | ||
| 290 | |||
| 291 | std::vector<std::uint32_t> decorations, globals, body, interface; | ||
| 292 | |||
| 293 | private: | ||
| 294 | std::uint32_t next_ = 1; | ||
| 295 | std::map<std::pair<std::uint32_t, std::vector<std::uint32_t>>, std::uint32_t> declared_; | ||
| 296 | }; | ||
| 297 | |||
| 298 | // One value copied from each input vertex to each emitted one: a whole Location output or Position, or one element | ||
| 299 | // of a clip or cull distance array. | ||
| 300 | struct Slot { | ||
| 301 | std::uint32_t in = 0, out = 0; // variables | ||
| 302 | std::vector<std::uint32_t> path; // constant indices after the vertex (input) / from the variable (output) | ||
| 303 | Kind kind = Kind::f32; | ||
| 304 | std::uint32_t count = 1; | ||
| 305 | bool position = false; | ||
| 306 | }; | ||
| 307 | |||
| 308 | } // namespace | ||
| 309 | |||
| 310 | std::string Signature::key() const { | ||
| 311 | std::string k; | ||
| 312 | const auto kind = [](Kind x) { return x == Kind::f32 ? 'f' : x == Kind::i32 ? 'i' : 'u'; }; | ||
| 313 | for (const Output& o : locations) | ||
| 314 | k += "L" + std::to_string(o.location) + "." + std::to_string(o.component) + kind(o.kind) + | ||
| 315 | std::to_string(o.count) + ";"; | ||
| 316 | k += block ? "B:" : "V:"; | ||
| 317 | for (const Output& o : builtins) k += std::to_string(o.builtin) + "x" + std::to_string(o.array) + ","; | ||
| 318 | k += clip ? ";clip" : ";"; | ||
| 319 | k += cull ? ";cull" : ";"; | ||
| 320 | return k; | ||
| 321 | } | ||
| 322 | |||
| 323 | bool read_signature(const std::vector<std::uint32_t>& vs, Signature& out, std::string& why) { | ||
| 324 | out = {}; | ||
| 325 | Interface in; | ||
| 326 | if (!in.read(vs, why)) return false; | ||
| 327 | bool position = false; | ||
| 328 | bool separate = false; | ||
| 329 | for (const std::uint32_t var : in.interface) { | ||
| 330 | const auto v = in.variables.find(var); | ||
| 331 | if (v == in.variables.end() || v->second.second != storage_output) continue; | ||
| 332 | const Type* pointer = in.find(v->second.first); | ||
| 333 | if (!pointer || pointer->op != op::type_pointer) { | ||
| 334 | why = "an output variable without a pointer type"; | ||
| 335 | return false; | ||
| 336 | } | ||
| 337 | const std::uint32_t type = pointer->b; | ||
| 338 | const auto deco = in.decorations.find(var); | ||
| 339 | const Decorations d = deco == in.decorations.end() ? Decorations{} : deco->second; | ||
| 340 | const Type* t = in.find(type); | ||
| 341 | if (d.builtin != Output::kNoBuiltin) { // a built-in variable | ||
| 342 | Output o; | ||
| 343 | if (!builtin_output(in, d.builtin, type, o, why)) return false; | ||
| 344 | if (out.block) { | ||
| 345 | why = "the vertex shader declares built-ins both in a block and alone"; | ||
| 346 | return false; | ||
| 347 | } | ||
| 348 | separate = true; | ||
| 349 | position |= o.builtin == builtin_position; | ||
| 350 | if (o.builtin != builtin_point_size) out.builtins.push_back(o); // a triangle has no point size | ||
| 351 | } else if (t && t->op == op::type_struct && in.member_builtins.count(type)) { // gl_PerVertex | ||
| 352 | if (out.block || separate) { | ||
| 353 | why = "the vertex shader declares more than one built-in output block"; | ||
| 354 | return false; | ||
| 355 | } | ||
| 356 | const auto& members = in.member_builtins.at(type); | ||
| 357 | for (std::uint32_t m = 0; m < t->members.size(); ++m) { | ||
| 358 | const auto b = members.find(m); | ||
| 359 | if (b == members.end()) { | ||
| 360 | why = "the vertex shader's built-in block has a member that is not a built-in"; | ||
| 361 | return false; | ||
| 362 | } | ||
| 363 | Output o; | ||
| 364 | if (!builtin_output(in, b->second, t->members[m], o, why)) return false; | ||
| 365 | position |= o.builtin == builtin_position; | ||
| 366 | out.builtins.push_back(o); | ||
| 367 | } | ||
| 368 | out.block = true; | ||
| 369 | } else if (d.has_location) { | ||
| 370 | Output o; | ||
| 371 | o.location = d.location; | ||
| 372 | o.component = d.component; | ||
| 373 | if (!in.scalar_or_vector(type, o.kind, o.count)) { | ||
| 374 | why = "the output at location " + std::to_string(d.location) + | ||
| 375 | " is not a 32-bit scalar or vector (an array, a struct or another width)"; | ||
| 376 | return false; | ||
| 377 | } | ||
| 378 | out.locations.push_back(o); | ||
| 379 | } else { | ||
| 380 | why = t && t->op == op::type_struct && in.located_members.count(type) | ||
| 381 | ? "the vertex shader has an output block with locations" | ||
| 382 | : "an output without a location or a built-in"; | ||
| 383 | return false; | ||
| 384 | } | ||
| 385 | } | ||
| 386 | if (!position) { | ||
| 387 | why = "the vertex shader writes no Position"; | ||
| 388 | return false; | ||
| 389 | } | ||
| 390 | for (const Output& o : out.builtins) { | ||
| 391 | out.clip |= o.builtin == builtin_clip_distance && in.clip_capability; | ||
| 392 | out.cull |= o.builtin == builtin_cull_distance && in.cull_capability; | ||
| 393 | } | ||
| 394 | if (!out.block) { // alone, a built-in the vertex shader does not write is not declared either | ||
| 395 | out.builtins.erase(std::remove_if(out.builtins.begin(), out.builtins.end(), | ||
| 396 | [&](const Output& o) { | ||
| 397 | return (o.builtin == builtin_clip_distance && !out.clip) || | ||
| 398 | (o.builtin == builtin_cull_distance && !out.cull); | ||
| 399 | }), | ||
| 400 | out.builtins.end()); | ||
| 401 | std::stable_sort(out.builtins.begin(), out.builtins.end(), | ||
| 402 | [](const Output& a, const Output& b) { return a.builtin < b.builtin; }); | ||
| 403 | } | ||
| 404 | std::stable_sort(out.locations.begin(), out.locations.end(), [](const Output& a, const Output& b) { | ||
| 405 | return std::make_pair(a.location, a.component) < std::make_pair(b.location, b.component); | ||
| 406 | }); | ||
| 407 | return true; | ||
| 408 | } | ||
| 409 | |||
| 410 | std::vector<std::uint32_t> build(const Signature& s, std::string& why) { | ||
| 411 | std::uint32_t scalars = 1; // the primitive ID | ||
| 412 | for (const Output& o : s.locations) scalars += o.count; | ||
| 413 | std::uint32_t user = scalars - 1; | ||
| 414 | for (const Output& o : s.builtins) { | ||
| 415 | if (o.builtin == builtin_position) scalars += 4; | ||
| 416 | if ((o.builtin == builtin_clip_distance && s.clip) || (o.builtin == builtin_cull_distance && s.cull)) | ||
| 417 | scalars += o.array; | ||
| 418 | } | ||
| 419 | if (user > kMaxScalarsPerVertex || scalars * kVertices > kMaxScalars) { | ||
| 420 | why = "the vertex shader has more output components (" + std::to_string(user) + | ||
| 421 | ") than a geometry stage emits in six vertices"; | ||
| 422 | return {}; | ||
| 423 | } | ||
| 424 | |||
| 425 | Builder b; | ||
| 426 | const std::uint32_t t_void = b.t_void(), t_bool = b.t_bool(), t_f32 = b.t_f32(), t_i32 = b.t_i32(); | ||
| 427 | const std::uint32_t t_fn = b.global(op::type_function, {t_void}); | ||
| 428 | std::vector<Slot> slots; | ||
| 429 | const auto decorate = [&](std::uint32_t target, std::initializer_list<std::uint32_t> words) { | ||
| 430 | std::vector<std::uint32_t> operands{target}; | ||
| 431 | operands.insert(operands.end(), words.begin(), words.end()); | ||
| 432 | Builder::put(b.decorations, op::decorate, operands); | ||
| 433 | }; | ||
| 434 | // A variable pair: an array of three `type` in, one `type` out. | ||
| 435 | const auto pair = [&](std::uint32_t type) { | ||
| 436 | const std::uint32_t in = b.variable(b.t_pointer(storage_input, b.t_array(type, 3)), storage_input); | ||
| 437 | const std::uint32_t out = b.variable(b.t_pointer(storage_output, type), storage_output); | ||
| 438 | return std::make_pair(in, out); | ||
| 439 | }; | ||
| 440 | |||
| 441 | for (const Output& o : s.locations) { | ||
| 442 | const auto [in, out] = pair(b.t_vector(b.t_scalar(o.kind), o.count)); | ||
| 443 | for (const std::uint32_t v : {in, out}) { | ||
| 444 | decorate(v, {deco_location, o.location}); | ||
| 445 | if (o.component) decorate(v, {deco_component, o.component}); | ||
| 446 | } | ||
| 447 | slots.push_back({in, out, {}, o.kind, o.count, false}); | ||
| 448 | } | ||
| 449 | const auto copied = [&](const Output& o) { | ||
| 450 | return o.builtin == builtin_position || (o.builtin == builtin_clip_distance && s.clip) || | ||
| 451 | (o.builtin == builtin_cull_distance && s.cull); | ||
| 452 | }; | ||
| 453 | // The slots of a built-in reached through `path` from variables `in` / `out`. | ||
| 454 | const auto builtin_slots = [&](const Output& o, std::uint32_t in, std::uint32_t out, | ||
| 455 | std::vector<std::uint32_t> path) { | ||
| 456 | if (!copied(o)) return; | ||
| 457 | if (o.builtin == builtin_position) { | ||
| 458 | slots.push_back({in, out, path, Kind::f32, 4, true}); | ||
| 459 | return; | ||
| 460 | } | ||
| 461 | for (std::uint32_t e = 0; e < o.array; ++e) { | ||
| 462 | std::vector<std::uint32_t> element = path; | ||
| 463 | element.push_back(b.c_i32(e)); | ||
| 464 | slots.push_back({in, out, element, Kind::f32, 1, false}); | ||
| 465 | } | ||
| 466 | }; | ||
| 467 | const auto builtin_type = [&](const Output& o) { | ||
| 468 | return o.array ? b.t_array(t_f32, o.array) : b.t_vector(t_f32, o.count); | ||
| 469 | }; | ||
| 470 | if (s.block) { | ||
| 471 | std::vector<std::uint32_t> members; | ||
| 472 | for (const Output& o : s.builtins) members.push_back(builtin_type(o)); | ||
| 473 | const std::uint32_t block_in = b.t_struct(members), block_out = b.t_struct(members); | ||
| 474 | for (const std::uint32_t block : {block_in, block_out}) { | ||
| 475 | decorate(block, {deco_block}); | ||
| 476 | for (std::uint32_t m = 0; m < s.builtins.size(); ++m) | ||
| 477 | Builder::put(b.decorations, op::member_decorate, {block, m, deco_builtin, s.builtins[m].builtin}); | ||
| 478 | } | ||
| 479 | const std::uint32_t in = | ||
| 480 | b.variable(b.t_pointer(storage_input, b.t_array(block_in, 3)), storage_input); | ||
| 481 | const std::uint32_t out = b.variable(b.t_pointer(storage_output, block_out), storage_output); | ||
| 482 | for (std::uint32_t m = 0; m < s.builtins.size(); ++m) builtin_slots(s.builtins[m], in, out, {b.c_i32(m)}); | ||
| 483 | } else { | ||
| 484 | for (const Output& o : s.builtins) { | ||
| 485 | if (!copied(o)) continue; | ||
| 486 | const auto [in, out] = pair(builtin_type(o)); | ||
| 487 | decorate(in, {deco_builtin, o.builtin}); | ||
| 488 | decorate(out, {deco_builtin, o.builtin}); | ||
| 489 | builtin_slots(o, in, out, {}); | ||
| 490 | } | ||
| 491 | } | ||
| 492 | const std::uint32_t primitive_in = b.variable(b.t_pointer(storage_input, t_i32), storage_input); | ||
| 493 | const std::uint32_t primitive_out = b.variable(b.t_pointer(storage_output, t_i32), storage_output); | ||
| 494 | decorate(primitive_in, {deco_builtin, builtin_primitive_id}); | ||
| 495 | decorate(primitive_out, {deco_builtin, builtin_primitive_id}); | ||
| 496 | |||
| 497 | // Types and constants the body uses, declared before the function. | ||
| 498 | std::vector<std::uint32_t> value_type, uint_type, bool_type; | ||
| 499 | for (const Slot& slot : slots) { | ||
| 500 | value_type.push_back(b.t_vector(b.t_scalar(slot.kind), slot.count)); | ||
| 501 | uint_type.push_back(b.t_vector(b.t_u32(), slot.count)); | ||
| 502 | bool_type.push_back(b.t_vector(t_bool, slot.count)); | ||
| 503 | } | ||
| 504 | std::vector<std::uint32_t> in_pointer, out_pointer; | ||
| 505 | for (const std::uint32_t t : value_type) { | ||
| 506 | in_pointer.push_back(b.t_pointer(storage_input, t)); | ||
| 507 | out_pointer.push_back(b.t_pointer(storage_output, t)); | ||
| 508 | } | ||
| 509 | const std::array<std::uint32_t, 3> vertex{b.c_i32(0), b.c_i32(1), b.c_i32(2)}; | ||
| 510 | const std::uint32_t zero = b.c_f32(0.0f); | ||
| 511 | const std::uint32_t function = b.id(), entry_label = b.id(); | ||
| 512 | |||
| 513 | Builder::put(b.body, op::function, {t_void, function, 0, t_fn}); | ||
| 514 | Builder::put(b.body, op::label, {entry_label}); | ||
| 515 | // Every input of the three vertices: [slot][vertex]. | ||
| 516 | std::vector<std::array<std::uint32_t, 3>> p(slots.size()); | ||
| 517 | std::size_t position = 0; | ||
| 518 | for (std::size_t i = 0; i < slots.size(); ++i) { | ||
| 519 | if (slots[i].position) position = i; | ||
| 520 | for (std::uint32_t v = 0; v < 3; ++v) { | ||
| 521 | std::vector<std::uint32_t> chain{slots[i].in, vertex[v]}; | ||
| 522 | chain.insert(chain.end(), slots[i].path.begin(), slots[i].path.end()); | ||
| 523 | const std::uint32_t pointer = b.value(op::access_chain, in_pointer[i], chain); | ||
| 524 | p[i][v] = b.value(op::load, value_type[i], {pointer}); | ||
| 525 | } | ||
| 526 | } | ||
| 527 | std::array<std::uint32_t, 3> x{}, y{}, w{}; | ||
| 528 | for (std::uint32_t v = 0; v < 3; ++v) { | ||
| 529 | x[v] = b.value(op::composite_extract, t_f32, {p[position][v], 0}); | ||
| 530 | y[v] = b.value(op::composite_extract, t_f32, {p[position][v], 1}); | ||
| 531 | w[v] = b.value(op::composite_extract, t_f32, {p[position][v], 3}); | ||
| 532 | } | ||
| 533 | const auto same = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::f_ord_equal, t_bool, {l, r}); }; | ||
| 534 | const auto both = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::logical_and, t_bool, {l, r}); }; | ||
| 535 | const auto either = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::logical_or, t_bool, {l, r}); }; | ||
| 536 | const auto no = [&](std::uint32_t l) { return b.value(op::logical_not, t_bool, {l}); }; | ||
| 537 | // One positive w, and no two vertices in one place. | ||
| 538 | std::uint32_t plain = b.value(op::f_ord_greater_than, t_bool, {w[0], zero}); | ||
| 539 | plain = both(plain, same(w[1], w[0])); | ||
| 540 | plain = both(plain, same(w[2], w[0])); | ||
| 541 | for (const auto [i, j] : {std::pair{0, 1}, std::pair{0, 2}, std::pair{1, 2}}) | ||
| 542 | plain = both(plain, no(both(same(x[i], x[j]), same(y[i], y[j])))); | ||
| 543 | // corner[i]: vertex i is the corner between the other two (the first that shares x with one and y with the other). | ||
| 544 | std::array<std::uint32_t, 3> corner{}; | ||
| 545 | for (std::uint32_t i = 0; i < 3; ++i) { | ||
| 546 | const std::uint32_t a = (i + 1) % 3, c = (i + 2) % 3; | ||
| 547 | const std::uint32_t one = both(same(x[i], x[a]), same(y[i], y[c])); | ||
| 548 | const std::uint32_t other = both(same(x[i], x[c]), same(y[i], y[a])); | ||
| 549 | std::uint32_t here = both(either(one, other), plain); | ||
| 550 | for (std::uint32_t earlier = 0; earlier < i; ++earlier) here = both(here, no(corner[earlier])); | ||
| 551 | corner[i] = here; | ||
| 552 | } | ||
| 553 | // The corner flags as conditions of each vector size (SPIR-V 1.0 selects a vector by a vector of bools). | ||
| 554 | std::map<std::uint32_t, std::array<std::uint32_t, 3>> splat; | ||
| 555 | for (const Slot& slot : slots) { | ||
| 556 | if (splat.count(slot.count)) continue; | ||
| 557 | std::array<std::uint32_t, 3>& flags = splat[slot.count]; | ||
| 558 | for (std::uint32_t k = 0; k < 3; ++k) { | ||
| 559 | if (slot.count == 1) { | ||
| 560 | flags[k] = corner[k]; | ||
| 561 | continue; | ||
| 562 | } | ||
| 563 | std::vector<std::uint32_t> parts(slot.count, corner[k]); | ||
| 564 | flags[k] = b.value(op::composite_construct, b.t_vector(t_bool, slot.count), parts); | ||
| 565 | } | ||
| 566 | } | ||
| 567 | |||
| 568 | // What the six emitted vertices carry: [slot][vertex]. | ||
| 569 | std::vector<std::array<std::uint32_t, kVertices>> emitted(slots.size()); | ||
| 570 | for (std::size_t i = 0; i < slots.size(); ++i) { | ||
| 571 | const std::uint32_t t = value_type[i]; | ||
| 572 | const auto& flag = splat[slots[i].count]; | ||
| 573 | const auto& [p0, p1, p2] = p[i]; | ||
| 574 | std::uint32_t fourth = p0; // integers (flat), and three vertices without a corner, keep the first vertex's | ||
| 575 | if (slots[i].kind == Kind::f32) { | ||
| 576 | // The vertex opposite the corner `at` of `a` and `c`: a + c - at, or exactly c (a) where a (c) has the | ||
| 577 | // corner's bits. | ||
| 578 | const std::array<std::uint32_t, 3> bits{b.value(op::bitcast, uint_type[i], {p0}), | ||
| 579 | b.value(op::bitcast, uint_type[i], {p1}), | ||
| 580 | b.value(op::bitcast, uint_type[i], {p2})}; | ||
| 581 | const auto equal = [&](std::uint32_t l, std::uint32_t r) { | ||
| 582 | return b.value(op::i_equal, bool_type[i], {bits[l], bits[r]}); | ||
| 583 | }; | ||
| 584 | const std::uint32_t eq01 = equal(0, 1), eq02 = equal(0, 2), eq12 = equal(1, 2); | ||
| 585 | const auto opposite = [&](std::uint32_t a, std::uint32_t c, std::uint32_t at, std::uint32_t a_is, | ||
| 586 | std::uint32_t c_is) { | ||
| 587 | const std::uint32_t sum = b.value(op::f_add, t, {a, c}); | ||
| 588 | std::uint32_t r = b.value(op::f_sub, t, {sum, at}); | ||
| 589 | r = b.value(op::select, t, {c_is, a, r}); | ||
| 590 | return b.value(op::select, t, {a_is, c, r}); | ||
| 591 | }; | ||
| 592 | fourth = b.value(op::select, t, {flag[0], opposite(p1, p2, p0, eq01, eq02), fourth}); | ||
| 593 | fourth = b.value(op::select, t, {flag[1], opposite(p2, p0, p1, eq12, eq01), fourth}); | ||
| 594 | fourth = b.value(op::select, t, {flag[2], opposite(p0, p1, p2, eq02, eq12), fourth}); | ||
| 595 | } | ||
| 596 | // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, v2), (v0, v2, v3). Third: (v0, v1, v2), | ||
| 597 | // (v0, v3, v1). | ||
| 598 | const std::uint32_t third = b.value(op::select, t, {flag[0], fourth, p2}); | ||
| 599 | const std::uint32_t fifth = b.value(op::select, t, {flag[1], p2, fourth}); | ||
| 600 | const std::uint32_t second = b.value(op::select, t, {flag[0], p2, p1}); | ||
| 601 | const std::uint32_t sixth = b.value(op::select, t, {flag[1], fourth, second}); | ||
| 602 | emitted[i] = {p0, p1, third, p0, fifth, sixth}; | ||
| 603 | } | ||
| 604 | // The rectangle's number: the triangle's, one triangle a rectangle. | ||
| 605 | const std::uint32_t primitive = b.value(op::load, t_i32, {primitive_in}); | ||
| 606 | std::vector<std::uint32_t> target(slots.size()); | ||
| 607 | for (std::size_t i = 0; i < slots.size(); ++i) { | ||
| 608 | if (slots[i].path.empty()) { | ||
| 609 | target[i] = slots[i].out; | ||
| 610 | continue; | ||
| 611 | } | ||
| 612 | std::vector<std::uint32_t> chain{slots[i].out}; | ||
| 613 | chain.insert(chain.end(), slots[i].path.begin(), slots[i].path.end()); | ||
| 614 | target[i] = b.value(op::access_chain, out_pointer[i], chain); | ||
| 615 | } | ||
| 616 | for (std::uint32_t v = 0; v < kVertices; ++v) { | ||
| 617 | for (std::size_t i = 0; i < slots.size(); ++i) Builder::put(b.body, op::store, {target[i], emitted[i][v]}); | ||
| 618 | Builder::put(b.body, op::store, {primitive_out, primitive}); | ||
| 619 | Builder::put(b.body, op::emit_vertex, {}); | ||
| 620 | if (v == 2 || v == kVertices - 1) Builder::put(b.body, op::end_primitive, {}); // two triangles | ||
| 621 | } | ||
| 622 | Builder::put(b.body, op::return_, {}); | ||
| 623 | Builder::put(b.body, op::function_end, {}); | ||
| 624 | |||
| 625 | std::vector<std::uint32_t> words{kMagic, 0x00010000u, 0, b.bound(), 0}; | ||
| 626 | Builder::put(words, op::capability, {cap_shader}); | ||
| 627 | Builder::put(words, op::capability, {cap_geometry}); | ||
| 628 | if (s.clip) Builder::put(words, op::capability, {cap_clip_distance}); | ||
| 629 | if (s.cull) Builder::put(words, op::capability, {cap_cull_distance}); | ||
| 630 | Builder::put(words, op::memory_model, {0, 1}); // Logical, GLSL450 | ||
| 631 | std::uint32_t name = 0; | ||
| 632 | std::memcpy(&name, "main", 4); | ||
| 633 | std::vector<std::uint32_t> entry{model_geometry, function, name, 0}; | ||
| 634 | entry.insert(entry.end(), b.interface.begin(), b.interface.end()); | ||
| 635 | Builder::put(words, op::entry_point, entry); | ||
| 636 | Builder::put(words, op::execution_mode, {function, mode_triangles}); | ||
| 637 | Builder::put(words, op::execution_mode, {function, mode_invocations, 1}); | ||
| 638 | Builder::put(words, op::execution_mode, {function, mode_output_triangle_strip}); | ||
| 639 | Builder::put(words, op::execution_mode, {function, mode_output_vertices, kVertices}); | ||
| 640 | for (const auto* section : {&b.decorations, &b.globals, &b.body}) | ||
| 641 | words.insert(words.end(), section->begin(), section->end()); | ||
| 642 | return words; | ||
| 643 | } | ||
| 644 | |||
| 645 | std::shared_ptr<const std::vector<std::uint32_t>> geometry_shader(const std::vector<std::uint32_t>& vs, | ||
| 646 | std::string& why) { | ||
| 647 | Signature signature; | ||
| 648 | if (!read_signature(vs, signature, why)) return nullptr; | ||
| 649 | static std::mutex mutex; | ||
| 650 | static std::map<std::string, std::shared_ptr<const std::vector<std::uint32_t>>> cache; | ||
| 651 | const std::string key = signature.key(); | ||
| 652 | std::lock_guard lock(mutex); | ||
| 653 | if (const auto found = cache.find(key); found != cache.end()) return found->second; | ||
| 654 | std::vector<std::uint32_t> words = build(signature, why); | ||
| 655 | if (words.empty()) return nullptr; | ||
| 656 | auto shared = std::make_shared<const std::vector<std::uint32_t>>(std::move(words)); | ||
| 657 | cache.emplace(key, shared); | ||
| 658 | return shared; | ||
| 659 | } | ||
| 660 | |||
| 661 | bool append_stage(PFN_vkCreateShaderModule create_module, VkDevice device, bool geometry_shader_feature, | ||
| 662 | const std::vector<std::uint32_t>& vs, std::vector<VkShaderModule>& modules, | ||
| 663 | std::vector<VkPipelineShaderStageCreateInfo>& stages) { | ||
| 664 | const auto refuse = [](const std::string& why) { | ||
| 665 | static std::mutex mutex; | ||
| 666 | static std::set<std::string> seen; | ||
| 667 | std::lock_guard lock(mutex); | ||
| 668 | if (seen.insert(why).second) | ||
| 669 | std::fprintf(stderr, "[rt] d3d12: a rectangle-list pipeline is refused: %s (logged once)\n", why.c_str()); | ||
| 670 | return false; | ||
| 671 | }; | ||
| 672 | if (!geometry_shader_feature) return refuse("its geometry stage needs the Vulkan geometryShader feature"); | ||
| 673 | std::string why; | ||
| 674 | const auto words = geometry_shader(vs, why); | ||
| 675 | if (!words) return refuse(why); | ||
| 676 | VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | ||
| 677 | info.codeSize = words->size() * 4; | ||
| 678 | info.pCode = words->data(); | ||
| 679 | VkShaderModule module = VK_NULL_HANDLE; | ||
| 680 | if (!create_module || create_module(device, &info, nullptr, &module) != VK_SUCCESS) | ||
| 681 | return refuse("vkCreateShaderModule failed for its geometry stage"); | ||
| 682 | modules.push_back(module); | ||
| 683 | VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | ||
| 684 | stage.stage = VK_SHADER_STAGE_GEOMETRY_BIT; | ||
| 685 | stage.module = module; | ||
| 686 | stage.pName = "main"; | ||
| 687 | stages.push_back(stage); | ||
| 688 | return true; | ||
| 689 | } | ||
| 690 | |||
| 691 | } // namespace leonida::rect_list | ||
diff --git a/runtime/src/rect_list_gs.h b/runtime/src/rect_list_gs.h deleted file mode 100644 index 1d3cf8d87..000000000 --- a/runtime/src/rect_list_gs.h +++ /dev/null | |||
| @@ -1,108 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // Rectangle lists: the geometry stage that completes the console's rectangles on Vulkan. | ||
| 4 | // | ||
| 5 | // Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; | ||
| 6 | // victory/crates/victory-shader/src/emit/rect.rs, commit 683ad7a99, and victory/crates/victory-gpu/src/primitive.rs); | ||
| 7 | // Leonida is GPL-3.0-or-later too. VIctory emits DXIL for host D3D12; this emits SPIR-V for the Vulkan layer. | ||
| 8 | // | ||
| 9 | // The title draws its full-screen passes and tiled lighting as rectangle lists: pipeline topology type 19 | ||
| 10 | // (kPipelineTopologyType) and list topology 17 (kListTopology; VIctory pipeline/host.rs:312, draw.rs:4022). A | ||
| 11 | // rectangle comes as three vertices, three corners of a screen-aligned rectangle; the console's hardware draws the | ||
| 12 | // whole rectangle and continues every vertex output linearly into the fourth corner. Vulkan has no such topology, so | ||
| 13 | // a rectangle pipeline gets this geometry shader behind the translated vertex shader and takes triangle lists: vertex | ||
| 14 | // counts, vertex numbers, indices and indirect arguments stay the title's, and each rectangle reaches the stage as one | ||
| 15 | // triangle (list topology 17 already draws as a triangle list, vulkan_replay.h vulkan_topology). | ||
| 16 | // | ||
| 17 | // The rule is VIctory's: | ||
| 18 | // * the corner is the vertex that shares x with one of the other two and y with the other (the title's full-screen | ||
| 19 | // rectangles come as top left, bottom left, bottom right: the second; its tiled lighting as top left, bottom | ||
| 20 | // left, top right: the first); the first vertex that qualifies wins; | ||
| 21 | // * the fourth vertex lies opposite it: a + b - corner for the position and every float output. Here a component | ||
| 22 | // whose a (or b) has the corner's exact bits takes b (or a) as it is, the same value without the rounding, so a | ||
| 23 | // position keeps its exact edges and a value equal on all three vertices (a bit pattern in a float output | ||
| 24 | // included) keeps its bits; | ||
| 25 | // * integer outputs, which are flat, take the first vertex's value at the fourth vertex; | ||
| 26 | // * three vertices whose w differ (or whose w is not positive), two in one place, or three that are not such | ||
| 27 | // corners, stay the triangle they make (the second triangle is empty). | ||
| 28 | // The stage emits two triangles, both starting with the first vertex: (v0, v1, v3), (v0, v3, v2) when the corner is | ||
| 29 | // the first vertex, (v0, v1, v2), (v0, v2, v3) when it is the second, (v0, v1, v2), (v0, v3, v1) when it is the | ||
| 30 | // third. Both turn as the title's triangle does (so culling is unchanged), and the first vertex is the provoking | ||
| 31 | // vertex of both, so a flat input reads it there and a PerVertexKHR input finds it at index 0. That is six vertices, | ||
| 32 | // not one four-vertex strip: in a strip the second triangle's provoking vertex would be the strip's second vertex. | ||
| 33 | // The primitive ID is passed on (the rectangle's number: one triangle a rectangle), since with a geometry stage the | ||
| 34 | // pixel shader reads the one that stage writes. | ||
| 35 | // | ||
| 36 | // shortcut: that the console takes a rectangle's flat values from its first vertex follows from the hardware's | ||
| 37 | // provoking-vertex setting for triangles; it is not measured on a rectangle (VIctory rect.rs says the same). A pixel | ||
| 38 | // shader that reads its barycentrics raw (not to interpolate) sees the second triangle's, not the rectangle's. | ||
| 39 | // | ||
| 40 | // The stage is built from the vertex shader's SPIR-V output interface, so it links with the module as created (after | ||
| 41 | // the f16-halves link, which can add outputs): every Location output (32-bit float, int or uint, scalar or vector), | ||
| 42 | // Position, and ClipDistance / CullDistance when the shader declares their capability, which the translator and | ||
| 43 | // glslang do only when they write them. Built-ins are declared as the vertex shader declares them: separate | ||
| 44 | // variables (the translator) or one gl_PerVertex block (glslang), mirrored member for member. Refused with a reason: | ||
| 45 | // no Position, a Layer or ViewportIndex output (a geometry stage cannot read them), an output of another type, and | ||
| 46 | // more components than a geometry stage may emit (6 vertices of at most 128 scalars, at most 1024 in all). | ||
| 47 | // The words are cached per output signature (Signature::key); tests/test_rect_list_gs.py runs the generator through | ||
| 48 | // rect_list_gs_tool and checks what the stage emits, d3d12_rect_list_test draws rectangles with it on the GPU. | ||
| 49 | |||
| 50 | #include <cstdint> | ||
| 51 | #include <memory> | ||
| 52 | #include <string> | ||
| 53 | #include <vector> | ||
| 54 | |||
| 55 | #include <vulkan/vulkan_core.h> | ||
| 56 | |||
| 57 | namespace leonida::rect_list { | ||
| 58 | |||
| 59 | // D3D12.X's rectangle-list topologies: the pipeline's PrimitiveTopologyType and the list's IASetPrimitiveTopology. | ||
| 60 | constexpr std::uint32_t kPipelineTopologyType = 19; | ||
| 61 | constexpr std::uint32_t kListTopology = 17; | ||
| 62 | |||
| 63 | // Vertices the stage emits per rectangle: two triangles. | ||
| 64 | constexpr std::uint32_t kVertices = 6; | ||
| 65 | |||
| 66 | enum class Kind : std::uint8_t { f32, i32, u32 }; | ||
| 67 | |||
| 68 | // One value the stage copies from each vertex: a Location output, or a built-in (alone or a member of the vertex | ||
| 69 | // shader's gl_PerVertex block). | ||
| 70 | struct Output { | ||
| 71 | static constexpr std::uint32_t kNoBuiltin = ~0u; | ||
| 72 | std::uint32_t builtin = kNoBuiltin; // SPIR-V BuiltIn, or kNoBuiltin for a Location output | ||
| 73 | std::uint32_t location = 0; | ||
| 74 | std::uint32_t component = 0; | ||
| 75 | Kind kind = Kind::f32; | ||
| 76 | std::uint32_t count = 1; // vector size; 1 is a scalar | ||
| 77 | std::uint32_t array = 0; // ClipDistance / CullDistance: an array of `array` floats (count 1) | ||
| 78 | }; | ||
| 79 | |||
| 80 | struct Signature { | ||
| 81 | std::vector<Output> locations; // by (location, component) | ||
| 82 | // Built-ins: Position, and PointSize, ClipDistance, CullDistance as the vertex shader declares them. | ||
| 83 | std::vector<Output> builtins; | ||
| 84 | bool block = false; // `builtins` are the members of one gl_PerVertex block, in order | ||
| 85 | bool clip = false, cull = false; // the vertex shader writes ClipDistance / CullDistance (declares the capability) | ||
| 86 | std::string key() const; | ||
| 87 | }; | ||
| 88 | |||
| 89 | // The output interface of a vertex shader's SPIR-V (its first Vertex entry point). False with `why` when the stage | ||
| 90 | // cannot be made for it. | ||
| 91 | bool read_signature(const std::vector<std::uint32_t>& vs, Signature& out, std::string& why); | ||
| 92 | |||
| 93 | // The geometry shader's SPIR-V (version 1.0) for a signature read_signature accepted. Empty, with `why`, when the | ||
| 94 | // stage would emit more than a geometry shader may. | ||
| 95 | std::vector<std::uint32_t> build(const Signature& signature, std::string& why); | ||
| 96 | |||
| 97 | // read_signature, then build, cached per Signature::key (thread safe). Null with `why` when refused. | ||
| 98 | std::shared_ptr<const std::vector<std::uint32_t>> geometry_shader(const std::vector<std::uint32_t>& vs, | ||
| 99 | std::string& why); | ||
| 100 | |||
| 101 | // For a rectangle pipeline: creates the stage's module for the vertex shader `vs` on `device`, appends it to | ||
| 102 | // `modules` (the pipeline destroys it with its others) and its stage to `stages`. False, logged once per reason, | ||
| 103 | // without the geometryShader feature, when the stage is refused, or when the module cannot be created. | ||
| 104 | bool append_stage(PFN_vkCreateShaderModule create_module, VkDevice device, bool geometry_shader_feature, | ||
| 105 | const std::vector<std::uint32_t>& vs, std::vector<VkShaderModule>& modules, | ||
| 106 | std::vector<VkPipelineShaderStageCreateInfo>& stages); | ||
| 107 | |||
| 108 | } // namespace leonida::rect_list | ||
diff --git a/runtime/src/resource_detile.h b/runtime/src/resource_detile.h index 368b0a377..74f22aac5 100644 --- a/runtime/src/resource_detile.h +++ b/runtime/src/resource_detile.h | |||
| @@ -9,14 +9,6 @@ | |||
| 9 | // | 9 | // |
| 10 | // Independent X and Y coordinate bit mappings permit O(1) intra-tile offset resolution via compile-time | 10 | // Independent X and Y coordinate bit mappings permit O(1) intra-tile offset resolution via compile-time |
| 11 | // lookup tables (lut_x[x % tile_w] | lut_y[y % tile_h]). No Windows or Vulkan dependency. | 11 | // lookup tables (lut_x[x % tile_w] | lut_y[y % tile_h]). No Windows or Vulkan dependency. |
| 12 | // | ||
| 13 | // Scope, against the console's whole layout (gfx10::ConsoleTexture, VIctory texture.rs, which xg_xs.dll's texture | ||
| 14 | // computer and the layer's fill_from_title use): one SW_64KB_D level read from the start of its memory. For that, | ||
| 15 | // both agree byte for byte (xg_xs_test detiler_agrees, every element size and BC). They disagree on two things: | ||
| 16 | // - with mips the console puts the mip tail first and mip 0 last (256x256 BC7: mip 0 at 64 KiB), so this reads mip | ||
| 17 | // 0 only from that mip's offset in the layout; | ||
| 18 | // - VIctory reads the layout word as 0x100 | the swizzle mode, so 0x101 is SW_256B_S, not SW_64KB_D as assumed | ||
| 19 | // here (docs/d3d12_vulkan.md section 4.2). Nothing on the layer's path calls this file's functions. | ||
| 20 | 12 | ||
| 21 | #include "resource_tiling.h" | 13 | #include "resource_tiling.h" |
| 22 | 14 | ||
diff --git a/runtime/src/spirv_output_splat.h b/runtime/src/spirv_output_splat.h deleted file mode 100644 index d98aabc94..000000000 --- a/runtime/src/spirv_output_splat.h +++ /dev/null | |||
| @@ -1,116 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // A fragment shader's colour output whose alpha is stored in all four components (`.wwww`), for a render target the | ||
| 4 | // GPU has no format for: an A8_UNORM target is an R8_UNORM attachment, which stores the first component, while the | ||
| 5 | // pixel shader writes the target's one channel, alpha, in the fourth (D3D12's SV_Target.a for an A8 target). | ||
| 6 | // | ||
| 7 | // The translator (tools/rdna2spirv.py `export`) writes each colour output as one whole-vector OpStore to an Output | ||
| 8 | // variable decorated with its Location. Each such store is given an OpVectorShuffle of the stored value first. Loads | ||
| 9 | // of the output (the translator keeps an earlier export for lanes that do not export) read the splatted value, which | ||
| 10 | // splats to itself, so a later partial export still ends with the latest alpha in every component. | ||
| 11 | // | ||
| 12 | // No Vulkan headers; the caller has checked the binary's framing (spirv_words.h). Portable C++20. | ||
| 13 | |||
| 14 | #include <cstddef> | ||
| 15 | #include <cstdint> | ||
| 16 | #include <span> | ||
| 17 | #include <string> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | namespace leonida { | ||
| 21 | |||
| 22 | // `words` with every store to the Output variable at `location` made `.wwww`, or an empty vector with `why` set when | ||
| 23 | // the module has no such four-component output (then the caller leaves the target as it is). | ||
| 24 | inline std::vector<std::uint32_t> splat_output_alpha(std::span<const std::uint32_t> words, std::uint32_t location, | ||
| 25 | std::string& why) { | ||
| 26 | constexpr std::uint32_t magic = 0x07230203; | ||
| 27 | constexpr std::uint16_t op_type_vector = 23, op_type_pointer = 32, op_variable = 59, op_store = 62, | ||
| 28 | op_decorate = 71, op_vector_shuffle = 79; | ||
| 29 | constexpr std::uint32_t decoration_location = 30, class_output = 3; | ||
| 30 | if (words.size() < 5 || words[0] != magic) { | ||
| 31 | why = "not a SPIR-V module"; | ||
| 32 | return {}; | ||
| 33 | } | ||
| 34 | const auto for_each = [&](auto&& visit) { | ||
| 35 | for (std::size_t at = 5; at < words.size();) { | ||
| 36 | const std::uint32_t count = words[at] >> 16; | ||
| 37 | if (!count || at + count > words.size()) return false; | ||
| 38 | visit(at, static_cast<std::uint16_t>(words[at] & 0xffff), count); | ||
| 39 | at += count; | ||
| 40 | } | ||
| 41 | return true; | ||
| 42 | }; | ||
| 43 | // The Location decorations, the Output variables and their pointer types, the vector types. | ||
| 44 | std::vector<std::uint32_t> at_location; | ||
| 45 | struct Variable { | ||
| 46 | std::uint32_t id, pointer; | ||
| 47 | }; | ||
| 48 | std::vector<Variable> outputs; | ||
| 49 | struct Pointer { | ||
| 50 | std::uint32_t id, pointee; | ||
| 51 | }; | ||
| 52 | std::vector<Pointer> output_pointers; | ||
| 53 | struct Vector { | ||
| 54 | std::uint32_t id, count; | ||
| 55 | }; | ||
| 56 | std::vector<Vector> vectors; | ||
| 57 | const bool framed = for_each([&](std::size_t at, std::uint16_t op, std::uint32_t count) { | ||
| 58 | if (op == op_decorate && count >= 4 && words[at + 2] == decoration_location && words[at + 3] == location) | ||
| 59 | at_location.push_back(words[at + 1]); | ||
| 60 | else if (op == op_variable && count >= 4 && words[at + 3] == class_output) | ||
| 61 | outputs.push_back({words[at + 2], words[at + 1]}); | ||
| 62 | else if (op == op_type_pointer && count >= 4 && words[at + 2] == class_output) | ||
| 63 | output_pointers.push_back({words[at + 1], words[at + 3]}); | ||
| 64 | else if (op == op_type_vector && count >= 4) | ||
| 65 | vectors.push_back({words[at + 1], words[at + 3]}); | ||
| 66 | }); | ||
| 67 | if (!framed) { | ||
| 68 | why = "an instruction runs past the module"; | ||
| 69 | return {}; | ||
| 70 | } | ||
| 71 | std::uint32_t variable = 0, vector_type = 0; | ||
| 72 | for (const Variable& v : outputs) { | ||
| 73 | bool located = false; | ||
| 74 | for (std::uint32_t id : at_location) located |= id == v.id; | ||
| 75 | if (!located) continue; | ||
| 76 | for (const Pointer& p : output_pointers) | ||
| 77 | if (p.id == v.pointer) | ||
| 78 | for (const Vector& vec : vectors) | ||
| 79 | if (vec.id == p.pointee && vec.count == 4) vector_type = vec.id; | ||
| 80 | if (vector_type) { | ||
| 81 | variable = v.id; | ||
| 82 | break; | ||
| 83 | } | ||
| 84 | } | ||
| 85 | if (!variable) { | ||
| 86 | why = "no four-component Output variable at Location " + std::to_string(location); | ||
| 87 | return {}; | ||
| 88 | } | ||
| 89 | std::vector<std::uint32_t> out; | ||
| 90 | out.reserve(words.size() + 64); | ||
| 91 | out.insert(out.end(), words.begin(), words.begin() + 5); | ||
| 92 | std::uint32_t bound = words[3]; | ||
| 93 | unsigned stores = 0; | ||
| 94 | for_each([&](std::size_t at, std::uint16_t op, std::uint32_t count) { | ||
| 95 | if (op == op_store && count >= 3 && words[at + 1] == variable) { | ||
| 96 | const std::uint32_t splat = bound++; | ||
| 97 | const std::uint32_t value = words[at + 2]; | ||
| 98 | out.insert(out.end(), {(9u << 16) | op_vector_shuffle, vector_type, splat, value, value, 3u, 3u, 3u, 3u}); | ||
| 99 | out.push_back(words[at]); | ||
| 100 | out.push_back(variable); | ||
| 101 | out.push_back(splat); | ||
| 102 | out.insert(out.end(), words.begin() + std::ptrdiff_t(at + 3), words.begin() + std::ptrdiff_t(at + count)); | ||
| 103 | ++stores; | ||
| 104 | return; | ||
| 105 | } | ||
| 106 | out.insert(out.end(), words.begin() + std::ptrdiff_t(at), words.begin() + std::ptrdiff_t(at + count)); | ||
| 107 | }); | ||
| 108 | if (!stores) { | ||
| 109 | why = "the output at Location " + std::to_string(location) + " is never stored"; | ||
| 110 | return {}; | ||
| 111 | } | ||
| 112 | out[3] = bound; | ||
| 113 | return out; | ||
| 114 | } | ||
| 115 | |||
| 116 | } // namespace leonida | ||
diff --git a/runtime/src/title_memory.h b/runtime/src/title_memory.h deleted file mode 100644 index 1a4387bfc..000000000 --- a/runtime/src/title_memory.h +++ /dev/null | |||
| @@ -1,145 +0,0 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // Title memory as GPU memory: a GPU address is the title's CPU address (docs/d3d12_vulkan.md section 3.3, "Title | ||
| 4 | // memory"). The translated shaders reach memory at heap_base + VA (push-constant dwords 32-33), so the D3D12 layer | ||
| 5 | // gives every piece of GPU-visible memory the device address heap_base + its VA: | ||
| 6 | // - the GPU address arena (default-heap buffers, the layer's own descriptor heaps, shader code) at VA = its offset, | ||
| 7 | // so its device memory sits at heap_base; | ||
| 8 | // - the title's graphics memory (xmem) at VA = its CPU address, imported with VK_EXT_external_memory_host at | ||
| 9 | // heap_base + that address. | ||
| 10 | // Both are allocated with an opaque capture address (bufferDeviceAddressCaptureReplay), which asks the driver for that | ||
| 11 | // device address. Measured on an RTX 4060 Ti, driver 616.64 (Vulkan 1.4.351; probes run 2026-11-25): | ||
| 12 | // - capture-replay memory, plain device-local, BAR and imported host memory alike, gets the device address asked for | ||
| 13 | // anywhere in about [0x2_FFF1_0000, 0xFF_FFFF_FFFF] (12 GiB to 1 TiB); an address at or above 2^40 is refused | ||
| 14 | // with VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS, and so is one the driver already uses; | ||
| 15 | // - a buffer bound at offset X of such memory has the memory's address + X; two imports at heap_base + their host | ||
| 16 | // addresses both get them; | ||
| 17 | // - the buffer's own opaque capture address reads 0: the address comes with the memory; | ||
| 18 | // - imported host memory cannot be bound into a sparse buffer there (a sparse buffer takes memory type 1, the device | ||
| 19 | // heap, only; host pointers import as types 2 and 3), so one sparse 2^40 mirror buffer (docs/port_plan.md, Frame | ||
| 20 | // time) is not possible on this driver. test/vk_sparse_title_memory_test.cpp asks again (2026-11-25): every sparse | ||
| 21 | // buffer, with or without residency, capture replay or VkExternalMemoryBufferCreateInfo for host allocations, | ||
| 22 | // lists type 1 alone, although vkGetPhysicalDeviceExternalBufferProperties calls host allocations importable for a | ||
| 23 | // sparse buffer (features 0x6). Bound anyway (--force-bind, invalid usage: the validation layer reports the memory | ||
| 24 | // type), the pages work: reads, GPU writes the CPU sees, CPU writes the GPU sees, one frame at two VAs, rebinds, | ||
| 25 | // and unbound pages read zero. One vkQueueBindSparse of 16,384 64 KiB pages took 70 ms to idle, 16,384 calls of one | ||
| 26 | // page 1.7 s; a sparse buffer at a capture-replay address may be up to 64 GiB (128 GiB was refused). The AMD | ||
| 27 | // driver (2026.04.17) lists host memory types for sparse buffers but has no bufferDeviceAddressCaptureReplay; | ||
| 28 | // - an import pins its pages (256 MiB never touched: 17.9 ms and +256 MiB of working set) but does not stop the CPU | ||
| 29 | // from decommitting or protecting them: the import keeps the old physical pages, so a range the title frees has to | ||
| 30 | // leave the GPU first (xmem tells the layer, rt::xmem::set_graphics_listener). | ||
| 31 | // - every host import but a device's first also gets an ordinary device address from the driver, of its size, | ||
| 32 | // first fit right after the arena: the retail title's 4.5 GB of pools took [heap_base + 256 MiB, | ||
| 33 | // heap_base + 4.7 GiB) that way, so its 32-bit memory, imported later, found its addresses taken. A sparse buffer | ||
| 34 | // at a capture-replay address holds addresses without memory, and keeps those mappings out (one of 384 GiB was | ||
| 35 | // refused, 16 GiB pieces were not); | ||
| 36 | // - device addresses go to imports 2 MiB at a time: an import that ends inside a 2 MiB block takes the rest of it, | ||
| 37 | // one that starts inside a block another holds is refused, and from 64 MiB on one must start on a 2 MiB line. The | ||
| 38 | // retail title's 32-bit windows lie side by side on 1 MiB lines, so imports that share a block are merged. | ||
| 39 | // | ||
| 40 | // Sparse title memory (the default: the imports path lost the device on the title; LEONIDA_TITLE_MEMORY=imports opts out; SparseTitleMemory in shims/d3d12_vulkan_device.cpp, | ||
| 41 | // docs/d3d12_vulkan.md section 3.3): sparse buffers over both windows at heap_base + VA, xmem's physical-page pools | ||
| 42 | // imported once each (in 256 MiB pieces) and every mapped page a sparse bind of its VA to its pool's import, every | ||
| 43 | // unmapped page bound to nothing (it reads zero), the title's other GPU memory imported once per range and bound at its | ||
| 44 | // own address. ON NVIDIA THAT BIND IS OUTSIDE THE VULKAN SPEC: the host imports' memory types (2, 3) are not in the | ||
| 45 | // sparse buffers' memoryTypeBits (1), which breaks VUID-VkSparseMemoryBind-memory-01096 (the validation layer: | ||
| 46 | // "memory has a type index (2) that is not among the allowed types mask (0x2) for this resource"). The driver does it | ||
| 47 | // correctly (measured above), so the path runs only after a self-test on the device passes; otherwise the imports | ||
| 48 | // below run. | ||
| 49 | // | ||
| 50 | // So heap_base is fixed at 512 GiB and the arena lies at [heap_base, heap_base + arena size). xmem places the title's | ||
| 51 | // 32-bit graphics memory (VIctory xmem.rs:69-88, attribute bit 2) in [1 GiB, 4 GiB), where the descriptor-table | ||
| 52 | // pointers the shaders truncate to 32 bits need it (docs/d3d12_vulkan.md, "Descriptor-table high-dword truncation"), | ||
| 53 | // and its other memory in [64 GiB, 448 GiB). The layer holds both windows' device addresses with sparse buffers and | ||
| 54 | // gives an import the part it needs; the driver's own mappings get [heap_base + 4 GiB, heap_base + 64 GiB) and what | ||
| 55 | // lies above 448 GiB, and heap_base + every title address stays below 1 TiB. | ||
| 56 | // | ||
| 57 | // No Windows or Vulkan dependency. | ||
| 58 | |||
| 59 | #include <cstdint> | ||
| 60 | |||
| 61 | namespace leonida::title_memory { | ||
| 62 | |||
| 63 | inline constexpr std::uint64_t kHeapBase = std::uint64_t(1) << 39; // 512 GiB: heap_base on a capture-replay device | ||
| 64 | inline constexpr std::uint64_t kDeviceAddressEnd = std::uint64_t(1) << 40; // the driver's capture-replay limit | ||
| 65 | // Where xmem puts the title's memory (VIctory xmem.rs:73-88, which uses [4 GiB, 2^40) and the low 4 GiB for 32-bit | ||
| 66 | // memory; narrowed here to leave the driver's mappings room, as above). | ||
| 67 | inline constexpr std::uint64_t kLow32Start = std::uint64_t(1) << 30; // above any arena of up to 1 GiB | ||
| 68 | inline constexpr std::uint64_t kLow32End = std::uint64_t(1) << 32; | ||
| 69 | inline constexpr std::uint64_t kWindowStart = std::uint64_t(64) << 30; | ||
| 70 | inline constexpr std::uint64_t kWindowEnd = std::uint64_t(448) << 30; | ||
| 71 | static_assert(kHeapBase + kWindowEnd <= kDeviceAddressEnd); | ||
| 72 | |||
| 73 | // The largest single import. Bigger visible ranges are imported in pieces of this size, which keeps one failed or | ||
| 74 | // released import from taking more than this with it (Windows drivers cap a process at 4,096 allocations, so imports | ||
| 75 | // are kept few and large: docs/port_plan.md, Frame time). | ||
| 76 | inline constexpr std::uint64_t kMaxImport = std::uint64_t(1) << 30; | ||
| 77 | |||
| 78 | // The device address of title VA `va` on a capture-replay device. | ||
| 79 | constexpr std::uint64_t device_address(std::uint64_t va) { return kHeapBase + va; } | ||
| 80 | |||
| 81 | // Whether [va, va + bytes) can have the device address heap_base + va: inside one window, non-empty, no wrap. | ||
| 82 | constexpr bool addressable(std::uint64_t va, std::uint64_t bytes) { | ||
| 83 | const auto inside = [&](std::uint64_t first, std::uint64_t end) { | ||
| 84 | return va >= first && va < end && bytes <= end - va; | ||
| 85 | }; | ||
| 86 | return bytes && (inside(kLow32Start, kLow32End) || inside(kWindowStart, kWindowEnd)); | ||
| 87 | } | ||
| 88 | |||
| 89 | // XMem attribute words (VIctory xmem.rs:63-88): bits 0-1 the memory type, 3 for graphics memory (both processors); | ||
| 90 | // bit 2 a 32-bit address; bits 12-14, when set, the address width as 47 minus the field. The retail title passes | ||
| 91 | // 0x21, 0x3, 0x183, 0x283, 0x181, 0x7 and 0x27 (gta6rt --trace, xmem_attributes events). | ||
| 92 | constexpr bool graphics_attributes(std::uint64_t attributes) { return (attributes & 3) == 3; } | ||
| 93 | constexpr bool address_32bit(std::uint64_t attributes) { return (attributes & 4) != 0; } | ||
| 94 | |||
| 95 | // The address range xmem places an allocation with these attributes in: [first, last] (VIctory's address_range, | ||
| 96 | // narrowed to the device-address window above). | ||
| 97 | struct Range { | ||
| 98 | std::uint64_t first; | ||
| 99 | std::uint64_t last; | ||
| 100 | }; | ||
| 101 | constexpr Range placement(std::uint64_t attributes) { | ||
| 102 | if (address_32bit(attributes)) return {kLow32Start, kLow32End - 1}; | ||
| 103 | const std::uint64_t field = attributes >> 12 & 7; | ||
| 104 | std::uint64_t end = kWindowEnd; | ||
| 105 | if (field) { | ||
| 106 | const std::uint64_t bits = 47 - field; | ||
| 107 | if (bits < 63 && (std::uint64_t(1) << bits) < end) end = std::uint64_t(1) << bits; | ||
| 108 | } | ||
| 109 | return {kWindowStart, end - 1}; | ||
| 110 | } | ||
| 111 | |||
| 112 | // XMemAlloc attribute words, another layout than XMemVirtualAlloc's above (VIctory xmem.rs:228-233 and resource.rs: | ||
| 113 | // 951-963, GPL-3.0-or-later, Marvisak and contributors, DexNom fork): bits 14-15 the page size (1: 64 KiB, 2: 2 MiB), | ||
| 114 | // 16-23 the allocator id, 24-28 the alignment as log2, 29-32 the memory type, bit 33 a 32-bit address. | ||
| 115 | // ASSUMPTION: memory type 0 is the CPU heap and every other type memory both processors reach. VIctory gives its | ||
| 116 | // committed resources type 1 (a default heap, write-combined on the console) or 3 (the CPU-visible heaps, cacheable); | ||
| 117 | // no other type has been seen. | ||
| 118 | constexpr unsigned alloc_page_size(std::uint64_t attributes) { return unsigned(attributes >> 14 & 3); } | ||
| 119 | constexpr unsigned alloc_allocator_id(std::uint64_t attributes) { return unsigned(attributes >> 16 & 0xff); } | ||
| 120 | constexpr unsigned alloc_alignment_log2(std::uint64_t attributes) { return unsigned(attributes >> 24 & 0x1f); } | ||
| 121 | constexpr unsigned alloc_memory_type(std::uint64_t attributes) { return unsigned(attributes >> 29 & 0xf); } | ||
| 122 | constexpr bool alloc_32bit(std::uint64_t attributes) { return (attributes >> 33 & 1) != 0; } | ||
| 123 | // Whether XMemAllocDefault gives GPU memory (pages in the window above, visible to the D3D12 layer) for these | ||
| 124 | // attributes: a graphics memory type or a 32-bit address (VIctory's XMemAllocDefault takes 32-bit graphics memory | ||
| 125 | // for the latter). | ||
| 126 | constexpr bool alloc_gpu_memory(std::uint64_t attributes) { | ||
| 127 | return alloc_memory_type(attributes) != 0 || alloc_32bit(attributes); | ||
| 128 | } | ||
| 129 | |||
| 130 | // The attributes of a committed resource's memory, as the console's D3D runtime asks the title's allocator for it | ||
| 131 | // (VIctory resource.rs:951-963, resource_attributes): the graphics allocator id 128, 2 MiB pages from 2 MiB up (else | ||
| 132 | // 64 KiB), the alignment as log2, memory type 1 for a default heap and 3 for the CPU-visible ones. VIctory's own | ||
| 133 | // note: the console runtime's page size and memory type are not known, these are the plausible ones. | ||
| 134 | inline constexpr std::uint64_t kGraphicsAllocatorId = 128; | ||
| 135 | constexpr std::uint64_t resource_attributes(std::uint64_t size, std::uint64_t alignment, bool default_heap) { | ||
| 136 | std::uint64_t log2 = 0; | ||
| 137 | for (std::uint64_t a = alignment ? alignment : 1; !(a & 1) && log2 < 63; a >>= 1) ++log2; // trailing zeros | ||
| 138 | const std::uint64_t pages = size >= (std::uint64_t(2) << 20) ? 2 : 1; | ||
| 139 | const std::uint64_t memory = default_heap ? 1 : 3; | ||
| 140 | return kGraphicsAllocatorId << 16 | pages << 14 | (log2 & 0x1f) << 24 | memory << 29; | ||
| 141 | } | ||
| 142 | static_assert(resource_attributes(33423360, 0x10000, true) == 0x30808000); // a 3840x2160 RGBA8 back buffer | ||
| 143 | static_assert(resource_attributes(0x10000, 0x10000, false) == 0x70804000); | ||
| 144 | |||
| 145 | } // namespace leonida::title_memory | ||
diff --git a/runtime/src/xma_context.cpp b/runtime/src/xma_context.cpp deleted file mode 100644 index dec4d1a79..000000000 --- a/runtime/src/xma_context.cpp +++ /dev/null | |||
| @@ -1,224 +0,0 @@ | |||
| 1 | // The SHAPE XMA context machine. Ported from VIctory (crates/victory-hle/src/modules/audio.rs), GPL-3.0-or-later, by | ||
| 2 | // Marvisak and contributors (DexNom fork). Leonida is GPL-3.0-or-later. See xma_context.h. | ||
| 3 | #include "xma_context.h" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cstring> | ||
| 7 | |||
| 8 | namespace rt::xma { | ||
| 9 | |||
| 10 | namespace { | ||
| 11 | |||
| 12 | constexpr uint32_t kRates[4] = {24000, 32000, 44100, 48000}; | ||
| 13 | |||
| 14 | int16_t saturating_abs(int16_t v) { return v == INT16_MIN ? INT16_MAX : static_cast<int16_t>(v < 0 ? -v : v); } | ||
| 15 | |||
| 16 | } // namespace | ||
| 17 | |||
| 18 | void pump(Context context, Voice& voice, ApuBytes memory) { | ||
| 19 | const uint32_t size = context.field(0, 22, 5); | ||
| 20 | if (size == 0) return; | ||
| 21 | while (context.field(1, 31, 1) == 1) { | ||
| 22 | if (voice.pcm.size() < kSamplesPerBlock && !decode(context, voice, memory)) return; | ||
| 23 | // The write block is the title's too: taken modulo the ring before the first write, which would otherwise | ||
| 24 | // land past the ring's end. | ||
| 25 | uint32_t write = context.field(0, 27, 5) % size; | ||
| 26 | const uint32_t address = static_cast<uint32_t>(context.get(7) + uint64_t{write} * kBlockBytes); | ||
| 27 | uint8_t* out = memory(address, kBlockBytes); | ||
| 28 | if (!out) return; | ||
| 29 | for (size_t i = 0; i < kSamplesPerBlock; ++i) { | ||
| 30 | int16_t sample = 0; | ||
| 31 | if (!voice.pcm.empty()) { | ||
| 32 | sample = voice.pcm.front(); | ||
| 33 | voice.pcm.pop_front(); | ||
| 34 | } | ||
| 35 | voice.trace.peak = std::max(voice.trace.peak, saturating_abs(sample)); | ||
| 36 | const uint16_t bits = static_cast<uint16_t>(sample); | ||
| 37 | out[2 * i] = static_cast<uint8_t>(bits & 0xff); | ||
| 38 | out[2 * i + 1] = static_cast<uint8_t>(bits >> 8); | ||
| 39 | } | ||
| 40 | voice.trace.produced += kSamplesPerBlock / context.channels(); | ||
| 41 | write = (write + 1) % size; | ||
| 42 | context.set_field(0, 27, 5, write); | ||
| 43 | // The read block is the title's: taken modulo the ring like the write block and advance_read's. Compared as | ||
| 44 | // it is, one at or past the end would never be met, and a stream that loops would keep this voice (and its | ||
| 45 | // lock) filling forever. | ||
| 46 | if (write == context.field(9, 0, 5) % size) { | ||
| 47 | // Full: nothing more until the title advances its read block. | ||
| 48 | context.set_field(1, 31, 1, 0); | ||
| 49 | } | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | bool decode(Context context, Voice& voice, ApuBytes memory) { | ||
| 54 | if (voice.ended) return false; | ||
| 55 | const size_t channels = context.channels(); | ||
| 56 | uint32_t current = context.field(4, 31, 1); | ||
| 57 | const uint32_t valid = context.field(0, 20, 2); | ||
| 58 | if ((valid & (1u << current)) == 0) { | ||
| 59 | if ((valid & (1u << (1 - current))) == 0) { | ||
| 60 | // Out of input: the overlap tail, then nothing. | ||
| 61 | if (voice.decoder) { | ||
| 62 | voice.frame.clear(); | ||
| 63 | voice.decoder->flush(voice.frame); | ||
| 64 | voice.pcm.insert(voice.pcm.end(), voice.frame.begin(), voice.frame.end()); | ||
| 65 | } | ||
| 66 | voice.ended = true; | ||
| 67 | voice.trace.input_ended = true; | ||
| 68 | context.set_field(2, 26, 5, kInputInvalid); | ||
| 69 | context.set_field(2, 31, 1, 1); | ||
| 70 | return !voice.pcm.empty(); | ||
| 71 | } | ||
| 72 | current = 1 - current; | ||
| 73 | context.set_field(4, 31, 1, current); | ||
| 74 | context.set_field(2, 0, 26, 0); | ||
| 75 | } | ||
| 76 | const uint32_t address = current == 0 ? context.get(5) : context.get(6); | ||
| 77 | const uint32_t packets = current == 0 ? context.field(0, 0, 12) : context.field(1, 0, 12); | ||
| 78 | const size_t bytes = size_t{packets} * kPacketBytes; | ||
| 79 | const uint8_t* data = memory(address & ~0x7ffu, bytes); | ||
| 80 | if (!data) { | ||
| 81 | context.set_field(0, 20 + current, 1, 0); | ||
| 82 | return true; | ||
| 83 | } | ||
| 84 | const std::span<const uint8_t> input(data, bytes); | ||
| 85 | size_t at = context.field(2, 0, 26); | ||
| 86 | if (at < kHeaderBits) { | ||
| 87 | const auto first = packet(input, 0); | ||
| 88 | at = kHeaderBits + (first ? first->first_frame_bit : 0); | ||
| 89 | } | ||
| 90 | const auto frame = read_frame(input, at); | ||
| 91 | if (!frame) { | ||
| 92 | // This input is used up. | ||
| 93 | context.set_field(0, 20 + current, 1, 0); | ||
| 94 | return true; | ||
| 95 | } | ||
| 96 | if (!voice.decoder) voice.decoder.emplace(channels, kRates[context.field(1, 27, 2)]); | ||
| 97 | voice.frame.clear(); | ||
| 98 | ++voice.trace.frames; | ||
| 99 | if (voice.decoder->decode(frame->data, frame->bits, voice.frame)) ++voice.trace.bad_frames; | ||
| 100 | size_t next = frame->next.value_or(0); | ||
| 101 | const uint32_t loops = context.field(0, 12, 8); | ||
| 102 | const size_t loop_end = context.field(4, 0, 26); | ||
| 103 | const bool ends_loop = loop_end != 0 && (frame->start == loop_end || | ||
| 104 | (frame->start < loop_end && (!frame->next || loop_end < *frame->next))); | ||
| 105 | const bool looping = loops > 0 && ends_loop; | ||
| 106 | if (looping) { | ||
| 107 | const size_t keep = (context.field(1, 12, 2) + size_t{1}) * kSubframeSamples * channels; | ||
| 108 | if (voice.frame.size() > keep) voice.frame.resize(keep); | ||
| 109 | next = context.field(3, 0, 26); | ||
| 110 | if (loops != 255) context.set_field(0, 12, 8, loops - 1); | ||
| 111 | } | ||
| 112 | // What is still to skip is this frame's (the stream's first, or a loop's first when it is its last too). | ||
| 113 | const size_t skip = std::min(voice.skip * channels, voice.frame.size()); | ||
| 114 | voice.skip -= skip / channels; | ||
| 115 | voice.pcm.insert(voice.pcm.end(), voice.frame.begin() + static_cast<ptrdiff_t>(skip), voice.frame.end()); | ||
| 116 | if (looping) { | ||
| 117 | // The loop's own skip is of its first frame, decoded next: not of this one, its last. | ||
| 118 | voice.skip = context.field(1, 17, 3) * kSubframeSamples; | ||
| 119 | } | ||
| 120 | if (next == 0) context.set_field(0, 20 + current, 1, 0); | ||
| 121 | context.set_field(2, 0, 26, static_cast<uint32_t>(next)); | ||
| 122 | return true; | ||
| 123 | } | ||
| 124 | |||
| 125 | void Engine::attach(uint32_t* array, uint32_t count) { | ||
| 126 | std::unique_lock lock(lock_); | ||
| 127 | array_ = array; | ||
| 128 | count_ = array ? count : 0; | ||
| 129 | slots_ = count_ ? std::make_unique<Slot[]>(count_) : nullptr; | ||
| 130 | } | ||
| 131 | |||
| 132 | void Engine::detach() { | ||
| 133 | std::unique_lock lock(lock_); | ||
| 134 | array_ = nullptr; | ||
| 135 | count_ = 0; | ||
| 136 | slots_.reset(); | ||
| 137 | } | ||
| 138 | |||
| 139 | std::optional<Context> Engine::context(uint32_t index) const { | ||
| 140 | if (index >= count_ || !array_) return std::nullopt; | ||
| 141 | return Context(array_ + size_t{index} * (kContextBytes / 4)); | ||
| 142 | } | ||
| 143 | |||
| 144 | void Engine::enable(uint32_t index) { | ||
| 145 | const auto context = this->context(index); | ||
| 146 | if (!context) return; | ||
| 147 | { | ||
| 148 | std::lock_guard slot(slots_[index].mutex); | ||
| 149 | context->set_field(2, 26, 6, 0); | ||
| 150 | Voice& voice = slots_[index].voice.emplace(); | ||
| 151 | voice.skip = context->field(1, 24, 3) * kSubframeSamples; | ||
| 152 | } | ||
| 153 | if (wake_) wake_(); | ||
| 154 | } | ||
| 155 | |||
| 156 | void Engine::disable(uint32_t index) { | ||
| 157 | if (!this->context(index)) return; | ||
| 158 | std::lock_guard slot(slots_[index].mutex); | ||
| 159 | slots_[index].voice.reset(); | ||
| 160 | } | ||
| 161 | |||
| 162 | void Engine::advance_read(uint32_t index, uint32_t blocks) { | ||
| 163 | const auto context = this->context(index); | ||
| 164 | if (!context) return; | ||
| 165 | { | ||
| 166 | // The decoder writes the same words. | ||
| 167 | std::lock_guard slot(slots_[index].mutex); | ||
| 168 | const uint32_t size = std::max<uint32_t>(context->field(0, 22, 5), 1); | ||
| 169 | // The count is the title's: reduced first, so the sum stays small. | ||
| 170 | const uint32_t read = (context->field(9, 0, 5) + blocks % size) % size; | ||
| 171 | context->set_field(9, 0, 5, read); | ||
| 172 | if (blocks > 0) context->set_field(1, 31, 1, 1); | ||
| 173 | if (auto& voice = slots_[index].voice) { | ||
| 174 | voice->trace.taken += blocks; | ||
| 175 | ++voice->trace.takes; | ||
| 176 | voice->trace.partial_takes += blocks < size ? 1 : 0; | ||
| 177 | } | ||
| 178 | } | ||
| 179 | if (wake_) wake_(); | ||
| 180 | } | ||
| 181 | |||
| 182 | bool Engine::command(uint32_t command, const void* data) { | ||
| 183 | const auto word = [data](size_t at) -> std::optional<uint32_t> { | ||
| 184 | if (!data) return std::nullopt; | ||
| 185 | uint32_t v = 0; | ||
| 186 | std::memcpy(&v, static_cast<const uint8_t*>(data) + at * 4, sizeof v); | ||
| 187 | return v; | ||
| 188 | }; | ||
| 189 | std::shared_lock lock(lock_); | ||
| 190 | switch (command) { | ||
| 191 | case kEnableXma: enable(word(0).value_or(UINT32_MAX)); break; | ||
| 192 | case kDisableXma: disable(word(0).value_or(UINT32_MAX)); break; | ||
| 193 | case kEnableXmas: | ||
| 194 | case kDisableXmas: | ||
| 195 | for (uint32_t i = 0; i < count_; ++i) { | ||
| 196 | if ((word(i / 32).value_or(0) & (1u << (i % 32))) == 0) continue; | ||
| 197 | if (command == kEnableXmas) enable(i); | ||
| 198 | else disable(i); | ||
| 199 | } | ||
| 200 | break; | ||
| 201 | case kAdvanceXmaRead: advance_read(word(0).value_or(UINT32_MAX), word(1).value_or(0)); break; | ||
| 202 | default: return false; | ||
| 203 | } | ||
| 204 | return true; | ||
| 205 | } | ||
| 206 | |||
| 207 | void Engine::pump() { | ||
| 208 | std::shared_lock lock(lock_); | ||
| 209 | for (uint32_t index = 0; index < count_; ++index) { | ||
| 210 | const auto context = this->context(index); | ||
| 211 | std::lock_guard slot(slots_[index].mutex); | ||
| 212 | if (context && slots_[index].voice) xma::pump(*context, *slots_[index].voice, memory_); | ||
| 213 | } | ||
| 214 | } | ||
| 215 | |||
| 216 | std::optional<Trace> Engine::trace(uint32_t index) { | ||
| 217 | std::shared_lock lock(lock_); | ||
| 218 | if (!this->context(index)) return std::nullopt; | ||
| 219 | std::lock_guard slot(slots_[index].mutex); | ||
| 220 | if (!slots_[index].voice) return std::nullopt; | ||
| 221 | return slots_[index].voice->trace; | ||
| 222 | } | ||
| 223 | |||
| 224 | } // namespace rt::xma | ||
diff --git a/runtime/src/xma_context.h b/runtime/src/xma_context.h deleted file mode 100644 index f4c6dbe16..000000000 --- a/runtime/src/xma_context.h +++ /dev/null | |||
| @@ -1,143 +0,0 @@ | |||
| 1 | // The audio coprocessor's XMA decoder: enabled SHAPE XMA contexts are decoded into their output rings, like the | ||
| 2 | // hardware does. | ||
| 3 | // | ||
| 4 | // Ported from VIctory (crates/victory-hle/src/modules/audio.rs, the XMA part), GPL-3.0-or-later, by Marvisak and | ||
| 5 | // contributors (DexNom fork). Leonida is GPL-3.0-or-later. The DexNom snapshot in victory/ is the base; three fixes | ||
| 6 | // from VIctory's own history in this repository that the snapshot lacks are kept: the write block (7a5d85e6a) and the | ||
| 7 | // read block (1054fe87d) are taken modulo the ring, so neither writes past the ring's end nor fills it for good, and | ||
| 8 | // a loop's start skip applies to the loop's first frame, not its last (985d8d4b0). Pure C++: no OS headers; the | ||
| 9 | // acphal shim owns the decoding thread and the APU memory lookup. | ||
| 10 | // | ||
| 11 | // An XMA context (16 words in the shared context array) names up to two input buffers of 2 KiB packets, a ring of | ||
| 12 | // 256-byte output blocks the hardware fills with 16-bit PCM, and the read offset the title advances by command. Words | ||
| 13 | // and bit fields, as titles write them: | ||
| 14 | // 0: input 0 size in packets (0-11), loop count (12-19, 255 forever), valid inputs (20-21), output size in blocks | ||
| 15 | // (22-26), write block (27-31, hardware); | ||
| 16 | // 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes to skip (17-19), subframes to skip at the | ||
| 17 | // start (24-26), sample rate (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31); | ||
| 18 | // 2: read position in bits (0-25), error status (26-30), error (31); | ||
| 19 | // 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input (31); 5, 6: input addresses; 7: output | ||
| 20 | // address; 8: overlap buffer; 9: read block (0-4). | ||
| 21 | // Titles read back only the write block, "writable" and the read block, and take whatever lies between read and | ||
| 22 | // write. Each enabled context decodes from a cold state and the overlap buffer is ignored (titles copy it between | ||
| 23 | // consecutive contexts of one voice), as in VIctory. | ||
| 24 | #pragma once | ||
| 25 | |||
| 26 | #include <cstddef> | ||
| 27 | #include <cstdint> | ||
| 28 | #include <deque> | ||
| 29 | #include <memory> | ||
| 30 | #include <mutex> | ||
| 31 | #include <optional> | ||
| 32 | #include <shared_mutex> | ||
| 33 | #include <vector> | ||
| 34 | |||
| 35 | #include "xma_decode.h" | ||
| 36 | |||
| 37 | namespace rt::xma { | ||
| 38 | |||
| 39 | // Coprocessor commands that drive XMA contexts (IAcpHal::SubmitCommand ids, VIctory audio.rs). | ||
| 40 | inline constexpr uint32_t kEnableXma = 5; // word 0: the context index | ||
| 41 | inline constexpr uint32_t kEnableXmas = 6; // words: a bit per context | ||
| 42 | inline constexpr uint32_t kDisableXma = 7; // word 0: the context index | ||
| 43 | inline constexpr uint32_t kDisableXmas = 8; // words: a bit per context | ||
| 44 | inline constexpr uint32_t kAdvanceXmaRead = 18; // word 0: the context index, word 1: blocks the title took | ||
| 45 | |||
| 46 | inline constexpr size_t kContextBytes = 64; | ||
| 47 | inline constexpr size_t kBlockBytes = 256; | ||
| 48 | inline constexpr size_t kSamplesPerBlock = kBlockBytes / 2; | ||
| 49 | // Error status (word 2, bits 26-30): the input ran out. | ||
| 50 | inline constexpr uint32_t kInputInvalid = 4; | ||
| 51 | |||
| 52 | // `len` host bytes of APU memory at a device address when one live heap block holds them all, else null. | ||
| 53 | using ApuBytes = uint8_t* (*)(uint32_t apu, size_t len); | ||
| 54 | |||
| 55 | // A context's words in title memory. Read and written as volatile: the title reads and writes them concurrently, as | ||
| 56 | // it does the hardware's. | ||
| 57 | class Context { | ||
| 58 | public: | ||
| 59 | explicit Context(uint32_t* words) : words_(words) {} | ||
| 60 | |||
| 61 | uint32_t get(size_t word) const { return static_cast<volatile const uint32_t*>(words_)[word]; } | ||
| 62 | void set(size_t word, uint32_t value) const { static_cast<volatile uint32_t*>(words_)[word] = value; } | ||
| 63 | uint32_t field(size_t word, uint32_t shift, uint32_t bits) const { | ||
| 64 | return (get(word) >> shift) & ((uint32_t{1} << bits) - 1); | ||
| 65 | } | ||
| 66 | void set_field(size_t word, uint32_t shift, uint32_t bits, uint32_t value) const { | ||
| 67 | const uint32_t mask = ((uint32_t{1} << bits) - 1) << shift; | ||
| 68 | set(word, (get(word) & ~mask) | ((value << shift) & mask)); | ||
| 69 | } | ||
| 70 | size_t channels() const { return 1 + field(1, 29, 1); } | ||
| 71 | |||
| 72 | private: | ||
| 73 | uint32_t* words_; | ||
| 74 | }; | ||
| 75 | |||
| 76 | // What a voice did. | ||
| 77 | struct Trace { | ||
| 78 | size_t produced = 0; // samples per channel written to the ring | ||
| 79 | size_t taken = 0; // blocks the title took (command 18), how often, and how often it found the ring not full | ||
| 80 | uint32_t takes = 0; | ||
| 81 | uint32_t partial_takes = 0; | ||
| 82 | uint32_t frames = 0; | ||
| 83 | uint32_t bad_frames = 0; | ||
| 84 | int16_t peak = 0; // the loudest sample written | ||
| 85 | bool input_ended = false; | ||
| 86 | }; | ||
| 87 | |||
| 88 | // An enabled context's decoding state. | ||
| 89 | struct Voice { | ||
| 90 | std::optional<Decoder> decoder; | ||
| 91 | std::deque<int16_t> pcm; | ||
| 92 | size_t skip = 0; // samples per channel still to drop (start or loop subframe skips) | ||
| 93 | bool ended = false; | ||
| 94 | Trace trace; | ||
| 95 | std::vector<int16_t> frame; // one frame's samples, reused | ||
| 96 | }; | ||
| 97 | |||
| 98 | // Decodes the next frame of the context's current input into voice.pcm; false when there is nothing left to decode. | ||
| 99 | bool decode(Context context, Voice& voice, ApuBytes memory); | ||
| 100 | |||
| 101 | // Fills the context's output ring as far as it has room. | ||
| 102 | void pump(Context context, Voice& voice, ApuBytes memory); | ||
| 103 | |||
| 104 | // The voices of the XMA context array: one per context, set while the context is enabled. Each has its own lock, so a | ||
| 105 | // command for one voice never waits for others to decode (the title sends them from its time-critical mixer thread). | ||
| 106 | // The array is attached when the context arrays are allocated and detached when they are released. | ||
| 107 | class Engine { | ||
| 108 | public: | ||
| 109 | // `wake` (optional) is called when a voice was enabled or read from, to have the decoding thread fill rings now. | ||
| 110 | explicit Engine(ApuBytes memory, void (*wake)() = nullptr) : memory_(memory), wake_(wake) {} | ||
| 111 | |||
| 112 | void attach(uint32_t* array, uint32_t count); | ||
| 113 | void detach(); | ||
| 114 | |||
| 115 | // Runs an XMA command whose data words start at `data` (null: none); false for a command this does not know. | ||
| 116 | bool command(uint32_t command, const void* data); | ||
| 117 | |||
| 118 | // Fills every enabled context's output as far as it has room. | ||
| 119 | void pump(); | ||
| 120 | |||
| 121 | // The trace of an enabled voice; none when the context is not enabled. | ||
| 122 | std::optional<Trace> trace(uint32_t index); | ||
| 123 | |||
| 124 | private: | ||
| 125 | struct Slot { | ||
| 126 | std::mutex mutex; | ||
| 127 | std::optional<Voice> voice; | ||
| 128 | }; | ||
| 129 | |||
| 130 | std::optional<Context> context(uint32_t index) const; | ||
| 131 | void enable(uint32_t index); | ||
| 132 | void disable(uint32_t index); | ||
| 133 | void advance_read(uint32_t index, uint32_t blocks); | ||
| 134 | |||
| 135 | ApuBytes memory_; | ||
| 136 | void (*wake_)(); | ||
| 137 | std::shared_mutex lock_; // exclusive only to attach and detach | ||
| 138 | uint32_t* array_ = nullptr; | ||
| 139 | uint32_t count_ = 0; | ||
| 140 | std::unique_ptr<Slot[]> slots_; | ||
| 141 | }; | ||
| 142 | |||
| 143 | } // namespace rt::xma | ||
diff --git a/runtime/src/xma_decode.cpp b/runtime/src/xma_decode.cpp deleted file mode 100644 index add0e5e89..000000000 --- a/runtime/src/xma_decode.cpp +++ /dev/null | |||
| @@ -1,897 +0,0 @@ | |||
| 1 | // XMA2 frame decoder. Ported from VIctory (crates/victory-formats/src/xma.rs), GPL-3.0-or-later, by Marvisak and | ||
| 2 | // contributors (DexNom fork). Leonida is GPL-3.0-or-later. See xma_decode.h for what it covers and which of VIctory's | ||
| 3 | // later fixes are kept. | ||
| 4 | #include "xma_decode.h" | ||
| 5 | |||
| 6 | #include <algorithm> | ||
| 7 | #include <cmath> | ||
| 8 | #include <iterator> | ||
| 9 | #include <numbers> | ||
| 10 | |||
| 11 | #include "xma_tables.h" | ||
| 12 | |||
| 13 | namespace rt::xma { | ||
| 14 | |||
| 15 | namespace detail { | ||
| 16 | |||
| 17 | // Bitstream reading inside one gathered frame, MSB first. Reads past the data see zeros; `end` is where the frame's | ||
| 18 | // bits end, so a decoder that read further has overread. | ||
| 19 | struct BitReader { | ||
| 20 | std::span<const uint8_t> data; | ||
| 21 | size_t pos = 0; | ||
| 22 | size_t end = 0; | ||
| 23 | |||
| 24 | uint32_t peek32() const { | ||
| 25 | uint64_t v = 0; | ||
| 26 | const size_t byte = pos / 8; | ||
| 27 | for (size_t i = 0; i < 5; ++i) v = v << 8 | (byte + i < data.size() ? data[byte + i] : 0u); | ||
| 28 | return static_cast<uint32_t>((v << (24 + pos % 8)) >> 32); | ||
| 29 | } | ||
| 30 | |||
| 31 | uint32_t read(uint32_t n) { | ||
| 32 | if (n == 0) return 0; | ||
| 33 | const uint32_t v = peek32() >> (32 - n); | ||
| 34 | pos += n; | ||
| 35 | return v; | ||
| 36 | } | ||
| 37 | |||
| 38 | bool bit() { return read(1) != 0; } | ||
| 39 | |||
| 40 | int32_t sign_extend(uint32_t n) { return static_cast<int32_t>(read(n) << (32 - n)) >> (32 - n); } | ||
| 41 | |||
| 42 | bool overread() const { return pos > end; } | ||
| 43 | }; | ||
| 44 | |||
| 45 | } // namespace detail | ||
| 46 | |||
| 47 | namespace { | ||
| 48 | |||
| 49 | using detail::BitReader; | ||
| 50 | |||
| 51 | // 512 >> 2: the smallest subframe. | ||
| 52 | constexpr size_t kMinSubframe = kSubframeSamples; | ||
| 53 | |||
| 54 | uint32_t log2_floor(size_t v) { | ||
| 55 | v = std::max<size_t>(v, 1); | ||
| 56 | uint32_t r = 0; | ||
| 57 | while (v >>= 1) ++r; | ||
| 58 | return r; | ||
| 59 | } | ||
| 60 | |||
| 61 | // Packets. | ||
| 62 | |||
| 63 | // Bit positions in a buffer of packets, skipping each packet's header and the packets of other streams. | ||
| 64 | struct Cursor { | ||
| 65 | std::span<const uint8_t> data; | ||
| 66 | size_t pos = 0; | ||
| 67 | |||
| 68 | bool bit(uint32_t& out) { | ||
| 69 | // Past the data nothing is read, whatever the skips would say; checking first keeps the packet arithmetic | ||
| 70 | // below from overflowing for a position far past the end. | ||
| 71 | if (pos / 8 >= data.size()) return false; | ||
| 72 | if (pos % kPacketBits == 0) { | ||
| 73 | // Leaving a packet: jump over the other streams' packets. | ||
| 74 | const size_t previous = pos / kPacketBits; | ||
| 75 | if (previous > 0) { | ||
| 76 | const auto header = packet(data, previous - 1); | ||
| 77 | if (!header) return false; | ||
| 78 | pos = (previous + header->skip) * kPacketBits; | ||
| 79 | } | ||
| 80 | pos += kHeaderBits; | ||
| 81 | } | ||
| 82 | if (pos / 8 >= data.size()) return false; | ||
| 83 | out = (data[pos / 8] >> (7 - pos % 8)) & 1u; | ||
| 84 | ++pos; | ||
| 85 | return true; | ||
| 86 | } | ||
| 87 | |||
| 88 | bool bits(uint32_t n, uint32_t& out) { | ||
| 89 | uint32_t v = 0; | ||
| 90 | for (uint32_t i = 0; i < n; ++i) { | ||
| 91 | uint32_t b = 0; | ||
| 92 | if (!bit(b)) return false; | ||
| 93 | v = v << 1 | b; | ||
| 94 | } | ||
| 95 | out = v; | ||
| 96 | return true; | ||
| 97 | } | ||
| 98 | |||
| 99 | // A payload byte, MSB first. At a packet edge the individual bits may be separated by a header and other | ||
| 100 | // streams' packets. | ||
| 101 | bool byte(uint8_t& out) { | ||
| 102 | const size_t in_packet = pos % kPacketBits; | ||
| 103 | if (in_packet == 0 || in_packet > kPacketBits - 8) { | ||
| 104 | uint32_t v = 0; | ||
| 105 | if (!bits(8, v)) return false; | ||
| 106 | out = static_cast<uint8_t>(v); | ||
| 107 | return true; | ||
| 108 | } | ||
| 109 | const size_t at = pos / 8; | ||
| 110 | const unsigned shift = static_cast<unsigned>(pos % 8); | ||
| 111 | if (at >= data.size()) return false; | ||
| 112 | const unsigned first = data[at]; | ||
| 113 | if (shift == 0) { | ||
| 114 | out = static_cast<uint8_t>(first); | ||
| 115 | } else { | ||
| 116 | if (at + 1 >= data.size()) return false; | ||
| 117 | out = static_cast<uint8_t>(((first << shift) | (data[at + 1] >> (8 - shift))) & 0xffu); | ||
| 118 | } | ||
| 119 | pos += 8; | ||
| 120 | return true; | ||
| 121 | } | ||
| 122 | }; | ||
| 123 | |||
| 124 | // Where the frame after the one at `start`..`end` begins: right after it, unless it was the last frame to begin in its | ||
| 125 | // packet and the rest of that packet is padding. | ||
| 126 | std::optional<size_t> next_frame(std::span<const uint8_t> data, size_t start, size_t end) { | ||
| 127 | const size_t index = start / kPacketBits; | ||
| 128 | const auto header = packet(data, index); | ||
| 129 | if (!header) return std::nullopt; | ||
| 130 | size_t at = index * kPacketBits + kHeaderBits + header->first_frame_bit; | ||
| 131 | uint32_t number = 0; | ||
| 132 | while (at < start) { | ||
| 133 | Cursor cursor{data, at}; | ||
| 134 | uint32_t bits = 0; | ||
| 135 | if (!cursor.bits(kLengthBits, bits)) return std::nullopt; | ||
| 136 | // The same rule as read_frame: a length that does not cover its own field is not a frame. A zero length | ||
| 137 | // would never move `at`, so a damaged packet would loop here for good. | ||
| 138 | if (bits <= kLengthBits) return std::nullopt; | ||
| 139 | at += bits; | ||
| 140 | ++number; | ||
| 141 | } | ||
| 142 | const bool last = number + 1 >= header->frames; | ||
| 143 | // A frame that ends in a packet where no frame begins (the tail of a frame that crossed packets, then padding) | ||
| 144 | // is the last one before the next packet that has frames. | ||
| 145 | bool ends_in_packet_without_frames = false; | ||
| 146 | if (end / kPacketBits != index && end % kPacketBits != 0) { | ||
| 147 | const auto there = packet(data, end / kPacketBits); | ||
| 148 | if (!there) return std::nullopt; | ||
| 149 | ends_in_packet_without_frames = there->frames == 0; | ||
| 150 | } | ||
| 151 | if (end % kPacketBits == 0 || (last && end / kPacketBits == index) || ends_in_packet_without_frames) { | ||
| 152 | // The next frame begins in the next packet of this stream that has one; a packet with none (a frame spans | ||
| 153 | // all of it) holds no start. | ||
| 154 | const auto ending = packet(data, (end - 1) / kPacketBits); | ||
| 155 | if (!ending) return std::nullopt; | ||
| 156 | size_t next = (end - 1) / kPacketBits + 1 + ending->skip; | ||
| 157 | auto following = packet(data, next); | ||
| 158 | if (!following) return std::nullopt; | ||
| 159 | while (following->frames == 0) { | ||
| 160 | next += 1 + following->skip; | ||
| 161 | following = packet(data, next); | ||
| 162 | if (!following) return std::nullopt; | ||
| 163 | } | ||
| 164 | end = next * kPacketBits + kHeaderBits + following->first_frame_bit; | ||
| 165 | } | ||
| 166 | if (end / 8 < data.size()) return end; | ||
| 167 | return std::nullopt; | ||
| 168 | } | ||
| 169 | |||
| 170 | // A prefix code built like FFmpeg's ff_vlc_init_from_lengths: codes are handed out in table order, each the next free | ||
| 171 | // one of its length. | ||
| 172 | class Vlc { | ||
| 173 | public: | ||
| 174 | void add(int32_t symbol, uint8_t length) { | ||
| 175 | codes_.push_back({static_cast<uint32_t>(next_), length, symbol}); | ||
| 176 | next_ += uint64_t{1} << (32 - length); | ||
| 177 | } | ||
| 178 | |||
| 179 | int32_t read(BitReader& b) const { | ||
| 180 | const uint32_t v = b.peek32(); | ||
| 181 | // The last code at or below v; the first code is 0, so there is always one. | ||
| 182 | auto it = std::upper_bound(codes_.begin(), codes_.end(), v, | ||
| 183 | [](uint32_t value, const Code& c) { return value < c.code; }); | ||
| 184 | const Code& c = *(it - 1); | ||
| 185 | b.pos += c.length; | ||
| 186 | return c.symbol; | ||
| 187 | } | ||
| 188 | |||
| 189 | private: | ||
| 190 | struct Code { | ||
| 191 | uint32_t code; // left-aligned | ||
| 192 | uint8_t length; | ||
| 193 | int32_t symbol; | ||
| 194 | }; | ||
| 195 | std::vector<Code> codes_; // sorted by code | ||
| 196 | uint64_t next_ = 0; | ||
| 197 | }; | ||
| 198 | |||
| 199 | struct Codes { | ||
| 200 | Vlc scale, scale_rl, coef[2], vec4, vec2, vec1; | ||
| 201 | }; | ||
| 202 | |||
| 203 | template <size_t N> | ||
| 204 | void add_pairs(Vlc& vlc, const tables::SymbolLength (&pairs)[N], int32_t offset) { | ||
| 205 | for (const auto& p : pairs) vlc.add(static_cast<int32_t>(p.symbol) + offset, p.length); | ||
| 206 | } | ||
| 207 | |||
| 208 | const Codes& codes() { | ||
| 209 | static const Codes built = [] { | ||
| 210 | Codes c; | ||
| 211 | add_pairs(c.scale, tables::kScale, -60); | ||
| 212 | add_pairs(c.scale_rl, tables::kScaleRl, 0); | ||
| 213 | static_assert(std::size(tables::kCoef0Syms) == std::size(tables::kCoef0Lens)); | ||
| 214 | for (size_t i = 0; i < std::size(tables::kCoef0Syms); ++i) | ||
| 215 | c.coef[0].add(static_cast<int32_t>(tables::kCoef0Syms[i]), tables::kCoef0Lens[i]); | ||
| 216 | add_pairs(c.coef[1], tables::kCoef1, 0); | ||
| 217 | static_assert(std::size(tables::kVec4Syms) == std::size(tables::kVec4Lens)); | ||
| 218 | for (size_t i = 0; i < std::size(tables::kVec4Syms); ++i) | ||
| 219 | c.vec4.add(static_cast<int32_t>(tables::kVec4Syms[i]) - 1, tables::kVec4Lens[i]); | ||
| 220 | add_pairs(c.vec2, tables::kVec2, -1); | ||
| 221 | add_pairs(c.vec1, tables::kVec1, 0); | ||
| 222 | return c; | ||
| 223 | }(); | ||
| 224 | return built; | ||
| 225 | } | ||
| 226 | |||
| 227 | // ff_wma_get_large_val. | ||
| 228 | uint32_t large_value(BitReader& b) { | ||
| 229 | uint32_t n = 8; | ||
| 230 | if (b.bit()) { | ||
| 231 | n += 8; | ||
| 232 | if (b.bit()) { | ||
| 233 | n += 8; | ||
| 234 | if (b.bit()) n += 7; | ||
| 235 | } | ||
| 236 | } | ||
| 237 | return b.read(n); | ||
| 238 | } | ||
| 239 | |||
| 240 | // The inverse transform. | ||
| 241 | |||
| 242 | // Everything imdct_half needs for one size `n` that does not depend on the coefficients: the pre-rotation | ||
| 243 | // exp(-iπk/n) and post-rotation exp(-iπ(4k+1)/4n) of each of the n/2 FFT points, the FFT's bit-reversed order and its | ||
| 244 | // butterfly rotations. Each value is computed with the expression (for the butterflies the running product) the | ||
| 245 | // transform would work out on every call, so it gives the same bits. | ||
| 246 | struct Rotations { | ||
| 247 | std::vector<double> pre_re, pre_im, post_re, post_im; | ||
| 248 | std::vector<uint16_t> reversed; // where the bit-reversal permutation puts each point | ||
| 249 | // The butterfly rotations of every stage, the stage of length `len` starting at len / 2 - 1. | ||
| 250 | std::vector<double> twiddle_re, twiddle_im; | ||
| 251 | |||
| 252 | explicit Rotations(size_t n) { | ||
| 253 | const size_t m = n / 2; | ||
| 254 | constexpr double pi = std::numbers::pi; | ||
| 255 | for (size_t k = 0; k < m; ++k) { | ||
| 256 | const double a = -pi * static_cast<double>(k) / static_cast<double>(n); | ||
| 257 | pre_re.push_back(std::cos(a)); | ||
| 258 | pre_im.push_back(std::sin(a)); | ||
| 259 | const double b = -pi * static_cast<double>(4 * k + 1) / static_cast<double>(4 * n); | ||
| 260 | post_re.push_back(std::cos(b)); | ||
| 261 | post_im.push_back(std::sin(b)); | ||
| 262 | } | ||
| 263 | // The swaps of the in-place bit reversal, applied to the identity. | ||
| 264 | for (size_t i = 0; i < m; ++i) reversed.push_back(static_cast<uint16_t>(i)); | ||
| 265 | size_t j = 0; | ||
| 266 | for (size_t i = 1; i < m; ++i) { | ||
| 267 | size_t bit = m >> 1; | ||
| 268 | while (j & bit) { | ||
| 269 | j ^= bit; | ||
| 270 | bit >>= 1; | ||
| 271 | } | ||
| 272 | j |= bit; | ||
| 273 | if (i < j) std::swap(reversed[i], reversed[j]); | ||
| 274 | } | ||
| 275 | for (size_t len = 2; len <= m; len <<= 1) { | ||
| 276 | const double a = -2.0 * pi / static_cast<double>(len); | ||
| 277 | const double ws = std::sin(a), wc = std::cos(a); | ||
| 278 | double cr = 1.0, ci = 0.0; | ||
| 279 | for (size_t k = 0; k < len / 2; ++k) { | ||
| 280 | twiddle_re.push_back(cr); | ||
| 281 | twiddle_im.push_back(ci); | ||
| 282 | const double nr = cr * wc - ci * ws; | ||
| 283 | const double ni = cr * ws + ci * wc; | ||
| 284 | cr = nr; | ||
| 285 | ci = ni; | ||
| 286 | } | ||
| 287 | } | ||
| 288 | } | ||
| 289 | |||
| 290 | // The butterfly stages of an in-place radix-2 forward DFT (exp(-2πi nk/N)) on m points already in bit-reversed | ||
| 291 | // order. | ||
| 292 | void butterflies(double* re, double* im, size_t m) const { | ||
| 293 | for (size_t len = 2; len <= m; len <<= 1) { | ||
| 294 | const size_t half = len / 2; | ||
| 295 | const double* wr = twiddle_re.data() + (half - 1); | ||
| 296 | const double* wi = twiddle_im.data() + (half - 1); | ||
| 297 | for (size_t start = 0; start < m; start += len) { | ||
| 298 | for (size_t k = 0; k < half; ++k) { | ||
| 299 | const size_t a = start + k, b = a + half; | ||
| 300 | const double tr = re[b] * wr[k] - im[b] * wi[k]; | ||
| 301 | const double ti = re[b] * wi[k] + im[b] * wr[k]; | ||
| 302 | re[b] = re[a] - tr; | ||
| 303 | im[b] = im[a] - ti; | ||
| 304 | re[a] = re[a] + tr; | ||
| 305 | im[a] = im[a] + ti; | ||
| 306 | } | ||
| 307 | } | ||
| 308 | } | ||
| 309 | } | ||
| 310 | }; | ||
| 311 | |||
| 312 | // Rotations for subframes of 128, 256 and 512 samples. | ||
| 313 | const Rotations* cached_rotations(size_t n) { | ||
| 314 | static const Rotations r128(128), r256(256), r512(512); | ||
| 315 | switch (n) { | ||
| 316 | case 128: return &r128; | ||
| 317 | case 256: return &r256; | ||
| 318 | case 512: return &r512; | ||
| 319 | default: return nullptr; | ||
| 320 | } | ||
| 321 | } | ||
| 322 | |||
| 323 | // Sine windows for blocks of 128, 256 and 512 samples. | ||
| 324 | const std::vector<float>& window_for(size_t winlen) { | ||
| 325 | static const std::vector<float> w[3] = {sine_window(128), sine_window(256), sine_window(512)}; | ||
| 326 | return w[log2_floor(winlen) - 7]; | ||
| 327 | } | ||
| 328 | |||
| 329 | int16_t to_i16(float v) { | ||
| 330 | const float s = std::round(v * 32768.0f); | ||
| 331 | if (s != s) return 0; // NaN, as Rust's saturating cast gives | ||
| 332 | if (s <= -32768.0f) return -32768; | ||
| 333 | if (s >= 32767.0f) return 32767; | ||
| 334 | return static_cast<int16_t>(s); | ||
| 335 | } | ||
| 336 | |||
| 337 | } // namespace | ||
| 338 | |||
| 339 | std::optional<Packet> packet(std::span<const uint8_t> data, size_t index) { | ||
| 340 | if (index > (SIZE_MAX - 4) / kPacketBytes) return std::nullopt; | ||
| 341 | const size_t start = index * kPacketBytes; | ||
| 342 | if (start > data.size() || data.size() - start < 4) return std::nullopt; | ||
| 343 | const uint32_t h = static_cast<uint32_t>(data[start]) << 24 | static_cast<uint32_t>(data[start + 1]) << 16 | | ||
| 344 | static_cast<uint32_t>(data[start + 2]) << 8 | data[start + 3]; | ||
| 345 | return Packet{h >> 26, (h >> 11) & 0x7fffu, h & 0xffu}; | ||
| 346 | } | ||
| 347 | |||
| 348 | std::optional<Frame> read_frame(std::span<const uint8_t> data, size_t start) { | ||
| 349 | Cursor cursor{data, start}; | ||
| 350 | uint32_t length = 0; | ||
| 351 | if (!cursor.bits(kLengthBits, length)) return std::nullopt; | ||
| 352 | const size_t bits = length; | ||
| 353 | if (bits <= kLengthBits || bits == 0x7fff) return std::nullopt; | ||
| 354 | Frame frame; | ||
| 355 | frame.data.reserve((bits + 7) / 8); | ||
| 356 | Cursor gather{data, start}; | ||
| 357 | for (size_t i = 0; i < bits / 8; ++i) { | ||
| 358 | uint8_t v = 0; | ||
| 359 | if (!gather.byte(v)) return std::nullopt; | ||
| 360 | frame.data.push_back(v); | ||
| 361 | } | ||
| 362 | const uint32_t tail = static_cast<uint32_t>(bits % 8); | ||
| 363 | if (tail != 0) { | ||
| 364 | uint32_t v = 0; | ||
| 365 | if (!gather.bits(tail, v)) return std::nullopt; | ||
| 366 | frame.data.push_back(static_cast<uint8_t>(v << (8 - tail))); | ||
| 367 | } | ||
| 368 | frame.bits = bits; | ||
| 369 | frame.start = start; | ||
| 370 | frame.next = next_frame(data, start, gather.pos); | ||
| 371 | return frame; | ||
| 372 | } | ||
| 373 | |||
| 374 | void imdct_half(std::span<const float> input, std::span<float> out, float scale) { | ||
| 375 | const size_t n = input.size(); | ||
| 376 | const size_t m = n / 2; | ||
| 377 | if (m == 0 || out.size() < n) return; | ||
| 378 | const Rotations* rotations = cached_rotations(n); | ||
| 379 | std::optional<Rotations> built; | ||
| 380 | if (!rotations) rotations = &built.emplace(n); | ||
| 381 | double stack[kFrameSamples]; | ||
| 382 | std::vector<double> heap; | ||
| 383 | double* re = stack; | ||
| 384 | if (m > kFrameSamples / 2) { | ||
| 385 | heap.resize(2 * m); | ||
| 386 | re = heap.data(); | ||
| 387 | } | ||
| 388 | double* im = re + m; | ||
| 389 | // Pre-rotation, each point stored at its bit-reversed place, which is where the FFT's input permutation would | ||
| 390 | // move it. | ||
| 391 | for (size_t k = 0; k < m; ++k) { | ||
| 392 | const double a = input[2 * k], b = input[n - 1 - 2 * k]; | ||
| 393 | const double c = rotations->pre_re[k], s = rotations->pre_im[k]; | ||
| 394 | const size_t to = rotations->reversed[k]; | ||
| 395 | re[to] = a * c - b * s; | ||
| 396 | im[to] = a * s + b * c; | ||
| 397 | } | ||
| 398 | rotations->butterflies(re, im, m); | ||
| 399 | for (size_t k = 0; k < m; ++k) { | ||
| 400 | const double c = rotations->post_re[k], s = rotations->post_im[k]; | ||
| 401 | const double wr = re[k] * c - im[k] * s; | ||
| 402 | const double wi = re[k] * s + im[k] * c; | ||
| 403 | // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. | ||
| 404 | out[n - 1 - 2 * k] = static_cast<float>(wr) * scale; | ||
| 405 | out[2 * k] = -static_cast<float>(wi) * scale; | ||
| 406 | } | ||
| 407 | } | ||
| 408 | |||
| 409 | std::vector<float> sine_window(size_t n) { | ||
| 410 | std::vector<float> w(n); | ||
| 411 | for (size_t i = 0; i < n; ++i) | ||
| 412 | w[i] = static_cast<float>( | ||
| 413 | std::sin((static_cast<double>(i) + 0.5) * std::numbers::pi / (2.0 * static_cast<double>(n)))); | ||
| 414 | return w; | ||
| 415 | } | ||
| 416 | |||
| 417 | void window_overlap(std::span<float> block, std::span<const float> window) { | ||
| 418 | const size_t len = block.size() / 2; | ||
| 419 | if (window.size() < 2 * len) return; | ||
| 420 | for (size_t k = 0; k < len; ++k) { | ||
| 421 | const size_t i = k, j = 2 * len - 1 - k; | ||
| 422 | const float s0 = block[i], s1 = block[j]; | ||
| 423 | const float wi = window[i], wj = window[j]; | ||
| 424 | block[i] = s0 * wj - s1 * wi; | ||
| 425 | block[j] = s0 * wi + s1 * wj; | ||
| 426 | } | ||
| 427 | } | ||
| 428 | |||
| 429 | // The frame decoder. | ||
| 430 | |||
| 431 | Decoder::Decoder(size_t channels, uint32_t sample_rate) { | ||
| 432 | channels_ = std::clamp<size_t>(channels, 1, 2); | ||
| 433 | const size_t rate = sample_rate > 44100 ? 48000 : sample_rate > 32000 ? 44100 : sample_rate > 24000 ? 32000 : 24000; | ||
| 434 | for (size_t i = 0; i < kBlockSizes; ++i) { | ||
| 435 | const size_t subframe_len = kFrameSamples >> i; | ||
| 436 | auto& offsets = sfb_offsets_[i]; | ||
| 437 | size_t band = 1; | ||
| 438 | for (size_t f = 0; f < kMaxBands - 1; ++f) { | ||
| 439 | if (offsets[band - 1] >= subframe_len) break; | ||
| 440 | const size_t offset = ((subframe_len * 2 * tables::kCriticalFreq[f]) / rate + 2) & ~size_t{3}; | ||
| 441 | if (offset > offsets[band - 1]) { | ||
| 442 | offsets[band] = offset; | ||
| 443 | ++band; | ||
| 444 | } | ||
| 445 | if (offset >= subframe_len) break; | ||
| 446 | } | ||
| 447 | offsets[band - 1] = subframe_len; | ||
| 448 | num_sfb_[i] = band - 1; | ||
| 449 | } | ||
| 450 | for (size_t i = 0; i < kBlockSizes; ++i) { | ||
| 451 | for (size_t b = 0; b < num_sfb_[i]; ++b) { | ||
| 452 | const size_t offset = ((sfb_offsets_[i][b] + sfb_offsets_[i][b + 1] - 1) << i) >> 1; | ||
| 453 | for (size_t x = 0; x < kBlockSizes; ++x) { | ||
| 454 | size_t v = 0; | ||
| 455 | while (v + 1 < kMaxBands && (sfb_offsets_[x][v + 1] << x) < offset) ++v; | ||
| 456 | sf_offsets_[i][x][b] = v; | ||
| 457 | } | ||
| 458 | } | ||
| 459 | } | ||
| 460 | } | ||
| 461 | |||
| 462 | void Decoder::reset() { ch_ = {}; } | ||
| 463 | |||
| 464 | const char* Decoder::decode(std::span<const uint8_t> data, size_t bits, std::vector<int16_t>& out) { | ||
| 465 | // Past the data there are only zeros to read. A count beyond it would never let a stereo tile header overread, | ||
| 466 | // and its loop takes no subframe on zero bits, so it would spin for good. | ||
| 467 | const size_t data_bits = data.size() > SIZE_MAX / 8 ? SIZE_MAX : data.size() * 8; | ||
| 468 | BitReader b{data, 0, std::min(bits, data_bits)}; | ||
| 469 | const size_t len = b.read(kLengthBits); | ||
| 470 | const char* result = frame(b, len); | ||
| 471 | if (result) { | ||
| 472 | // Whatever the frame held is lost; keep the stream's timing. | ||
| 473 | for (size_t c = 0; c < channels_; ++c) ch_[c].out.fill(0.0f); | ||
| 474 | } | ||
| 475 | out.reserve(out.size() + kFrameSamples * channels_); | ||
| 476 | for (size_t i = 0; i < kFrameSamples; ++i) | ||
| 477 | for (size_t c = 0; c < channels_; ++c) out.push_back(to_i16(ch_[c].out[i])); | ||
| 478 | for (size_t c = 0; c < channels_; ++c) | ||
| 479 | std::copy(ch_[c].out.begin() + kFrameSamples, ch_[c].out.end(), ch_[c].out.begin()); | ||
| 480 | return result; | ||
| 481 | } | ||
| 482 | |||
| 483 | void Decoder::flush(std::vector<int16_t>& out) { | ||
| 484 | for (size_t i = 0; i < kFrameSamples / 2; ++i) | ||
| 485 | for (size_t c = 0; c < channels_; ++c) out.push_back(to_i16(ch_[c].out[i])); | ||
| 486 | reset(); | ||
| 487 | } | ||
| 488 | |||
| 489 | const char* Decoder::frame(BitReader& b, size_t len) { | ||
| 490 | if (const char* e = tile_header(b)) return e; | ||
| 491 | // Post-processing transform. | ||
| 492 | if (channels_ > 1 && b.bit() && b.bit()) b.read(static_cast<uint32_t>(channels_ * channels_ * 4)); | ||
| 493 | // Dynamic range compression gain, unused. | ||
| 494 | b.read(8); | ||
| 495 | if (b.bit()) { | ||
| 496 | // Trim at start and end, which only WMA Pro files apply. | ||
| 497 | if (b.bit()) b.read(log2_floor(kFrameSamples * 2)); | ||
| 498 | if (b.bit()) b.read(log2_floor(kFrameSamples * 2)); | ||
| 499 | } | ||
| 500 | parsed_all_subframes_ = false; | ||
| 501 | for (size_t c = 0; c < channels_; ++c) { | ||
| 502 | ch_[c].decoded_samples = 0; | ||
| 503 | ch_[c].cur_subframe = 0; | ||
| 504 | ch_[c].reuse_sf = false; | ||
| 505 | } | ||
| 506 | while (!parsed_all_subframes_) | ||
| 507 | if (const char* e = subframe(b)) return e; | ||
| 508 | // FFmpeg flags `len != consumed + 2` but keeps the samples; so do we. | ||
| 509 | if (b.overread() || b.pos > len) return "frame overread"; | ||
| 510 | return nullptr; | ||
| 511 | } | ||
| 512 | |||
| 513 | const char* Decoder::subframe_length(BitReader& b, size_t offset, size_t& len) { | ||
| 514 | if (offset == kFrameSamples - kMinSubframe) { | ||
| 515 | len = kMinSubframe; | ||
| 516 | return nullptr; | ||
| 517 | } | ||
| 518 | // Four subframe sizes: a 1-bit "not maximal", then 1 bit of shift. | ||
| 519 | const uint32_t shift = b.bit() ? 1 + b.read(1) : 0; | ||
| 520 | len = kFrameSamples >> shift; | ||
| 521 | if (len < kMinSubframe) return "subframe length"; | ||
| 522 | return nullptr; | ||
| 523 | } | ||
| 524 | |||
| 525 | const char* Decoder::tile_header(BitReader& b) { | ||
| 526 | size_t num_samples[2] = {0, 0}; | ||
| 527 | bool contains[2] = {false, false}; | ||
| 528 | size_t channels_for_cur_subframe = channels_; | ||
| 529 | size_t min_channel_len = 0; | ||
| 530 | for (size_t c = 0; c < channels_; ++c) ch_[c].num_subframes = 0; | ||
| 531 | const bool fixed = b.bit(); | ||
| 532 | for (;;) { | ||
| 533 | for (size_t c = 0; c < channels_; ++c) | ||
| 534 | contains[c] = num_samples[c] == min_channel_len && | ||
| 535 | (fixed || channels_for_cur_subframe == 1 || | ||
| 536 | min_channel_len == kFrameSamples - kMinSubframe || b.bit()); | ||
| 537 | size_t subframe_len = 0; | ||
| 538 | if (const char* e = subframe_length(b, min_channel_len, subframe_len)) return e; | ||
| 539 | min_channel_len += subframe_len; | ||
| 540 | for (size_t c = 0; c < channels_; ++c) { | ||
| 541 | Channel& ch = ch_[c]; | ||
| 542 | if (contains[c]) { | ||
| 543 | if (ch.num_subframes >= kMaxSubframes) return "too many subframes"; | ||
| 544 | ch.subframe_len[ch.num_subframes] = subframe_len; | ||
| 545 | num_samples[c] += subframe_len; | ||
| 546 | ++ch.num_subframes; | ||
| 547 | if (num_samples[c] > kFrameSamples) return "channel longer than a frame"; | ||
| 548 | } else if (num_samples[c] <= min_channel_len) { | ||
| 549 | if (num_samples[c] < min_channel_len) { | ||
| 550 | channels_for_cur_subframe = 0; | ||
| 551 | min_channel_len = num_samples[c]; | ||
| 552 | } | ||
| 553 | ++channels_for_cur_subframe; | ||
| 554 | } | ||
| 555 | } | ||
| 556 | if (min_channel_len >= kFrameSamples || b.overread()) break; | ||
| 557 | } | ||
| 558 | if (b.overread()) return "tile header"; | ||
| 559 | return nullptr; | ||
| 560 | } | ||
| 561 | |||
| 562 | const char* Decoder::channel_transform(BitReader& b) { | ||
| 563 | transform_ = false; | ||
| 564 | if (channels_ == 1) return nullptr; | ||
| 565 | if (b.bit()) return "channel transform bit"; | ||
| 566 | // One group holding every channel of the subframe. | ||
| 567 | if (channels_for_cur_subframe_ == 2) { | ||
| 568 | if (b.bit()) { | ||
| 569 | if (b.bit()) return "channel transform type"; | ||
| 570 | } else { | ||
| 571 | transform_ = true; | ||
| 572 | } | ||
| 573 | } | ||
| 574 | if (transform_) { | ||
| 575 | if (!b.bit()) { | ||
| 576 | for (size_t i = 0; i < num_bands_; ++i) transform_band_[i] = b.bit(); | ||
| 577 | } else { | ||
| 578 | transform_band_.fill(true); | ||
| 579 | } | ||
| 580 | } | ||
| 581 | return nullptr; | ||
| 582 | } | ||
| 583 | |||
| 584 | const char* Decoder::coefficients(BitReader& b, size_t c) { | ||
| 585 | const Codes& vlc = codes(); | ||
| 586 | const size_t table = b.bit() ? 1 : 0; | ||
| 587 | const uint16_t* run = table == 1 ? tables::kCoef1Run : tables::kCoef0Run; | ||
| 588 | const float* level = table == 1 ? tables::kCoef1Level : tables::kCoef0Level; | ||
| 589 | const size_t subframe_len = subframe_len_; | ||
| 590 | Channel& ch = ch_[c]; | ||
| 591 | bool rl_mode = false; | ||
| 592 | size_t cur = 0; | ||
| 593 | size_t num_zeros = 0; | ||
| 594 | while ((transmit_num_vec_coeffs_ || !rl_mode) && cur + 3 < ch.num_vec_coeffs) { | ||
| 595 | uint32_t vals[4] = {0, 0, 0, 0}; | ||
| 596 | const int32_t idx = vlc.vec4.read(b); | ||
| 597 | if (idx < 0) { | ||
| 598 | for (size_t i = 0; i < 4; i += 2) { | ||
| 599 | const int32_t idx2 = vlc.vec2.read(b); | ||
| 600 | if (idx2 < 0) { | ||
| 601 | for (size_t k = i; k < i + 2; ++k) { | ||
| 602 | uint32_t x = static_cast<uint32_t>(vlc.vec1.read(b)); | ||
| 603 | if (x == std::size(tables::kVec1) - 1) x += large_value(b); | ||
| 604 | vals[k] = x; | ||
| 605 | } | ||
| 606 | } else { | ||
| 607 | vals[i] = static_cast<uint32_t>(idx2 >> 4); | ||
| 608 | vals[i + 1] = static_cast<uint32_t>(idx2 & 0xf); | ||
| 609 | } | ||
| 610 | } | ||
| 611 | } else { | ||
| 612 | vals[0] = static_cast<uint32_t>(idx >> 12); | ||
| 613 | vals[1] = static_cast<uint32_t>((idx >> 8) & 0xf); | ||
| 614 | vals[2] = static_cast<uint32_t>((idx >> 4) & 0xf); | ||
| 615 | vals[3] = static_cast<uint32_t>(idx & 0xf); | ||
| 616 | } | ||
| 617 | for (const uint32_t v : vals) { | ||
| 618 | if (v != 0) { | ||
| 619 | const bool negative = !b.bit(); | ||
| 620 | ch.coeffs[cur] = negative ? -static_cast<float>(v) : static_cast<float>(v); | ||
| 621 | num_zeros = 0; | ||
| 622 | } else { | ||
| 623 | ch.coeffs[cur] = 0.0f; | ||
| 624 | ++num_zeros; | ||
| 625 | rl_mode |= num_zeros > (subframe_len >> 8); | ||
| 626 | } | ||
| 627 | ++cur; | ||
| 628 | } | ||
| 629 | if (b.overread()) return "vector coefficients"; | ||
| 630 | } | ||
| 631 | if (cur < subframe_len) { | ||
| 632 | std::fill(ch.coeffs.begin() + static_cast<ptrdiff_t>(cur), | ||
| 633 | ch.coeffs.begin() + static_cast<ptrdiff_t>(subframe_len), 0.0f); | ||
| 634 | // ff_wma_run_level_decode, version 1. | ||
| 635 | const size_t mask = subframe_len - 1; | ||
| 636 | size_t offset = cur; | ||
| 637 | while (offset < subframe_len) { | ||
| 638 | const int32_t code = vlc.coef[table].read(b); | ||
| 639 | if (code > 1) { | ||
| 640 | offset += run[code]; | ||
| 641 | const bool negative = !b.bit(); | ||
| 642 | const float v = level[code]; | ||
| 643 | ch.coeffs[offset & mask] = negative ? -v : v; | ||
| 644 | } else if (code == 1) { | ||
| 645 | break; | ||
| 646 | } else { | ||
| 647 | const int32_t value = static_cast<int32_t>(large_value(b)); | ||
| 648 | if (b.bit()) { | ||
| 649 | if (b.bit()) { | ||
| 650 | // A broken escape ends the channel's coefficients, as in FFmpeg. | ||
| 651 | if (b.bit()) break; | ||
| 652 | offset += b.read(esc_len_) + 4; | ||
| 653 | } else { | ||
| 654 | offset += b.read(2) + 1; | ||
| 655 | } | ||
| 656 | } | ||
| 657 | const bool negative = !b.bit(); | ||
| 658 | ch.coeffs[offset & mask] = static_cast<float>(negative ? -value : value); | ||
| 659 | } | ||
| 660 | if (b.overread()) return "run level coefficients"; | ||
| 661 | ++offset; | ||
| 662 | } | ||
| 663 | } | ||
| 664 | return nullptr; | ||
| 665 | } | ||
| 666 | |||
| 667 | const char* Decoder::scale_factors(BitReader& b) { | ||
| 668 | const Codes& vlc = codes(); | ||
| 669 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 670 | const size_t c = channel_indexes_[i]; | ||
| 671 | const auto sf_offsets = sf_offsets_[table_idx_][ch_[c].table_idx]; | ||
| 672 | Channel& ch = ch_[c]; | ||
| 673 | const size_t target = 1 - ch.scale_factor_idx; | ||
| 674 | ch.scale_factors = target; | ||
| 675 | if (ch.reuse_sf) { | ||
| 676 | const auto from = ch.saved_scale_factors[ch.scale_factor_idx]; | ||
| 677 | for (size_t band = 0; band < num_bands_; ++band) | ||
| 678 | ch.saved_scale_factors[target][band] = from[sf_offsets[band]]; | ||
| 679 | } | ||
| 680 | if (ch.cur_subframe == 0 || b.bit()) { | ||
| 681 | if (!ch.reuse_sf) { | ||
| 682 | ch.scale_factor_step = static_cast<int32_t>(b.read(2)) + 1; | ||
| 683 | int32_t val = 45 / ch.scale_factor_step; | ||
| 684 | for (size_t band = 0; band < num_bands_; ++band) { | ||
| 685 | val += vlc.scale.read(b); | ||
| 686 | ch.saved_scale_factors[target][band] = val; | ||
| 687 | } | ||
| 688 | } else { | ||
| 689 | size_t band = 0; | ||
| 690 | while (band < num_bands_) { | ||
| 691 | const int32_t idx = vlc.scale_rl.read(b); | ||
| 692 | size_t skip = 0; | ||
| 693 | int32_t val = 0; | ||
| 694 | bool negative = false; | ||
| 695 | if (idx == 0) { | ||
| 696 | const uint32_t code = b.read(14); | ||
| 697 | skip = (code & 0x3f) >> 1; | ||
| 698 | val = static_cast<int32_t>(code >> 6); | ||
| 699 | negative = (code & 1) == 0; | ||
| 700 | } else if (idx == 1) { | ||
| 701 | break; | ||
| 702 | } else { | ||
| 703 | skip = tables::kScaleRlRun[idx]; | ||
| 704 | val = tables::kScaleRlLevel[idx]; | ||
| 705 | negative = !b.bit(); | ||
| 706 | } | ||
| 707 | band += skip; | ||
| 708 | if (band >= num_bands_) return "scale factor run"; | ||
| 709 | ch.saved_scale_factors[target][band] += negative ? -val : val; | ||
| 710 | ++band; | ||
| 711 | } | ||
| 712 | } | ||
| 713 | ch.scale_factor_idx = target; | ||
| 714 | ch.table_idx = table_idx_; | ||
| 715 | ch.reuse_sf = true; | ||
| 716 | } | ||
| 717 | const auto& sf = ch.saved_scale_factors[ch.scale_factors]; | ||
| 718 | int32_t max = 0; | ||
| 719 | for (size_t band = 0; band < num_bands_; ++band) max = band == 0 ? sf[band] : std::max(max, sf[band]); | ||
| 720 | ch.max_scale_factor = max; | ||
| 721 | } | ||
| 722 | return nullptr; | ||
| 723 | } | ||
| 724 | |||
| 725 | const char* Decoder::subframe(BitReader& b) { | ||
| 726 | size_t offset = kFrameSamples; | ||
| 727 | size_t subframe_len = kFrameSamples; | ||
| 728 | int64_t total_samples = static_cast<int64_t>(kFrameSamples * channels_); | ||
| 729 | for (size_t c = 0; c < channels_; ++c) { | ||
| 730 | const Channel& ch = ch_[c]; | ||
| 731 | if (offset > ch.decoded_samples) { | ||
| 732 | offset = ch.decoded_samples; | ||
| 733 | subframe_len = ch.subframe_len[std::min(ch.cur_subframe, kMaxSubframes - 1)]; | ||
| 734 | } | ||
| 735 | } | ||
| 736 | channels_for_cur_subframe_ = 0; | ||
| 737 | for (size_t c = 0; c < channels_; ++c) { | ||
| 738 | Channel& ch = ch_[c]; | ||
| 739 | total_samples -= static_cast<int64_t>(ch.decoded_samples); | ||
| 740 | if (offset == ch.decoded_samples && ch.cur_subframe < ch.num_subframes && | ||
| 741 | subframe_len == ch.subframe_len[ch.cur_subframe]) { | ||
| 742 | total_samples -= static_cast<int64_t>(subframe_len); | ||
| 743 | ch.decoded_samples += subframe_len; | ||
| 744 | channel_indexes_[channels_for_cur_subframe_] = c; | ||
| 745 | ++channels_for_cur_subframe_; | ||
| 746 | } | ||
| 747 | } | ||
| 748 | // A tile header that parsed gives every channel subframes of 128 to 512 samples; a length outside that is a | ||
| 749 | // channel without one, which no subframe can take. | ||
| 750 | if (channels_for_cur_subframe_ == 0 || subframe_len < kMinSubframe) return "no channel in subframe"; | ||
| 751 | if (total_samples == 0) parsed_all_subframes_ = true; | ||
| 752 | table_idx_ = log2_floor(kFrameSamples / subframe_len); | ||
| 753 | num_bands_ = num_sfb_[table_idx_]; | ||
| 754 | subframe_len_ = subframe_len; | ||
| 755 | esc_len_ = log2_floor(subframe_len - 1) + 1; | ||
| 756 | |||
| 757 | // Extended header: fill bits. | ||
| 758 | if (b.bit()) { | ||
| 759 | size_t fill = b.read(2); | ||
| 760 | if (fill == 0) { | ||
| 761 | const uint32_t len = b.read(4); | ||
| 762 | fill = static_cast<size_t>(b.read(len)) + 1; | ||
| 763 | } | ||
| 764 | b.pos += fill; | ||
| 765 | } | ||
| 766 | if (b.bit()) return "reserved bit"; | ||
| 767 | if (const char* e = channel_transform(b)) return e; | ||
| 768 | |||
| 769 | bool transmit_coeffs = false; | ||
| 770 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 771 | const size_t c = channel_indexes_[i]; | ||
| 772 | ch_[c].transmit_coefs = b.bit(); | ||
| 773 | transmit_coeffs |= ch_[c].transmit_coefs; | ||
| 774 | } | ||
| 775 | if (transmit_coeffs) { | ||
| 776 | transmit_num_vec_coeffs_ = b.bit(); | ||
| 777 | if (transmit_num_vec_coeffs_) { | ||
| 778 | const uint32_t num_bits = log2_floor((subframe_len + 3) / 4) + 1; | ||
| 779 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 780 | const size_t c = channel_indexes_[i]; | ||
| 781 | const size_t n = static_cast<size_t>(b.read(num_bits)) << 2; | ||
| 782 | if (n > subframe_len) return "vector coefficient count"; | ||
| 783 | ch_[c].num_vec_coeffs = n; | ||
| 784 | } | ||
| 785 | } else { | ||
| 786 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) | ||
| 787 | ch_[channel_indexes_[i]].num_vec_coeffs = subframe_len; | ||
| 788 | } | ||
| 789 | // Quantisation step (16-bit samples: 90 * 16 >> 4). | ||
| 790 | int32_t quant_step = 90; | ||
| 791 | int32_t step = b.sign_extend(6); | ||
| 792 | quant_step += step; | ||
| 793 | if (step == -32 || step == 31) { | ||
| 794 | const bool negative = step == -32; | ||
| 795 | int32_t quant = 0; | ||
| 796 | while (b.pos + 5 < b.end) { | ||
| 797 | step = static_cast<int32_t>(b.read(5)); | ||
| 798 | if (step != 31) break; | ||
| 799 | quant += 31; | ||
| 800 | } | ||
| 801 | quant_step += negative ? -(quant + step) : quant + step; | ||
| 802 | } | ||
| 803 | if (channels_for_cur_subframe_ == 1) { | ||
| 804 | ch_[channel_indexes_[0]].quant_step = quant_step; | ||
| 805 | } else { | ||
| 806 | const uint32_t modifier_len = b.read(3); | ||
| 807 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 808 | const size_t c = channel_indexes_[i]; | ||
| 809 | ch_[c].quant_step = quant_step; | ||
| 810 | if (b.bit()) | ||
| 811 | ch_[c].quant_step += modifier_len > 0 ? static_cast<int32_t>(b.read(modifier_len)) + 1 : 1; | ||
| 812 | } | ||
| 813 | } | ||
| 814 | if (const char* e = scale_factors(b)) return e; | ||
| 815 | } | ||
| 816 | |||
| 817 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 818 | const size_t c = channel_indexes_[i]; | ||
| 819 | if (ch_[c].transmit_coefs && b.pos < b.end) { | ||
| 820 | if (const char* e = coefficients(b, c)) return e; | ||
| 821 | } else { | ||
| 822 | std::fill(ch_[c].coeffs.begin(), ch_[c].coeffs.begin() + static_cast<ptrdiff_t>(subframe_len), 0.0f); | ||
| 823 | } | ||
| 824 | } | ||
| 825 | |||
| 826 | // Where this subframe's samples go in the channel output. | ||
| 827 | const size_t at = offset + kFrameSamples / 2; | ||
| 828 | if (transmit_coeffs) { | ||
| 829 | inverse_channel_transform(); | ||
| 830 | // Output in [-1, 1] for 16-bit streams. | ||
| 831 | const float scale = 2.0f / static_cast<float>(subframe_len) / 32768.0f; | ||
| 832 | const auto& sfb = sfb_offsets_[table_idx_]; | ||
| 833 | float tmp[kFrameSamples] = {}; | ||
| 834 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 835 | Channel& ch = ch_[channel_indexes_[i]]; | ||
| 836 | const auto& sf = ch.saved_scale_factors[ch.scale_factors]; | ||
| 837 | for (size_t band = 0; band < num_bands_; ++band) { | ||
| 838 | const size_t end = std::min(sfb[band + 1], subframe_len); | ||
| 839 | const int32_t exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; | ||
| 840 | const float quant = std::pow(10.0f, static_cast<float>(exp) / 20.0f); | ||
| 841 | for (size_t k = sfb[band]; k < end; ++k) tmp[k] = ch.coeffs[k] * quant; | ||
| 842 | } | ||
| 843 | imdct_half({tmp, subframe_len}, {ch.out.data() + at, subframe_len}, scale); | ||
| 844 | } | ||
| 845 | } else { | ||
| 846 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 847 | Channel& ch = ch_[channel_indexes_[i]]; | ||
| 848 | std::fill(ch.out.begin() + static_cast<ptrdiff_t>(at), | ||
| 849 | ch.out.begin() + static_cast<ptrdiff_t>(at + subframe_len), 0.0f); | ||
| 850 | } | ||
| 851 | } | ||
| 852 | |||
| 853 | // Window and overlap-add with the previous block. | ||
| 854 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 855 | Channel& ch = ch_[channel_indexes_[i]]; | ||
| 856 | size_t winlen = ch.prev_block_len; | ||
| 857 | size_t start = at - winlen / 2; | ||
| 858 | if (subframe_len < winlen) { | ||
| 859 | start += (winlen - subframe_len) / 2; | ||
| 860 | winlen = subframe_len; | ||
| 861 | } | ||
| 862 | window_overlap({ch.out.data() + start, winlen}, window_for(winlen)); | ||
| 863 | ch.prev_block_len = subframe_len; | ||
| 864 | } | ||
| 865 | |||
| 866 | for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { | ||
| 867 | Channel& ch = ch_[channel_indexes_[i]]; | ||
| 868 | if (ch.cur_subframe >= ch.num_subframes) return "subframe overrun"; | ||
| 869 | ++ch.cur_subframe; | ||
| 870 | } | ||
| 871 | if (b.overread()) return "subframe overread"; | ||
| 872 | return nullptr; | ||
| 873 | } | ||
| 874 | |||
| 875 | void Decoder::inverse_channel_transform() { | ||
| 876 | if (!transform_ || channels_for_cur_subframe_ != 2) return; | ||
| 877 | const auto& sfb = sfb_offsets_[table_idx_]; | ||
| 878 | Channel& a = ch_[0]; | ||
| 879 | Channel& b = ch_[1]; | ||
| 880 | for (size_t band = 0; band < num_bands_; ++band) { | ||
| 881 | const size_t end = std::min(sfb[band + 1], subframe_len_); | ||
| 882 | if (transform_band_[band]) { | ||
| 883 | for (size_t y = sfb[band]; y < end; ++y) { | ||
| 884 | const float l = a.coeffs[y], r = b.coeffs[y]; | ||
| 885 | a.coeffs[y] = l - r; | ||
| 886 | b.coeffs[y] = l + r; | ||
| 887 | } | ||
| 888 | } else { | ||
| 889 | for (size_t y = sfb[band]; y < end; ++y) { | ||
| 890 | a.coeffs[y] *= 181.0f / 128.0f; | ||
| 891 | b.coeffs[y] *= 181.0f / 128.0f; | ||
| 892 | } | ||
| 893 | } | ||
| 894 | } | ||
| 895 | } | ||
| 896 | |||
| 897 | } // namespace rt::xma | ||
diff --git a/runtime/src/xma_decode.h b/runtime/src/xma_decode.h deleted file mode 100644 index 6a983a562..000000000 --- a/runtime/src/xma_decode.h +++ /dev/null | |||
| @@ -1,154 +0,0 @@ | |||
| 1 | // XMA2, the console's hardware audio codec: mono or stereo WMA Pro frames of 512 samples per channel, packed into | ||
| 2 | // 2048-byte packets. | ||
| 3 | // | ||
| 4 | // Ported from VIctory (crates/victory-formats/src/xma.rs), GPL-3.0-or-later, by Marvisak and contributors (DexNom | ||
| 5 | // fork). Leonida is GPL-3.0-or-later. The DexNom snapshot in victory/ is the base; four fixes from VIctory's own | ||
| 6 | // history in this repository that the snapshot lacks are kept (ba42db643: the frame after packets a frame spans | ||
| 7 | // whole; d4d182204: a frame's bit count is clamped to its data; 03a6f2290 and 4eb0898b3: payload bytes gathered a byte | ||
| 8 | // at a time and the inverse transform's rotations built once per size, which give the same bits). | ||
| 9 | // | ||
| 10 | // A packet starts with a 32-bit header (MSB first): the number of frames that begin in it (6 bits), the number of | ||
| 11 | // bits that finish the previous frame before the first new one (15), metadata (3) and how many packets of other | ||
| 12 | // streams follow before this stream's next packet (8). Every frame starts with its length in bits (15) and ends with a | ||
| 13 | // "more frames" bit. | ||
| 14 | // | ||
| 15 | // The frame decoder follows FFmpeg's wmaprodec.c (LGPL-2.1-or-later, used under GPL-3.0-or-later) restricted to what | ||
| 16 | // XMA needs: at most two channels, four subframe sizes (512 down to 128), no LFE channel. Pure C++: no OS headers. | ||
| 17 | // wmaprodec.c's own notices, kept as the LGPL asks: Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion; | ||
| 18 | // Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson (the same lines are in third_party/xma/NOTICE.md). | ||
| 19 | #pragma once | ||
| 20 | |||
| 21 | #include <array> | ||
| 22 | #include <cstddef> | ||
| 23 | #include <cstdint> | ||
| 24 | #include <optional> | ||
| 25 | #include <span> | ||
| 26 | #include <vector> | ||
| 27 | |||
| 28 | namespace rt::xma { | ||
| 29 | |||
| 30 | inline constexpr size_t kPacketBytes = 2048; | ||
| 31 | inline constexpr size_t kPacketBits = kPacketBytes * 8; | ||
| 32 | inline constexpr size_t kHeaderBits = 32; | ||
| 33 | // Samples per channel in one frame. | ||
| 34 | inline constexpr size_t kFrameSamples = 512; | ||
| 35 | // Samples per channel in one subframe, the unit of skips and loop ends. | ||
| 36 | inline constexpr size_t kSubframeSamples = 128; | ||
| 37 | inline constexpr uint32_t kLengthBits = 15; | ||
| 38 | |||
| 39 | // A packet's header fields. | ||
| 40 | struct Packet { | ||
| 41 | uint32_t frames = 0; | ||
| 42 | uint32_t first_frame_bit = 0; | ||
| 43 | uint32_t skip = 0; | ||
| 44 | }; | ||
| 45 | |||
| 46 | // The header of packet `index` of `data`; none when the packet's header is not all inside `data`. | ||
| 47 | std::optional<Packet> packet(std::span<const uint8_t> data, size_t index); | ||
| 48 | |||
| 49 | // One frame's bits gathered out of its packets. | ||
| 50 | struct Frame { | ||
| 51 | std::vector<uint8_t> data; // the frame from its length field on, MSB first; unused bits of the last byte are 0 | ||
| 52 | size_t bits = 0; | ||
| 53 | size_t start = 0; // bit offset in the buffer where it starts | ||
| 54 | std::optional<size_t> next; // where the next frame starts; none when the buffer has no further frame | ||
| 55 | }; | ||
| 56 | |||
| 57 | // Reads the frame starting at bit `start` (a frame start inside a packet's payload) of `data`, a buffer of whole | ||
| 58 | // packets of one stream. | ||
| 59 | std::optional<Frame> read_frame(std::span<const uint8_t> data, size_t start); | ||
| 60 | |||
| 61 | namespace detail { | ||
| 62 | struct BitReader; // xma_decode.cpp | ||
| 63 | } | ||
| 64 | |||
| 65 | // Decodes the frames of one mono or stereo stream. | ||
| 66 | class Decoder { | ||
| 67 | public: | ||
| 68 | // The stream format: the channel count (clamped to 1..2) and the sample rate, which sets the scale factor band | ||
| 69 | // layout. | ||
| 70 | Decoder(size_t channels, uint32_t sample_rate); | ||
| 71 | |||
| 72 | size_t channels() const { return channels_; } | ||
| 73 | |||
| 74 | // Forgets the overlap with earlier frames (a new stream or a seek). | ||
| 75 | void reset(); | ||
| 76 | |||
| 77 | // Decodes one frame (Frame::data, Frame::bits) and appends kFrameSamples interleaved samples per channel to | ||
| 78 | // `out`, whether it decodes or not. Null on success, else what was wrong; a frame that does not decode leaves | ||
| 79 | // silence, so the stream keeps its timing. | ||
| 80 | const char* decode(std::span<const uint8_t> data, size_t bits, std::vector<int16_t>& out); | ||
| 81 | |||
| 82 | // The overlap left after the last frame, then silence: half a frame of samples per channel. | ||
| 83 | void flush(std::vector<int16_t>& out); | ||
| 84 | |||
| 85 | static constexpr size_t kMaxBands = 29; | ||
| 86 | static constexpr size_t kMaxSubframes = 32; | ||
| 87 | static constexpr size_t kBlockSizes = 3; | ||
| 88 | |||
| 89 | private: | ||
| 90 | using Bits = detail::BitReader; | ||
| 91 | |||
| 92 | struct Channel { | ||
| 93 | size_t prev_block_len = kFrameSamples; | ||
| 94 | bool transmit_coefs = false; | ||
| 95 | size_t num_subframes = 0; | ||
| 96 | std::array<size_t, kMaxSubframes> subframe_len{}; | ||
| 97 | size_t cur_subframe = 0; | ||
| 98 | size_t decoded_samples = 0; | ||
| 99 | int32_t quant_step = 0; | ||
| 100 | bool reuse_sf = false; | ||
| 101 | int32_t scale_factor_step = 1; | ||
| 102 | int32_t max_scale_factor = 0; | ||
| 103 | std::array<std::array<int32_t, kMaxBands>, 2> saved_scale_factors{}; | ||
| 104 | size_t scale_factor_idx = 0; | ||
| 105 | size_t scale_factors = 0; // which of the two saved sets is in use for this subframe | ||
| 106 | size_t table_idx = 0; | ||
| 107 | size_t num_vec_coeffs = 0; | ||
| 108 | std::array<float, kFrameSamples> coeffs{}; | ||
| 109 | // The frame's output, then half a frame of overlap for the next one. | ||
| 110 | std::array<float, kFrameSamples + kFrameSamples / 2> out{}; | ||
| 111 | }; | ||
| 112 | |||
| 113 | const char* frame(Bits& b, size_t len); | ||
| 114 | const char* subframe_length(Bits& b, size_t offset, size_t& len); | ||
| 115 | const char* tile_header(Bits& b); | ||
| 116 | const char* channel_transform(Bits& b); | ||
| 117 | const char* coefficients(Bits& b, size_t c); | ||
| 118 | const char* scale_factors(Bits& b); | ||
| 119 | const char* subframe(Bits& b); | ||
| 120 | void inverse_channel_transform(); | ||
| 121 | |||
| 122 | size_t channels_ = 1; | ||
| 123 | std::array<size_t, kBlockSizes> num_sfb_{}; | ||
| 124 | std::array<std::array<size_t, kMaxBands + 1>, kBlockSizes> sfb_offsets_{}; | ||
| 125 | std::array<std::array<std::array<size_t, kMaxBands>, kBlockSizes>, kBlockSizes> sf_offsets_{}; | ||
| 126 | std::array<Channel, 2> ch_{}; | ||
| 127 | // Per subframe. | ||
| 128 | size_t subframe_len_ = kFrameSamples; | ||
| 129 | size_t channels_for_cur_subframe_ = 0; | ||
| 130 | std::array<size_t, 2> channel_indexes_{0, 1}; | ||
| 131 | size_t num_bands_ = 0; | ||
| 132 | size_t table_idx_ = 0; | ||
| 133 | uint32_t esc_len_ = 0; | ||
| 134 | bool transmit_num_vec_coeffs_ = false; | ||
| 135 | bool transform_ = false; | ||
| 136 | std::array<bool, kMaxBands> transform_band_{}; | ||
| 137 | bool parsed_all_subframes_ = false; | ||
| 138 | }; | ||
| 139 | |||
| 140 | // Exposed for the tests. | ||
| 141 | |||
| 142 | // Half-length inverse MDCT as FFmpeg defines it (av_tx MDCT, inverse): `n` coefficients (input.size(), a power of | ||
| 143 | // two) to the middle `n` samples of the 2n-sample window, negated and scaled by `scale`. Computed as a DCT-IV through | ||
| 144 | // an n/2-point complex FFT. | ||
| 145 | void imdct_half(std::span<const float> input, std::span<float> out, float scale); | ||
| 146 | |||
| 147 | // ff_sine_windows: the rising half of a sine window of length `n`. | ||
| 148 | std::vector<float> sine_window(size_t n); | ||
| 149 | |||
| 150 | // FFmpeg's vector_fmul_window in place: the first half of `block` holds the previous block's tail, the second half the | ||
| 151 | // current block's head. | ||
| 152 | void window_overlap(std::span<float> block, std::span<const float> window); | ||
| 153 | |||
| 154 | } // namespace rt::xma | ||
diff --git a/runtime/src/xma_tables.h b/runtime/src/xma_tables.h deleted file mode 100644 index 548255da7..000000000 --- a/runtime/src/xma_tables.h +++ /dev/null | |||
| @@ -1,226 +0,0 @@ | |||
| 1 | // Huffman and level tables of the WMA Pro bitstream that XMA2 frames use. | ||
| 2 | // | ||
| 3 | // Ported from VIctory (crates/victory-formats/src/xma/tables.rs), GPL-3.0-or-later, by Marvisak and contributors | ||
| 4 | // (DexNom fork); converted mechanically, value for value. VIctory converted them from FFmpeg's | ||
| 5 | // libavcodec/wmaprodata.h (LGPL-2.1-or-later, used under GPL-3.0-or-later as that licence allows). Leonida is | ||
| 6 | // GPL-3.0-or-later. Pairs are (symbol, code length) in canonical code order. | ||
| 7 | #pragma once | ||
| 8 | |||
| 9 | #include <cstdint> | ||
| 10 | |||
| 11 | namespace rt::xma::tables { | ||
| 12 | |||
| 13 | struct SymbolLength { | ||
| 14 | uint16_t symbol; | ||
| 15 | uint8_t length; | ||
| 16 | }; | ||
| 17 | |||
| 18 | constexpr uint16_t kCriticalFreq[28] = { | ||
| 19 | 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, 4400, 5300, 6400, | ||
| 20 | 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, | ||
| 21 | }; | ||
| 22 | |||
| 23 | constexpr SymbolLength kScale[121] = { | ||
| 24 | {58, 5}, {64, 6}, {66, 7}, {65, 7}, {62, 5}, {63, 6}, {68, 9}, {69, 10}, {54, 15}, {19, 19}, {20, 19}, {21, 19}, | ||
| 25 | {22, 19}, {23, 19}, {24, 19}, {25, 19}, {26, 19}, {27, 19}, {28, 19}, {29, 19}, {30, 19}, {31, 19}, {32, 19}, | ||
| 26 | {33, 19}, {34, 19}, {17, 19}, {36, 19}, {37, 19}, {38, 19}, {39, 19}, {40, 19}, {41, 19}, {42, 19}, {43, 19}, | ||
| 27 | {44, 19}, {45, 19}, {46, 19}, {47, 19}, {48, 19}, {49, 19}, {50, 19}, {51, 19}, {52, 19}, {15, 19}, {16, 19}, | ||
| 28 | {14, 19}, {13, 19}, {12, 19}, {11, 19}, {10, 19}, {0, 19}, {9, 19}, {8, 19}, {7, 19}, {6, 19}, {5, 19}, {4, 19}, | ||
| 29 | {55, 13}, {70, 13}, {3, 19}, {2, 19}, {1, 19}, {35, 19}, {71, 19}, {72, 19}, {73, 19}, {74, 19}, {75, 19}, | ||
| 30 | {76, 19}, {77, 19}, {78, 19}, {79, 19}, {80, 19}, {81, 19}, {82, 19}, {83, 19}, {84, 19}, {85, 19}, {86, 19}, | ||
| 31 | {87, 19}, {88, 19}, {89, 19}, {90, 19}, {91, 19}, {92, 19}, {93, 19}, {94, 19}, {95, 19}, {96, 19}, {97, 19}, | ||
| 32 | {98, 19}, {99, 19}, {100, 19}, {101, 19}, {102, 19}, {103, 19}, {104, 19}, {105, 19}, {106, 19}, {107, 19}, | ||
| 33 | {108, 19}, {109, 19}, {110, 19}, {111, 19}, {112, 19}, {113, 19}, {114, 19}, {115, 19}, {116, 19}, {117, 19}, | ||
| 34 | {118, 19}, {119, 19}, {120, 19}, {18, 18}, {53, 16}, {56, 11}, {57, 8}, {67, 7}, {61, 3}, {59, 2}, {60, 1}, | ||
| 35 | }; | ||
| 36 | |||
| 37 | constexpr SymbolLength kScaleRl[120] = { | ||
| 38 | {103, 7}, {80, 11}, {60, 11}, {18, 10}, {56, 10}, {21, 12}, {90, 12}, {58, 11}, {27, 11}, {69, 12}, {84, 15}, | ||
| 39 | {48, 15}, {86, 14}, {47, 13}, {19, 10}, {32, 9}, {78, 6}, {5, 5}, {28, 4}, {53, 5}, {9, 7}, {31, 8}, {38, 8}, | ||
| 40 | {10, 7}, {88, 11}, {25, 12}, {105, 12}, {118, 11}, {23, 12}, {82, 14}, {98, 16}, {110, 16}, {108, 15}, {93, 13}, | ||
| 41 | {68, 10}, {72, 12}, {97, 12}, {81, 12}, {42, 12}, {64, 8}, {4, 4}, {1, 2}, {7, 6}, {14, 7}, {0, 9}, {55, 9}, | ||
| 42 | {61, 9}, {117, 10}, {24, 12}, {44, 12}, {67, 12}, {70, 16}, {99, 18}, {96, 21}, {95, 21}, {2, 21}, {77, 21}, | ||
| 43 | {52, 21}, {111, 21}, {102, 20}, {101, 17}, {46, 15}, {73, 15}, {109, 15}, {51, 14}, {92, 14}, {30, 7}, {11, 7}, | ||
| 44 | {66, 7}, {15, 8}, {16, 8}, {116, 9}, {65, 9}, {57, 10}, {59, 10}, {115, 9}, {12, 7}, {35, 9}, {17, 9}, {41, 9}, | ||
| 45 | {20, 11}, {91, 11}, {26, 12}, {75, 15}, {45, 15}, {107, 14}, {83, 14}, {100, 15}, {89, 15}, {43, 11}, {62, 9}, | ||
| 46 | {37, 9}, {104, 8}, {6, 5}, {39, 8}, {40, 9}, {34, 9}, {79, 7}, {8, 6}, {63, 6}, {87, 12}, {94, 14}, {49, 14}, | ||
| 47 | {50, 13}, {22, 11}, {119, 10}, {33, 9}, {36, 9}, {113, 11}, {106, 12}, {112, 13}, {71, 15}, {85, 15}, {74, 14}, | ||
| 48 | {76, 10}, {114, 7}, {29, 5}, {54, 6}, {13, 6}, {3, 2}, | ||
| 49 | }; | ||
| 50 | |||
| 51 | constexpr uint8_t kScaleRlRun[120] = { | ||
| 52 | 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, | ||
| 53 | 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, | ||
| 54 | 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
| 55 | 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, | ||
| 56 | }; | ||
| 57 | |||
| 58 | constexpr uint8_t kScaleRlLevel[120] = { | ||
| 59 | 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, | ||
| 60 | 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, | ||
| 61 | 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, | ||
| 62 | 6, 6, 6, 7, 7, 8, 8, 9, 9, | ||
| 63 | }; | ||
| 64 | |||
| 65 | constexpr uint8_t kCoef0Lens[272] = { | ||
| 66 | 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, 15, 15, 14, 12, | ||
| 67 | 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, 17, 18, 18, 15, 15, 13, 12, 14, | ||
| 68 | 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, | ||
| 69 | 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, | ||
| 70 | 15, 14, 14, 14, 13, 13, 9, 9, 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, | ||
| 71 | 9, 10, 10, 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, 10, | ||
| 72 | 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, 10, 11, 11, 13, 14, | ||
| 73 | 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, 13, 12, 13, 13, 14, 14, 13, 13, 13, | ||
| 74 | 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, | ||
| 75 | 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, 4, | ||
| 76 | }; | ||
| 77 | |||
| 78 | constexpr uint16_t kCoef0Syms[272] = { | ||
| 79 | 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, 178, 86, 140, | ||
| 80 | 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, 256, 266, 270, 262, 260, 248, | ||
| 81 | 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, | ||
| 82 | 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, | ||
| 83 | 14, 112, 263, 144, 217, 104, 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, | ||
| 84 | 193, 28, 50, 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, | ||
| 85 | 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, 113, 117, 89, 128, | ||
| 86 | 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, 15, 222, 22, 30, 83, 199, 173, 73, | ||
| 87 | 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, | ||
| 88 | 192, 23, 214, 243, 166, 200, 176, 68, 224, 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, | ||
| 89 | 99, 158, 24, 212, 8, 33, 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, | ||
| 90 | 167, 245, 229, 17, 12, 4, 152, 6, | ||
| 91 | }; | ||
| 92 | |||
| 93 | constexpr SymbolLength kCoef1[244] = { | ||
| 94 | {2, 2}, {3, 3}, {102, 3}, {4, 4}, {148, 6}, {134, 9}, {171, 10}, {18, 10}, {11, 8}, {159, 8}, {14, 9}, | ||
| 95 | {156, 14}, {235, 15}, {61, 15}, {38, 13}, {153, 13}, {48, 14}, {49, 14}, {23, 11}, {203, 13}, {208, 19}, | ||
| 96 | {204, 19}, {129, 18}, {94, 17}, {87, 16}, {62, 15}, {174, 15}, {147, 15}, {29, 12}, {191, 12}, {64, 15}, | ||
| 97 | {65, 15}, {146, 14}, {164, 13}, {142, 5}, {132, 4}, {103, 5}, {154, 7}, {165, 9}, {181, 11}, {109, 12}, | ||
| 98 | {30, 12}, {86, 16}, {92, 16}, {239, 15}, {138, 14}, {39, 13}, {50, 14}, {115, 15}, {238, 21}, {228, 21}, | ||
| 99 | {236, 21}, {222, 21}, {216, 20}, {226, 20}, {196, 18}, {192, 17}, {120, 16}, {221, 14}, {51, 14}, {24, 11}, | ||
| 100 | {143, 8}, {7, 6}, {9, 7}, {152, 10}, {136, 12}, {160, 12}, {241, 15}, {66, 15}, {168, 14}, {219, 14}, {113, 14}, | ||
| 101 | {193, 12}, {19, 10}, {173, 10}, {105, 8}, {149, 9}, {15, 9}, {205, 13}, {207, 13}, {125, 17}, {190, 17}, | ||
| 102 | {182, 16}, {68, 15}, {70, 15}, {67, 15}, {137, 13}, {31, 12}, {223, 14}, {116, 15}, {210, 19}, {220, 19}, | ||
| 103 | {198, 18}, {126, 17}, {88, 16}, {41, 13}, {25, 11}, {40, 13}, {73, 15}, {243, 15}, {53, 14}, {195, 12}, | ||
| 104 | {183, 11}, {225, 14}, {52, 14}, {71, 15}, {121, 16}, {89, 16}, {170, 14}, {55, 14}, {69, 15}, {83, 15}, | ||
| 105 | {209, 13}, {108, 11}, {32, 12}, {54, 14}, {122, 16}, {184, 16}, {176, 15}, {42, 13}, {12, 8}, {161, 8}, {6, 5}, | ||
| 106 | {167, 9}, {106, 9}, {20, 10}, {145, 12}, {111, 13}, {43, 13}, {26, 11}, {175, 10}, {107, 10}, {34, 12}, | ||
| 107 | {33, 12}, {197, 12}, {74, 15}, {128, 17}, {232, 20}, {212, 20}, {224, 19}, {202, 18}, {90, 16}, {57, 14}, | ||
| 108 | {227, 14}, {97, 16}, {93, 16}, {140, 15}, {185, 11}, {27, 11}, {16, 9}, {158, 11}, {211, 13}, {56, 14}, | ||
| 109 | {117, 15}, {72, 15}, {166, 13}, {91, 16}, {95, 16}, {80, 15}, {101, 16}, {194, 17}, {127, 17}, {82, 15}, | ||
| 110 | {21, 10}, {144, 10}, {177, 10}, {151, 6}, {10, 7}, {157, 7}, {8, 6}, {5, 4}, {13, 8}, {0, 9}, {213, 13}, | ||
| 111 | {46, 13}, {199, 12}, {35, 12}, {162, 12}, {135, 10}, {169, 9}, {45, 13}, {59, 14}, {114, 14}, {44, 13}, | ||
| 112 | {188, 16}, {186, 16}, {75, 15}, {79, 15}, {118, 15}, {187, 11}, {112, 13}, {139, 14}, {178, 15}, {81, 15}, | ||
| 113 | {110, 12}, {28, 11}, {163, 8}, {133, 6}, {104, 6}, {17, 9}, {22, 10}, {229, 14}, {172, 14}, {217, 13}, | ||
| 114 | {201, 12}, {36, 12}, {218, 20}, {242, 22}, {240, 22}, {234, 21}, {230, 19}, {206, 18}, {200, 18}, {214, 18}, | ||
| 115 | {130, 17}, {131, 17}, {141, 15}, {84, 15}, {76, 15}, {215, 13}, {58, 14}, {231, 14}, {233, 14}, {180, 15}, | ||
| 116 | {77, 15}, {37, 12}, {189, 11}, {179, 10}, {155, 10}, {47, 13}, {96, 16}, {99, 16}, {119, 15}, {63, 14}, | ||
| 117 | {237, 14}, {78, 15}, {85, 15}, {60, 14}, {98, 16}, {100, 16}, {124, 16}, {123, 16}, {150, 11}, {1, 7}, | ||
| 118 | }; | ||
| 119 | |||
| 120 | constexpr uint16_t kCoef0Run[272] = { | ||
| 121 | 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, | ||
| 122 | 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, | ||
| 123 | 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, | ||
| 124 | 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, | ||
| 125 | 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, | ||
| 126 | 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, | ||
| 127 | 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, | ||
| 128 | 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, | ||
| 129 | 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, | ||
| 130 | 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, | ||
| 131 | }; | ||
| 132 | |||
| 133 | constexpr float kCoef0Level[272] = { | ||
| 134 | 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 135 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 136 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 137 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 138 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 139 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 140 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 141 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 142 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, | ||
| 143 | 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, | ||
| 144 | 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, | ||
| 145 | 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, 4.0f, 4.0f, | ||
| 146 | 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, | ||
| 147 | 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, | ||
| 148 | 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, | ||
| 149 | 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, | ||
| 150 | }; | ||
| 151 | |||
| 152 | constexpr uint16_t kCoef1Run[244] = { | ||
| 153 | 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, | ||
| 154 | 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, | ||
| 155 | 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, | ||
| 156 | 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, | ||
| 157 | 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, | ||
| 158 | 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, | ||
| 159 | 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, | ||
| 160 | 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, | ||
| 161 | }; | ||
| 162 | |||
| 163 | constexpr float kCoef1Level[244] = { | ||
| 164 | 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 165 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 166 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 167 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 168 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, | ||
| 169 | 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, | ||
| 170 | 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, | ||
| 171 | 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, | ||
| 172 | 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 6.0f, 7.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, 9.0f, 10.0f, | ||
| 173 | 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, 17.0f, 18.0f, | ||
| 174 | 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, 25.0f, 26.0f, | ||
| 175 | 26.0f, 27.0f, 27.0f, 28.0f, 28.0f, 29.0f, 29.0f, 30.0f, 30.0f, 31.0f, 31.0f, 32.0f, 32.0f, 33.0f, 33.0f, 34.0f, | ||
| 176 | 34.0f, 35.0f, 35.0f, 36.0f, 36.0f, 37.0f, 37.0f, 38.0f, 38.0f, 39.0f, 39.0f, 40.0f, 40.0f, 41.0f, 41.0f, 42.0f, | ||
| 177 | 42.0f, 43.0f, 43.0f, 44.0f, 44.0f, 45.0f, 45.0f, 46.0f, 46.0f, 47.0f, 47.0f, 48.0f, 48.0f, 49.0f, 49.0f, 50.0f, | ||
| 178 | 51.0f, 52.0f, | ||
| 179 | }; | ||
| 180 | |||
| 181 | constexpr uint8_t kVec4Lens[127] = { | ||
| 182 | 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 12, 12, | ||
| 183 | 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, 11, 10, 11, 11, 10, 10, 11, 11, 9, | ||
| 184 | 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, | ||
| 185 | 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, | ||
| 186 | }; | ||
| 187 | |||
| 188 | constexpr uint16_t kVec4Syms[127] = { | ||
| 189 | 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, 8961, 321, 1041, | ||
| 190 | 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, 81, 6, 801, 8196, 8481, 8449, | ||
| 191 | 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, | ||
| 192 | 516, 21, 12546, 8466, 4353, 4371, 4626, 257, 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, | ||
| 193 | 785, 4116, 8209, 4099, 273, 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, | ||
| 194 | 4356, 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, 4866, 8721, | ||
| 195 | 291, 8450, 8465, 4115, | ||
| 196 | }; | ||
| 197 | |||
| 198 | constexpr SymbolLength kVec2[137] = { | ||
| 199 | {19, 5}, {165, 10}, {211, 11}, {46, 11}, {75, 10}, {177, 11}, {12, 11}, {86, 8}, {83, 7}, {38, 7}, {133, 9}, | ||
| 200 | {178, 10}, {28, 10}, {104, 9}, {73, 9}, {35, 5}, {52, 6}, {113, 9}, {8, 9}, {101, 8}, {69, 7}, {0, 3}, {71, 8}, | ||
| 201 | {119, 9}, {91, 10}, {179, 10}, {114, 8}, {166, 10}, {10, 10}, {44, 10}, {145, 10}, {66, 6}, {21, 6}, {24, 8}, | ||
| 202 | {146, 9}, {26, 9}, {65, 7}, {5, 7}, {226, 11}, {225, 12}, {15, 12}, {180, 10}, {147, 9}, {115, 8}, {40, 8}, | ||
| 203 | {89, 9}, {134, 9}, {84, 7}, {54, 7}, {42, 9}, {60, 10}, {31, 11}, {193, 11}, {181, 10}, {76, 10}, {148, 9}, | ||
| 204 | {37, 6}, {67, 6}, {33, 6}, {3, 6}, {17, 6}, {2, 6}, {102, 8}, {87, 8}, {116, 8}, {56, 8}, {50, 5}, {20, 5}, | ||
| 205 | {120, 9}, {58, 9}, {29, 10}, {194, 10}, {135, 9}, {97, 8}, {7, 8}, {105, 9}, {13, 11}, {241, 12}, {16, 12}, | ||
| 206 | {45, 10}, {149, 9}, {74, 9}, {98, 7}, {23, 7}, {85, 7}, {70, 7}, {195, 10}, {161, 10}, {129, 9}, {72, 8}, | ||
| 207 | {51, 5}, {36, 5}, {117, 8}, {61, 10}, {11, 10}, {162, 9}, {1, 7}, {4, 6}, {49, 6}, {68, 6}, {9, 9}, {27, 9}, | ||
| 208 | {130, 8}, {39, 7}, {53, 6}, {99, 7}, {25, 8}, {150, 9}, {90, 9}, {103, 8}, {163, 9}, {196, 10}, {210, 10}, | ||
| 209 | {136, 9}, {121, 9}, {41, 8}, {131, 8}, {43, 9}, {164, 9}, {118, 8}, {88, 8}, {81, 7}, {6, 7}, {55, 7}, {59, 9}, | ||
| 210 | {30, 10}, {209, 11}, {14, 11}, {151, 9}, {106, 9}, {82, 6}, {22, 6}, {100, 7}, {132, 8}, {57, 8}, {18, 4}, | ||
| 211 | {34, 4}, | ||
| 212 | }; | ||
| 213 | |||
| 214 | constexpr SymbolLength kVec1[101] = { | ||
| 215 | {7, 5}, {32, 8}, {59, 10}, {60, 10}, {83, 11}, {82, 11}, {62, 10}, {33, 8}, {45, 9}, {61, 10}, {84, 11}, | ||
| 216 | {85, 11}, {1, 6}, {13, 5}, {19, 6}, {25, 7}, {34, 8}, {46, 9}, {47, 9}, {14, 5}, {6, 5}, {64, 10}, {87, 11}, | ||
| 217 | {86, 11}, {63, 10}, {88, 11}, {90, 11}, {35, 8}, {26, 7}, {0, 7}, {48, 9}, {65, 10}, {66, 10}, {36, 8}, {15, 5}, | ||
| 218 | {20, 6}, {91, 11}, {89, 11}, {67, 10}, {49, 9}, {50, 9}, {69, 10}, {92, 11}, {93, 11}, {27, 7}, {5, 5}, {37, 8}, | ||
| 219 | {68, 10}, {71, 10}, {51, 9}, {52, 9}, {70, 10}, {94, 11}, {96, 11}, {38, 8}, {21, 6}, {16, 5}, {4, 5}, {28, 7}, | ||
| 220 | {53, 9}, {95, 11}, {97, 11}, {73, 10}, {39, 8}, {29, 7}, {72, 10}, {98, 11}, {99, 11}, {54, 9}, {40, 8}, | ||
| 221 | {22, 6}, {30, 7}, {55, 9}, {74, 10}, {76, 10}, {56, 9}, {75, 10}, {77, 10}, {17, 5}, {3, 5}, {23, 6}, {41, 8}, | ||
| 222 | {57, 9}, {78, 10}, {79, 10}, {31, 7}, {10, 4}, {9, 4}, {100, 5}, {2, 5}, {11, 4}, {8, 4}, {18, 5}, {42, 8}, | ||
| 223 | {58, 9}, {80, 10}, {81, 10}, {43, 8}, {44, 8}, {24, 6}, {12, 4}, | ||
| 224 | }; | ||
| 225 | |||
| 226 | } // namespace rt::xma::tables | ||