Skip to content

vk/textures: parallelize CPU BC1-BC7 and BC1->ASTC decode on BC-less GPUs - #531

Merged
mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:feat/vk-bc-parallel-decode
Nov 24, 2026
Merged

mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:feat/vk-bc-parallel-decode

Conversation

@Propinbo

Copy link
Copy Markdown
Contributor

Problem

On mobile GPUs that lack native BC1–BC7 texture compression (such as Mali), textures.c decodes BC textures on the CPU during upload (bcdec for BC2–BC7/fallback and bc1_to_astc for BC1→ASTC 4×4). Previously this decoding ran single-threaded on the render thread, causing up to ~1.2 s CPU decode spikes during scene loads and ~50–230 ms hitches when streaming new area/object textures during camera movement.

Changes

  1. Persistent dynamic work-stealing pool (runtime/nvn/vulkan/bc_parallel.h):
    • Added a single-owner worker pool (VkBcPool) using atomic chunk draining (_Atomic uint64_t next, target threads * 16 chunks with per-task min_chunk floors of 2 block-rows for bcdec and 256 blocks for bc1_to_astc) to avoid tail stalls across heterogeneous big.LITTLE/dynamically-clocked cores.
    • Split thresholds (vk_bc_parallel_should_split) leave small textures inline (blocks >= 512 && hb >= 4 for BC6H/BC7, blocks >= 2048 && hb >= 4 for BC1–BC5, blocks >= 4096 for BC1→ASTC) so small uploads incur zero synchronization overhead.
    • Safe init/spawn failure fallbacks (init_failed, spawn_failed), generation tracking per worker (start_gen), and clean full-struct reset on vk_bc_pool_destroy.
  2. Non-little worker placement & render-pin unpinning (runtime/nvn/vulkan/bc_parallel.h, runtime/platform/android.c):
    • Workers name themselves vk-bc, restore the pre-pin process affinity via plat_thread_unpin() (updated plat_render_thread_pin() to save pre-pin g_all_cores atomically so workers created lazily on render_main in low-RAM / RAM saving / LARECOMP_RENDER_BIG=1 configs do not inherit a 1–2 core pin), and exclude the slowest core tier only when >= max(3, threads) faster cores remain in the allowed mask.
  3. Render-thread integration, watchdog & env controls (runtime/nvn/vulkan/textures.c, watchdog.h, watchdog.c):
    • Wrapped parallel waits in a dedicated watchdog stage (WD_R_BC_DECODE: "waiting for parallel BC texture decode").
    • Guarded wb * 4 * bpp against INT_MAX pitch overflow before 64-bit row offsets in bc_decode_rows().
    • Enabled 4 worker threads by default when bc_cpu_device() is true (!g_vk.phys, missing hardware BC1/BC7, or LARECOMP_NO_BC), logged once at first parallel-eligible decode, with env rollback (LARECOMP_NO_BC_PARALLEL=1 for 1T; LARECOMP_BC_THREADS=<1-8> override).
  4. Tests (tools/test_bc_parallel.c, tools/test_bc_shadow.c, tools/test_android_runtime.ps1):
    • Added Bionic/host tests covering env parsing, split thresholds, chunk sizing, concurrent coverage across 1..8 threads, 10× destroy/reuse stress, affinity tier selection, bit-exactness against 1T across all 12 BC formats + BC1→ASTC across odd and power-of-2 sizes, and multi-thread speedups.
    • Separated vk_readback()'s scratch buffer from vk_transient()'s staging in tools/test_bc_shadow.c to avoid test-harness buffer aliasing on 2048x16 shadow resolves.

Zero-Cost Guarantee & Non-Target GPUs

  • Everything in bc_parallel.h / textures.c parallel decode is guarded under #ifdef __ANDROID__ — desktop builds have zero code changes.
  • On Android GPUs with hardware BC support (Adreno/Turnip without LARECOMP_NO_BC), b->bc_vf remains VK_FORMAT_UNDEFINED, so neither bc_decode nor bc_upload_blocks executes, zero vkGetPhysicalDeviceFormatProperties calls occur, and zero worker threads are spawned.
  • Rollback / tuning: LARECOMP_NO_BC_PARALLEL=1 disables parallel decode cleanly; LARECOMP_BC_THREADS=1..8 overrides thread count.

Verification (Exact Final Commit 122e11e9fdb5af850fe0b59fce3915bec17acdd7)

Environment

  • Device: Samsung Galaxy Tab S11 (SM-X730), SoC MT6991 (Dimensity 9400+: 4× A720 + 3× Cortex-X4 + 1× Cortex-X925), Android 16 (API 36)
  • GPU / Driver: Mali-G925-Immortalis MC12 - v1.r49p1-03bet0.f8a98b506b89b21c80a508d70abfcb3f
  • Game / Base: BOTW 1.9.0 (native), stacked cleanly on v0.4.10-beta (1c02adf9)
  • Signed Release APK SHA-256: 475714955e2636174e4fd2fcef4bbd0e334abab7f7027a317f20fcc6afb3c84c (0 compiler warnings in touched files)

