diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index a33cf37e49..01ae9fd830 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -10,6 +10,17 @@ add_subdirectory(adrenotools) add_subdirectory(thirdparty/dxbc) +# Pin ZeroFG to a fixed revision instead of vendoring thousands of generated shader lines. +include(FetchContent) +set(ZEROFG_VULKAN_HEADERS_DIR "${CMAKE_SYSROOT}/usr/include" CACHE PATH "" FORCE) +set(ZEROFG_PREBUILT_SHADERS ON CACHE STRING "" FORCE) +FetchContent_Declare(zerofg + GIT_REPOSITORY https://github.com/hy300leosquizz-ctrl/ZeroFG.git + GIT_TAG e6ca7ef9f9765db89847b6d8eed352e458f1a8bb + GIT_PROGRESS TRUE +) +FetchContent_MakeAvailable(zerofg) + set(DDFG_UPSTREAM "v0.3.0") set(DDFG_CHAIN_SRC framegen/ddfg/framegen.cpp diff --git a/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md new file mode 100644 index 0000000000..0872e65ca9 --- /dev/null +++ b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md @@ -0,0 +1 @@ +ZeroFG is fetched by CMake from hy300leosquizz-ctrl/ZeroFG (the upstream repository) at pinned commit e6ca7ef9f9765db89847b6d8eed352e458f1a8bb. DroidDeck keeps ownership of presentation; the independent presenter is not used. License: Apache-2.0 OR GPL-2.0-or-later; see the fetched ZeroFG source tree for the license text. diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index ca528afb88..2cd55b2761 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -64,6 +64,7 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, DD-FG Native)") target_sources(droiddeckwayland PRIVATE src/framegen_engine.cpp + src/framegen_zerofg.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp @@ -90,12 +91,12 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../framegen ) target_compile_options(droiddeckwayland PRIVATE - $<$:-std=c++17 -fvisibility=hidden>) + $<$:-std=c++20 -fvisibility=hidden>) target_compile_definitions(droiddeckwayland PRIVATE DDFG_UPSTREAM="${DDFG_UPSTREAM}" DDFG_CHAIN_HASH="${DDFG_CHAIN_HASH}" ) - target_link_libraries(droiddeckwayland dxbc atomic) + target_link_libraries(droiddeckwayland dxbc atomic zerofg::zerofg) else() message(STATUS "droiddeckwayland: frame-generation engines NOT built in (standalone build): stub") target_sources(droiddeckwayland PRIVATE src/framegen_engine_stub.c) diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.c b/app/src/main/cpp/waylandcomp/src/effects_chain.c index a94d7b7906..6d307dcd7d 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.c +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.c @@ -366,6 +366,44 @@ void vkp_effects_forget_image(VkImage img) { g_context = saved; } +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt) { + if (!g_dev || !img || w <= 0 || h <= 0 || fmt == VK_FORMAT_UNDEFINED) return VK_NULL_HANDLE; + + for (int i = 0; i < FX_CONTEXTS; ++i) { + struct fx_context *ctx = &g_contexts[i]; + if (ctx->scene.img == img && ctx->scene.view) return ctx->scene.view; + for (int j = 0; j < 2; ++j) + if (ctx->targets[j].img == img && ctx->targets[j].view) return ctx->targets[j].view; + if (ctx->mid.img == img && ctx->mid.view) return ctx->mid.view; + if (ctx->nissrc.img == img && ctx->nissrc.view) return ctx->nissrc.view; + } + if (g_smaa_edges.img == img && g_smaa_edges.view) return g_smaa_edges.view; + if (g_smaa_weights.img == img && g_smaa_weights.view) return g_smaa_weights.view; + + /* The effects chain can bypass every pass and return the compositor's scene image + * directly. Keep a view for that image in the existing per-context cache so the + * normal image-forget path destroys it before the image itself. */ + int saved = g_context; + g_context = 0; + if (g_scene.img != img || g_scene.view == VK_NULL_HANDLE || + g_scene.w != w || g_scene.h != h) { + scene_release(); + VkImageView view = make_view(img, fmt); + if (!view) { + g_context = saved; + return VK_NULL_HANDLE; + } + g_scene.img = img; + g_scene.view = view; + g_scene.w = w; + g_scene.h = h; + g_scene.ds = VK_NULL_HANDLE; + } + VkImageView result = g_scene.view; + g_context = saved; + return result; +} + void vkp_effects_release_generated_sources(void) { for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release(); g_context = 0; @@ -1026,13 +1064,18 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_ struct fx_source_state source_state = {0}; VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h, VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state); - barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); - if (result != scene) + if (result != scene) { + barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); barrier(cmd, scene, source_state.layout, VK_IMAGE_LAYOUT_GENERAL, source_state.stage, source_state.access, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); + } else if (source_state.layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); + } g_context = 0; return result; } diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.h b/app/src/main/cpp/waylandcomp/src/effects_chain.h index 99f2ad93d5..a0aba31138 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.h +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.h @@ -28,6 +28,7 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_ void vkp_effects_destroy(void); void vkp_effects_forget_image(VkImage img); +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt); void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_is_pq); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index 385475f950..7745c3ddc0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -3,6 +3,7 @@ #include "framegen_engine.h" #include "effects_chain.h" #include "vk_loader.h" +#include "sc_layer.h" #include #include #include @@ -36,7 +37,7 @@ static VkQueue g_queue; static uint32_t g_qfam; static _Atomic int g_dev_ready, g_dev_lost; static int g_features_enabled; -static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok; +static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok, g_caps_zero_ok; static VkPhysicalDeviceMemoryProperties g_memprops; static struct { PFN_vkCreateImage CreateImage; @@ -87,9 +88,44 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +/* The pair the last run made, for the display probe and the pacer: when its real frame reached the + * compositor, the game moment each generated frame shows, and the refresh the pacer timed each for. */ +static _Atomic int g_pacer_on; +static int g_layer_path; +static int g_out_gens; +static int64_t g_out_planned[VKP_FG_MAX_GENERATIONS + 1]; +static int64_t g_completion_issue; + +void vkp_framegen_set_pacer(int on) { + if (atomic_exchange(&g_pacer_on, on ? 1 : 0) != (on ? 1 : 0)) { + fge_pacer_reset(); + FGLOG("ZeroFG pacer %s", on ? "on: frame generation times its frames itself" : "off: the display layer times them"); + } +} + +static int pacer_wanted(void) { return atomic_load(&g_pacer_on); } + +void vkp_framegen_pacer_abort(void) { + g_completion_issue = 0; + fge_pacer_reset(); +} + +void vkp_framegen_output_planned(int k, int gens, int64_t *planned) { + *planned = (k < 0 || k >= gens || k >= g_out_gens) + ? g_out_planned[g_out_gens] : g_out_planned[k]; +} + +void vkp_framegen_completed(void) { + if (!g_completion_issue) return; + fge_pacer_completed(g_completion_issue, now_ns()); + g_completion_issue = 0; +} + +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns) { fge_pacer_shown(planned_ns, shown_ns); } + void vkp_framegen_set_engine(int kind) { - if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG) kind = VKP_FG_ENGINE_LSFG; + if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG && kind != VKP_FG_ENGINE_ZEROFG) kind = VKP_FG_ENGINE_LSFG; atomic_store(&g_kind, kind); atomic_store(&g_failed_kind, -1); atomic_store(&g_cfg_dirty, 1); @@ -118,6 +154,11 @@ void vkp_framegen_set_lsfg_cache_path(const char *path) { pthread_mutex_unlock(&g_lock); } +void vkp_framegen_set_layer_timing(int layer) { + g_layer_path = layer; + fge_set_layer_timing(layer); +} + void vkp_framegen_set_tuning(float flow_scale, float refresh_hz) { if (flow_scale < 0.25f) flow_scale = 0.25f; if (flow_scale > 1.0f) flow_scale = 1.0f; @@ -146,15 +187,15 @@ static void mark_failed(int kind) { int vkp_framegen_problem(void) { if (!atomic_load(&g_dev_ready)) return -1; int kind = atomic_load(&g_kind); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); if (!caps_ok) return 1; if (start_failed_for(kind)) return 2; if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2; return 0; } -const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(); } +const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(atomic_load(&g_kind)); } void vkp_framegen_stats(float out[6]) { float accepted = 0.0f, src = 0.0f, thermal = -1.0f; @@ -187,12 +228,14 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled); atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG)); atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG)); + atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG)); atomic_store(&g_dev_lost, 0); atomic_store(&g_dev_ready, vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier); - FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s", - fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(), - fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable"); + FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s", + fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable"); } void vkp_framegen_device_lost(void) { @@ -283,16 +326,18 @@ static int engine_usable(void) { int kind = atomic_load(&g_kind); int ready = atomic_load(&g_dev_ready); int lost = atomic_load(&g_dev_lost); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); return ready && !lost && caps_ok && !start_failed_for(kind); } int vkp_framegen_format_ok(VkFormat fmt) { - if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; if (!g_dev_ready || g_dev_lost || format_refused(fmt)) return 0; - return fge_format_ok(fmt); + int kind = atomic_load(&g_kind); + if (kind == VKP_FG_ENGINE_ZEROFG) return fge_format_ok(VKP_FG_ENGINE_ZEROFG, fmt); + if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; + return fge_format_ok(kind, fmt); } static void refuse_format(VkFormat fmt, int kind, int w, int h, const char *what) { @@ -377,11 +422,14 @@ static void log_arm_transition(int armed, int kind, int mult) { int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]) { - (void)scene_view; int kind = atomic_load(&g_kind); int armed = atomic_load(&g_armed); int mult = atomic_load(&g_mult); g_planned = 0; + const int64_t issue = now_ns(); + g_out_gens = 0; + memset(g_out_planned, 0, sizeof(g_out_planned)); + g_completion_issue = 0; if (!armed || !engine_usable() || w <= 0 || h <= 0) { log_arm_transition(0, kind, mult); return 0; } if (!ensure_engine(kind)) { log_arm_transition(0, kind, mult); return 0; } log_arm_transition(1, kind, mult); @@ -423,8 +471,31 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, ++g_source_frames; const uint64_t game_frames = droiddeck_game_frames(); - uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate); + const uint64_t planning_sequence = game_frames ? game_frames : g_source_frames; + uint32_t n_gen = fge_plan(g_ring_n, planning_sequence, g_presented_rate); if (n_gen > g_ring_n) n_gen = g_ring_n; + if (kind == VKP_FG_ENGINE_ZEROFG && n_gen > 0 && !scene_view) { + scene_view = vkp_effects_framegen_image_view(scene, w, h, fmt); + if (!scene_view) { + static int view_warning; + if (!view_warning++) FGLOG("ZeroFG could not create a view for the source image; showing real frames only"); + n_gen = 0; + } + } + fge_set_phases(NULL, 0); + if (kind == VKP_FG_ENGINE_ZEROFG && pacer_wanted() && g_layer_path) { + int64_t vsync = 0, period = 0; + sc_layer_timeline(&vsync, &period); + int64_t planned[VKP_FG_MAX_GENERATIONS + 1]; + float phases[VKP_FG_MAX_GENERATIONS + 1]; + const uint32_t count = period > 0 + ? fge_pacer_plan((uint32_t)mult, period, vsync, issue, n_gen, planned, phases) : 0; + if (count >= 1 && count - 1 <= n_gen) { + n_gen = count - 1; + for (uint32_t i = 0; i < count; i++) g_out_planned[i] = planned[i]; + fge_set_phases(phases, n_gen); + } + } g_planned = n_gen; VkImageMemoryBarrier bars[1 + VKP_FG_MAX_GENERATIONS]; @@ -452,21 +523,25 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, nb, bars); - fge_process(cmd, scene, (uint32_t)w, (uint32_t)h, n_gen); + fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen); for (uint32_t g = 0; g < n_gen; g++) { fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h); gens[g] = g_ring[g].img; } if (n_gen) { nb = 0; + const VkAccessFlags generated_access = kind == VKP_FG_ENGINE_ZEROFG + ? VK_ACCESS_MEMORY_WRITE_BIT : VK_ACCESS_SHADER_WRITE_BIT; + const VkPipelineStageFlags generated_stage = kind == VKP_FG_ENGINE_ZEROFG + ? VK_PIPELINE_STAGE_ALL_COMMANDS_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; for (uint32_t g = 0; g < n_gen; g++) bars[nb++] = (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcAccessMask = generated_access, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_ring[g].img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + vk.CmdPipelineBarrier(cmd, generated_stage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, nb, bars); if (!g_generating_logged) { g_generating_logged = 1; @@ -476,6 +551,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : ""); } } + g_out_gens = (int)n_gen; + if (n_gen > 0) g_completion_issue = issue; return (int)n_gen; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h index 573d6fd3c6..3412eda7f1 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h @@ -6,7 +6,7 @@ #endif #include -enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1 }; +enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1, VKP_FG_ENGINE_ZEROFG = 2 }; #define VKP_FG_MAX_GENERATIONS 3 void vkp_framegen_set_engine(int kind); @@ -26,6 +26,18 @@ void vkp_framegen_device_lost(void); int vkp_framegen_active(void); int vkp_framegen_extra_images(void); +/* 1 when the next run's frames are shown through the scene layer's timed group, 0 through the swapchain's FIFO. */ +void vkp_framegen_set_layer_timing(int layer); +/* ZeroFG's pacer (include/zerofg/inline_pacer.h) times the layer's frames instead of the layer's own spacing. */ +void vkp_framegen_set_pacer(int on); +/* Reset pacing history when a planned real-frame pair is aborted before presentation. */ +void vkp_framegen_pacer_abort(void); +/* Refresh planned for output k of the last run (k == gens: its real frame; 0: use layer timing). */ +void vkp_framegen_output_planned(int k, int gens, int64_t *planned); +/* The last run's GPU work finished (the compositor's fence signalled). */ +void vkp_framegen_completed(void); +/* A real frame the pacer timed for planned_ns was shown at shown_ns. */ +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns); int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]); void vkp_framegen_presented(int generated); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp index ed16dd4c88..6f0b6db6b0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -13,6 +14,9 @@ #include "lsfg/lsfg_probe.h" #include "lsfg/lsfg_vkd.h" #include "ddfg/ddfg_engine.h" +#include "framegen_zerofg.h" + +#include #define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__) #define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__) @@ -22,12 +26,17 @@ namespace { VkTable g_table{}; lsfg::Caps g_caps{}; VkPhysicalDeviceVulkan12Features g_v12{}; +VkPhysicalDeviceVulkan13Features g_v13{}; VkPhysicalDeviceFeatures2 g_f2{}; VkPhysicalDevice g_pd = VK_NULL_HANDLE; VkDevice g_dev = VK_NULL_HANDLE; VkQueue g_queue = VK_NULL_HANDLE; uint32_t g_qfam = 0; bool g_probed = false, g_ready = false; +bool g_zero_supported = false, g_zero_enabled = false; +zerofg::InlinePacer g_pacer; +zerofg::InlineReadiness g_readiness; +std::mutex g_pacer_mutex; std::unique_ptr g_lsfg; std::unique_ptr g_ddfg; @@ -88,30 +97,57 @@ const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica if (n) enumExts(pd, nullptr, &n, exts.data()); } g_caps = lsfg::Caps{}; - - - g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); + g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); g_caps.probedFormat = ring_fmt; g_caps.storageOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeStorageFormat(g_table, pd, ring_fmt) : false; g_caps.linearBlitOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeLinearBlit(g_table, pd, ring_fmt) : false; g_probed = true; - if (!g_caps.features.deviceGatesPass()) { + + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + VkPhysicalDeviceVulkan13Features supported13{}; + supported13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + VkPhysicalDeviceFeatures2 supported2{}; + supported2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + if (props.apiVersion >= VK_API_VERSION_1_3) supported2.pNext = &supported13; + if (g_table.GetPhysicalDeviceFeatures2) g_table.GetPhysicalDeviceFeatures2(pd, &supported2); + g_zero_supported = props.apiVersion >= VK_API_VERSION_1_3 && + supported13.synchronization2 == VK_TRUE && + supported2.features.shaderStorageImageExtendedFormats == VK_TRUE; + g_zero_enabled = false; + + const bool lsfg_supported = g_caps.features.deviceGatesPass(); + if (!lsfg_supported) { lsfg::explain(g_caps); ELOG("device gates for the LSFG chain fail: %s", g_caps.reason); + } + if (!lsfg_supported && !g_zero_supported) { + g_v12 = {}; + g_v13 = {}; + g_f2 = {}; return nullptr; } + g_v12 = VkPhysicalDeviceVulkan12Features{}; g_v12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; - g_v12.vulkanMemoryModel = VK_TRUE; + g_v12.vulkanMemoryModel = + g_caps.features.vulkanMemoryModel ? VK_TRUE : VK_FALSE; g_v12.vulkanMemoryModelDeviceScope = g_caps.features.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE; + g_v13 = VkPhysicalDeviceVulkan13Features{}; + g_v13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + g_v13.synchronization2 = g_zero_supported ? VK_TRUE : VK_FALSE; + if (g_zero_supported) g_v12.pNext = &g_v13; + g_f2 = VkPhysicalDeviceFeatures2{}; g_f2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; g_f2.pNext = &g_v12; - g_f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; - g_f2.features.shaderStorageImageExtendedFormats = VK_TRUE; + g_f2.features.shaderStorageImageWriteWithoutFormat = + supported2.features.shaderStorageImageWriteWithoutFormat ? VK_TRUE : VK_FALSE; + g_f2.features.shaderStorageImageExtendedFormats = + supported2.features.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE; return &g_f2; } @@ -122,9 +158,17 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica fill_device(dev); g_caps.featuresEnabled = features_enabled != 0; lsfg::explain(g_caps); + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + g_zero_enabled = g_zero_supported && features_enabled != 0; + zfg_device_ready(gipa, inst, pd, dev, + props.apiVersion > VK_API_VERSION_1_3 ? VK_API_VERSION_1_3 : props.apiVersion, + g_zero_enabled, + g_zero_enabled && g_f2.features.shaderStorageImageExtendedFormats == VK_TRUE); g_ready = true; - ELOG("device ready: lsfg caps '%s', storage on ring format %d", g_caps.reason, - (int)g_caps.storageOnSwapchainFormat); + ELOG("device ready: lsfg caps '%s', storage on ring format %d, ZeroFG %s", + g_caps.reason, (int)g_caps.storageOnSwapchainFormat, + g_zero_enabled ? "available" : "unavailable"); } void fge_device_lost(void) { @@ -149,24 +193,45 @@ void fge_device_lost(void) { g_v12 = {}; g_f2 = {}; g_build[0] = 0; + g_zero_supported = g_zero_enabled = false; + zfg_device_lost(); } int fge_caps_ok(int kind) { if (!g_ready) return 0; + if (kind == 2) return g_zero_enabled && zfg_caps_ok(); if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0; return g_caps.supported() ? 1 : 0; } -const char *fge_caps_reason(void) { return g_caps.reason; } +int fge_engine_available(int kind) { return fge_caps_ok(kind); } -int fge_format_ok(VkFormat fmt) { +const char *fge_caps_reason(int kind) { + if (kind == 2 && !g_zero_enabled) + return "ZeroFG requires Vulkan 1.3, synchronization2 and extended storage-image formats"; + if (kind == 2) return zfg_caps_reason(); + return g_caps.reason; +} + +int fge_format_ok(int kind, VkFormat fmt) { + if (kind == 2) return zfg_format_ok(fmt); if (!g_ready || !g_table.GetPhysicalDeviceFormatProperties || fmt == VK_FORMAT_UNDEFINED) return 0; return lsfg::probeStorageFormat(g_table, g_pd, fmt) && lsfg::probeLinearBlit(g_table, g_pd, fmt) ? 1 : 0; } int fge_start(int kind, const char *cache_path) { fge_stop(); + fge_pacer_reset(); if (!g_ready) return -1; + if (kind == 2) { + if (!g_zero_enabled || !zfg_start()) { + ELOGE("ZeroFG engine init failed"); + return -1; + } + g_kind = 2; + std::snprintf(g_build, sizeof(g_build), "ZeroFG ReallyZero, Vulkan 1.3 Compat"); + return 0; + } if (kind == 1) { auto e = std::make_unique(); if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) { @@ -201,14 +266,16 @@ int fge_start(int kind, const char *cache_path) { } void fge_stop(void) { - if (g_lsfg) { - if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); - g_lsfg.reset(); - } + if ((g_kind == 0 || g_kind == 2) && g_table.DeviceWaitIdle && g_dev) + g_table.DeviceWaitIdle(g_dev); + + g_lsfg.reset(); + for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) { if ((*it)->destroy()) it = g_retained_ddfg.erase(it); else ++it; } + if (g_ddfg) { if (g_ddfg->destroy()) g_ddfg.reset(); else { @@ -216,10 +283,13 @@ void fge_stop(void) { g_retained_ddfg.push_back(std::move(g_ddfg)); } } + + zfg_stop(); g_kind = -1; } int fge_unavailable(void) { + if (g_kind == 2) return zfg_unavailable(); if (g_kind == 1) return g_ddfg && g_ddfg->unavailable() ? 1 : 0; return g_lsfg && g_lsfg->unavailable() ? 1 : 0; } @@ -227,11 +297,13 @@ int fge_unavailable(void) { void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, int model, int perf_preset) { if (multiplier < 2) multiplier = 2; + if (g_kind == 2) { zfg_configure(multiplier, refresh_hz); return; } if (g_kind == 1 && g_ddfg) g_ddfg->configure(multiplier, model, perf_preset, flow_scale); else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz); } int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { + if (g_kind == 2) return zfg_prepare(w, h, fmt); if (g_kind == 1) return g_ddfg && g_ddfg->prepare(w, h, fmt) ? 1 : 0; if (!g_lsfg) return 0; g_lsfg->setGuestExtent(w, h); @@ -239,24 +311,74 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { } uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { + if (g_kind == 2) return zfg_plan(capacity, source_frames); if (g_kind == 1) return g_ddfg ? g_ddfg->plan(capacity) : 0; if (!g_lsfg) return 0; g_lsfg->setPresentedRate(presented_rate); return g_lsfg->plan(capacity, source_frames); } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens) { + if (g_kind == 2) { + zfg_process(cmd, source, source_view, w, h, fmt, sequence, gens); + return; + } if (g_kind == 1) { if (g_ddfg) g_ddfg->process(cmd, source, w, h, gens); return; } if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens); } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { + if (g_kind == 2) { zfg_generate(cmd, g, count, img, view, w, h); return; } if (g_kind == 1) { if (g_ddfg) g_ddfg->generateInto(cmd, g, count, img, view, w, h); return; } if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h); } +void fge_set_layer_timing(int layer) { zfg_set_layer_timing(layer); } + +void fge_set_phases(const float *phases, uint32_t count) { zfg_set_phases(phases, count); } + +float fge_phase(uint32_t index, uint32_t count) { + if (g_kind == 2) return zfg_phase(index, count); + return static_cast(index + 1) / static_cast(count + 1); +} + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + if (period_ns <= 0 || issue_ns <= 0) return 0; + std::lock_guard lock(g_pacer_mutex); + g_pacer.SetMultiplier(multiplier); + g_pacer.ObserveVsync(static_cast(period_ns), static_cast(vsync_ns > 0 ? vsync_ns : 0)); + const uint64_t issue = static_cast(issue_ns); + const zerofg::InlinePacer::Plan plan = + g_pacer.PlanPair(issue, issue + g_readiness.MarginNs(static_cast(period_ns)), max_generated + 1); + for (uint32_t i = 0; i < plan.count; i++) { + present_ns[i] = static_cast(plan.outputs[i].present_ns); + phases[i] = plan.outputs[i].phase; + } + return plan.count; +} + +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { + std::lock_guard lock(g_pacer_mutex); + if (issue_ns > 0 && done_ns > issue_ns) + g_readiness.ObserveCompleted(static_cast(issue_ns), static_cast(done_ns)); +} + +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { + std::lock_guard lock(g_pacer_mutex); + if (planned_ns > 0 && shown_ns > 0) + g_pacer.ObserveRealShown(static_cast(planned_ns), static_cast(shown_ns)); +} + +void fge_pacer_reset(void) { + std::lock_guard lock(g_pacer_mutex); + g_pacer.Reset(); +} + void fge_forget_targets(void) { + if (g_kind == 2) { zfg_forget_targets(); return; } if (g_lsfg) g_lsfg->forgetTargets(); } @@ -266,10 +388,14 @@ void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = (float)g_lsfg->acceptedGenerations(); *source_rate = g_lsfg->sourceRate(); *thermal = (float)g_lsfg->thermalStatus(); + } else if (g_kind == 2) { + zfg_telemetry(accepted, source_rate); } } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { + return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; +} const char *fge_build_info(void) { return g_build; } } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.h b/app/src/main/cpp/waylandcomp/src/framegen_engine.h index d52ce3ffd4..8295a930f3 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.h @@ -16,8 +16,9 @@ void fge_device_lost(void); void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd, VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled); int fge_caps_ok(int kind); -const char *fge_caps_reason(void); -int fge_format_ok(VkFormat fmt); +const char *fge_caps_reason(int kind); +int fge_format_ok(int kind, VkFormat fmt); +int fge_engine_available(int kind); int fge_start(int kind, const char *cache_path); void fge_stop(void); @@ -26,10 +27,22 @@ void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, f int model, int perf_preset); int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt); uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate); -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens); +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens); void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h); void fge_forget_targets(void); +void fge_set_layer_timing(int layer); +/* The phases the pacer chose for the next pair's generated frames (engines that can take any phase). */ +void fge_set_phases(const float *phases, uint32_t count); +/* The phase generated frame [index] of [count] shows. */ +float fge_phase(uint32_t index, uint32_t count); + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases); +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns); +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns); +void fge_pacer_reset(void); void fge_telemetry(float *accepted, float *source_rate, float *thermal); const char *fge_engine_name(int kind); const char *fge_build_info(void); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c index 3d11228577..6dcf3a8d5b 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c @@ -10,9 +10,12 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica (void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled; } void fge_device_lost(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} int fge_caps_ok(int kind) { (void)kind; return 0; } -const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; } -int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; } +const char *fge_caps_reason(int kind) { (void)kind; return "frame-generation engines not built into this compositor"; } +int fge_format_ok(int kind, VkFormat fmt) { (void)kind; (void)fmt; return 0; } +int fge_engine_available(int kind) { (void)kind; return 0; } int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; } void fge_stop(void) {} int fge_unavailable(void) { return 1; } @@ -24,16 +27,28 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void) uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { (void)capacity; (void)source_frames; (void)presented_rate; return 0; } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { - (void)cmd; (void)source; (void)w; (void)h; (void)gens; +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, uint32_t w, uint32_t h, + VkFormat fmt, uint64_t sequence, uint32_t gens) { + (void)cmd; (void)source; (void)source_view; (void)w; (void)h; (void)fmt; (void)sequence; (void)gens; } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { (void)cmd; (void)g; (void)count; (void)img; (void)view; (void)w; (void)h; } void fge_forget_targets(void) {} +void fge_set_layer_timing(int layer) { (void)layer; } +void fge_set_phases(const float *phases, uint32_t count) { (void)phases; (void)count; } +float fge_phase(uint32_t index, uint32_t count) { return (float)(index + 1) / (float)(count + 1); } +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + (void)multiplier; (void)period_ns; (void)vsync_ns; (void)issue_ns; (void)max_generated; (void)present_ns; (void)phases; + return 0; +} +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { (void)issue_ns; (void)done_ns; } +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { (void)planned_ns; (void)shown_ns; } +void fge_pacer_reset(void) {} void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f; } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; } const char *fge_build_info(void) { return "stub"; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_jni.c b/app/src/main/cpp/waylandcomp/src/framegen_jni.c index e5a51456ed..e210597b8f 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_jni.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_jni.c @@ -14,6 +14,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNI vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenPacer(JNIEnv *env, jclass clazz, jboolean on) { + (void)env; (void)clazz; + vkp_framegen_set_pacer(on ? 1 : 0); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLsfgCachePath(JNIEnv *env, jclass clazz, jstring path) { (void)clazz; diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp new file mode 100644 index 0000000000..786c830964 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp @@ -0,0 +1,602 @@ +#include "framegen_zerofg.h" +#include "sc_layer.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define ZFG_LOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) +#define ZFG_ERR(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) + +namespace { +PFN_vkGetInstanceProcAddr g_gipa = nullptr; +PFN_vkGetDeviceProcAddr g_gdpa = nullptr; +VkInstance g_instance = VK_NULL_HANDLE; +VkPhysicalDevice g_physical = VK_NULL_HANDLE; +VkDevice g_device = VK_NULL_HANDLE; +uint32_t g_api_version = VK_API_VERSION_1_0; +bool g_synchronization2 = false, g_extended_formats = false; +bool g_ready = false, g_supported = false, g_failed = false; +char g_reason[160] = "device has not been checked"; + +PFN_vkGetPhysicalDeviceMemoryProperties g_GetPhysicalDeviceMemoryProperties = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties g_GetPhysicalDeviceFormatProperties = nullptr; +PFN_vkCreateImage g_CreateImage = nullptr; +PFN_vkDestroyImage g_DestroyImage = nullptr; +PFN_vkCreateImageView g_CreateImageView = nullptr; +PFN_vkDestroyImageView g_DestroyImageView = nullptr; +PFN_vkGetImageMemoryRequirements g_GetImageMemoryRequirements = nullptr; +PFN_vkAllocateMemory g_AllocateMemory = nullptr; +PFN_vkFreeMemory g_FreeMemory = nullptr; +PFN_vkBindImageMemory g_BindImageMemory = nullptr; +PFN_vkCmdPipelineBarrier g_CmdPipelineBarrier = nullptr; +PFN_vkCmdCopyImage g_CmdCopyImage = nullptr; +PFN_vkDeviceWaitIdle g_DeviceWaitIdle = nullptr; +VkPhysicalDeviceMemoryProperties g_memory_properties{}; + +std::unique_ptr g_interpolator; +VkImage g_history = VK_NULL_HANDLE; +VkImageView g_history_view = VK_NULL_HANDLE; +VkDeviceMemory g_history_memory = VK_NULL_HANDLE; +uint32_t g_width = 0, g_height = 0; +VkFormat g_format = VK_FORMAT_UNDEFINED; +bool g_history_layout_defined = false, g_history_valid = false; +uint64_t g_history_sequence = 0; +bool g_history_recorded_pending = false; +uint64_t g_history_recorded_sequence = 0; +std::array g_fallback_outputs{}; +VkImage g_current = VK_NULL_HANDLE; +VkImageView g_current_view = VK_NULL_HANDLE; +uint64_t g_current_sequence = 0; +bool g_pair_pending = false; + +// Pacing. The compositor presents a pair's generated frames and its real frame back to back in FIFO, +// so they reach the panel on consecutive refreshes right after the tick that drew them. +constexpr uint64_t kBreakNs = 250000000ull; +constexpr size_t kIntervalWindow = 8; +constexpr size_t kMinIntervals = 4; +constexpr double kSlotTolerance = 0.15; +uint32_t g_multiplier = 2; +float g_refresh_hz = 0.0f; +bool g_layer_timing = false; +// The phases the pacer chose for this pair (count 0: none, the timing above decides). +std::array g_external_phases{}; +uint32_t g_external_count = 0; +uint64_t g_last_sequence = 0; +uint64_t g_last_issue_ns = 0; +uint64_t g_pair_interval_ns = 0; +uint32_t g_prev_count = 0, g_pair_count = 0; +std::array g_intervals{}; +size_t g_interval_count = 0, g_interval_next = 0; + +uint64_t now_ns() { + return static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count()); +} + +void reset_pacing() { + g_last_issue_ns = 0; + g_pair_interval_ns = 0; + g_prev_count = g_pair_count = 0; + g_interval_count = g_interval_next = 0; +} + +uint64_t period_ns() { + return g_refresh_hz > 1.0f ? static_cast(1e9 / static_cast(g_refresh_hz)) : 0; +} + +uint64_t typical_interval_ns() { + if (g_interval_count < kMinIntervals) return 0; + std::array sorted = g_intervals; + std::sort(sorted.begin(), sorted.begin() + g_interval_count); + return sorted[g_interval_count / 2]; +} + +void note_sequence(uint64_t sequence) { + if (sequence == g_last_sequence) return; + const uint64_t now = now_ns(); + if (sequence < g_last_sequence) { + // The frame counter changed source (game frames vs compositor scenes): no pair across it. + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); + } else if (g_last_issue_ns && now > g_last_issue_ns) { + const uint64_t interval = now - g_last_issue_ns; + if (interval > kBreakNs) { + reset_pacing(); + } else { + g_pair_interval_ns = interval; + g_intervals[g_interval_next] = interval; + g_interval_next = (g_interval_next + 1) % kIntervalWindow; + g_interval_count = std::min(g_interval_count + 1, kIntervalWindow); + } + } + g_last_sequence = sequence; + g_last_issue_ns = now; +} + +// Generated frames a pair can show without its presents queueing past the next game frame: +// one refresh each, the real frame one more, all inside the game's typical frame interval. +uint32_t pair_capacity(uint32_t wanted) { + const uint64_t period = period_ns(); + const uint64_t typical = typical_interval_ns(); + if (!period || !typical) return wanted; + const double slots = std::floor(static_cast(typical) / static_cast(period) + kSlotTolerance); + return slots < 2.0 ? 0u : std::min(wanted, static_cast(slots) - 1u); +} + +// The scene layer (sc_layer.c) shows a group of [count] generated frames and then B, frame k of the group +// max(k, round(k * gap / (count + 1))) refreshes after the first, a group every game frame interval. +float layer_phase(uint32_t index, uint32_t count, uint64_t period) { + const float even = static_cast(index + 1) / static_cast(count + 1); + int64_t cadence_gap = 0; + int cadence_frames = 0; + sc_layer_cadence_info(&cadence_gap, &cadence_frames); + const uint64_t gap = cadence_gap > 0 ? static_cast(cadence_gap) : typical_interval_ns(); + const uint32_t group_frames = cadence_frames > static_cast(count) + ? static_cast(cadence_frames) : count + 1; + if (!gap) return even; + const int64_t slots = static_cast((gap + period / 2) / period); + if (slots < static_cast(group_frames)) return even; + const auto step = [&](uint32_t k) { + const int64_t s = static_cast((static_cast(k) * gap / group_frames + period / 2) / period); + return std::max(s, k); + }; + const double phase = static_cast(step(index) - step(count) + slots) / static_cast(slots); + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +// FIFO presents the generated group and B back-to-back; phase uses the measured real-frame span. +float pair_phase(uint32_t index, uint32_t count) { + if (g_external_count == count && index < count) return std::clamp(g_external_phases[index], 0.01f, 0.99f); + const float even = static_cast(index + 1) / static_cast(count + 1); + const uint64_t period = period_ns(); + if (!period) return even; + if (g_layer_timing) return layer_phase(index, count, period); + if (!g_pair_interval_ns) return even; + const double span = static_cast(g_pair_interval_ns) + + (static_cast(count) - static_cast(g_prev_count)) * static_cast(period); + if (span <= static_cast(period) * (count + 1)) return even; + const double phase = 1.0 - static_cast(count - index) * static_cast(period) / span; + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +void load_device_functions() { + if (g_gipa && g_instance) { + g_GetPhysicalDeviceMemoryProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceMemoryProperties")); + g_GetPhysicalDeviceFormatProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceFormatProperties")); + } + if (!g_gdpa || !g_device) return; +#define LOAD(name) g_##name = reinterpret_cast(g_gdpa(g_device, "vk" #name)) + LOAD(CreateImage); + LOAD(DestroyImage); + LOAD(CreateImageView); + LOAD(DestroyImageView); + LOAD(GetImageMemoryRequirements); + LOAD(AllocateMemory); + LOAD(FreeMemory); + LOAD(BindImageMemory); + LOAD(CmdPipelineBarrier); + LOAD(CmdCopyImage); + LOAD(DeviceWaitIdle); +#undef LOAD +} + +void clear_history_state() { + g_history_valid = false; + g_history_sequence = 0; + g_pair_pending = false; + g_current = VK_NULL_HANDLE; + g_current_view = VK_NULL_HANDLE; + g_current_sequence = 0; +} + +void destroy_history() { + if (g_device) { + if (g_history_view && g_DestroyImageView) g_DestroyImageView(g_device, g_history_view, nullptr); + if (g_history && g_DestroyImage) g_DestroyImage(g_device, g_history, nullptr); + if (g_history_memory && g_FreeMemory) g_FreeMemory(g_device, g_history_memory, nullptr); + } + g_history = VK_NULL_HANDLE; + g_history_view = VK_NULL_HANDLE; + g_history_memory = VK_NULL_HANDLE; + g_width = g_height = 0; + g_format = VK_FORMAT_UNDEFINED; + g_history_layout_defined = false; + clear_history_state(); +} + +uint32_t find_memory_type(uint32_t bits) { + uint32_t fallback = UINT32_MAX; + for (uint32_t i = 0; i < g_memory_properties.memoryTypeCount; ++i) { + if ((bits & (1u << i)) == 0) continue; + const auto flags = g_memory_properties.memoryTypes[i].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) return i; + if (fallback == UINT32_MAX) fallback = i; + } + return fallback; +} + +bool make_history(uint32_t width, uint32_t height, VkFormat format) { + if (!g_CreateImage || !g_GetImageMemoryRequirements || !g_AllocateMemory || + !g_BindImageMemory || !g_CreateImageView || !g_GetPhysicalDeviceMemoryProperties) { + std::snprintf(g_reason, sizeof(g_reason), "Vulkan image functions unavailable"); + return false; + } + VkImageCreateInfo image_info{}; + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = format; + image_info.extent = {width, height, 1}; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + if (g_CreateImage(g_device, &image_info, nullptr, &g_history) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history image"); + return false; + } + + VkMemoryRequirements requirements{}; + g_GetImageMemoryRequirements(g_device, g_history, &requirements); + const uint32_t memory_index = find_memory_type(requirements.memoryTypeBits); + if (memory_index == UINT32_MAX) { + std::snprintf(g_reason, sizeof(g_reason), "no compatible memory for temporal history"); + destroy_history(); + return false; + } + VkMemoryAllocateInfo allocation{}; + allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = memory_index; + if (g_AllocateMemory(g_device, &allocation, nullptr, &g_history_memory) != VK_SUCCESS || + g_BindImageMemory(g_device, g_history, g_history_memory, 0) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not allocate temporal history memory"); + destroy_history(); + return false; + } + + VkImageViewCreateInfo view_info{}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.image = g_history; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format; + view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (g_CreateImageView(g_device, &view_info, nullptr, &g_history_view) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history view"); + destroy_history(); + return false; + } + g_width = width; + g_height = height; + g_format = format; + g_history_layout_defined = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + clear_history_state(); + return true; +} + +void copy_current_to_history(VkCommandBuffer cmd, VkImage source, + uint32_t width, uint32_t height, uint64_t sequence) { + if (!g_history || !source || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + const bool layout_defined = g_history_layout_defined || g_history_recorded_pending; + before.srcAccessMask = layout_defined ? VK_ACCESS_SHADER_READ_BIT : 0; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = layout_defined ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED; + before.newLayout = VK_IMAGE_LAYOUT_GENERAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = g_history; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, + layout_defined ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &before); + + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, source, VK_IMAGE_LAYOUT_GENERAL, g_history, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion); + + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = g_history; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); + g_history_recorded_pending = true; + g_history_recorded_sequence = sequence; + g_pair_pending = false; +} + +void copy_current_to_output(VkCommandBuffer cmd, VkImage output, uint32_t width, uint32_t height) { + if (!g_current || !output || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + before.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = output; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &before); + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, g_current, VK_IMAGE_LAYOUT_GENERAL, + output, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = output; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); +} +} // namespace + +extern "C" { +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled) { + g_gipa = gipa; + g_instance = instance; + g_physical = physical_device; + g_device = device; + g_api_version = api_version; + g_synchronization2 = synchronization2_enabled != 0; + g_extended_formats = extended_storage_formats_enabled != 0; + g_gdpa = g_gipa && g_instance + ? reinterpret_cast(g_gipa(g_instance, "vkGetDeviceProcAddr")) + : nullptr; + load_device_functions(); + if (g_GetPhysicalDeviceMemoryProperties && g_physical) + g_GetPhysicalDeviceMemoryProperties(g_physical, &g_memory_properties); + g_ready = g_device != VK_NULL_HANDLE; + g_supported = g_ready && g_api_version >= VK_API_VERSION_1_3 && + g_synchronization2 && g_extended_formats; + g_failed = false; + std::snprintf(g_reason, sizeof(g_reason), "%s", g_supported ? "available" : + "requires Vulkan 1.3, synchronization2 and shaderStorageImageExtendedFormats"); +} + +void zfg_device_lost(void) { + g_interpolator.reset(); + destroy_history(); + g_gipa = nullptr; g_gdpa = nullptr; + g_instance = VK_NULL_HANDLE; g_physical = VK_NULL_HANDLE; g_device = VK_NULL_HANDLE; + g_ready = g_supported = g_failed = false; + g_synchronization2 = g_extended_formats = false; + g_api_version = VK_API_VERSION_1_0; + g_GetPhysicalDeviceMemoryProperties = nullptr; + g_GetPhysicalDeviceFormatProperties = nullptr; + g_CreateImage = nullptr; g_DestroyImage = nullptr; + g_CreateImageView = nullptr; g_DestroyImageView = nullptr; + g_GetImageMemoryRequirements = nullptr; g_AllocateMemory = nullptr; + g_FreeMemory = nullptr; g_BindImageMemory = nullptr; + g_CmdPipelineBarrier = nullptr; g_CmdCopyImage = nullptr; g_DeviceWaitIdle = nullptr; + g_memory_properties = {}; + std::snprintf(g_reason, sizeof(g_reason), "device lost"); +} + +int zfg_caps_ok(void) { return g_supported ? 1 : 0; } +const char *zfg_caps_reason(void) { return g_reason; } + +int zfg_start(void) { + if (!g_supported || !g_ready) return 0; + if (g_interpolator) return 1; + zerofg::CreateInfo info{}; + info.vulkan.instance = g_instance; + info.vulkan.physical_device = g_physical; + info.vulkan.device = g_device; + info.vulkan.get_instance_proc_addr = g_gipa; + info.mode = zerofg::Mode::kReallyZero; + info.backend = zerofg::Backend::kCompat; + info.frame_context_count = 4; + info.capabilities.effective_api_version = g_api_version; + info.capabilities.synchronization2_enabled = g_synchronization2; + info.capabilities.shader_storage_image_extended_formats_enabled = g_extended_formats; + zerofg::Status status = zerofg::Status::kSuccess; + g_interpolator = zerofg::Interpolator::Create(info, &status); + if (!g_interpolator) { + std::snprintf(g_reason, sizeof(g_reason), "interpolator creation failed (%d)", (int)status); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + g_failed = false; + ZFG_LOG("ReallyZero engine ready (Compat backend)"); + return 1; +} + +void zfg_stop(void) { + g_interpolator.reset(); + destroy_history(); + reset_pacing(); + g_last_sequence = 0; + g_failed = false; +} +int zfg_unavailable(void) { return g_failed || !g_interpolator ? 1 : 0; } + +int zfg_format_ok(VkFormat format) { + if (!g_supported || !g_GetPhysicalDeviceFormatProperties || format == VK_FORMAT_UNDEFINED) return 0; + VkFormatProperties input{}; + g_GetPhysicalDeviceFormatProperties(g_physical, format, &input); + const VkFormatFeatureFlags sampled = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + if ((input.optimalTilingFeatures & sampled) != sampled) return 0; + if (format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + VkFormatProperties internal{}; + g_GetPhysicalDeviceFormatProperties(g_physical, VK_FORMAT_A2B10G10R10_UNORM_PACK32, &internal); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_BLIT_SRC_BIT; + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT) != 0 && + (internal.optimalTilingFeatures & needed) == needed; +} + +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format) { + if (!g_interpolator || g_failed || !width || !height) return 0; + if (!zfg_format_ok(format)) { + std::snprintf(g_reason, sizeof(g_reason), "unsupported input/output format %d", (int)format); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (g_width == width && g_height == height && g_format == format && g_history) return 1; + if (g_DeviceWaitIdle) g_DeviceWaitIdle(g_device); + destroy_history(); + const zerofg::Status resized = g_interpolator->Resize(width, height, format, format); + if (resized != zerofg::Status::kSuccess) { + std::snprintf(g_reason, sizeof(g_reason), "resize failed (%d)", (int)resized); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (!make_history(width, height, format)) { + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + ZFG_LOG("prepared %ux%u format %d", width, height, (int)format); + return 1; +} + +void zfg_configure(uint32_t multiplier, float refresh_hz) { + g_multiplier = std::clamp(multiplier, 2, 4); + g_refresh_hz = refresh_hz > 1.0f ? refresh_hz : 0.0f; +} + +void zfg_set_layer_timing(int layer) { g_layer_timing = layer != 0; } + +void zfg_set_phases(const float *phases, uint32_t count) { + g_external_count = phases ? std::min(count, static_cast(g_external_phases.size())) : 0; + for (uint32_t i = 0; i < g_external_count; i++) g_external_phases[i] = phases[i]; +} + +float zfg_phase(uint32_t index, uint32_t count) { return pair_phase(index, count); } + +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence) { + if (!g_interpolator || g_failed) return 0; + note_sequence(sequence); + if (!g_history_valid || sequence <= g_history_sequence || !g_pair_interval_ns) return 0; + return pair_capacity(std::min({capacity, 3u, g_multiplier - 1})); +} + +void zfg_telemetry(float *generated, float *source_rate) { + const uint64_t typical = typical_interval_ns(); + *generated = static_cast(g_pair_count); + *source_rate = typical ? static_cast(1e9 / static_cast(typical)) : 0.0f; +} + +void zfg_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations) { + g_pair_pending = false; + g_fallback_outputs.fill(false); + if (!g_interpolator || g_failed || !source || !g_history || + format != g_format || width != g_width || height != g_height) return; + if (sequence > g_history_sequence) { + g_prev_count = g_pair_count; + g_pair_count = generations; + } + if (generations == 0 || !g_history_valid || sequence <= g_history_sequence) { + copy_current_to_history(cmd, source, width, height, sequence); + return; + } + if (!source_view) return; + g_current = source; + g_current_view = source_view; + g_current_sequence = sequence; + g_pair_pending = true; +} + +void zfg_generate(VkCommandBuffer cmd, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, uint32_t width, uint32_t height) { + if (!g_pair_pending || !g_interpolator || !g_history_valid || index >= count || !output || !output_view) return; + const float phase = pair_phase(index, count); + zerofg::Image previous{}; + previous.image = g_history; previous.view = g_history_view; + previous.layout = VK_IMAGE_LAYOUT_GENERAL; previous.format = g_format; + previous.width = g_width; previous.height = g_height; + previous.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + previous.sequence = g_history_sequence; + zerofg::Image current{}; + current.image = g_current; current.view = g_current_view; + current.layout = VK_IMAGE_LAYOUT_GENERAL; current.format = g_format; + current.width = g_width; current.height = g_height; + current.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + current.sequence = g_current_sequence; + zerofg::Image result{}; + result.image = output; result.view = output_view; + result.layout = VK_IMAGE_LAYOUT_GENERAL; result.format = g_format; + result.width = width; result.height = height; + result.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + + const zerofg::Status status = + g_interpolator->Interpolate(cmd, index, previous, current, phase, result); + if (status != zerofg::Status::kSuccess) { + ZFG_ERR("interpolation status %d; copying the real frame as fallback", (int)status); + g_fallback_outputs[index] = true; + copy_current_to_output(cmd, output, width, height); + } + if (index + 1 >= count) { + copy_current_to_history(cmd, g_current, width, height, g_current_sequence); + g_pair_pending = false; + } +} + +void zfg_commit_history_update(void) { + if (!g_history_recorded_pending) return; + g_history_layout_defined = true; + g_history_valid = true; + g_history_sequence = g_history_recorded_sequence; + g_history_recorded_pending = false; +} + +void zfg_discard_history_update(void) { + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; +} + +void zfg_forget_targets(void) { + g_pair_pending = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); +} +} // extern "C" diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h new file mode 100644 index 0000000000..83c9c39e24 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h @@ -0,0 +1,38 @@ +#ifndef FRAMEGEN_ZEROFG_H +#define FRAMEGEN_ZEROFG_H +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled); +void zfg_device_lost(void); +int zfg_caps_ok(void); +const char *zfg_caps_reason(void); +int zfg_start(void); +void zfg_stop(void); +int zfg_unavailable(void); +int zfg_format_ok(VkFormat format); +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format); +void zfg_configure(uint32_t multiplier, float refresh_hz); +void zfg_set_layer_timing(int layer); +void zfg_set_phases(const float *phases, uint32_t count); +float zfg_phase(uint32_t index, uint32_t count); +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence); +void zfg_telemetry(float *generated, float *source_rate); +void zfg_process(VkCommandBuffer command_buffer, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations); +void zfg_generate(VkCommandBuffer command_buffer, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, + uint32_t width, uint32_t height); +void zfg_forget_targets(void); +void zfg_commit_history_update(void); +void zfg_discard_history_update(void); +#ifdef __cplusplus +} +#endif +#endif diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index 3093feb28e..d38cc7ede5 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -58,6 +58,7 @@ static struct { void (*reparent)(ASurfaceTransaction *, ASurfaceControl *, ASurfaceControl *); void (*setOnComplete)(ASurfaceTransaction *, void *, sc_complete_fn); int (*prevReleaseFence)(ASurfaceTransactionStats *, ASurfaceControl *); + int (*presentFence)(ASurfaceTransactionStats *); void (*setFrameRate)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t); void (*setFrameRateStrategy)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t, int8_t); void (*setBufferDataSpace)(ASurfaceTransaction *, ASurfaceControl *, int32_t); @@ -102,6 +103,7 @@ static int load_api(void) { SYM(reparent, "ASurfaceTransaction_reparent"); SYM(setOnComplete, "ASurfaceTransaction_setOnComplete"); SYM(prevReleaseFence, "ASurfaceTransactionStats_getPreviousReleaseFenceFd"); + SYM(presentFence, "ASurfaceTransactionStats_getPresentFenceFd"); SYM(setFrameRate, "ASurfaceTransaction_setFrameRate"); SYM(setFrameRateStrategy, "ASurfaceTransaction_setFrameRateWithChangeStrategy"); SYM(setBufferDataSpace, "ASurfaceTransaction_setBufferDataSpace"); @@ -265,7 +267,33 @@ static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { return target; } +static int64_t g_planned_next_ns; + +void sc_layer_set_planned(int64_t present_ns) { + pthread_mutex_lock(&g_lock); + g_planned_next_ns = present_ns; + pthread_mutex_unlock(&g_lock); +} + +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns) { + pthread_mutex_lock(&g_timeline_lock); + *present_ns = g_timeline_present_ns; + *period_ns = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames) { + if (gap_ns) *gap_ns = g_cadence_gap_ns; + if (group_frames) *group_frames = g_group_frames; +} + static void apply_present_time(ASurfaceTransaction *tx, int game) { + pthread_mutex_lock(&g_lock); + const int64_t planned = game ? g_planned_next_ns : 0; + if (game) { + g_planned_next_ns = 0; + } + pthread_mutex_unlock(&g_lock); if (!api.setDesiredPresentTime) return; pthread_mutex_lock(&g_timeline_lock); const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; @@ -285,6 +313,9 @@ static void apply_present_time(ASurfaceTransaction *tx, int game) { target = cadence_target(now, target, period); } if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + if (planned > 0) { + target = planned; + } api.setDesiredPresentTime(tx, target - period / 2); } @@ -893,7 +924,9 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d int translucent) { struct slot *s = &l->slots[idx]; ASurfaceTransaction *tx = api.txCreate(); - if (!tx) return -1; + if (!tx) { + return -1; + } const int was_shown = l->shown; const int32_t ds_applied = l->ds_applied; const uint32_t md_applied = l->md_applied; @@ -1114,7 +1147,7 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); - if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); vkp_framegen_pacer_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } pthread_mutex_lock(&g_lock); l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; pthread_mutex_unlock(&g_lock); @@ -1136,13 +1169,18 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!have_fd) { first_fd = fd; have_fd = 1; } } if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, 0, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); return -1; } g_group_frames = m + 1; for (int k = 0; k < m; k++) { + int64_t planned; + vkp_framegen_output_planned(k, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[k], r, color, 0) == 0) continue; + vkp_framegen_pacer_abort(); slots_idle(l, idx, k, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; @@ -1151,7 +1189,11 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const } vkp_framegen_presented(m); if (real) { + int64_t planned; + vkp_framegen_output_planned(m, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; g_group_frames = 1; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index b6ecead4a4..a7977378fa 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -4,6 +4,10 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + struct vkp_image; struct vkp_draw; struct droiddeck_color; @@ -51,7 +55,16 @@ void sc_layer_window_gone(void); void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); +/* The refresh the next game-layer frame is timed for, instead of the layer's own spacing (0: the layer's). */ +void sc_layer_set_planned(int64_t present_ns); +/* The display's frame timeline: the next expected present and the refresh period (0 until known). */ +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns); +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); +#ifdef __cplusplus +} +#endif + #endif diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 909eb830d8..ab0d50bea6 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -7,6 +7,7 @@ #include "effects_chain.h" #include "cardboard.h" #include "framegen_bridge.h" +#include "framegen_zerofg.h" #include "hdr_compose.h" #include "blend_pass.h" #include "gpu_busy.h" @@ -2899,6 +2900,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (!(pass && fx)) release_external_client_draws(cmd, draws, n); int ngen = 0; + int history_staged = 0; VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE}; VkImage result = scene_img; int rw = input_w, rh = input_h; @@ -2937,6 +2939,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i 0, 0, NULL, 0, NULL, 1, &b_general); if (fg) { + vkp_framegen_set_layer_timing(0); + history_staged = 1; ngen = vkp_framegen_run(cmd, result, VK_NULL_HANDLE, rw, rh, scene_fmt, gens); if (ngen < 0) ngen = 0; if (ngen > VKP_FG_MAX_GENERATIONS) ngen = VKP_FG_MAX_GENERATIONS; @@ -2962,7 +2966,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i /* Teardown may have retained this frame's pending work, or * acquire may have reported real device loss. Neither permits * a completion-marker submit or another fence wait. */ - if (g_dev_state != 1) return -1; + if (g_dev_state != 1) { + if (history_staged) zfg_discard_history_update(); + return -1; + } droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents); pr = VK_ERROR_OUT_OF_DATE_KHR; break; @@ -2986,6 +2993,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (img >= g_rnd_count || !g_rnds[img]) { droiddeck_log("error", "present: image index %u exceeds semaphore count %u", img, g_rnd_count); + if (history_staged) zfg_discard_history_update(); destroy_swapchain(); return -1; } @@ -2994,12 +3002,17 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i .pCommandBuffers = &g_cmds[k], .signalSemaphoreCount = 1, .pSignalSemaphores = &g_rnds[img]}; VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, last ? g_fence : VK_NULL_HANDLE); if (qr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("submit"); else LOGE("present: submit %d/%d failed (%d)", k + 1, presents, (int)qr); if (g_dev_state != -2) destroy_swapchain(); return -1; } fence_submitted = last; + if (k == 0 && history_staged) { + zfg_commit_history_update(); + history_staged = 0; + } VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &g_rnds[img], .swapchainCount = 1, .pSwapchains = &g_swapchain, .pImageIndices = &img}; @@ -3007,21 +3020,37 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i pr = g_vk.QueuePresentKHR(g_queue, &pi); perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres); if (k < ngen) presented_gen++; - if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } + if (pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break; } if (!fence_submitted) { VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO}; VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (marker != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit"); else quarantine_pending_work(marker, "frame completion submit"); return -1; /* no fence was submitted; never wait on its unsignalled state */ } + if (history_staged) { + zfg_discard_history_update(); + history_staged = 0; + } } VkResult fr = timed_wait(g_fence, UINT64_MAX); - if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } - if (fr != VK_SUCCESS) return -1; + if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } + if (fr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); + return -1; + } vkp_effects_release_generated_sources(); if (fg) vkp_framegen_presented(presented_gen); if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) { @@ -3373,6 +3402,9 @@ static struct { int active; VkImage result; int rw, rh; + /* The layer buffers' size: rw x rh, or the spatial filter's output when it runs on each frame after generation. */ + int ow, oh; + int post_upscale; int ngen; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; @@ -3512,10 +3544,29 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + g_pass.post_upscale = generate && !hf && vkp_effects_active() && vkp_effects_upscaling() && + vkp_effects_prepare_generated() && (mapped_w > input_w || mapped_h > input_h); + if (g_pass.post_upscale) { + static int last_input_w, last_input_h, last_output_w, last_output_h; + if (input_w != last_input_w || input_h != last_input_h || mapped_w != last_output_w || mapped_h != last_output_h) { + droiddeck_log("framegen", "post-upscale on the display layer: interpolate %dx%d, spatial filter each " + "frame to %dx%d", input_w, input_h, mapped_w, mapped_h); + last_input_w = input_w; last_input_h = input_h; + last_output_w = mapped_w; last_output_h = mapped_h; + } + } if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; - g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, - &g_pass.rw, &g_pass.rh); + if (g_pass.post_upscale) { + g_pass.ow = (int)(scene_w * g_map.kx + 0.5f); + g_pass.oh = (int)(scene_h * g_map.ky + 0.5f); + g_pass.result = vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &g_pass.rw, &g_pass.rh); + } else { + g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, + &g_pass.rw, &g_pass.rh); + g_pass.ow = g_pass.rw; + g_pass.oh = g_pass.rh; + } effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); @@ -3530,38 +3581,45 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, &b); + vkp_framegen_set_layer_timing(1); int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); if (ngen < 0) ngen = 0; g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; } g_pass.active = 1; - if (rw) *rw = g_pass.rw; - if (rh) *rh = g_pass.rh; + if (rw) *rw = g_pass.ow; + if (rh) *rh = g_pass.oh; return 0; } static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, int wait_fd) { - if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (!g_pass.active) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; - if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (g_dev_state != 1) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; for (int i = 0; i < n; i++) { if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); + zfg_discard_history_update(); return -1; } const int gpu_wait = take_wait_fd(wait_fd); - if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } + if (gpu_wait < 0) { zfg_discard_history_update(); g_vk.EndCommandBuffer(cmd); return -1; } + const int post_upscale = g_pass.post_upscale && src_layout == VK_IMAGE_LAYOUT_GENERAL; for (int i = 0; i < n; i++) { struct vkp_image *dst = dsts[i]; + VkImage src = srcs[i]; + int sw = g_pass.rw, sh = g_pass.rh; + if (post_upscale) + src = vkp_effects_run_generated(cmd, src, g_pass.rw, g_pass.rh, g_pass.ow, g_pass.oh, i, &sw, &sh); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .srcOffsets = {{0, 0, 0}, {sw, sh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - blit_to_layer(cmd, srcs[i], src_layout, dst, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + blit_to_layer(cmd, src, src_layout, dst, &blit, + (sw == dst->w && sh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); } g_vk.EndCommandBuffer(cmd); @@ -3572,13 +3630,17 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp g_vk.ResetFences(g_dev, 1, &g_fence); VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (qr != VK_SUCCESS) { + zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("layer pass"); else LOGE("layer: effects pass submit failed (%d)", (int)qr); return -1; } + zfg_commit_history_update(); VkResult fr = timed_wait(g_fence, 1000000000ULL); if (fr == VK_ERROR_DEVICE_LOST) { device_lost("layer pass"); return -1; } if (fr != VK_SUCCESS) { LOGE("layer: effects pass fence wait -> %s", vk_result_name(fr)); return -1; } + if (post_upscale) vkp_effects_release_generated_sources(); + vkp_framegen_completed(); return 0; } @@ -3596,6 +3658,7 @@ int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_ima } void vkp_pass_abort(void) { + zfg_discard_history_update(); if (!g_pass.active) return; g_pass.active = 0; if (g_dev_state == 1) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 9f08a424a1..2ae97cfc4f 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -10,11 +10,13 @@ object FrameGen { const val ENGINE_DDFG = "ddfg" private const val LEGACY_ENGINE_WINFG = "winfg" const val ENGINE_LSFG = "lsfg" + const val ENGINE_ZEROFG = "zerofg" private const val DDFG_PERF_PRESET = 2 private const val DDFG_MODEL = 4 private const val FLOW_SCALE_DDFG = 0.60f private const val FLOW_SCALE_LSFG = 0.80f + private const val FLOW_SCALE_ZEROFG = 1.0f val ADAPTIVE_TARGETS = listOf(120, 90, 60) @@ -69,6 +71,14 @@ object FrameGen { .putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply() } + fun pacerEnabled(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("pacer", false) + + fun setPacer(context: Context, enabled: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("pacer", enabled).apply() + WaylandCompositor.nativeSetFrameGenPacer(enabled) + } + fun clearGlobal(context: Context) { context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() .remove("engine").remove("multiplier").remove("target").apply() @@ -80,6 +90,7 @@ object FrameGen { mode.engine == ENGINE_DDFG -> context.getString(R.string.frame_gen_ddfg, mode.multiplier) mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target) mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier) + mode.engine == ENGINE_ZEROFG -> context.getString(R.string.frame_gen_zerofg, mode.multiplier) else -> context.getString(R.string.frame_gen_off) } @@ -104,6 +115,7 @@ object FrameGen { fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? { val mode = prepared.mode + WaylandCompositor.nativeSetFrameGenPacer(pacerEnabled(context)) when (mode.engine) { ENGINE_LSFG -> { val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED @@ -127,6 +139,11 @@ object FrameGen { WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_DDFG, refreshHz) WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) } + ENGINE_ZEROFG -> { + WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_ZEROFG) + WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_ZEROFG, refreshHz) + WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) + } else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) } Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz") diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt index 9e6667a28c..2c7ed785ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -11,6 +11,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource @@ -29,18 +33,22 @@ internal fun FrameGenMenu( onResetGame: () -> Unit = {}, focusModifier: Modifier = Modifier, legacyButtons: Boolean = false, + listLayout: Boolean = false, ) { val need = stringResource(R.string.lsfg_needs_steam) val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF } val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF) val colors = MaterialTheme.colorScheme - val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG") + val context = LocalContext.current + var pacerEnabled by remember { mutableStateOf(FrameGen.pacerEnabled(context)) } + val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG", FrameGen.ENGINE_ZEROFG to "ZeroFG") if (legacyButtons) { val context = LocalContext.current val options = buildList { add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) } + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, it)) } (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) } FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) } } @@ -99,48 +107,85 @@ internal fun FrameGenMenu( ), ) { Text(offLabel) } - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - val focusIndex = engines.indexOfFirst { (engine, _) -> - selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + if (listLayout) { + Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + engines.forEach { (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } } - engines.forEachIndexed { index, (engine, label) -> - val selected = selectedEngine == engine - val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready - val pick = { - onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } else { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val focusIndex = engines.indexOfFirst { (engine, _) -> + selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + } + engines.forEachIndexed { index, (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == focusIndex) focusModifier else Modifier) + .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } } - OutlinedButton( - onClick = pick, - enabled = enabled, - modifier = (if (index == focusIndex) focusModifier else Modifier) - .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, - contentColor = if (selected) colors.primary else colors.onSurface, - ), - ) { Text(label) } } } - if (selectedEngine != null) { - val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready + val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready + if (listLayout) { + Column( + Modifier.fillMaxWidth().padding(top = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + (2..4).forEach { multiplier -> + val selected = mode.multiplier == multiplier && mode.target == 0 + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } + OutlinedButton( + onClick = pickMultiplier, + enabled = multiplierEnabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, + contentColor = if (selected) colors.secondary else colors.onSurface, + ), + ) { Text("${multiplier}×") } + } + } + } else { Row( Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { (2..4).forEach { multiplier -> val selected = mode.multiplier == multiplier && mode.target == 0 - val pickMultiplier = { - onPick(mode.copy(multiplier = multiplier, target = 0)) - } + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } OutlinedButton( onClick = pickMultiplier, enabled = multiplierEnabled, - modifier = Modifier.weight(1f).controllerConfirm( - enabled = multiplierEnabled, - onClick = pickMultiplier, - ), + modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, @@ -151,6 +196,25 @@ internal fun FrameGenMenu( } } + val togglePacer = { + val enabled = !pacerEnabled + FrameGen.setPacer(context, enabled) + pacerEnabled = enabled + } + OutlinedButton( + onClick = togglePacer, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp) + .controllerConfirm(onClick = togglePacer), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (pacerEnabled) colors.primary else colors.onSurface, + ), + ) { + Text("ZeroPacer" + if (pacerEnabled) " ✓" else "") + } + + if (selectedEngine == FrameGen.ENGINE_LSFG) { Row( Modifier.fillMaxWidth().padding(top = 8.dp), @@ -196,6 +260,5 @@ internal fun FrameGenMenu( Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") } } - } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 2fa213d89c..d7d596aa92 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -482,6 +482,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } + LaunchedEffect(host.open) { + if (host.open == "frame-generation") repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request("frame-generation") + if (focus.focused == "frame-generation") return@LaunchedEffect + } + } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -910,24 +917,31 @@ private fun DrawerPerformancePage(host: MenuHost, a: DrawerActions, track: (Stri @Composable -private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { +private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) val scope = if (a.frameGenTargetGameId != null) "${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}" else stringResource(R.string.frame_gen_scope_global) SettingsGroup(stringResource(R.string.frame_gen_title), compact = true, key = "frame-generation", detail = summary(fgLabel, scope)) { - SettingsRow(stringResource(R.string.frame_gen_title), scope, stacked = true, tightControlSpacing = true) { - FrameGenMenu( - a.frameGen, a.lossless, a.onFrameGenPick, - gameProfileId = a.frameGenTargetGameId, - hasGameOverride = a.hasGameOverride, - onResetGame = a.onFrameGenReset, - ) - } + FrameGenMenu( + mode = a.frameGen, + lossless = a.lossless, + onPick = a.onFrameGenPick, + + gameProfileId = a.frameGenTargetGameId, + hasGameOverride = a.hasGameOverride, + onResetGame = a.onFrameGenReset, + focusModifier = track("frame-generation"), + ) } } +@Composable +private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + DrawerFrameGenSettings(host, a, track) +} + @Composable private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 86e5b90601..2cc0ecd638 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -460,12 +460,14 @@ public final class WaylandCompositor { public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12; public static final int WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256; - public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1; + public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1, FG_ENGINE_ZEROFG = 2; public static native void nativeSetFrameGenEngine(int kind); public static native void nativeSetFrameGenArmed(boolean armed, int multiplier, int targetFps); + public static native void nativeSetFrameGenPacer(boolean on); + public static native void nativeSetLsfgCachePath(String path); public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz); diff --git a/app/src/main/res/values/zerofg_framegen.xml b/app/src/main/res/values/zerofg_framegen.xml new file mode 100644 index 0000000000..0f98cf7e8e --- /dev/null +++ b/app/src/main/res/values/zerofg_framegen.xml @@ -0,0 +1,4 @@ + + + ZeroFG %1$d× + diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt index 5afd7f83a9..0eda995f76 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt @@ -30,6 +30,16 @@ class FrameGenTest { assertEquals(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90), FrameGen.mode(context)) } + @Test fun zeroFgModeRoundTrips() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), FrameGen.mode(context)) + } + + @Test fun zeroFgDoesNotKeepAdaptiveTarget() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, multiplier = 4, target = 60)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 4), FrameGen.mode(context)) + } + @Test fun fixedMultiplierReplacesATarget() { FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 120)) FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, 3)) diff --git a/docs/development/framegen-post-upscale.md b/docs/development/framegen-post-upscale.md index 084040d96d..dcec8257f0 100644 --- a/docs/development/framegen-post-upscale.md +++ b/docs/development/framegen-post-upscale.md @@ -50,8 +50,9 @@ feature-level or game compatibility changes. - Compare the same scene on baseline main and this branch: FG off/on, Linear, FSR, GSR, GSR HQ, NIS, FSR Fit, sharpen-only and nearest. -- Test each supported interpolation multiplier, both engines, warm-up/no - generated frames, 720p-to-1080p and 1080p-to-panel scaling, and no upscale. +- Test each supported interpolation multiplier on LSFG, DDFG and ZeroFG, + including warm-up/no generated frames, 720p-to-1080p and 1080p-to-panel + scaling, and no upscale. - Check real and generated frames for consistent sharpness, halos, ghosting, text/cursor artifacts, black bars, stretching and frame-order errors. - Change resolution/filter/engine/multiplier live; open Steam/QAM, rotate, diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index fbbff9271e..38ca6f9f3c 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -31,7 +31,7 @@ class EffectsSourceResolutionTest(unittest.TestCase): 'static int draw_to_scene_blit(', 'static int effects_source_draw(', 'static void effects_source_note(', 'static void effects_overlay_draws(', - 'static int render_impl(', 'static int pass_begin_impl(')) + 'static int render_impl(', 'static int pass_begin_impl(', 'static int pass_finish(', 'int vkp_pass_copy_generated(')) functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' + re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' + function(effects, 'int vkp_effects_upscaling(') + @@ -109,6 +109,9 @@ class EffectsSourceResolutionTest(unittest.TestCase): def test_frame_generation_runs_spatial_post_upscale(self): self.check_case('framegen-upscale') + def test_display_layer_interpolates_before_the_spatial_upscale(self): + self.check_case('framegen-layer-upscale') + TYPES = r''' #include @@ -116,6 +119,7 @@ TYPES = r''' #include #include #include +#include typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer; typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags; typedef uint64_t VkDeviceSize; @@ -179,6 +183,8 @@ typedef struct AHardwareBuffer AHardwareBuffer; STUBS = r''' +static void zfg_discard_history_update(void) {} +static void zfg_commit_history_update(void) {} static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; } static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; } static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; } @@ -214,7 +220,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; +static struct { int active, rw, rh, ow, oh, post_upscale, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -294,6 +300,21 @@ static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int fo return generations; } static void vkp_effects_release_generated_sources(void) {} +static void vkp_framegen_set_layer_timing(int layer) {} +static int g_wait_sem, blit_count, blit_src_w[4], blit_src_h[4], blit_dst_w[4], blit_dst_h[4]; +static VkImage blit_src_images[4], blit_dst_images[4]; +static VkImageLayout blit_layouts[4]; +static int take_wait_fd(int fd) { return fd < 0 ? 0 : fd; } +static void blit_to_layer(int cmd, VkImage src, VkImageLayout layout, struct vkp_image *dst, + const VkImageBlit *blit, VkFilter filter) { + assert(blit_count < 4); + blit_src_images[blit_count] = src; blit_dst_images[blit_count] = dst->image; + blit_layouts[blit_count] = layout; + blit_src_w[blit_count] = blit->srcOffsets[1].x; blit_src_h[blit_count] = blit->srcOffsets[1].y; + blit_dst_w[blit_count] = blit->dstOffsets[1].x; blit_dst_h[blit_count] = blit->dstOffsets[1].y; + blit_count++; +} +static void vkp_framegen_completed(void) {} static VkImage vkp_effects_run_generated(int cmd, int source, int w, int h, int ow, int oh, int slot, int *rw, int *rh) { assert(slot == post_count && slot < 4); @@ -660,6 +681,40 @@ static void check_framegen_upscale(void) { struct vkp_hdr_frame hdr = {0}; run_path(0, &draw, 1, &hdr); assert(post_count == 0); } +static void check_framegen_layer_upscale(void) { + reset(); framegen = 1; generations = 2; + struct vkp_draw draw = fullscreen(); + int rw = 0, rh = 0; + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(effects_count == 1 && output_w == 1280 && output_h == 720); + assert(fg_w == 1280 && fg_h == 720); + assert(g_pass.post_upscale && g_pass.rw == 1280 && g_pass.rh == 720); + assert(rw == 1920 && rh == 1080); + struct vkp_image generated_dst[2] = {{.image = 50, .w = 1920, .h = 1080, .blit_dst = 1}, {.image = 51, .w = 1920, .h = 1080, .blit_dst = 1}}; + struct vkp_image real_dst = {.image = 52, .w = 1920, .h = 1080, .blit_dst = 1}; + struct vkp_image *generated_ptrs[2] = {&generated_dst[0], &generated_dst[1]}; + g_pass.gens[0] = 20; g_pass.gens[1] = 21; g_pass.result = 4; g_pass.ngen = 2; + assert(vkp_pass_copy_generated(generated_ptrs, 2, &real_dst, -1) == 0); + assert(post_count == 3 && blit_count == 3); + assert(post_sources[0] == 20 && post_sources[1] == 21 && post_sources[2] == 4); + for (int i = 0; i < 3; i++) { + assert(blit_src_images[i] == 40 + i); + assert(blit_dst_images[i] == 50 + i); + assert(blit_layouts[i] == VK_IMAGE_LAYOUT_GENERAL); + } + for (int i = 0; i < 3; i++) { + assert(blit_src_w[i] == 1920 && blit_src_h[i] == 1080); + assert(blit_dst_w[i] == 1920 && blit_dst_h[i] == 1080); + } + reset(); framegen = 1; postprocessing = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(!g_pass.post_upscale && rw == g_pass.rw && rh == g_pass.rh); + reset(); framegen = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 0, &rw, &rh) == 0); + assert(!g_pass.post_upscale); +} int main(int argc, char **argv) { assert(argc == 2); reset(); if (!strcmp(argv[1], "helper")) check_helper(); @@ -677,6 +732,7 @@ int main(int argc, char **argv) { else if (!strcmp(argv[1], "postprocessing")) check_postprocessing(); else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening(); else if (!strcmp(argv[1], "framegen-upscale")) check_framegen_upscale(); + else if (!strcmp(argv[1], "framegen-layer-upscale")) check_framegen_layer_upscale(); else assert(0); puts("PASS"); } diff --git a/tools/tests/test_framegen_ring_lifetime.py b/tools/tests/test_framegen_ring_lifetime.py index ca39670844..082edc32ba 100644 --- a/tools/tests/test_framegen_ring_lifetime.py +++ b/tools/tests/test_framegen_ring_lifetime.py @@ -31,6 +31,8 @@ static void destroy_image(int d, int image, const void *a) { static void destroy_view(int d, int view, const void *a) { assert(idle == 1); views++; } static void free_memory(int d, int mem, const void *a) { assert(images > memory); memory++; } static void fge_forget_targets(void) { assert(images == 3); engine++; } +static void vkp_framegen_set_layer_timing(int layer) { (void)layer; } +static void vkp_framegen_completed(void) {} static struct { void (*DeviceWaitIdle)(int); void (*DestroyImage)(int, int, const void *); diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 0bc1bf31ba..be7b2f328a 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -108,6 +108,10 @@ int vkp_framegen_run(VkCommandBuffer c, VkImage s, VkImageView v, int w, int h, return generated; } void vkp_framegen_presented(int n) { ++presented_notifications; } +void vkp_framegen_set_layer_timing(int layer) {} +void vkp_framegen_completed(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {} void vkp_gpu_busy_device_lost(void) {} void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}