Triforce v0.8.5

A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-28 10:54:41 -06:00
parent 2df08c751e
commit b527e29adb
203 changed files with 18821 additions and 2051 deletions

View File

@@ -49,8 +49,8 @@ void hos_log(const char *fmt, ...);
int rx_option(int id, int otherwise);
const char *hos_version(void); /* hos_main.c */
/* (hos_main.c, read on the game's thread while hos_oot_discord_watch is 1: the map Link was last seen in, its state, his stats) */
int hos_oot_current_map(char *out, size_t cap);
int hos_oot_state(int *event, int *loading, int *child);
int hos_oot_discord_map(char *out, size_t cap); /* ((Triforce, 11-27) host/hos_main.c: the copy kept for Discord */
int hos_oot_discord_state(int *event, int *loading, int *child);
int hos_oot_stats(int *life, int *max_life, int *rupees, int *tokens, int *pieces); /* (-1 each when not known) */
int64_t hos_oot_player_seen_ns(void); /* (when Link's update last ran, 0 never) */
void hos_oot_discord_watch(int on);
@@ -244,9 +244,9 @@ static void activity_now(unsigned nonce, long long started, char *json, size_t c
char version[64], build[64], commit[64], release[64], map[96] = "", area[128] = "";
discord_version_parts(hos_version(), version, build, commit, release, sizeof version);
const int game = discord_settings_use_game(&settings);
const int known = game && hos_oot_current_map(map, sizeof map);
const int known = game && hos_oot_discord_map(map, sizeof map);
int event = 0, loading = 0, child = 1;
const int have_age = game && hos_oot_state(&event, &loading, &child);
const int have_age = game && hos_oot_discord_state(&event, &loading, &child);
if (known) hos_oot_area_name(map, area, sizeof area);
/* (not in a map, the title: no location, age or map, so the template's {location|...} part is left out) */
const int in_map = discord_in_map(known, hos_oot_player_seen_ns(), hos_now_ns());

View File

@@ -362,6 +362,7 @@ int hos_mouse_game_pointer(int *x, int *y, int *w, int *h, uint32_t *pressed, in
return shown ? 1 : 2;
}
int hos_oot_options_front(void); /* (host/oot_menu.c) */
int hos_oot_title_tabs(void);
static void game_menu_press(LPARAM lp, LONG bit) {
ptr_x = (short)LOWORD(lp), ptr_y = (short)HIWORD(lp), ptr_in = 1;
gm_mouse_used();
@@ -369,6 +370,9 @@ static void game_menu_press(LPARAM lp, LONG bit) {
/* ((Triforce) the game's Options screen: the options' tabs over its header (gpu/vk/vk_menu.cpp draw_game_tab) take their
clicks through hos_mouse_pointer as the open menu does; host/oot_menu.c leaves the header to them, the rest is the game's) */
if (bit == HOS_MOUSE_LEFT && hos_oot_options_front()) InterlockedOr(&ptr_pressed, bit);
/* ((Triforce) and on the title, whose Mods and Save Select tabs at the top left are the renderer's own (draw_title_tabs):
it looks at each click there, and takes the one on a tab; host/oot_menu.c has no button under those) */
else if (bit == HOS_MOUSE_LEFT && hos_oot_title_tabs()) InterlockedOr(&ptr_pressed, bit);
}
static void menu_press(HWND w, LPARAM lp, LONG bit) { /* (a click while the menu is open: the menu's) */
ptr_x = (short)LOWORD(lp), ptr_y = (short)HIWORD(lp), ptr_in = 1;

View File

@@ -14,6 +14,10 @@
host/hos_main.c and their names; HOS_BENCH_SECONDS each, default 15) a teleport, its arrival (the map loaded and no event
playing), 1.5 s settling (not counted), then every present's interval is measured while the camera turns steadily
(the right stick at 35%, Link standing). The next teleport follows the moment a scene ends.
((Triforce) 11-26) HOS_BENCH_PAN=<percent>: the right stick's push instead of 35 (0: the camera holds still, so an in-run
A/B, RX_VK_LAB_AB, compares its phases on one view per scene instead of on views the turn changed; a phase that holds a
teleport still spans two scenes; measurement only). Unset: 35. When it is set, the push in force is logged once (a value
that is not a percent from 0 to 100 too) and written to the results as "pan".
3. The results (version 1): average fps, 1% and 0.1% lows (nearest rank, as gpu/vk/perf_stats.h), frames, seconds and the
frame times in ~120 points per scene, the GPU and the options that shape the frame rate, written atomically (.new, then
renamed); then the game quits as its window's close does (host/hos_relaunch.c: a save being committed finished, the
@@ -110,6 +114,8 @@ static struct {
the scene's half being measured (0, 1), the way it holds (0 off, 1 on), and the halves measured so far */
int helpers, helper_threads, half, way, way_set;
Half halves[2];
int pan; /* (the right stick's push: PAN, or HOS_BENCH_PAN's) */
int pan_set, pan_rejected; /* ((Triforce) 11-26) HOS_BENCH_PAN set (not empty), and its value not a percent from 0 to 100 */
} B = {SRWLOCK_INIT};
int hos_bench_on(void) { return B.on; }
@@ -143,6 +149,21 @@ static void parse_scenes(const char *s) {
}
}
/* ((Triforce) 11-26) HOS_BENCH_PAN: the stick's push in percent, 0 to 100 (the leading number: 35% is 35), rounded up as PAN
is, so 35 gives PAN; unset or empty: PAN (35%); not a number (nan too) or outside 0-100: PAN, with *rejected set. The range
test is written so that a NaN, which every comparison fails, is rejected too: converting it to int is undefined */
static int bench_pan(const char *e, int *rejected) {
*rejected = 0;
if (!e || !*e) return PAN;
char *end;
const double v = strtod(e, &end);
if (end == e || !(v >= 0 && v <= 100)) {
*rejected = 1;
return PAN;
}
return (int)ceil(v * 32767.0 / 100.0);
}
void hos_bench_init(void) {
const char *p = getenv("HOS_BENCHMARK");
if (!p || !*p) return;
@@ -155,6 +176,9 @@ void hos_bench_init(void) {
B.slot = B.newest = -1;
const char *helpers = getenv("HOS_BENCH_HELPERS");
B.helpers = helpers && atoi(helpers) != 0;
const char *pan = getenv("HOS_BENCH_PAN");
B.pan = bench_pan(pan, &B.pan_rejected);
B.pan_set = pan && *pan;
B.helper_threads = -1;
B.t_start = hos_now_ns();
B.phase = MKWVK_BENCH_BOOT;
@@ -421,6 +445,7 @@ static void write_results(int stopped) { /* (under the lock; once) */
for (int i = 0; i < B.nskipped; i++) fprintf(f, "%s", i ? "," : ""), json_text(f, B.scenes[B.skipped[i]].name);
fprintf(f, "]");
if (B.helpers) fprintf(f, ",\"helper_test\":{\"threads\":%d}", B.helper_threads > 0 ? B.helper_threads : 0);
if (B.pan_set) fprintf(f, ",\"pan\":%.2f", B.pan * 100.0 / 32767.0); /* ((Triforce) 11-26) HOS_BENCH_PAN's push, percent */
fprintf(f, ",\"settings\":");
json_settings(f);
fprintf(f, "}\n");
@@ -615,6 +640,15 @@ void hos_bench_present(int64_t now) {
if (!told) {
told = 1;
hos_log("benchmark: on: %d scenes of %.1f s, results to %s", B.nscenes, B.seconds, B.path);
if (B.pan_set) { /* ((Triforce) 11-26) the camera turn in force, once; unset logs nothing, as before */
const char *pan = getenv("HOS_BENCH_PAN");
if (B.pan_rejected)
hos_log("benchmark: HOS_BENCH_PAN=%.40s is not a percent from 0 to 100: the right stick at 35%%, as unset",
pan ? pan : "");
else
hos_log("benchmark: HOS_BENCH_PAN=%.40s: the right stick at %.2f%% (%d of 32767)", pan ? pan : "",
B.pan * 100.0 / 32767.0, B.pan);
}
}
switch (B.phase) {
case MKWVK_BENCH_BOOT: {
@@ -631,7 +665,7 @@ void hos_bench_present(int64_t now) {
}
break;
case MKWVK_BENCH_SETTLE:
hos_hid_stick(0, 0, PAN, 0, 250);
hos_hid_stick(0, 0, B.pan, 0, 250);
if (B.helpers && B.helper_threads < 0) { /* ((Triforce) 11-22) the helper-thread test: what it can use, asked once */
B.helper_threads = rx_option(HOS_OPT_HELPERS_FORCE, 0);
if (helper_test())
@@ -650,7 +684,7 @@ void hos_bench_present(int64_t now) {
}
break;
case MKWVK_BENCH_MEASURE:
hos_hid_stick(0, 0, PAN, 0, 250);
hos_hid_stick(0, 0, B.pan, 0, 250);
if (B.measure_t0 != now && d > 0) {
if (B.n == B.cap) {
const int cap = B.cap ? B.cap * 2 : 16384;

View File

@@ -780,6 +780,24 @@ int hos_oot_stats(int *life, int *max_life, int *rupees, int *tokens, int *piece
oot_discord_unlock();
return have;
}
/* ((Triforce, 11-27, a player's report: the status said only "Playing Triforce" with the time) The map and the state for the
Discord status, from the copy kept for it here. discord_rpc.c read hos_oot_current_map/hos_oot_state, the control bridge's
copy, which only HOS_CONTROL fills: the place, the age and the stats never showed for any player */
int hos_oot_discord_map(char *out, size_t cap) {
oot_discord_lock();
const int have = oot_discord_map[0] != 0;
if (have) snprintf(out, cap, "%s", oot_discord_map);
oot_discord_unlock();
return have;
}
int hos_oot_discord_state(int *event, int *loading, int *child) {
oot_discord_lock();
const int f = oot_discord_flags;
oot_discord_unlock();
if (f < 0) return 0;
*event = f & 1, *loading = (f >> 1) & 1, *child = (f >> 2) & 1;
return 1;
}
#if defined(_WIN32) || defined(__linux__) /* (the debug tools: host/posix has what they call) */
/* QueryGetPouchContentNumByActorName (f_82a3c260): f_805b63e0(pouch manager, &name, 0, 0) counts one content. */
@@ -3070,6 +3088,85 @@ static DWORD WINAPI game_thread(void *p) {
hos_crash_clean_end(); /* ((Triforce) ExitProcess is quick_exit here, which runs no atexit: host/hos_crash_record.c */
ExitProcess(result);
}
/* ((Triforce, 11-27) A PC whose NVIDIA shader cache did not keep the game's (triforce_nvidia_cache.own beside the game, left
by the renderer's library check: gpu/vk/vk_draw.cpp nv_own_folder_mark_path): the driver's cache in a folder of the game's
own, triforce_nvidia_cache, with 10 GB of room, set here before anything loads the driver. v0.8.4 set it in the renderer's
create_instance, which Windows' driver still honoured but Linux's did not: SDL had loaded it with the window, and a
player's RTX 5090 (Arch) rebuilt every shader at every start, the folder empty and ~/.cache/nvidia growing instead. A path
the player set wins; the size too. Nothing is done without the marker */
#ifndef _WIN32
#include <dirent.h>
/* the files under dir, summed into *total (bytes); with drop, removed instead. Two levels of folders, as NVIDIA's are */
static void nv_cache_sum(const char *dir, unsigned long long *total, int drop) {
DIR *d = opendir(dir);
if (!d) return;
struct dirent *e;
char p[4096];
while ((e = readdir(d))) {
if (e->d_name[0] == '.') continue;
snprintf(p, sizeof p, "%s/%s", dir, e->d_name);
struct stat st;
if (lstat(p, &st)) continue;
if (S_ISDIR(st.st_mode)) {
nv_cache_sum(p, total, drop);
if (drop) rmdir(p);
} else if (S_ISREG(st.st_mode)) {
if (drop) remove(p);
else *total += (unsigned long long)st.st_size;
}
}
closedir(d);
}
#endif
static void nv_own_cache_folder(void) {
char mark[MAX_PATH], dir[MAX_PATH + 32];
const DWORD len = hos_game_path_a(mark, MAX_PATH);
char *slash = len ? strrchr(mark, '\\') : NULL;
if (!slash && len) slash = strrchr(mark, '/');
if (!slash) return;
const size_t at = (size_t)(slash + 1 - mark);
memcpy(dir, mark, at);
dir[at] = 0;
snprintf(slash + 1, (size_t)(MAX_PATH - at), "triforce_nvidia_cache.own");
FILE *f = fopen(mark, "rb");
const char *own = getenv("HOS_NV_OWN_CACHE");
#ifdef _WIN32
if (!f) return;
#else
/* ((Triforce, 11-27) On Linux for every PC, marker or not: a second player's RTX 3070 (v0.8.3, a start whose check found
the caches warm) still had 52 recorded pipelines compiled in play, 40 ms to 2.3 s each, the shared ~/.cache/nvidia
having lost them. The variables touch NVIDIA's driver alone (Mesa reads its own). HOS_NV_OWN_CACHE=0: the shared
folder, as before; on Windows the marker alone decides, as there the driver keeps what it is given unless its
control-panel size is too small */
if (!f && own && !strcmp(own, "0")) return;
#endif
if (f) fclose(f);
if (own && !strcmp(own, "0")) return;
if (getenv("__GL_SHADER_DISK_CACHE_PATH")) return;
snprintf(dir + at, sizeof dir - at, "triforce_nvidia_cache");
#ifdef _WIN32
CreateDirectoryA(dir, NULL);
_putenv_s("__GL_SHADER_DISK_CACHE_PATH", dir);
SetEnvironmentVariableA("__GL_SHADER_DISK_CACHE_PATH", dir);
if (!getenv("__GL_SHADER_DISK_CACHE_SIZE")) {
_putenv_s("__GL_SHADER_DISK_CACHE_SIZE", "10737418240");
SetEnvironmentVariableA("__GL_SHADER_DISK_CACHE_SIZE", "10737418240");
}
#else
mkdir(dir, 0700);
setenv("__GL_SHADER_DISK_CACHE_PATH", dir, 0);
setenv("__GL_SHADER_DISK_CACHE_SIZE", "10737418240", 0);
/* ((Triforce, 11-27) and NVIDIA's cleanup pass left out in this folder alone: the same player's shared cache lost its
entries between starts with 10 GiB of room (1.7 GB -> 405 MB -> 170 MB). The folder holds the game's shaders only;
its size is kept here instead: past 12 GB (stale updates' shaders) it is emptied, and the next start makes them again */
setenv("__GL_SHADER_DISK_CACHE_SKIP_CLEANUP", "1", 0);
{
unsigned long long total = 0;
nv_cache_sum(dir, &total, 0);
if (total > 12ull << 30) nv_cache_sum(dir, &total, 1);
}
#endif
}
int main(int argc, char **argv) {
{ /* ((Triforce) the crash window's helper of a run (host/hos_crash_dialog.c): first, so it starts nothing of the game */
int hos_crash_helper_main(int argc, char **argv);
@@ -3079,6 +3176,7 @@ int main(int argc, char **argv) {
int hos_display_init(void);
void hos_display_loop(void);
load_hookshot_env();
nv_own_cache_folder(); /* ((Triforce, 11-27) before the driver loads: see above (and before driver_cache_folder makes it) */
#ifdef __linux__
driver_env_choose(); /* ((Triforce) after the env file, which may set HOS_HALF_RATE_SHADING; before Vulkan, the builder's run too) */
driver_cache_room(); /* ((Triforce, 11-22) the performance audit's PIPE-97: 10 GiB for the driver's shader cache, likewise */

View File

@@ -124,5 +124,21 @@ void hos_window_closed_exit(void) {
{ void rx_option_set(int id, int value); rx_option_set(HOS_OPT_EXITING, 1); }
{ void hos_crash_clean_end(void); hos_crash_clean_end(); } /* ((Triforce) a clean end: host/hos_crash_record.c */
if (again) relaunch();
/* ((Triforce, 11-27) a file the renderer was still writing when its wait ended (vk_replay.cpp's HOS_OPT_EXITING: the
pipeline cache's save, 2 GB, inside the driver's vkGetPipelineCacheData) is cut here: ExitProcess stops that thread
wherever it is, holding the driver's own lock, and then runs every library's unloading, where the driver waits for that
lock forever. A player's RX 6800 XT hung at every close after "1 still under way: cut" and had to be ended in Task
Manager. The game's own ends are all done above and the log written: the process ends as Task Manager ends it, without
the unloading (as hos_fatal's end, host/hos_thread.c). Nothing cut: ExitProcess as before */
{
int rx_option(int id, int otherwise);
if (rx_option(HOS_OPT_EXITING, 0) > 0) {
hos_log("display: a file was still being written at the exit (the pipeline cache's save): the game ends without "
"the libraries' unloading, which waited for it forever");
hos_log_flush();
fflush(NULL);
TerminateProcess(GetCurrentProcess(), 0);
}
}
ExitProcess(0);
}

View File

@@ -1800,6 +1800,11 @@ static struct {
sleep (NX2navi's "core grant to run", runtime/kernel.c grant_at) */
int64_t spun, slept, spin_ns, spin_capped, run_spin_ns, run_spin_n, run_sleep_ns, run_sleep_n, run_max_ns;
int64_t pin_waits; /* ((Triforce, 11-23) waits past esc_eq kept to their one core behind a better holder: vc_acquire */
/* (Triforce, the AMD limits work) who the longest wait was: the waiter and the holders of the cores it may use, read a
millisecond into the wait (vc_acquire). The 5 s line says how long the longest wait was, not whose: the title screen's
hitches (frames of 50-250 ms "outside the replay and the present" while the movie plays) had waits of 70-190 ms with
no name on them */
char max_who[224];
} vc_st;
/* ((Triforce, 11-22, the performance audit's OS-51) the waits since the last present, beside vc_st's 5 s: their time summed
over the threads, how many, the longest. Added to with vc_lock held, taken by the present's look without it
@@ -1899,6 +1904,8 @@ static void vc_stats_locked(int64_t now) {
if (vc_st.pin_waits) /* ((Triforce, 11-23) vc_acquire: the escapes the one-core rule held back) */
hos_log("vcores: %lld waits held to their one core past the escape, behind a holder of better priority there "
"(HOS_VCORE_PIN_ESCAPE_MS=0: they escape at HOS_VCORE_ESCAPE_EQ_US, as before)", (long long)vc_st.pin_waits);
if (vc_st.max_ns >= 20000000 && vc_st.max_who[0]) /* (20 ms: more than a frame at 60 fps) */
hos_log("vcores: the longest wait, %.1f ms: %s", vc_st.max_ns / 1e6, vc_st.max_who);
memset(&vc_st, 0, sizeof vc_st);
vc_st.since = now;
}
@@ -1988,6 +1995,7 @@ static void vc_acquire(HosThread *t) {
vc_st.waits++;
int spun = 0, slept = 0, ended = 0; /* ((Triforce) the spin tried, a sleep taken, the wait ended in the spin) */
int pin_noted = 0; /* ((Triforce, 11-23) this wait counted in vc_st.pin_waits */
char holders[160] = ""; /* ((Triforce) the holders of t's cores, a millisecond into the wait) */
for (;;) {
/* the worst holder worse than t on a core t may use gives it up at its next checkpoint; after
HOS_VCORE_SLICE_US (2000) of waiting, a holder as good as t does too (a time slice: Horizon would leave
@@ -2039,6 +2047,13 @@ static void vc_acquire(HosThread *t) {
vc_take(t, c);
break;
}
if (!holders[0]) {
int len = 0;
for (int k = 0; k < vc_cores() && len < 120; k++)
if ((m >> k & 1) && vc_owner[k])
len += snprintf(holders + len, sizeof holders - len, " core %d: %s (%d)%s;", k, vc_owner[k]->name,
vc_owner[k]->priority, vc_owner[k]->vc_kick ? " asked" : "");
}
const int64_t waited = hos_now_ns() - t0;
/* ((Triforce, 11-23) A waiter held to one core, behind a holder of better priority there, does not escape at
esc_eq: Horizon never runs it then, and the game pins threads to another's core so the two never overlap.
@@ -2079,7 +2094,11 @@ static void vc_acquire(HosThread *t) {
const int64_t now = hos_now_ns(), waited = now - t0;
HOS_CHAIN(HOS_CHAIN_WOKE, vc_chain_key(t));
vc_st.wait_ns += waited;
if (waited > vc_st.max_ns) vc_st.max_ns = waited;
if (waited > vc_st.max_ns) {
vc_st.max_ns = waited;
if (holders[0]) snprintf(vc_st.max_who, sizeof vc_st.max_who, "%s (priority %d) waited for%s", t->name, t->priority, holders);
else vc_st.max_who[0] = 0;
}
__atomic_add_fetch(&vc_gap.ns, waited, __ATOMIC_RELAXED), __atomic_add_fetch(&vc_gap.n, 1, __ATOMIC_RELAXED); /* ((Triforce, OS-51)) */
if (waited > __atomic_load_n(&vc_gap.longest, __ATOMIC_RELAXED)) __atomic_store_n(&vc_gap.longest, waited, __ATOMIC_RELAXED);
if (ended) vc_st.spun++; /* ((Triforce) every wait ends in the spin or after a sleep) */

View File

@@ -25,11 +25,16 @@
the mix moved the new sound on by a block it never played (or ended one shorter than a block unheard). Here both
run on the sound thread, one after the other.
((Triforce, 11-25) Whose sound: the settings' tabs, the Mods screen and the step back to the pause menu's System list
have a sound each for moving, choosing and going back (HOS_MENU_SOUND_SETTINGS_NAVIGATE and the six after it), the
system menu's files unless the environment names another (roles, roles_from_env).)
The level: the Audio tab's Menu sounds row (menu_sounds= in triforce_options.ini, 0 to 100, 80 unless set; 0
silent), read at each block, and the Master volume over it as over the game's own sound (the sounds are added before
render_frame applies it). They are added after the game's limiter, and the block is clipped as it is made 16-bit. */
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -64,7 +69,7 @@ typedef struct {
uint32_t frames;
} Sound;
static const char *const files[SOUNDS] = {
static const char *files[SOUNDS] = { /* (a role's is another's when the environment says so: roles_from_env) */
[HOS_MENU_SOUND_OPEN] = "Sound/Resource/Stream/SE_Sys_PlusMenu_Open00.bwav",
[HOS_MENU_SOUND_CLOSE] = "Sound/Resource/Stream/SE_Sys_PlusMenu_Close00.bwav",
[HOS_MENU_SOUND_CURSOR] = "Sound/Resource/Stream/SE_Sys_Cursor00.bwav",
@@ -79,8 +84,75 @@ static const char *const files[SOUNDS] = {
file opens: the title's cursor, its Continue and the Load list's choice) */
[HOS_MENU_SOUND_SYS_CURSOR] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cursor00.bwav",
[HOS_MENU_SOUND_SYS_DECIDE] = "Sound/Resource/Stream/SE_Sys_SysMenu_DecideL00.bwav",
/* ((Triforce, 11-25) the owner: "The SFX are incorrect. They should be using the title screen's SFX instead of the
in-game Menu SFX." The settings' tabs, the Mods screen and the step back to the pause menu's System list, a sound
each: the system menu's cursor, its decide and its cancel (Cansel: the file's own spelling), as the owner chose them
from the game's own (the settings' Select the large decide, the title's Continue's; the Mods screen's the small
one). The in-game menu's three above, the cursor's, decide's and cancel's, are what these were until then) */
[HOS_MENU_SOUND_SETTINGS_NAVIGATE] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cursor00.bwav",
[HOS_MENU_SOUND_SETTINGS_SELECT] = "Sound/Resource/Stream/SE_Sys_SysMenu_DecideL00.bwav",
[HOS_MENU_SOUND_SETTINGS_BACK] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cansel00.bwav",
[HOS_MENU_SOUND_MODS_NAVIGATE] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cursor00.bwav",
[HOS_MENU_SOUND_MODS_SELECT] = "Sound/Resource/Stream/SE_Sys_SysMenu_DecideS00.bwav",
[HOS_MENU_SOUND_MODS_BACK] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cansel00.bwav",
[HOS_MENU_SOUND_PAUSE_BACK] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cansel00.bwav",
/* ((Triforce, 11-25) a toggle of the settings' tabs switched On, and Off (the owner, in the lab: 'In the display, the
on and off SFX are incorrect ... let me pick the correct SFX for the on and off selection for the settings'): as the
owner chose them, On the system menu's small decide, Off its cancel */
[HOS_MENU_SOUND_SETTINGS_ON] = "Sound/Resource/Stream/SE_Sys_SysMenu_DecideS00.bwav",
[HOS_MENU_SOUND_SETTINGS_OFF] = "Sound/Resource/Stream/SE_Sys_SysMenu_Cansel00.bwav",
};
/* ((Triforce, 11-25) the seven roles above, each with the variable of the environment that names another sound for it, so
that one can be tried without a build: HOS_MENU_SOUND_SETTINGS_NAVIGATE=SE_Sys_Cursor00, in the environment or in
triforce_env.txt (host/hos_main.c env_line_allowed takes these names and a sound's bare name). The value is a file's
name in Sound/Resource/Stream without its .bwav: letters, digits and _, 64 at most, so it names nothing outside that
folder; any other value is left out with a line in the log. Read once, when the files are (load_all) */
static const struct { int id; const char *env; } roles[] = {
{HOS_MENU_SOUND_SETTINGS_NAVIGATE, "HOS_MENU_SOUND_SETTINGS_NAVIGATE"},
{HOS_MENU_SOUND_SETTINGS_SELECT, "HOS_MENU_SOUND_SETTINGS_SELECT"},
{HOS_MENU_SOUND_SETTINGS_BACK, "HOS_MENU_SOUND_SETTINGS_BACK"},
{HOS_MENU_SOUND_MODS_NAVIGATE, "HOS_MENU_SOUND_MODS_NAVIGATE"},
{HOS_MENU_SOUND_MODS_SELECT, "HOS_MENU_SOUND_MODS_SELECT"},
{HOS_MENU_SOUND_MODS_BACK, "HOS_MENU_SOUND_MODS_BACK"},
{HOS_MENU_SOUND_PAUSE_BACK, "HOS_MENU_SOUND_PAUSE_BACK"},
{HOS_MENU_SOUND_SETTINGS_ON, "HOS_MENU_SOUND_SETTINGS_ON"},
{HOS_MENU_SOUND_SETTINGS_OFF, "HOS_MENU_SOUND_SETTINGS_OFF"},
};
#define ROLES (int)(sizeof roles / sizeof *roles)
#define ROLE_NAME_MOST 64
static char role_files[ROLES][sizeof "Sound/Resource/Stream/.bwav" + ROLE_NAME_MOST];
static const char *role_own[ROLES]; /* (a role's own file while the environment's is in files[]; NULL: files[] has its own) */
/* 1 when name is a sound's bare name: letters, digits and _, 1 to ROLE_NAME_MOST of them */
static int role_name_ok(const char *name) {
size_t n = 0;
for (; name[n]; n++) {
const char c = name[n];
if (n >= ROLE_NAME_MOST) return 0;
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')) return 0;
}
return n > 0;
}
#ifndef MENU_SOUND_ENV /* (tests/menu_sound_test.c: the environment the test says) */
#define MENU_SOUND_ENV(name) getenv(name)
#endif
static void roles_from_env(void) {
for (int k = 0; k < ROLES; k++) {
const char *name = MENU_SOUND_ENV(roles[k].env);
if (!name || !*name) continue;
if (!role_name_ok(name)) {
hos_log("menu sounds: %s: its value is not a sound's name (letters, digits and _, 64 at most, as SE_Sys_Cursor00): "
"left out", roles[k].env);
continue;
}
snprintf(role_files[k], sizeof role_files[k], "Sound/Resource/Stream/%s.bwav", name);
if (!strcmp(role_files[k], files[roles[k].id])) continue; /* (its own: nothing to say) */
role_own[k] = files[roles[k].id], files[roles[k].id] = role_files[k];
hos_log("menu sounds: %s: %s, the environment's (its own: %s)", roles[k].env, role_files[k], role_own[k]);
}
}
static Sound sounds[SOUNDS];
static atomic_int loaded; /* 0 not yet, 1 being read (sounds[] is written before the release store of 2), 2 ready */
@@ -201,22 +273,40 @@ float *hos_menu_sound_decode_long(const uint8_t *b, uint64_t size, uint32_t *fra
return decode_most(b, size, frames_out, seconds);
}
/* sounds[id] from files[id]: 1 when it plays. ((Triforce, 11-25) a file a sound before it has is not read again, and its
samples are both sounds': the roles' seven are three files, and one of them the system menu's cursor's) */
static int load_sound(int id) {
for (int k = 1; k < id; k++)
if (!strcmp(files[k], files[id])) return sounds[id] = sounds[k], sounds[id].pcm != NULL;
uint64_t size = 0;
uint8_t *b = hos_fs_rom_file(files[id], FILE_MOST, &size);
if (!b) return 0;
uint32_t frames = 0;
float *pcm = hos_menu_sound_decode(b, size, &frames);
free(b);
if (!pcm) {
hos_log("menu sounds: %s is not a BWAV file the options play (PCM16 or DSP-ADPCM, one or two channels, at most 10 s): "
"left out", files[id]);
return 0;
}
sounds[id] = (Sound){pcm, frames};
return 1;
}
static void load_all(void) { /* (once: hos_menu_sound_frame's store of 1 into loaded starts it) */
int n = 0;
roles_from_env();
for (int id = 1; id < SOUNDS; id++) {
uint64_t size = 0;
uint8_t *b = hos_fs_rom_file(files[id], FILE_MOST, &size);
if (!b) continue;
uint32_t frames = 0;
float *pcm = hos_menu_sound_decode(b, size, &frames);
free(b);
if (!pcm) {
hos_log("menu sounds: %s is not a BWAV file the options play (PCM16 or DSP-ADPCM, one or two channels, at most 10 s): "
"left out", files[id]);
continue;
}
sounds[id] = (Sound){pcm, frames};
n++;
int ok = load_sound(id);
/* ((Triforce, 11-25) a role's sound from the environment that the game's files do not have, or that is not a
sound: the role's own again, and said: not a role gone silent for a name typed wrong) */
for (int k = 0; !ok && k < ROLES; k++)
if (roles[k].id == id && role_own[k]) {
hos_log("menu sounds: %s: no sound %s in the game's files: its own, %s", roles[k].env, files[id], role_own[k]);
files[id] = role_own[k], role_own[k] = NULL;
ok = load_sound(id);
}
n += ok;
}
for (int i = 0; i < VOICES; i++) atomic_store(&voices[i].at, -1);
hos_log("menu sounds: %d of %d interface sounds from the game's files", n, SOUNDS - 1);
@@ -225,36 +315,55 @@ static void load_all(void) { /* (once: hos_menu_sound_frame's store of 1 into
float hos_menu_sound_gain(int percent) { return percent <= 0 ? 0.0f : percent >= 100 ? 1.0f : (float)percent / 100.0f; }
/* The least time between a cursor tick and the sound before it. Moving down a list or changing a value asks for a tick
at every step, up to 30 a second while a direction is held, and the focus moving with a press or a tab change is
part of that sound: at most five ticks a second are heard. */
#define CURSOR_GAP_NS 180000000ll
#define CURSOR_GAIN 0.6f /* the tick under the sounds of a decision */
static _Atomic int64_t last_start_ns = -CURSOR_GAP_NS;
/* ((Triforce, 11-26) The navigation sounds: the cursor's tick, the settings' tabs' and the Mods screen's own, and the system
menu's cursor, as the game's own Options screen plays its cursor. The owner sent a clip of the game's Options and ours
navigated quickly: "match the game's vanilla's navigation effects" and "Increase to the same exact volume as the vanilla
navigation sound effect". Measured in it: the game's cursor sound starts with each move and the one before rings on under
it (none is cut), at 0.70 of the file's level; ours were cut short by the next (11-25) and played at 0.43, the 0.6 the
ticks had under the other sounds. Now each plays whole, at the whole level, beside the ones before it; a held direction
moves at the game's own pace (vk_menu.cpp: 330 ms, then each 135 ms), so they ring over one another no more than the
game's do. Only an ask within NAV_GAP_NS of the sound before is left out: one press that asks twice, or a move that comes
with a tab's or a page's own sound */
#define NAV_GAP_NS 45000000ll
static _Atomic int64_t last_start_ns = -NAV_GAP_NS;
/* ((Triforce, 11-25) the ticks: the cursor's, and the settings' tabs' and the Mods screen's own now that each has a sound of
its own) */
static int is_tick(int id) {
return id == HOS_MENU_SOUND_CURSOR || id == HOS_MENU_SOUND_SETTINGS_NAVIGATE || id == HOS_MENU_SOUND_MODS_NAVIGATE;
}
/* (the navigation sounds: the ticks and the system menu's cursor) */
static int is_nav(int id) { return is_tick(id) || id == HOS_MENU_SOUND_SYS_CURSOR; }
void hos_menu_sound_play(int id, int64_t now_ns) {
if (id <= 0 || id >= SOUNDS) return;
if (id == HOS_MENU_SOUND_CURSOR && now_ns - atomic_load(&last_start_ns) < CURSOR_GAP_NS) return;
if (is_nav(id) && now_ns - atomic_load(&last_start_ns) < NAV_GAP_NS) return;
atomic_store(&last_start_ns, now_ns);
if (atomic_load_explicit(&loaded, memory_order_acquire) != 2 || !sounds[id].pcm) return;
int pick = 0;
uint64_t oldest = UINT64_MAX;
for (int i = 0; i < VOICES; i++) {
if (atomic_load_explicit(&voices[i].at, memory_order_acquire) < 0) { pick = i; break; }
if (voices[i].started < oldest) oldest = voices[i].started, pick = i;
}
/* A sound that replaces itself restarts instead of stacking up, and a decision replaces the tick of the same press
(a row changes its value in the tick the press is seen). ((Triforce, 11-19) the system menu's tick too: the mouse
onto Mods or Quit and its click in one tick is their decide alone) */
for (int i = 0; i < VOICES; i++) {
/* A decision replaces the tick of the same press (a row changes its value in the tick the press is seen), and a sound
that replaces itself restarts instead of stacking up. ((Triforce, 11-19) the system menu's tick too: the mouse onto
Mods or Quit and its click in one tick is their decide alone.) ((Triforce, 11-26) A navigation sound never takes
another's voice this way: the one before rings on beside it, as the game's) */
int pick = -1;
for (int i = 0; !is_nav(id) && i < VOICES; i++) {
const int64_t at = atomic_load_explicit(&voices[i].at, memory_order_acquire);
const int was = atomic_load(&voices[i].sound);
if (at >= 0 && (was == id || was == HOS_MENU_SOUND_CURSOR || was == HOS_MENU_SOUND_SYS_CURSOR) &&
AT_FRAME(at) < 2400) { /* started under 50 ms ago */
if (at >= 0 && (was == id || is_nav(was)) && AT_FRAME(at) < 2400) { /* started under 50 ms ago */
pick = i;
break;
}
}
/* else a free voice; else the oldest navigation sound's (with all eight playing, the first of a held run, near its end),
so that a longer sound (the Mods screen's fanfare, the options' opening) is not cut by a tick; else the oldest */
if (pick < 0) {
int nav = -1, oldest = 0;
for (int i = 0; i < VOICES && pick < 0; i++) {
const int64_t at = atomic_load_explicit(&voices[i].at, memory_order_acquire);
if (at < 0) { pick = i; break; }
if (is_nav(atomic_load(&voices[i].sound)) && (nav < 0 || voices[i].started < voices[nav].started)) nav = i;
if (voices[i].started < voices[oldest].started) oldest = i;
}
if (pick < 0) pick = nav >= 0 ? nav : oldest;
}
atomic_store_explicit(&voices[pick].at, -1, memory_order_release);
atomic_store_explicit(&voices[pick].sound, id, memory_order_relaxed);
voices[pick].started = __atomic_add_fetch(&started_n, 1, __ATOMIC_RELAXED);
@@ -281,12 +390,13 @@ void hos_menu_sound_mix(float *left, float *right, uint32_t frames, float gain)
atomic_compare_exchange_strong(&voices[v].at, &at, -1);
continue;
}
const float vg = which == HOS_MENU_SOUND_CURSOR ? gain * CURSOR_GAIN : gain;
/* ((Triforce, 11-26) every sound at the whole level, the cursor's ticks too: the game's own cursor sound is (the
owner's clip) as loud as the rest of its menu's) */
const uint32_t n = s->frames - pos < frames ? s->frames - pos : frames;
const float *src = s->pcm + (size_t)pos * 2;
for (uint32_t i = 0; vg != 0.0f && i < n; i++) {
left[i] += src[2 * (size_t)i] * vg;
right[i] += src[2 * (size_t)i + 1] * vg;
for (uint32_t i = 0; gain != 0.0f && i < n; i++) {
left[i] += src[2 * (size_t)i] * gain;
right[i] += src[2 * (size_t)i + 1] * gain;
}
MENU_SOUND_BETWEEN(1);
/* Only advance if the voice was not restarted meanwhile. */

View File

@@ -17,8 +17,10 @@ float *hos_menu_sound_decode_long(const uint8_t *file, uint64_t size, uint32_t *
void hos_mods_music_frame(float *const *channels, int nch, uint32_t frames);
/* The Menu sounds row's percent as a gain: 0 at 0 and under, 1 at 100 and over */
float hos_menu_sound_gain(int percent);
/* Starts the sound of a HOS_MENU_SOUND_* (gpu/vk/vk_api.h) on a free voice, else on the oldest. No lock is taken: it
may run while another thread mixes. now_ns: the caller's clock (the cursor's tick is not started twice in 180 ms) */
/* Starts the sound of a HOS_MENU_SOUND_* (gpu/vk/vk_api.h) on a free voice, else on the oldest navigation sound's, else
on the oldest. ((Triforce, 11-26) Each plays whole beside the ones before it, as the game's own menu sounds; a
navigation sound asked for within 45 ms of the sound before is left out.) No lock is taken: it may run while
another thread mixes. now_ns: the caller's clock */
void hos_menu_sound_play(int id, int64_t now_ns);
/* Adds the playing sounds to `frames` samples of the left and the right channel at 48 kHz, times gain, and moves the
voices on (at gain 0 too: a sound goes on unheard) */

View File

@@ -402,7 +402,11 @@ uint64_t hos_mods_table_size(uint64_t size, uint64_t path) {
if (!need) {
const uint64_t real = packed ? zs_content_size(e->host) : e->size;
if (!real) return size; /* (a packed file whose header has no size: the table's figure, as the game has it) */
const uint64_t room = real / 8 > (128u << 10) ? real / 8 : (128u << 10);
/* ((Triforce, 11-27) at most 2 MB: two crash reports with big mods (a 50 MB-a-file animation mod, a 206 MB mod) ran
the game's heap out while loading (an allocation returned 0, written through), an eighth of each file on top of the
files' own size. A model's materials and shapes need a few KB each; 2 MB is far more than any of the game's needed */
const uint64_t eighth = real / 8 < (2u << 20) ? real / 8 : (2u << 20);
const uint64_t room = eighth > (128u << 10) ? eighth : (128u << 10);
need = (real + room + (64u << 10) + 0xfff) & ~(uint64_t)0xfff;
if (need > 0xfffff000u) need = 0xfffff000u;
e->need = need;

View File

@@ -126,8 +126,41 @@ void hos_mouse_native_stick(int held) { InterlockedExchange(&stick_held, held ?
whether the game left the camera free, whether a stick turned it, and the degrees the mouse turned it by), and a replay
gives them back at the same update (HOS_INPUT_PLAY) in place of the mouse, the menu's row and the window's clock: the
camera then turns as it did, whatever the mouse and the settings do now (host/input_movie.c) */
/* ((Triforce, 11-27) The player camera's state as it changes, the first 12 times a run, with what last pushed the right
stick (host/nn_hid.c): 3 follows Link, 4 the player's (the game's own centering waits for R3 or a recenter). A load of
his save in the lab: -1 -> 4 -> 0 -> 3 within 0.5 s, nothing on the stick. A report: at some loads the camera stopped
following Link until R3 (a Pro controller connected over Bluetooth while it loaded); the next log says whether the
camera stayed in 4 and whether a stick, the mouse or the keys pushed it then. Whatever the Mouse camera row */
static void camera_state_note(uint64_t cam) {
static uint32_t was = 0xffffffffu;
static int said;
static int64_t first_ns;
static SRWLOCK lock = SRWLOCK_INIT; /* (the game's executors update it on several threads) */
if (said >= 12 || !looks_like_camera(cam)) return;
uint32_t state;
memcpy(&state, GP(cam + STATE_AT), 4);
if (state == was) return;
AcquireSRWLockExclusive(&lock);
const uint32_t before = was;
was = state;
ReleaseSRWLockExclusive(&lock);
if (before == state) return;
const int64_t now = hos_now_ns();
if (!first_ns) first_ns = now;
said++;
void hos_hid_rstick_said(char *out, size_t n);
char who[320];
hos_hid_rstick_said(who, sizeof who);
hos_log("camera: state %d -> %u (%s), %.1f s after the first camera; the right stick last pushed by: %s",
before == 0xffffffffu ? -1 : (int)before, state,
state == STATE_PLAYER ? "the player's: the game follows Link again after R3" : state == STATE_FOLLOWS ? "follows Link" :
"another view",
(now - first_ns) / 1e9, who);
}
void hos_mouse_camera(uint64_t cam) {
if (!cam) return;
camera_state_note(cam);
/* (no recording written or played: as before, the mouse camera's row first, and nothing of the guest's read while it is
off. With one, every update goes through it, the native camera on or not) */
const int recorded = hos_input_movie_active();

View File

@@ -97,6 +97,7 @@ typedef struct {
float vol[MAX_CH][MAX_BUF]; /* to the destination mix */
float ramp_volume, ramp_vol[MAX_CH][MAX_BUF]; /* the volumes the last frame ended with (ramped to the above) */
int snap; /* started or a new destination: no ramp from the old volumes */
int64_t dry_at; /* (Triforce) the mix frame it first played with no buffer left; 0: fed */
uint64_t wb[MAX_WB]; /* queued WaveBuffer*, oldest first (their identity) */
WB wbc[MAX_WB]; /* and their contents when appended */
int nwb, pending_wb; /* (pending: appended, not yet applied by an update) */
@@ -120,6 +121,28 @@ typedef struct {
} Voice;
static uint64_t split_bq_epoch; /* (the last epoch given to a splitter's filter: never 0, a voice's "none yet") */
/* (Triforce, the AMD limits work) Late refills: a playing voice ran out of the game's wave buffers and was given one again
within half a second, so what it played in between was silence: the game's audio thread came late (it needs one of
the virtual cores). Nothing counted this, nor the mix frames dropped because the device was behind, so a stutter left
no line in the log. One line every 10 s that had any (au_late_report). A sound that ends and whose voice is used
again without a stop counts too when it is within the half second: read the count against a quiet stretch's.
au_mix_frame: the mix frame being rendered (5 ms each), from 1. tests/test_audio_late.py */
enum { AUDIO_LATE_MOST = 100 }; /* (mix frames: half a second) */
static int64_t au_mix_frame = 1;
static struct { int64_t gaps, frames, longest; } au_late;
/* the voice's dry mark after a mix frame: 0 while it played a source frame in it or has buffers queued, else the frame
it first played nothing in */
static inline int64_t audio_late_mark(int64_t dry_at, int any, int nwb, int64_t frame) {
if (any || nwb) return 0;
return dry_at ? dry_at : frame;
}
/* a buffer appended at mix frame `frame`: the mix frames a playing voice played dry before it, 0 when it was fed in time
or the gap is longer than a late refill's (a new sound on the voice) */
static inline int64_t audio_late_gap(int playing, int64_t dry_at, int64_t frame) {
if (!playing || !dry_at) return 0;
const int64_t gap = frame - dry_at;
return gap >= 1 && gap <= AUDIO_LATE_MOST ? gap : 0;
}
static CRITICAL_SECTION lock;
static int lock_ready;
static Voice voices[MAX_VOICES];
@@ -778,6 +801,13 @@ static void tv_delay_frame(void) { /* after the voices: each line takes its st
}
}
static void au_late_report(unsigned dropped) { /* (the mixer thread, every 2000 mix frames; see au_late) */
if (au_late.gaps || dropped)
hos_log("audio: in the last 10 s %lld late refills (a playing voice out of the game's buffers, fed again after %lld ms "
"in all, the longest %lld ms), %u mix frames dropped with the device behind",
(long long)au_late.gaps, (long long)au_late.frames * 5, (long long)au_late.longest * 5, dropped);
memset(&au_late, 0, sizeof au_late);
}
static void render_voice(Voice *v) {
/* (a started voice without a destination still plays, as on the DSP: its buffers run out and are released) */
if (v->state != PLAY_STARTED) return;
@@ -814,7 +844,7 @@ static void render_voice(Voice *v) {
}
if (ocarina) hos_pad_speaker_ocarina_seen();
v->ramp_volume = v->volume;
(void)any;
v->dry_at = audio_late_mark(v->dry_at, any, v->nwb, au_mix_frame); /* ((Triforce) late refills: see au_late) */
/* the biquad filters (transposed direct form II, as the DSP's) */
for (int f = 0; f < 2; f++) {
if (!v->bq_on[f]) continue;
@@ -1302,6 +1332,7 @@ static int out_next; /* the next candidate: 0 = HOS_AUDIO_DEVICE, 1 =
static uint64_t out_opened, out_stall_since;
static unsigned out_played, out_peak, out_reported;
static unsigned out_completed; /* ((Triforce) 11-24) blocks the device gave back since it opened: played, not only taken */
static unsigned out_dropped; /* ((Triforce) mix frames dropped with the device behind, since the mixer's last line) */
/* (hookshot) A device gone (a Bluetooth headset off, the audio service restarted: "no driver", "invalid handle" from the
next call) is closed and the default opened again; none opening, the default is tried every second until one does.
Opened as the default, the output follows Windows': its key (au_default_key) looked at every second, a change reopens
@@ -1573,6 +1604,7 @@ static void output_frame(const int16_t *pcm) {
WAVEHDR *h = &hdr[fill_block];
if (fill_frames == 0) {
if (!(h->dwFlags & WHDR_DONE)) { /* the device is behind: this frame is dropped */
out_dropped++; /* ((Triforce) counted: the mixer's "late refills" line) */
const uint64_t now = au_ms();
if (!out_stall_since) out_stall_since = now;
else if (now - out_stall_since > 1500) output_reopen();
@@ -1690,10 +1722,19 @@ static void apply(const Cmd *k) { /* (with the lock held) */
v->yn1 = v->yn2 = 0;
}
if (k->i0 == PLAY_STARTED && v->state != PLAY_STARTED) v->snap = 1;
if (v->state != k->i0) v->dry_at = 0;
v->state = k->i0;
break;
case OP_VOICE_APPEND:
if (v->pending_wb > 0) v->pending_wb--;
{ /* ((Triforce) fed again after running dry: a late refill, see au_late) */
const int64_t gap = audio_late_gap(v->state == PLAY_STARTED, v->dry_at, au_mix_frame);
if (gap) {
au_late.gaps++, au_late.frames += gap;
if (gap > au_late.longest) au_late.longest = gap;
}
v->dry_at = 0;
}
if (v->nwb < MAX_WB) {
v->wbc[v->nwb] = k->wb;
v->wbc[v->nwb].source = k->i0; /* ((Triforce) its class, for the controller speaker: -1 none known) */
@@ -1829,6 +1870,8 @@ static DWORD WINAPI renderer_main(void *p) {
if (ncmds && hos_now_ns() - last_update_ns > 50000000) commit(); /* (no update came: see "parameter updates") */
render_frame(pcm, out_channels);
audio_mono(pcm, FRAME, out_channels, rx_option(HOS_OPT_AUDIO_OUTPUT, 0) == 3); /* ((Triforce) the Audio output row's Mono) */
const int report = ++au_mix_frame % 2000 == 0;
if (report) au_late_report(out_dropped), out_dropped = 0; /* (out_dropped: this thread's alone) */
au_unlock();
/* ((Triforce) the controller speaker's frame (every frame, silence too: the pad's stream runs on), after the Master
volume as the TV's; headphones in the pad's jack that take all the sound, as on the console: the TV silent */

View File

@@ -625,6 +625,30 @@ static void stick_max(int32_t stick[4], const int32_t v[4]) {
if ((v[i] < 0 ? -v[i] : v[i]) > (stick[i] < 0 ? -stick[i] : stick[i])) stick[i] = v[i];
}
/* ((Triforce, 11-27) What last pushed the right stick, by source, for host/mouse_native.c's camera lines: a report of the
camera that stopped following Link at a load until R3 (state 4, the player's) said a Pro controller had just connected;
which source turned it is asked of the next such log. Written on the reading threads, read for a log line: no lock */
enum { RS_SCRIPT, RS_PADS, RS_MOUSE, RS_KEYS, RS_N };
static volatile struct { int64_t ns; int32_t x, y; } rs_seen[RS_N];
static void rs_note(int src, const int32_t v[4]) {
if (v[2] || v[3]) rs_seen[src].x = v[2], rs_seen[src].y = v[3], rs_seen[src].ns = hos_now_ns();
}
void hos_hid_rstick_said(char *out, size_t n) {
static const char *const names[RS_N] = {"a script or the control bridge", "a controller", "the mouse", "the camera keys"};
const int64_t now = hos_now_ns();
size_t at = 0;
out[0] = 0;
for (int i = 0; i < RS_N && at + 1 < n; i++) {
const int64_t ns = rs_seen[i].ns;
if (!ns || now - ns > 3000000000LL) continue;
const int w = snprintf(out + at, n - at, "%s%s (%d, %d) %lld ms ago", at ? "; " : "", names[i], (int)rs_seen[i].x,
(int)rs_seen[i].y, (long long)((now - ns) / 1000000));
if (w < 0) break;
at += (size_t)w;
}
if (!out[0]) snprintf(out, n, "nothing in the last 3 s");
}
/* ---- (hookshot) the controls: the gamepad input (by position) and the keys that press each Switch button, from
triforce_options.ini beside the executable when it has them: pad_<button>=<HOS_PAD_* position, -1 none> and
key_<button>=<key code>,<key code> (Windows key codes, 0 none), <button> one of bind_names. Read once, at the
@@ -691,6 +715,7 @@ static int oc_live; /* (oc_notes ran this read with a button w
static volatile LONG toggle_reset;
static HoldToggle toggles;
static uint64_t host_taps_now; /* (read_input: the host's own presses of this read, in its buttons too) */
static uint64_t script_now; /* ((Triforce) read_input: the script's and the live input file's presses of this read */
void hos_input_clear_toggles(void) { InterlockedExchange(&toggle_reset, 1); }
static void binds_default(void) {
@@ -1437,6 +1462,8 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
kept apart: npad_states takes them out for the hold-to-toggle latch) */
uint64_t taps = 0;
scripted_input(buttons, &taps, stick);
rs_note(RS_SCRIPT, stick);
script_now = *buttons; /* ((Triforce) the test's own presses alone: the buttons were 0 before them) */
*buttons |= taps;
host_taps_now = taps;
/* ((Triforce, 11-19) benchmark mode (host/hos_bench.c) drives the game itself: its presses and stick alone, with the window
@@ -1451,7 +1478,9 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
}
/* (Triforce) HOS_CONTROL: the control bridge's presses (host/control.c); one that asked to be exclusive keeps the
player's devices out while it lasts. Without HOS_CONTROL: one load and back */
if (hos_control_input(buttons, stick)) return;
const int bridge_only = hos_control_input(buttons, stick);
rs_note(RS_SCRIPT, stick); /* ((Triforce, 11-27) the bridge's presses beside the script's */
if (bridge_only) return;
/* A scripted run (a test) takes no input from the player's devices until 5 s after its last press (a variable
left set in a shell no longer leaves the game without controls), and otherwise the pads count only
while the game's window is in front, like the keyboard: XInput is global, so a test run in the background
@@ -1485,6 +1514,7 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
if (!rx_option(1, 0)) {
*buttons |= pb;
stick_max(stick, ps);
rs_note(RS_PADS, ps);
}
}
hud_shortcut(0, 0); /* ((Triforce) Toggle HUD: with the window in front only) */
@@ -1539,6 +1569,7 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
if (pad_after_menu & rs) gs[2] = gs[3] = 0;
*buttons |= pad_after_menu ? bound_pad_buttons(pad_raw_game & ~pad_after_menu) : pb;
stick_max(stick, gs);
rs_note(RS_PADS, gs);
}
const int pushed = ps[0] > 12000 || ps[0] < -12000 || ps[1] > 12000 || ps[1] < -12000 || ps[2] > 12000 || ps[2] < -12000 ||
ps[3] > 12000 || ps[3] < -12000;
@@ -1587,7 +1618,7 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
if (as_stick) {
captured = mouse_stick(&mouse[2], &mouse[3], (int)((*buttons | toggles.latched) >> B_L & 1));
if (deck_builtin_input) mouse[2] = mouse[3] = 0; /* (taken for the pointer's sake, never the camera's) */
if (captured) stick_max(stick, mouse);
if (captured) stick_max(stick, mouse), rs_note(RS_MOUSE, mouse);
}
/* (the side buttons in the game's menus) */
int hos_mouse_in_game_menu(void); /* display.c */
@@ -1613,6 +1644,7 @@ static void read_input(uint64_t *buttons, int32_t stick[4]) {
controller's stick and the scripted presses are as they are) */
if (walk_vk && key(walk_vk)) walk_keys(keys, rx_option(HOS_OPT_WALK_SCALE, 51));
stick_max(stick, keys);
rs_note(RS_KEYS, keys);
if (keys[0] || keys[1] || keys[2] || keys[3]) player_used(); /* (display.c: the game menus' cursor hides again) */
}
@@ -1670,6 +1702,21 @@ static void mods_input(uint64_t *buttons_io, int32_t stick[4]) {
last_ns = 0;
}
was_down = down;
{ /* ((Triforce) the title's tabs, Mods and Save Select at the top left (gpu/vk/vk_menu.cpp draw_title_tabs): a controller's
button bound to X or Y is taken by the renderer itself, from the pad (it reads the pads while its menu is shut too).
What it cannot see is a test's scripted press (the script, the live input file: script_now; the lab's first run of
the tabs looked at host_taps_now, the host's own presses alone, and a scripted X went to the game), which reaches
no pad: told here, 6 Mods and 7 Save Select, and not given to the game */
int hos_oot_title_tabs(void);
static uint64_t taps_was;
const uint64_t taps = script_now, fresh = taps & ~taps_was;
taps_was = taps;
if (fresh & (1ULL << B_X | 1ULL << B_Y)) {
const int tabs = hos_oot_title_tabs();
if ((fresh >> B_X & 1) && (tabs & 1)) rx_option_set(HOS_OPT_MODS_ENTER, 6), buttons &= ~(1ULL << B_X);
else if ((fresh >> B_Y & 1) && (tabs & 2)) rx_option_set(HOS_OPT_MODS_ENTER, 7), buttons &= ~(1ULL << B_Y);
}
}
static uint64_t prev, held_over;
static int sel_was, stick_over, stick_was;
const int sel = rx_option(HOS_OPT_MODS_SELECTED, 0) != 0;

View File

@@ -7,6 +7,7 @@
#include "pace_steady.h" /* ((Triforce) the Steady frame rate row: steady_period) */
#include "movie_pace.h" /* ((Triforce, 11-22, PRESENT-30) paced at 240 while a movie plays at the 60 cap) */
#include "n64_pace.h" /* ((Triforce, 11-22, N64 Classic) paced at its frame rate: n64_pace_decide, pace_fps */
#include "res_follow.h" /* ((Triforce, 11-26) the Render resolution's scale as the menu applies it: realtime_step */
#include "../gpu/vk/vk_api.h" /* (HOS_OPT_HDR_*: the Insert menu's HDR, answered by the renderer) */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
@@ -361,6 +362,23 @@ static int pace_fps(void) {
return n64_pace_fps(n64_rate, movie_pace_fps(movie_raise, fps_max()));
}
static void n64_pace_decide(void); /* (below) */
/* ((Triforce, 11-26) The Frame pacing row's Steady frame rate, PACE_STEADY_*: HOS_FPS_STEADY, else the row as it is now
(gpu/vk/vk_menu.cpp menu_steady_row, HOS_OPT_STEADY_ROW: each present, so a change is taken at once; it was the options
file's at the start, and a change took a restart), else, until the renderer answers, the options file's */
static int steady_mode(void) {
static int env = -2, file = -2;
int rx_option(int id, int otherwise);
if (env == -2) {
const char *e = getenv("HOS_FPS_STEADY");
env = e && *e ? atoi(e) : -1;
}
int v = env >= 0 ? env : rx_option(HOS_OPT_STEADY_ROW, -1);
if (v < 0) {
if (file == -2) file = hos_ini_option("steady_frame_rate", PACE_STEADY_OFF);
v = file;
}
return v < PACE_STEADY_OFF || v > PACE_STEADY_REFRESH ? PACE_STEADY_OFF : v;
}
static void movie_pace_decide(void) {
static int on = -1, steady = -1;
static long long raised;
@@ -374,11 +392,7 @@ static void movie_pace_decide(void) {
hos_log("vi: no movie pacing in a run that records or plays an input recording (HOS_INPUT_RECORD, HOS_INPUT_PLAY)");
}
}
if (steady < 0) { /* (the Steady frame rate row, read as steady_period reads it) */
const char *e = getenv("HOS_FPS_STEADY");
steady = e && *e ? atoi(e) : hos_ini_option("steady_frame_rate", PACE_STEADY_OFF);
if (steady < PACE_STEADY_OFF || steady > PACE_STEADY_REFRESH) steady = PACE_STEADY_OFF;
}
steady = steady_mode(); /* (the Steady frame rate row, read as steady_period reads it: ((Triforce, 11-26)) each present) */
const int raise = movie_pace_raise(on, fps_max(), steady != PACE_STEADY_OFF, movie_plays());
if (raise && !movie_raise)
hos_log("vi: a movie plays at the 60 cap: frames paced at %d while it does (HOS_MOVIE_PACE=0: the cap kept)", MOVIE_PACE_FPS);
@@ -631,6 +645,9 @@ static int realtime_rate(double ratio, int maximum, double *carry) {
}
static void realtime_step(int64_t now) {
int rx_option(int id, int otherwise);
/* ((Triforce, 11-26) the menu's Render resolution Auto as applied: 1 Auto (the game's dynamic path), 0 a fixed scale, -1
before the renderer answers */
static int res_dyn = -1;
/* (Resolution 100% from the start once came out black (the dynamic block's fields unset), so the dynamic path ran 30
frames first. Those frames left the 3D at the controller's size, 60% of 1440p (1536x864, then the game's network to
2048x1152), whatever the fixed scale said. 11-08: from the first frame, as EvilOOT's Max Resolution patch, the 3D
@@ -645,12 +662,17 @@ static void realtime_step(int64_t now) {
frame++;
const int pulsed = pulse >= 0 && frame >= pulse && frame < pulse + 240;
if (pulse >= 0 && (frame == pulse || frame == pulse + 240)) hos_log("vi: resolution pulse: %s at frame %lld", pulsed ? "Auto" : "back to fixed", frame);
/* (the menu's Resolution is read once, at the start: switching to Auto in game ran the dynamic path, whose size the
/* (the menu's Resolution was read once, at the start: switching to Auto in game ran the dynamic path, whose size the
game keeps elsewhere, and 100% after it stayed at that size; putting the resolution object back did not undo it.
Read when the renderer answers: before, rx_option gives its fallback) */
static int dyn_at_start = -1;
if (dyn_at_start < 0) dyn_at_start = rx_option(2, -1);
hos_fixed_resolution = !pulsed && dyn_at_start == 0 && hos_dynres_runs >= from;
((Triforce, 11-26) Each present now, as the menu applies it (gpu/vk/vk_menu.cpp menu_apply): the fixed path asks the
game for its recompute while the 3D's scale is not the chosen one (nx2/oot_patches.py APPLY_NEW), and that undoes
the dynamic path's size too. Before the renderer answers, rx_option gives its fallback: the last answer stays) */
const int asked = rx_option(2, -1);
if (asked >= 0 && asked != res_dyn) {
if (res_dyn >= 0) hos_log("vi: resolution: %s from frame %lld (the menu's Apply)", asked ? "Auto, the game's dynamic path," : "fixed", frame);
res_dyn = asked;
}
hos_fixed_resolution = !pulsed && res_dyn == 0 && hos_dynres_runs >= from;
}
{ /* (Evil Hookshot, HOS_RES_LOG=1: the resolution switch's state every 600 frames) */
static int on = -1;
@@ -670,13 +692,31 @@ static void realtime_step(int64_t now) {
void hos_evil_hd_tick(int row);
hos_evil_hd_tick(rx_option(HOS_OPT_EVIL_HD, 0));
}
{ /* (the Insert menu's Resolution: the fixed path's scale in 1/10000, read once at the start as the mode above;
HOS_RES_SCALE below stays over it) */
static int scale = -1;
if (scale < 0) scale = rx_option(3, -1);
if (scale > 0 && !getenv("HOS_RES_SCALE")) {
const float v = scale / 10000.0f;
memcpy((void *)&hos_fixed_scale_bits, &v, 4);
{ /* (the Insert menu's Resolution: the fixed path's scale in 1/10000, ((Triforce, 11-26)) each present as the mode above,
so the menu's Apply reaches the 3D in play; HOS_RES_SCALE below stays over it) */
/* (host/res_follow.h: where the render targets' pool is held to its size, a 3D larger than any this run has had waits
for the next start, and the menu says so, HOS_OPT_RES_HELD; smaller ones are taken) */
static ResFollow follow = {-1, 0, 0};
static int env = -1;
if (env < 0) env = getenv("HOS_RES_SCALE") != NULL;
if (!env) {
extern int hos_rt_pool_pinned(void);
void rx_option_set(int id, int value);
const int asked = rx_option(3, -1), was = follow.scale, was_held = follow.held;
const int pinned = asked > 0 && asked != was ? hos_rt_pool_pinned() : 0; /* (asked only when it matters) */
const int what = res_follow(&follow, res_dyn, asked, pinned);
if (what == RES_TAKE) {
if (was > 0) hos_log("vi: resolution: the 3D's scale %.3f, was %.3f (the menu's Apply)", follow.scale / 10000.0, was / 10000.0);
if (was_held) rx_option_set(HOS_OPT_RES_HELD, 0);
const float v = follow.scale / 10000.0f;
memcpy((void *)&hos_fixed_scale_bits, &v, 4);
} else if (what == RES_HOLD) {
hos_log("vi: resolution: the 3D's scale %.3f is kept for the next start: the render targets' pool is held to its "
"size at this output, and %.3f is the largest this run has had", asked / 10000.0, follow.largest / 10000.0);
rx_option_set(HOS_OPT_RES_HELD, asked);
} else if (what == RES_FREE) {
rx_option_set(HOS_OPT_RES_HELD, 0);
}
}
}
{
@@ -895,10 +935,20 @@ static int64_t steady_period(int64_t base, int64_t now) {
const int64_t other = (int64_t)__atomic_exchange_n(&frame_waited_other_ns, 0, __ATOMIC_RELAXED);
const int handed = __atomic_exchange_n(&frame_handed, 0, __ATOMIC_RELAXED) != 0;
frame_waited_own_ns = 0, last = now;
if (mode < 0) {
const char *e = getenv("HOS_FPS_STEADY");
mode = e && *e ? atoi(e) : hos_ini_option("steady_frame_rate", PACE_STEADY_OFF);
if (mode < PACE_STEADY_OFF || mode > PACE_STEADY_REFRESH) mode = PACE_STEADY_OFF;
{ /* ((Triforce, 11-26) the row as it is now (steady_mode): another choice in play starts its set again, from the cap, as a
start does; Off lets the frames go at once, and the renderer no longer holds them to a Steady period */
const int want = steady_mode();
if (want != mode) {
if (mode >= 0)
hos_log("vi: steady frame rate: %s now (the Frame pacing row, in play)",
want == PACE_STEADY_OFF ? "off" : want == PACE_STEADY_REFRESH ? "steps of the display's refresh" : "any rate");
if (mode > PACE_STEADY_OFF) {
pace_steady_reset(&steady);
rx_option_set(HOS_OPT_PACE_STEADY, 0);
}
mode = want, cap = 0, frames = 0;
window.n = window.frames = 0, window.own = window.other = window.held = 0, window.since = now;
}
}
if (mode == PACE_STEADY_OFF) return base;
frames++;

View File

@@ -8,7 +8,8 @@
pictures by buffer index (AcquireXDecoderOutputBuffer, GetXDecoderOutputBufferProperties), reads them back to
its own memory as RGBA or NV12 (ReadDecoderOutputImageRgba / Nv12) and gives the buffer back (Release).
Here a submission is decoded at once; a finished picture waits in a queue until an Acquire puts it in the first
Here a submission is kept and decoded later (ahead of the game by a host thread of the decoder's, see
decode_ahead_main; else in the Acquire); a finished picture waits in a queue until an Acquire puts it in the first
free registered buffer (host memory: the pool's guest memory is not used). The video service itself (nn::gsv) is
not emulated: nn::codec::video::Initialize does nothing. */
#include "hos.h"
@@ -34,7 +35,7 @@
#define DEC_MAGIC 0x43454456u /* 'VDEC' */
#define PREF_MAGIC 0x46455250u /* 'PREF' */
#define MAX_SLOTS 16
#define MAX_QUEUE 8
#define MAX_QUEUE 16 /* ((Triforce) 8 before the pictures were decoded ahead: room for the most HOS_VIDEO_DECODE_AHEAD takes, 14) */
static int video_log(void) { /* HOS_VIDEO_LOG=1: submissions and acquisitions */
static int on = -1;
@@ -46,6 +47,7 @@ void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */
void hos_system_event_signal(uint64_t key);
void hos_system_event_clear(uint64_t key); /* ((Triforce, 11-22, IO-34) these two under a host lock: no checkpoint) */
void hos_system_event_signal_held(uint64_t key);
void hos_host_thread_register_self(const char *name); /* hos_prof.c */
/* an image pool: its pictures, w x h, as RGBA and as NV12 (both kept: the reader asks for either) */
typedef struct {
@@ -91,17 +93,51 @@ void mf_av1_decode(void *m, const uint8_t *data, size_t n, int64_t pts, mf_av1_p
void mf_av1_flush(void *m);
void mf_av1_close(void *m);
/* (Triforce, the AMD limits work) The rules of decoding ahead (decode_ahead_main), without the decoder: cut out and run by
tests/test_video_decode_ahead.py.
HOS_VIDEO_DECODE_AHEAD into the pictures kept decoded ahead of the game: unset or 1, VIDEO_AHEAD_PICTURES; 0 (or no
number), none: decoded in the game's call, as before; 2 and more, that many, with two places of the queue left over.
A 1080p picture is 3.1 MB as NV12 (Media Foundation's), so twelve ahead are ~37 MB; libavcodec's are kept as RGBA too,
11.4 MB each, ~137 MB. Twelve are 200 ms of a movie at 60 pictures a second: the title's movie has single pictures
that take 80-200 ms to decode, and in the lab six ahead still left an acquire waiting 30 ms twice in 600 (the title
with the menu loading over it), twelve none */
enum { VIDEO_AHEAD_PICTURES = 12, VIDEO_LATE_NS = 25000000 };
static inline int video_ahead_count(const char *e, int max_queue) {
const int n = e ? atoi(e) : 1, most = max_queue - 2;
if (n <= 0 || most < 1) return 0;
const int want = n == 1 ? VIDEO_AHEAD_PICTURES : n;
return want < most ? want : most;
}
/* 1 while the worker decodes the next submission now: the stream's end as soon as it is next, pictures queued or not
(the last picture must get its flag before it goes out, see decode_pending), a picture while fewer than `ahead` wait.
It never decodes into a queue that has its count, so nothing decoded is ever dropped for room */
static inline int video_ahead_decode(int has_next, int next_is_end, int queued, int ahead) {
return has_next && (next_is_end || queued < ahead);
}
/* the catch-up's rule: a picture more than `late` behind the movie's clock (the picture at clock_pts was due at clock_ns) */
static inline int video_picture_late(int64_t pts, int64_t clock_pts, int64_t clock_ns, int64_t now, int64_t late) {
return pts + late < clock_pts + (now - clock_ns);
}
typedef struct {
/* ((Triforce) The decoder: ctx or mf, frame, sws, and out, the pictures of the submission being decoded. One thread
at a time uses it, and it has no lock of its own: with a worker (decode ahead), the worker while `decoding` is set,
d->lock not held, and a flush under d->lock once `decoding` is clear (ahead_stop); out is the worker's alone.
Without a worker, whoever holds d->lock. ctx and mf themselves are set at the start and never change) */
AVCodecContext *ctx;
void *mf; /* (hookshot) an AV1 decoder on Media Foundation instead of ctx */
AVPacket *pkt;
AVFrame *frame;
struct SwsContext *sws;
int sws_w, sws_h, sws_fmt;
Picture *out; /* (Triforce) pictures decoded, not in the queue yet (out_push, decode_next, the worker) */
int nout, cap_out;
/* (the buffers: the game's calls only, never the worker) */
uint64_t slots[MAX_SLOTS]; /* registered pools (guest pointers), by buffer index */
int busy[MAX_SLOTS]; /* acquired, not released */
int64_t slot_pts[MAX_SLOTS];
int slot_last[MAX_SLOTS]; /* the stream's last picture (the submission marked last, all decoded) */
/* (from here on: under d->lock, the worker's reads and writes too) */
Picture queue[MAX_QUEUE];
int qhead, qn;
int eos; /* the last submission is in and decoded: an empty queue is the end */
@@ -122,6 +158,20 @@ typedef struct {
uint64_t ready; /* ((Triforce, 11-22, IO-34) its "ready for a submission" event, a guest address: set,
and clear from a refused submission until there is room again) */
int ready_clear; /* (... whether it is clear now; changed only under the lock, with the event) */
/* (Triforce) what the decoding cost since the last "video: ... pictures taken" line: submissions decoded, their time,
the longest one, the longest time one acquire waited for its picture (for the worker; without one, decoding in the
call, where the catch-up decodes several), pictures skipped, acquires that found their picture ready and that waited */
int64_t st_since, st_taken, st_decoded, st_ns, st_max_ns, st_call_max_ns, st_skipped, st_ready, st_waited;
/* (Triforce) decode ahead (decode_ahead_main). worker and ahead are set at the start and never change */
HANDLE worker; /* the decoder's host thread; NULL: none (the switch, or no thread): decoded in the acquire */
int ahead; /* the pictures it keeps decoded ahead */
CONDITION_VARIABLE work; /* the worker sleeps here: a submission, a picture taken, a flush and the close wake it */
CONDITION_VARIABLE idle; /* the game's calls wait here for the worker: woken when a decode ends, a picture is queued */
int decoding, ending; /* the worker is in the decoder (d->lock let go); and with the stream's end */
int uncommitted; /* decoded pictures the worker has yet to queue (the queue was full) */
int hold; /* flushes that wait for the decoder: no decode begins */
int closing; /* the decoder is being finalized: the worker ends */
uint32_t gen; /* counts the flushes: pictures of a decode begun before one are thrown away */
SRWLOCK lock;
} Dec;
@@ -302,6 +352,8 @@ HLE(_ZN2nn5codec26ReadDecoderOutputImageNv12EPKNS0_25VideoDecoderImagePoolTypeEj
}
/* ---- decoders ---- */
static void ahead_start(Dec *d);
static void ahead_close(Dec *d);
static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, int h);
static void dec_init(Ctx *c, enum AVCodecID id, const char *what) { dec_init_sized(c, id, what, 0, 0); }
#ifdef _WIN32
@@ -376,11 +428,13 @@ static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, i
d->pkt = av_packet_alloc();
d->frame = av_frame_alloc();
d->ready = ready_new(); /* ((Triforce, 11-22, IO-34) before the game can ask for it or submit) */
if (d->ctx || d->mf) ahead_start(d); /* ((Triforce) before the game can find the decoder: no call sees it change) */
set_host(ARG(0), DEC_MAGIC, d);
static int logged;
if (logged++ < 4)
hos_log("video: %s decoder %s%s (%dx%d)", what, d->ctx ? "ready: " : d->mf ? "ready on Media Foundation" :
"not available in this FFmpeg", d->ctx ? d->ctx->codec->name : "", w, h);
hos_log("video: %s decoder %s%s (%dx%d)%s", what, d->ctx ? "ready: " : d->mf ? "ready on Media Foundation" :
"not available in this FFmpeg", d->ctx ? d->ctx->codec->name : "", w, h,
d->worker ? ", its pictures decoded ahead by a host thread (HOS_VIDEO_DECODE_AHEAD)" : "");
RET(0);
}
static void picture_free(Picture *p) {
@@ -413,27 +467,56 @@ static void movie_end(Dec *d) {
static void dec_finalize(Ctx *c) {
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
if (!d) return;
set_host(ARG(0), DEC_MAGIC, NULL); /* ((Triforce) first: no later call finds the decoder while its worker is waited for) */
ahead_close(d); /* (the worker out of the decoder and ended, before any of it is freed) */
movie_end(d);
/* ((Triforce, 11-22, IO-34) its ready event is left set: a thread that still waits for it is not left waiting. No
lock: nothing else has this decoder any more) */
if (d->ready_clear) hos_system_event_signal(d->ready);
pending_free(d);
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
for (int i = 0; i < d->nout; i++) picture_free(&d->out[i]);
free(d->out);
if (d->sws) sws_freeContext(d->sws);
avcodec_free_context(&d->ctx);
mf_av1_close(d->mf);
av_packet_free(&d->pkt);
av_frame_free(&d->frame);
free(d);
set_host(ARG(0), DEC_MAGIC, NULL);
}
static int rgba_eager(void) { /* ((Triforce, 11-22, IO-36) HOS_VIDEO_RGBA=1, read once: planar pictures made RGBA at once) */
static int on = -1;
if (on < 0) on = getenv("HOS_VIDEO_RGBA") != NULL && atoi(getenv("HOS_VIDEO_RGBA")) != 0;
return on;
}
/* a decoded frame into the queue, as RGBA and NV12 (the oldest dropped when the reader falls behind).
((Triforce, 11-22, the performance audit's IO-36, after Source A's) As NV12 alone for libdav1d's planar 4:2:0 too, as
/* ((Triforce) a decoded picture kept for the queue, in the decoding thread's own list (see Dec): no lock, and not the
queue, which the game's calls read meanwhile. 0: no memory for the list, the picture is freed) */
static int out_push(Dec *d, Picture *p) {
if (d->nout == d->cap_out) {
const int cap = d->cap_out ? d->cap_out * 2 : 4;
Picture *more = (Picture *)realloc(d->out, (size_t)cap * sizeof *more);
if (!more) {
picture_free(p);
return 0;
}
d->out = more, d->cap_out = cap;
}
d->out[d->nout++] = *p;
return 1;
}
/* ((Triforce) a decoded picture into the queue, d->lock held. Without a worker the oldest is dropped when the reader falls
behind, as before; the worker never comes here with a full queue: it waits for room, decode_ahead_main) */
static void queue_push(Dec *d, const Picture *p) {
if (d->qn == MAX_QUEUE) {
picture_free(&d->queue[d->qhead]);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
}
d->queue[(d->qhead + d->qn) % MAX_QUEUE] = *p;
d->qn++;
}
/* a decoded frame as RGBA and NV12, for the queue (out_push: this runs on the thread that decodes, which with a worker
does not hold d->lock; it touches the decoder alone) */
/* ((Triforce, 11-22, the performance audit's IO-36, after Source A's) As NV12 alone for libdav1d's planar 4:2:0 too, as
Media Foundation's NV12 already was: no swscale context, no RGBA buffer and no conversion, the pool making the RGBA
only if it is read (pool_rgba; dec_acquire copies no RGBA rows for such a picture). Each 1080p picture was converted
on the movie thread for a game that reads only the NV12. The NV12 buffer is zeroed only where a copy leaves bytes
@@ -475,14 +558,7 @@ static void queue_frame(Dec *d, const AVFrame *f) {
video_uv_interleave(uv + (size_t)y * w, f->data[1] + (size_t)y * f->linesize[1],
f->data[2] + (size_t)y * f->linesize[2], w / 2);
}
if (d->qn == MAX_QUEUE) {
picture_free(&d->queue[d->qhead]);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
}
d->queue[(d->qhead + d->qn) % MAX_QUEUE] = p;
d->qn++;
d->movie.pictures++;
video_pace_picture(&d->pace, f->pts); /* ((Triforce, 11-22, THREAD-82) the gap between pictures, from their own times) */
if (!out_push(d, &p)) hos_log("video: no memory to keep a %dx%d frame: dropped", w, h);
}
static void mf_picture(void *user, const uint8_t *y, const uint8_t *uv, int w, int h, int stride, int64_t pts) {
AVFrame f;
@@ -506,47 +582,67 @@ static void decode_next(Dec *d);
static void decode_pending(Dec *d) {
while (d->phead && (!d->qn || !d->phead->pkt)) decode_next(d);
}
/* one submission decoded (its pictures into the queue, if any) */
/* (d->lock held) the oldest submission off the list; data after the end starts a stream again */
static Pending *pending_pop(Dec *d) {
Pending *n = d->phead;
d->phead = n->next;
if (!d->phead) d->ptail = NULL;
d->npending--; /* ((Triforce, 11-22, IO-34) no longer waiting to be decoded) */
if (n->pkt) d->eos = 0;
return n;
}
/* ((Triforce) one submission through the decoder, its pictures into d->out (mf_picture, drain: queue_frame), and the
submission freed. For the thread that has the decoder (see Dec): the worker comes here without d->lock, so nothing
under that lock is read or written here, and no guest memory (the submission's data was copied by dec_submit)) */
static void decode_one(Dec *d, Pending *n) {
if (d->mf) { /* (hookshot) */
if (n->pkt) mf_av1_decode(d->mf, n->pkt->data, (size_t)n->pkt->size, n->pkt->pts, mf_picture, d);
else mf_av1_decode(d->mf, NULL, 0, 0, mf_picture, d);
} else if (n->pkt) {
if (avcodec_send_packet(d->ctx, n->pkt) == AVERROR(EAGAIN)) { /* (full: its pictures out first) */
drain(d);
avcodec_send_packet(d->ctx, n->pkt);
}
drain(d);
} else { /* (the end: the rest out) */
avcodec_send_packet(d->ctx, NULL);
drain(d);
avcodec_flush_buffers(d->ctx); /* (a stream after it starts again) */
}
av_packet_free(&n->pkt);
free(n);
}
/* (d->lock held) after decode_one: its time counted; at the stream's end the last picture marked, the last one this
submission gave (d->out, queued next) or else the last one queued.
((Triforce, 11-22) The movie's own counts (v0.7.0's IO-32 line and THREAD-82 pace) are taken here, under the lock, from
the pictures in d->out and their times: queue_frame, where v0.7.0 counted them, runs on the worker without the lock.
live 0: a decode a flush overtook, of a movie whose line is already out: not counted into the next one) */
static void decode_done(Dec *d, int end, int64_t ns, int live) {
d->st_decoded++, d->st_ns += ns;
if (ns > d->st_max_ns) d->st_max_ns = ns;
if (live) {
video_movie_decoded(&d->movie, ns);
for (int i = 0; i < d->nout; i++) d->movie.pictures++, video_pace_picture(&d->pace, d->out[i].pts);
/* ((Triforce, 11-22, THREAD-82) and what a decode that gives a picture takes lately, for the catch-up's bound) */
if (d->nout) video_pace_decoded(&d->pace, ns);
}
if (end) {
d->eos = 1;
d->log_submits = 8; /* (data after the end: a restart, worth seeing) */
if (d->nout) d->out[d->nout - 1].last = 1;
else if (d->qn) d->queue[(d->qhead + d->qn - 1) % MAX_QUEUE].last = 1;
}
}
/* one submission decoded in the caller's thread, d->lock held all through (no worker): its pictures into the queue, if any */
static void decode_next(Dec *d) {
if (d->phead) {
const int64_t began = hos_now_ns(); /* ((Triforce, 11-22, IO-32) each submission timed, for the movie's line) */
const int64_t pictures = d->movie.pictures;
Pending *n = d->phead;
d->phead = n->next;
if (!d->phead) d->ptail = NULL;
d->npending--;
if (d->mf) { /* (hookshot) */
if (n->pkt) {
d->eos = 0;
mf_av1_decode(d->mf, n->pkt->data, (size_t)n->pkt->size, n->pkt->pts, mf_picture, d);
av_packet_free(&n->pkt);
} else {
mf_av1_decode(d->mf, NULL, 0, 0, mf_picture, d);
d->eos = 1;
d->log_submits = 8; /* (data after the end: a restart, worth seeing) */
if (d->qn) d->queue[(d->qhead + d->qn - 1) % MAX_QUEUE].last = 1;
}
} else if (n->pkt) {
d->eos = 0;
if (avcodec_send_packet(d->ctx, n->pkt) == AVERROR(EAGAIN)) { /* (full: its pictures out first) */
drain(d);
avcodec_send_packet(d->ctx, n->pkt);
}
drain(d);
av_packet_free(&n->pkt);
} else { /* (the end: the rest out, the last picture marked) */
avcodec_send_packet(d->ctx, NULL);
drain(d);
d->eos = 1;
d->log_submits = 8;
if (d->qn) d->queue[(d->qhead + d->qn - 1) % MAX_QUEUE].last = 1;
avcodec_flush_buffers(d->ctx); /* (a stream after it starts again) */
}
free(n);
const int64_t took = hos_now_ns() - began;
video_movie_decoded(&d->movie, took);
/* ((Triforce, 11-22, THREAD-82) and what a decode that gives a picture takes lately, for the catch-up's bound) */
if (d->movie.pictures != pictures) video_pace_decoded(&d->pace, took);
const int64_t t0 = hos_now_ns();
Pending *n = pending_pop(d);
const int end = !n->pkt;
decode_one(d, n);
decode_done(d, end, hos_now_ns() - t0, 1);
for (int i = 0; i < d->nout; i++) queue_push(d, &d->out[i]);
d->nout = 0;
}
}
static void pending_push(Dec *d, AVPacket *pkt) {
@@ -557,8 +653,147 @@ static void pending_push(Dec *d, AVPacket *pkt) {
d->ptail = n;
d->npending++;
}
/* SubmitXDecoderInputBuffer(u64* id, decoder, data, size, TimeSpan pts, bool last): kept, decoded when a picture is
acquired (the library submits a whole movie at once: its pictures decoded then would not fit any queue) */
/* ---- decode ahead ---- */
/* (Triforce, the AMD limits work) The pictures were decoded in the game's Acquire call: 3-5 ms each for the title screen's
1080p AV1 movie in its quiet parts, 6-13 ms in busy ones, single ones 80-200 ms, and after a long frame several in a row
(the catch-up: one call decoded for 728 ms, and 47-250 of every ~650 pictures were thrown away to keep up with the
sound). Giving the virtual core up for the call (dec_acquire, HOS_VIDEO_KEEP_CORE) ended the sound's stutter; the movie still stuttered
wherever a scene loads over it. Now each decoder has a host thread of its own (no guest thread: it holds no virtual
core, touches no guest memory, runs at normal priority) that decodes the submissions ahead of the game and keeps
`ahead` pictures in the queue (video_ahead_count), so an acquire takes a picture that is there.
The locking. d->lock guards the lists, the queue and the counts, and is never held across a decode: the worker takes a
submission off the list under it, sets `decoding`, lets it go, decodes into its own list (d->out), takes it again,
clears `decoding` and queues the pictures. So a submit, an acquire, a flush wait for the lock no longer than a list
operation. The decoder itself has no lock: it is the worker's while `decoding` is set. A flush needs it too
(avcodec_flush_buffers, mf_av1_flush): ahead_stop counts the flush (gen: what a decode begun before it gives is thrown
away, also by a worker that waits for room in the queue), holds new decodes off (hold) and waits on `idle` until
`decoding` is clear; ahead_go lets the worker on. The close (ahead_close) sets `closing` and waits for the thread to
end before anything is freed. The worker sleeps on `work` with nothing to decode or the queue at its count, and with a
full queue (MAX_QUEUE: a submission that gave several pictures) it waits for room: it never drops a picture.
HOS_VIDEO_DECODE_AHEAD=0: no worker, decoded in the acquire as before; =<2..14>: that many pictures ahead (6) */
static int decode_ahead(void) {
static int n = -1;
if (n < 0) n = video_ahead_count(getenv("HOS_VIDEO_DECODE_AHEAD"), MAX_QUEUE);
return n;
}
/* (d->lock held) 1 while the last picture queued may yet turn out to be the stream's last: the stream's end is in the
decoder, or is next with nothing between that picture and it. Such a picture does not go out before the worker has
marked it (the rule above decode_pending); the end is decoded as soon as it is next, so this is short */
static int tail_unsettled(const Dec *d) {
return d->ending || (!d->decoding && !d->uncommitted && d->phead && !d->phead->pkt);
}
static DWORD WINAPI decode_ahead_main(LPVOID arg) {
Dec *d = (Dec *)arg;
hos_host_thread_register_self("video decode ahead");
AcquireSRWLockExclusive(&d->lock);
while (!d->closing) {
if (d->hold || !video_ahead_decode(d->phead != NULL, d->phead && !d->phead->pkt, d->qn, d->ahead)) {
SleepConditionVariableSRW(&d->work, &d->lock, INFINITE, 0);
continue;
}
Pending *n = pending_pop(d);
const int end = !n->pkt;
const uint32_t gen = d->gen;
d->decoding = 1, d->ending = end;
ReleaseSRWLockExclusive(&d->lock);
const int64_t t0 = hos_now_ns();
decode_one(d, n); /* (the decoder is this thread's; no call of the game waits for this) */
const int64_t ns = hos_now_ns() - t0;
AcquireSRWLockExclusive(&d->lock);
decode_done(d, end && gen == d->gen, ns, gen == d->gen); /* (after a flush it was the end of a stream that is gone) */
/* ((Triforce, 11-22, v0.7.0's IO-34) the submission left the list: the ready event a refused one cleared is set
again from here too, not only at the game's next call (hos_system_event_signal_held takes no checkpoint) */
input_room(d);
d->decoding = d->ending = 0;
d->uncommitted = d->nout;
WakeAllConditionVariable(&d->idle); /* (a flush that waits for the decoder; an acquire that waits for the end) */
int i = 0;
while (i < d->nout && gen == d->gen && !d->closing) {
if (d->qn == MAX_QUEUE) { /* (full: the oldest is not dropped; the next acquire makes room and wakes this) */
SleepConditionVariableSRW(&d->work, &d->lock, INFINITE, 0);
continue;
}
queue_push(d, &d->out[i++]);
d->uncommitted--;
WakeAllConditionVariable(&d->idle); /* (an acquire that waits for a picture) */
}
const int dropped = i < d->nout;
for (; i < d->nout; i++) picture_free(&d->out[i]); /* (a flush, the close: pictures of the stream before it) */
d->nout = d->uncommitted = 0;
/* (an acquire that counted on those pictures: woken, not left to its 2 ms look) */
if (dropped) WakeAllConditionVariable(&d->idle);
}
ReleaseSRWLockExclusive(&d->lock);
return 0;
}
/* the worker started, before the game has the decoder (dec_init_sized). None with the switch off, or when the thread
cannot be made: d->worker stays NULL for the decoder's life and the acquire decodes */
static void ahead_start(Dec *d) {
InitializeConditionVariable(&d->work);
InitializeConditionVariable(&d->idle);
d->ahead = decode_ahead();
if (!d->ahead) return;
d->worker = CreateThread(NULL, 0, decode_ahead_main, d, 0, NULL);
if (!d->worker) hos_log("video: no thread to decode a movie's pictures ahead: they are decoded in the game's calls");
/* (placed as the game's threads are: the decoding ran on the movie's game thread before, off the core kept for the
replay; left where Windows puts it, a busy decode could sit on that core. HOS_PIN names it "video decode ahead") */
else hos_thread_pin(d->worker, "video decode ahead");
}
/* the worker ended and waited for (the close, no other call has the decoder): it is in the decoder for one submission at
most, and that may take 100 ms and more, so not on a virtual core */
static void ahead_close(Dec *d) {
if (!d->worker) return;
AcquireSRWLockExclusive(&d->lock);
d->closing = 1;
WakeAllConditionVariable(&d->work);
ReleaseSRWLockExclusive(&d->lock);
const int away = hos_vcore_away();
WaitForSingleObject(d->worker, INFINITE);
if (away) hos_vcore_back();
CloseHandle(d->worker);
d->worker = NULL;
}
/* (d->lock held, let go while it waits) the decoder taken from the worker for a flush, and given back. hos_cv_sleep
gives the caller's virtual core up for the wait; it may let the lock go once more after `decoding` is clear, and
`hold` keeps the worker out of the decoder then */
static void ahead_stop(Dec *d) {
if (!d->worker) return;
d->gen++, d->hold++;
WakeAllConditionVariable(&d->work); /* (a worker that waits for room: its pictures are of the stream before) */
while (d->decoding) hos_cv_sleep(&d->idle, &d->lock, 20);
}
static void ahead_go(Dec *d) {
if (!d->worker) return;
d->hold--;
WakeAllConditionVariable(&d->work);
WakeAllConditionVariable(&d->idle); /* (an acquire that waited for what the flush threw away) */
}
/* (d->lock held, let go while it waits) What decode_pending and the wait after it give an acquire, from the worker: it
comes back with a picture queued whose last flag is settled, or with none when none will come: at the stream's end,
or after ~100 ms with nothing submitted (as before: the buffer goes out as it was). While the worker has something to
decode or to queue the wait goes on, as the acquire's own decoding did: the game is never handed an old buffer for a
picture that is on its way. The time waited for the worker (ns) comes back, for the pictures-taken line; 0 is the
rule: the picture was there */
static int64_t ahead_wait(Dec *d) {
const int64_t idle_until = hos_now_ns() + 100000000;
int64_t waited = 0;
for (;;) {
if (d->qn > 1 || (d->qn == 1 && !tail_unsettled(d))) break;
const int coming = d->qn || d->phead || d->decoding || d->uncommitted;
const int64_t t0 = hos_now_ns();
if (!coming && (d->eos || d->stopped || t0 >= idle_until)) break; /* (stopped: v0.7.0's rule, no wait after a Stop) */
WakeAllConditionVariable(&d->work);
hos_cv_sleep(&d->idle, &d->lock, 2);
if (coming) waited += hos_now_ns() - t0;
}
return waited;
}
/* SubmitXDecoderInputBuffer(u64* id, decoder, data, size, TimeSpan pts, bool last): kept, decoded a few pictures ahead
of the acquires by the worker, or without one when a picture is acquired (the library submits a whole movie at once:
its pictures decoded then would not fit any queue) */
static volatile LONG64 submissions;
/* (hookshot) A buffer handed out with nothing decoded into it, by a decoder with nothing left to decode, gets a sync
@@ -671,10 +906,27 @@ static void dec_submit(Ctx *c) {
if (video_log() && (d->submits <= 8 || (ARG(5) & 1) || logged_one))
hos_log("video: submit %lld (%llu bytes, pts %lld%s)", (long long)d->submits, (unsigned long long)ARG(3),
(long long)ARG(4), (ARG(5) & 1) ? ", last" : "");
if (d->worker) WakeAllConditionVariable(&d->work); /* ((Triforce) decoded ahead, from now) */
input_room(d); /* ((Triforce, 11-22, IO-34) as at every unlock that ends a call: the event never stays clear with room) */
ReleaseSRWLockExclusive(&d->lock);
RET(0);
}
/* (d->lock held) the flush itself. With a worker the decoder is taken from it first (ahead_stop waits for the decode in
flight, the lock let go meanwhile: a submission that comes in then is of the stream before, and goes with it); from
there to ahead_go the lock is held, so the decoder, the lists and the queue are emptied as one step */
static void flush_locked(Dec *d) {
ahead_stop(d);
d->log_submits = 8;
if (d->ctx) avcodec_flush_buffers(d->ctx);
else mf_av1_flush(d->mf);
pending_free(d);
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
d->qhead = d->qn = 0;
d->eos = 0;
d->clock_set = 0;
for (int i = 0; i < MAX_SLOTS; i++) d->slot_last[i] = 0;
ahead_go(d);
}
static void dec_flush(Ctx *c, const char *what) {
Dec *d = (Dec *)host_of(ARG(0), DEC_MAGIC);
if (d && (d->ctx || d->mf)) {
@@ -683,17 +935,10 @@ static void dec_flush(Ctx *c, const char *what) {
hos_log("video: %s after %lld submits and %lld acquires (%d queued, %s, lr %#llx)", what, (long long)d->submits,
(long long)d->acquires, d->qn, d->eos ? "at the end" : d->phead ? "submissions left" : "none left",
(unsigned long long)c->x[30]);
d->log_submits = 8;
movie_end(d); /* ((Triforce, 11-22, IO-32) what the movie cost to decode, once) */
if (d->ctx) avcodec_flush_buffers(d->ctx);
else mf_av1_flush(d->mf);
pending_free(d);
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
d->qhead = d->qn = 0;
d->eos = 0;
movie_end(d); /* ((Triforce, 11-22, IO-32) what the movie cost to decode, once; before the flush counts itself
(gen): what a decode still in flight gives is not counted into the next movie) */
flush_locked(d);
d->stopped = 1;
d->clock_set = 0;
for (int i = 0; i < MAX_SLOTS; i++) d->slot_last[i] = 0;
input_room(d); /* ((Triforce, 11-22, IO-34) nothing waits any more: ready for submissions) */
ReleaseSRWLockExclusive(&d->lock);
}
@@ -710,7 +955,11 @@ static void dec_unregister(Ctx *c) {
if (d && (uint32_t)ARG(1) < MAX_SLOTS) d->slots[(uint32_t)ARG(1)] = 0;
RET(0);
}
/* AcquireXDecoderOutputBuffer(u32* index, NativeSyncHandle*, decoder): the oldest picture into a free buffer */
/* AcquireXDecoderOutputBuffer(u32* index, NativeSyncHandle*, decoder): the oldest picture into a free buffer.
((Triforce, 11-22) The v0.6.0 branch gave the thread's virtual core up around this call (HOS_VIDEO_DECODE_AWAY); v0.7.0
does so itself below (HOS_VIDEO_KEEP_CORE=1: kept), so that wrapper is gone. With the pictures decoded ahead
("decode ahead" above) the call decodes nothing and mostly waits for nothing; where it does wait for the worker,
hos_cv_sleep gives the core up, with or without the switch) */
static void dec_acquire(Ctx *c) {
Dec *d = (Dec *)host_of(ARG(2), DEC_MAGIC);
if (ARG(1)) G64(ARG(1)) = 0;
@@ -728,13 +977,20 @@ static void dec_acquire(Ctx *c) {
if (keep_core < 0) keep_core = getenv("HOS_VIDEO_KEEP_CORE") && atoi(getenv("HOS_VIDEO_KEEP_CORE")) == 1;
const int away = keep_core ? 0 : hos_vcore_away();
AcquireSRWLockExclusive(&d->lock);
decode_pending(d);
const int64_t wait_until = hos_now_ns() + 100000000;
for (int tries = 0; !d->qn && !d->eos && (by_tries ? tries < 50 : !d->stopped && hos_now_ns() < wait_until); tries++) {
ReleaseSRWLockExclusive(&d->lock);
hos_sleep_ns(2000000);
AcquireSRWLockExclusive(&d->lock);
const int64_t call_ns0 = d->st_ns;
int64_t waited_ns = 0;
if (!d->st_since) d->st_since = hos_now_ns();
if (d->worker) { /* ((Triforce) decoded ahead: the worker's picture, waited for only when none is there) */
waited_ns = ahead_wait(d);
} else {
decode_pending(d);
const int64_t wait_until = hos_now_ns() + 100000000;
for (int tries = 0; !d->qn && !d->eos && (by_tries ? tries < 50 : !d->stopped && hos_now_ns() < wait_until); tries++) {
ReleaseSRWLockExclusive(&d->lock);
hos_sleep_ns(2000000);
AcquireSRWLockExclusive(&d->lock);
decode_pending(d);
}
}
int slot = -1;
for (int i = 0; i < MAX_SLOTS && slot < 0; i++)
@@ -750,7 +1006,9 @@ static void dec_acquire(Ctx *c) {
if (!d->qn) { /* (nothing decoded: the buffer's last picture again; after the last submission, as the last) */
d->busy[slot] = 1;
if (d->eos) d->slot_last[slot] = 1, d->slot_pts[slot] = d->last_pts; /* (the end at the last picture's time) */
const int idle = !d->eos && !d->phead; /* (nothing will come into this buffer: its sync is not reached) */
/* (nothing will come into this buffer: its sync is not reached. Nothing submitted, and with a worker nothing in
the decoder or on its way to the queue either, which ahead_wait has waited out) */
const int idle = !d->eos && !d->phead && !d->decoding && !d->uncommitted;
if (idle && ARG(1))
G64(ARG(1)) = SYNC_IDLE_TAG | ((uint64_t)InterlockedCompareExchange64(&submissions, 0, 0) & SYNC_IDLE_MASK);
if (video_log()) hos_log("video: acquire %lld: nothing decoded%s, buffer %d again", (long long)d->acquires,
@@ -766,7 +1024,11 @@ static void dec_acquire(Ctx *c) {
}
{ /* (hookshot) The game takes one picture a frame, and the sound plays on: under 60 fps the movie fell behind its
sound (the intro "slow motion, audio ahead", issues 146 and 179). Pictures behind the movie's clock are skipped:
the next ones decoded, as the whole movie is submitted at once. HOS_VIDEO_NO_CATCHUP=1: as before */
the next ones decoded, as the whole movie is submitted at once. HOS_VIDEO_NO_CATCHUP=1: as before.
(Triforce) With the pictures decoded ahead only queued ones are skipped, down to the newest: nothing is decoded
in the call, the worker decodes on into the room this makes and the next acquires skip what is still behind.
The picture before the last queued one stays while that one's last flag is not settled (tail_unsettled): the
one that goes out is never one the worker has yet to mark */
/* ((Triforce, 11-22, the performance audit's THREAD-82, after Source A's) Decoding ahead to skip had no bound but
the guard below. With a decoder slower than the movie every picture decoded to catch up puts the clock
further ahead, so an acquire decoded hundreds of pictures with the lock held, threw them away, and the next
@@ -777,16 +1039,16 @@ static void dec_acquire(Ctx *c) {
if (off < 0) off = getenv("HOS_VIDEO_NO_CATCHUP") != NULL;
if (unbounded < 0)
unbounded = getenv("HOS_VIDEO_UNBOUNDED_CATCHUP") != NULL && atoi(getenv("HOS_VIDEO_UNBOUNDED_CATCHUP")) != 0;
const int64_t now = hos_now_ns(), late = 25000000; /* (a frame and a half at 60 fps) */
const int64_t now = hos_now_ns(), late = VIDEO_LATE_NS; /* (a frame and a half at 60 fps) */
Picture *h = &d->queue[d->qhead];
if (!d->clock_set || h->pts < d->clock_pts) d->clock_set = 1, d->clock_ns = now, d->clock_pts = h->pts; /* (a start, a loop) */
int skipped = 0;
for (int guard = 0; !off && guard < 600 && !d->queue[d->qhead].last; guard++) {
const int64_t due = d->clock_pts + (now - d->clock_ns);
if (d->queue[d->qhead].pts + late >= due) break;
if (!video_picture_late(d->queue[d->qhead].pts, d->clock_pts, d->clock_ns, now, late)) break;
if (d->qn < 2) {
if (!d->phead) break;
if (d->worker || !d->phead) break;
if (video_catchup_stop(unbounded, video_pace_spacing(&d->pace), d->pace.recent_ns, hos_now_ns() - now)) {
const int64_t due = d->clock_pts + (now - d->clock_ns);
if (video_log())
hos_log("video: the catch-up stops %.2f s behind: a decode takes %.1f ms lately, a picture is due "
"every %.1f ms, and this acquire has decoded for %.1f ms", (double)(due - d->queue[d->qhead].pts) / 1e9,
@@ -797,13 +1059,22 @@ static void dec_acquire(Ctx *c) {
decode_next(d);
continue;
}
if (d->worker && d->qn == 2 && tail_unsettled(d)) break;
picture_free(&d->queue[d->qhead]);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
skipped++;
}
if (skipped && video_log()) hos_log("video: %d pictures skipped to catch up with the movie's clock", skipped);
d->movie.skipped += skipped; /* ((Triforce, 11-22, IO-32) and in the movie's line) */
d->st_skipped += skipped;
}
{ /* ((Triforce) what this acquire waited for its picture: for the worker, or without one its own decoding) */
const int64_t call_ns = d->worker ? waited_ns : d->st_ns - call_ns0;
if (call_ns > d->st_call_max_ns) d->st_call_max_ns = call_ns;
if (call_ns > 0) d->st_waited++;
else d->st_ready++;
}
d->st_taken++;
{ /* (Triforce) and none ahead of it. The game takes the next picture when its count of the movie's 60ths says so
(hos_movie_frames, host/nn_vi.c), and while a movie plays at the 60 cap the frames are paced at 240
(movie_pace.h) and the count follows their time, not the clock: at ~226 fps an opening's picture ran ahead,
@@ -894,8 +1165,21 @@ static void dec_acquire(Ctx *c) {
(unsigned long long)(n ? sum / n : 0), (unsigned long long)(n ? rgb[0] / n : 0),
(unsigned long long)(n ? rgb[1] / n : 0), (unsigned long long)(n ? rgb[2] / n : 0));
}
if (d->st_taken >= 600 || (p->last && d->st_taken)) { /* ((Triforce) what the decoding cost: one line per 600 pictures) */
hos_log("video: %lld pictures taken in %.1f s: %lld decoded in %.1f ms each (the longest %.1f ms), %s; %lld acquires "
"found their picture ready, %lld waited for it, %.1f ms at most in one acquire; %lld skipped to catch up with "
"the movie's clock; the thread's virtual core %s for the call (HOS_VIDEO_KEEP_CORE)",
(long long)d->st_taken, (double)(hos_now_ns() - d->st_since) / 1e9, (long long)d->st_decoded,
d->st_decoded ? (double)d->st_ns / 1e6 / (double)d->st_decoded : 0.0, (double)d->st_max_ns / 1e6,
d->worker ? "decoded ahead by a host thread (HOS_VIDEO_DECODE_AHEAD)" : "in the game's call",
(long long)d->st_ready, (long long)d->st_waited, (double)d->st_call_max_ns / 1e6, (long long)d->st_skipped,
keep_core ? "kept" : "given up");
d->st_since = d->st_taken = d->st_decoded = d->st_ns = d->st_max_ns = d->st_call_max_ns = d->st_skipped = 0;
d->st_ready = d->st_waited = 0;
}
picture_free(p);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
if (d->worker) WakeAllConditionVariable(&d->work); /* ((Triforce) room in the queue: the worker decodes on) */
input_room(d);
ReleaseSRWLockExclusive(&d->lock);
if (away) hos_vcore_back();

View File

@@ -718,7 +718,7 @@ static void mouse_tick_locked(Ctx *c, uint64_t screen) {
if (moved && !hit.hit && !rx_option(HOS_OPT_MODS_SELECTED, 0)) {
const int onto = mods_entry_hit(hit.x, hit.y) ? 1 : quit_entry_hit(hit.x, hit.y) ? 4 : 0;
if (onto) rx_option_set(HOS_OPT_MODS_ENTER, onto);
if (onto && trace) hos_log("menu: mouse (%.0f, %.0f): onto the %s entry", hit.x, hit.y, onto == 1 ? "Mods" : "Quit");
if (onto && trace) hos_log("menu: mouse (%.0f, %.0f): onto the %s entry", hit.x, hit.y, onto == 1 ? "Mods (the title's: Quit Game)" : "Quit");
}
/* hover: the focus to the button under the mouse, only as it moves (the pad keeps the focus it moved) */
int just = 0;
@@ -919,7 +919,12 @@ extern volatile LONG64 hos_present_count; /* (display.c: the game's own presen
static Rect mods_entry; /* (the entry's box, as the renderer draws it: under the last button by the pitch) */
static Rect quit_entry; /* ((Triforce, 11-19) Quit's, under Mods by the pitch; empty on the title's list */
static volatile LONG64 mods_entry_ns;
int hos_save_files_on(void); /* ((Triforce) host/save_files.c: on the title the entry under Mods is Save Select then) */
/* ((Triforce) the owner: "move the mod tab and the save select tab to the top left of the screen ... Add a quit game option
below the Options tab". On the title the entry under the list's last button is Quit Game now, and Mods and Save Select are
tabs at the picture's top left, drawn and clicked in the renderer (gpu/vk/vk_menu.cpp draw_title_tabs, title_tabs.h): the
list last told of was the title's */
static volatile LONG mods_entry_title;
int hos_save_files_on(void); /* ((Triforce) host/save_files.c: the title has its Save Select tab then) */
typedef struct { Rect r[16]; uint64_t b[16]; int n, pause; } ModsList;
static void mods_list_entry(int i, uint64_t entry, uint64_t button, void *arg) {
(void)i, (void)entry;
@@ -1013,6 +1018,12 @@ static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {
Anything but a number from 0 to 1 there: all of it, as before) */
float alpha = 1.0f;
if (!peek(peek64(l.b[last] + 0x58) + 0x78, &alpha, 4) || !(alpha >= 0.0f && alpha <= 1.0f)) alpha = 1.0f;
if (trace && !title) { /* ((Triforce, 11-26) HOS_MENU_TRACE: the System list's buttons' amount as it changes, and its frame: how the
pause menu closes, the owner's Mods and Quit left on the game after it) */
static float told = -1.0f;
if (alpha != told) hos_log("menu: mods entry: the System list's buttons at %.3f (present %lld)", alpha,
(long long)InterlockedCompareExchange64(&hos_present_count, 0, 0)), told = alpha;
}
/* The button's state byte (+56) is its focus animation's: 0 none, 1 coming, 3 focused, 2 going. While Mods has the
cursor the game gets no input (nn_hid.c) and its last button is let go (mods_held, above) */
uint8_t state = 0;
@@ -1044,6 +1055,11 @@ static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {
Mods has the cursor */
int pend = 0;
if (!mods_cursor_button(screen, &pend) && !mods_held.button) {
static int64_t left_told; /* ((Triforce, 11-26) HOS_MENU_TRACE: the game's cursor gone from the System list, once a run of it */
if (trace && !title && now - left_told > 500000000LL)
hos_log("menu: mods entry: the game's cursor left the System list (its buttons at %.3f, present %lld)", alpha,
(long long)InterlockedCompareExchange64(&hos_present_count, 0, 0));
if (!title) left_told = now;
/* ((Triforce, 11-20) the game's buttons are hidden too (Options or the Load list opened over the title: their
alpha goes to 0 on that frame): said, not left to the renderer's 150 ms without a report, so the entry
goes on the frame they do. With the buttons still showing (the cursor between two of them for a frame) it
@@ -1064,14 +1080,10 @@ static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {
const float mx = (r.x0 + r.x1) / 2, my = (r.y0 + r.y1) / 2 - pitch;
mods_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};
}
/* ((Triforce) the title's list has the one entry, Quit Game: Save Select, a pitch under it before, is a tab at the top
left now, as Mods is (hos_oot_title_tabs) */
quit_entry = title ? (Rect){0, 0, 0, 0} : (Rect){r.x0, r.y0 - 2 * pitch, r.x1, r.y1 - 2 * pitch};
/* ((Triforce) on the title, while the save files are on (host/save_files.c), the entry under Mods is Save Select: a line
of the title's list as Mods is one, a pitch lower. Its words are Quit's (3 clicked, 4 the mouse onto it): the renderer
knows by the list which of the two it draws there (vk_menu.cpp files_row_shown) */
if (title && hos_save_files_on()) {
const float mx = (r.x0 + r.x1) / 2, my = (r.y0 + r.y1) / 2 - 2 * pitch;
quit_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};
}
InterlockedExchange(&mods_entry_title, title);
if (alpha >= 0.5f) InterlockedExchange64(&mods_entry_ns, (LONG64)now); /* (the mouse's: an entry not shown yet is not there to click) */
rx_option_set(HOS_OPT_MODS_ALPHA, (int)(alpha * 1000.0f + 0.5f));
rx_option_set(HOS_OPT_MODS_X0, (int)r.x0), rx_option_set(HOS_OPT_MODS_X1, (int)r.x1);
@@ -1095,6 +1107,14 @@ int hos_oot_mods_down(void) {
const LONG64 presents = InterlockedCompareExchange64(&hos_present_count, 0, 0) - InterlockedCompareExchange64(&mods_last_present, 0, 0);
return presents >= 0 && presents <= 1;
}
/* ((Triforce) The title's tabs are there to choose: the title's list was told of with its buttons shown within the last
second (as a click on its entry counts). 0 no; else 1, and 2 too while the save files are on (Save Select is one of them).
nn_hid.c: a test's scripted X or Y there is the tab's; display.c: a left click there is the renderer's to look at */
int hos_oot_title_tabs(void) {
const LONG64 t = InterlockedCompareExchange64(&mods_entry_ns, 0, 0);
if (!t || (LONG64)hos_now_ns() - t >= 1000000000LL || !InterlockedCompareExchange(&mods_entry_title, 0, 0)) return 0;
return 1 | (hos_save_files_on() ? 2 : 0);
}
static int quit_entry_hit(float x, float y) {
const LONG64 t = InterlockedCompareExchange64(&mods_entry_ns, 0, 0);
return t && (LONG64)hos_now_ns() - t < 1000000000LL && quit_entry.x1 > quit_entry.x0 && x >= quit_entry.x0 && x <= quit_entry.x1 &&
@@ -1302,4 +1322,5 @@ int hos_oot_options_front(void) {
has the cursor, so nn_hid.c never keeps a Down from the game. Without it every Linux build of v0.5.0 stopped at the link,
"undefined reference to hos_oot_mods_down" (#bug-tracker, 11-18). tests/test_oot_menu_linux_half.py) */
int hos_oot_mods_down(void) { return 0; }
int hos_oot_title_tabs(void) { return 0; } /* ((Triforce) the title's tabs: the Windows half's too) */
#endif

40
host/res_follow.h Normal file
View File

@@ -0,0 +1,40 @@
/* ((Triforce, 11-26) The Render resolution's scale as the menu applies it, each present (host/nn_vi.c realtime_step), as plain
code: tests/test_res_follow.py compiles it alone.
The owner: "Every option that requires a restart should be changed in game without having to restart". The menu's Render
resolution was read once, at the start; now the host takes the scale the menu has applied (gpu/vk/vk_menu.cpp menu_apply,
options 2 and 3) at each present, and the game's own recompute makes its 3D's targets again at it (nx2/oot_patches.py
APPLY_NEW). One case waits for the next start: where the render targets' pool is held to its size (host/nn_applet.c
hos_rt_pool_pinned: the 900 MB of a picture past 3840 x 2160's pixels, or HOS_RT_POOL_MB set), a 3D larger than any this run
has had. There is no room to spare in that pool, and the old targets and the new ones may be held at once while the game
makes them again; the menu then says the row takes a restart (HOS_OPT_RES_HELD). */
#pragma once
typedef struct {
int scale; /* the scale in force, 1/10000; -1 none yet (the game's 1.0 until the renderer answers) */
int largest; /* the largest 3D this run has had: the first scale, or 7500 from Auto (the dynamic path's own, 3/4) */
int held; /* the scale kept for the next start, 0 none */
} ResFollow;
enum { RES_SAME, RES_TAKE, RES_HOLD, RES_FREE }; /* (res_follow: nothing new; take f->scale; keep asked back; nothing kept back now) */
/* One present: dyn the menu's Auto (1), fixed (0) or not answered yet (-1); asked its scale (0 with Auto, -1 not answered);
pinned hos_rt_pool_pinned's answer (1 held to its size). What to do with the 3D's scale */
static inline int res_follow(ResFollow *f, int dyn, int asked, int pinned) {
if (!f->largest && dyn >= 0) f->largest = dyn ? 7500 : asked > 0 ? asked : 0;
if (asked > 0 && asked != f->scale) {
if (f->scale > 0 && f->largest && asked > f->largest && pinned == 1) {
if (f->held == asked) return RES_SAME;
f->held = asked;
return RES_HOLD;
}
f->held = 0;
f->scale = asked;
if (asked > f->largest) f->largest = asked;
return RES_TAKE;
}
if (f->held && (asked == f->scale || asked <= 0)) { /* (back to the scale in force, or Auto: nothing kept back) */
f->held = 0;
return RES_FREE;
}
return RES_SAME;
}