Tested vs. Untested Matrix

Target / GPU Status Notes
Mali-G925 (r49p1, SM-X730) Tested (commit 122e11e9) Bionic 9/9 + 3-scene cap30 A/B + post-teleport visual check
Adreno / Turnip (VK_FORMAT_BC* supported) Verified by inspection / b->bc_vf guard bc_upload_blocks unreachable without LARECOMP_NO_BC; zero threads spawned; not runtime-tested on hardware this run
Older Mali < r49 / Xclipse / 4+4 / 2+6 Affinity logic unit-tested vk_bc_select_fast_cpus unit-tested on 4+4, 2+6, 1+3+4, homogeneous; on-device tested on 1+3+4 only
Desktop (#ifndef __ANDROID__) Syntax-checked (-U__ANDROID__) -fsyntax-only -Wall -Wextra clean on test_bc_parallel.c; desktop builds skip #ifdef __ANDROID__ decode path

Unit & Regression Tests (tools/test_android_runtime.ps1 + NDK Clang)

  • tools/test_android_runtime.ps1 on SM-X730: 9/9 Bionic tests passed (test_kernel_affinity, test_bc_shadow, test_buffer_copy, test_rt_load_upload, test_cbwin_snap, test_nvn_lifetime, test_object_cache, test_benchmark_trace, test_bc_parallel), 0 warnings in modified files:
    • BC7 512x512 (128x128 blocks): 1T 1.22 ms vs 4T 0.97 ms (1.26×)
    • BC7 1024x1024 (256x256 blocks): 1T 5.29 ms vs 4T 3.73 ms (1.42×)
    • BC1->ASTC 1024x1024 (256x256 blocks): 1T 18.68 ms vs 4T 6.04 ms (3.09×)
  • Multi-target -fsyntax-only -Wall -Wextra (test_bc_parallel.c): 0 warnings across aarch64-linux-android30, armv7a-linux-androideabi30, -U__ANDROID__, and -U__ANDROID__ -U__linux__.

In-Game Isolated A/B (cap30, screen 75% SGSR1, shadows=1, inplace_reads=1, warm cache 10401 .spv)

Both arms started from an identical warm cache snapshot (SKIN=36.5C, TS=0):

  • Arm A (1T baseline via LARECOMP_NO_BC_PARALLEL=1): [vk] parallel BC CPU decode: 1 thread (LARECOMP_NO_BC_PARALLEL) (passport.commit = 122e11e9fdb5)
  • Arm B (4T driver default, no BC env vars): [vk] parallel BC CPU decode: 4 threads (driver default) (passport.commit = 122e11e9fdb5)
Scene (status=ok both arms) Metric Arm A (1T) Arm B (4T default) Delta
All 3 scenes combined (5,031 vs 5,071 frames) Total bc_decode_ns (ms) 9,369.58 ms 3,618.61 ms 2.59× faster (-61.4%, -5.75 s)
Peak single-frame bc_decode 1,244.51 ms 397.72 ms 3.13× reduction
Frames with bc_decode > 50 ms (all / camera) 24 / 6 14 / 0 0 camera spikes >50 ms
plateau (load_s + camera_s) Load/camera wall time 18.3s + 8.0s 17.3s + 7.6s -1.4s load+cam
Load/cam bc_ms sum (cam max) 3,975.81 ms (92.38 ms) 1,487.16 ms (19.92 ms) 2.67× (cam peak 4.64×)
Window display_fps / 1% low / gpu p50 / render p50 30.02 / 23.95 / 27.42 / 17.50 30.00 / 23.98 / 27.32 / 18.20 Neutral steady-state
zora-plaza (load_s + camera_s) Load/camera wall time 17.7s + 6.2s 16.9s + 6.1s -0.9s load+cam
Load/cam bc_ms sum (cam max) 2,591.24 ms (102.73 ms) 1,068.43 ms (21.17 ms) 2.43× (cam peak 4.85×)
Window display_fps / 1% low / gpu p50 / render p50 30.02 / 23.04 / 27.41 / 18.59 30.00 / 26.04 / 27.50 / 18.72 disp_p99 41.74 -> 33.44 ms
kakariko-day (load_s + camera_s) Load/camera wall time 17.6s + 6.9s 16.4s + 6.4s -1.7s load+cam
Load/cam bc_ms sum (cam max) 2,801.36 ms (228.15 ms) 1,051.15 ms (48.51 ms) 2.67× (cam peak 4.70×)
Window display_fps / 1% low / gpu p50 / render p50 30.02 / 23.97 / 27.69 / 20.12 30.00 / 22.19 / 27.90 / 20.08 Neutral steady-state

Honest note: Once scene textures are resident, steady-state window frames perform 0.00–0.01 ms of CPU BC decoding, so steady-state window FPS stays neutral at 30.00 fps; all decode gains occur during cold boots, scene streaming, teleports, and camera sweeps (4.64×–4.85× lower camera-phase peak decode hitches, 2.59× faster overall).

Teleport Visual Check & Evidence Branch

  • Live Great Plateau -> Shrine of Resurrection teleport run under default 4T ([vk] parallel BC CPU decode: 4 threads (driver default)) completed with 0 errors, 0 watchdog stalls, and clean BC textures verified visually in pre/post PNG screenshots (pre_tp1.png / post_tp1.png).
  • Evidence files (CODE_REVIEW.md, ab_summary.json, ArmA_1T_report.json, ArmB_4T_default_report.json, pre_tp1.png, post_tp1.png) are archived on orphan branch evidence/pr-bc-parallel-decode-20261121 (6df6519).

Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 21, 2026

@mamcjr mamcjr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The pool logic looks right to me: remaining = active-1 matches the workers, the owner drains too, the generation counter prevents stale wakeups, and both callers of bc_upload_blocks are on the render thread. On the POCO (native BC) nothing runs, and no threads start.

Before merging:

  1. plat_render_thread_pin() (android.c) now changes more than BC. It saves g_all_cores and sets g_pinned when nothing pinned first. From then on, every thread that calls plat_thread_unpin() restores that mask: dispatch.c, kernel.c, hle/vi.c and async.c, Adreno included, on low-RAM devices or with LARECOMP_RENDER_BIG=1. On main that call does nothing in that case. It may be the right fix, but it isn't BC-only. Also, pin_to_fastest_cores() still rewrites g_all_cores without checking g_pinned, so if it runs after the render pin another thread can read a half-written cpu_set_t. Could you guard that write too, or move this part to its own PR?

Smaller ones:

  • The 4-thread default doesn't depend on the core count. On a 4+4 phone vk_bc_select_fast_cpus returns 0 and the workers run on the little cores too. Maybe min(4, big cores)?
  • bc_decode_rows returns silently when pitch64 > INT_MAX, leaving the staging buffer as garbage. A log once would help.
  • WD_R_BC_DECODE is inserted mid-list in watchdog.h, which renumbers the later stages. Fine unless a tool reads those numbers.

@Propinbo

Propinbo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto v0.4.12-beta (79ba1909, commit 3abb640) and addressed all four review items:

  1. Removed runtime/platform/android.c changes completely (git diff upstream/main...HEAD -- runtime/platform/android.c is empty):

    • Instead of mutating global g_pinned / g_all_cores or pin_to_fastest_cores(), vk_bc_effective_affinity() in runtime/nvn/vulkan/bc_parallel.h reads both thread and process masks and recovers the wider process cpuset via sched_getaffinity(getpid(), ...) under a strict superset check ((pid_mask & mask) == mask && pid_mask != mask), while worker threads adjust only their own affinity locally.
  2. Scaled default worker count to big-core topology (min(4, big cores)):

    • Updated vk_bc_default_threads() in runtime/nvn/vulkan/bc_parallel.h to return min(4, big cores) when heterogeneous frequencies are present (falling back to min(4, allowed cores) when frequencies are uniform or n_fast < 2, and vk_bc_popcount64() when cpufreq is unavailable), while preserving LARECOMP_BC_THREADS=N and LARECOMP_NO_BC_PARALLEL=1.
  3. bc_decode_rows() pitch overflow logging:

    • Added a one-shot atomic log ([vk] bc_decode_rows: pitch overflow (wb=%u bpp=%u)) when pitch64 > INT_MAX in runtime/nvn/vulkan/textures.c, covered directly in tools/test_bc_shadow.c.
  4. WdStage enum ordering in watchdog.h:

    • Moved WD_R_BC_DECODE to the end of enum WdStage immediately before WD_STAGES in runtime/nvn/vulkan/watchdog.h (and watchdog.c) so earlier stage numbers remain unchanged.

Verified after the final edit on 3abb640:

  • Android NDK Clang (aarch64 & armv7a, -Werror) & Desktop -Werror: PASS (0 new warnings); python -B tools/test_soft_linear.py: PASS (23+3+203).
  • Native Bionic tools/test_android_runtime.ps1 on SM-X730: 9/9 PASS (test_bc_shadow pitch overflow PASS), plus standalone Bionic test_bc_parallel (-Wall -Wextra -Wno-unused-function -Werror): PASS (512x512 1.77x, 1024x1024 1.29x, ASTC 2.87x, cpus[4..7], test_pinned_render_thread_recovery PASS).
  • 2/2 independent pre-PR code reviews (READY, 0 CRITICAL / 0 MAJOR) and workspace_check.py pr: PASS (commits=1, files=7, mergeable=YES).

@Propinbo
Propinbo force-pushed the feat/vk-bc-parallel-decode branch from 122e11e to 3abb640 Compare November 24, 2026 14:11
@mamcjr
mamcjr merged commit 5b78b37 into mamcjr:main Nov 24, 2026
mamcjr added a commit that referenced this pull request Nov 24, 2026
…t on Mali r49+)

Conflict in tools/test_android_runtime.ps1 with #531: both test lists kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mamcjr

mamcjr commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Merged, thanks! All four points addressed, and nothing changes on Turnip. It's in 0.4.13-beta.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants