Fix audio for Unity/FMOD titles: thread priority, AudioOut2 grain and port table #147
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!147
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/147/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@StefanosCosta on GitHub · 2026-08-01 13:50 UTC · original
StefanosCosta:main→main· +481 −79 · 8 files · 4 commits · closed without mergingSummary
No Unity/FMOD title produced any sound. The Sony-side audio calls all reported success — a real
SDL device opened, handles were valid, the codec was supported — and FMOD tore the whole stack
down anyway, spawning no mixer thread and loading no sound bank.
The root cause was not in the audio layer at all: scePthreadAttrSetschedparam rejected the
thread priorities FMOD asks for, so FMOD abandoned thread creation. This fixes that, then the
output-pacing and AudioOut2 bugs that were behind it.
Windows behaviour is unchanged: the priority fix is confined to the non-Windows arm of an
existing platform guard, and the remaining changes are platform-independent.
What's included
Thread priority — the root cause
the host rejected the mapped priority. PthreadAttrSetschedpolicy hardcodes SCHED_OTHER,
under which glibc accepts only sched_priority 0, so the +2/0/−2 mapping was refused for
anything outside the middle band.
thread creation fails. Unity's ordinary workers ask for 700, mapped to 0, and were accepted —
which is why everything else worked and only audio died.
guest asked for a priority the host cannot honour under this policy, which is not the same as
an invalid request.
guest set instead of reconstructing it from the clamped host value and collapsing every
priority to 767/256/700.
path is untouched.
Output pacing
last_output_time + block_time before every submit, pinning submission to exactly 1× realtime,
so QueueSdlAudio's queue-depth backpressure never engaged and a cushion could never
accumulate. Measured 96.6% underruns.
wall-clock sleep is dropped and QueueSdlAudio provides the backpressure. The sleep is kept
for ports with no device (a failed open, or a vibration port), where nothing else would pace
the guest.
sixteen, rather than a fixed queue_size * 2 — so it no longer depends on the guest's buffer
size. Raising the fixed multiple alone had no effect, because the sleep was the binding
constraint.
AudioOut2
8-channel float32 — 8192 bytes — per push. Sizing the read as grain × channels × 4 gave
32768 bytes, four times the payload, dragging in 24 KB of unrelated process memory. Audible
as static.
followed by the format the context runs at; callers reading the wrong offsets saw
channels = 256, frequency = 0 and rejected the context. sceAudioOut2ContextQueryMemory now
fills a descriptor rather than writing a bare size_t.
value.
silently skipping the device open.
unresolved-import thunk, which returns 0 by luck, so there was no visible failure.
AudioOut2 port table
ever created this session" with "ports currently open". The 257th create of a session failed
permanently with all 256 slots free; a title that opens and closes ports as sounds come and go
would lose audio partway through, silently and unrecoverably. Capacity is now decided solely by
whether a slot is free.
AudioOutOpen, then re-took it to write the entry — with nothing marking the slot taken in
between. Two concurrent creates could select the same entry; the loser's already-opened device
became unreachable from any port and could never be closed. The slot is now reserved while the
lock is held, and the reserved-but-unfilled window is safe because the mixer requires
audio_handle > 0 && pcm_data != nullptr, both still zero.
FMOD compatibility shim
before Unity applies the startup output configuration, so FMOD Studio skips its real core init:
no mixer thread, no bank loading. Clearing that marker in setOutput, while recording the
requested output, lets Studio run the real init.
unusual for this codebase. RuntimeLinker::Resolve checks the host symbol database before
scanning guest module exports, so registering the NID is enough to take priority.
this shim — not the Sony audio layer — is the first thing to suspect.
sceKernelSyncOnAddress
six-argument signature that never read the word, never blocked on a wait queue, never woke
anything, and always returned success. Wait did not wait and wake did not wake, and callers
were told their condition was satisfied when it was not.
address, EAGAIN when the word already differs from the pattern, and otherwise parks on an
address-keyed bucket honouring the optional timeout. Wake broadcasts on that bucket; buckets
are shared between addresses so count cannot be honoured exactly, which is harmless because
every waiter re-checks its own word.
previously served by a function that did nothing.
during the same investigation.
Direct memory is never zeroed on allocation
allocation could read the bytes of whatever previously owned that range. The backing store is a
single object indexed by physical address, and UnmapBacking deliberately never clears it — that
is what lets direct-memory contents survive unmap/remap, and KernelMapDirectMemory documents
the requirement. Allocation was therefore the only point at which a range could be cleared, and
nothing did it. FlexibleMemory::Map has always called ZeroBacking for exactly this reason;
direct memory never got the equivalent.
The zeroing is done at allocation rather than at map time, so map/unmap/remap of an
already-allocated range still preserves its contents and the aliasing invariant is untouched.
The pool-expansion path had the same gap and is fixed alongside it.
This is a memory-correctness bug, not an audio one. Any subsystem reading direct memory before
writing it was exposed; audio is simply where it was noticed.
Subnautica lost all audio permanently a short way into gameplay, and buzzed painfully
underwater. FMOD read a buffer before writing it and loaded stale NaN-shaped bytes — the guest
heap is full of 0xffffffff, and 0x7fffffff, the payload seen in the dead mix, is exactly that
with the sign bit cleared by the standard SSE absolute-value mask. A NaN loaded from memory
propagates through FMA chains without raising any floating-point exception, so it entered the
DSP state silently and every later block was NaN × x = NaN. The mix buffer then held 512 NaN
samples in every 2048 for the rest of the process.
PowerWash Simulator's buzz has the same cause and is also fixed. That artifact was previously
localised to the guest's own buffer with no explanation of how it got there; stale bytes from a
prior allocation is how.
Intermittent by nature: it needs an allocation to land on a previously-used range whose stale
contents happen to be NaN-shaped, which is why it struck anywhere between 45 s and 229 s into a
session and why two consecutive clean runs were not evidence of a fix.
Unrelated fidelity fixes found along the way
None of these fix the above; the clock change in particular was bisected and refuted as a
cause, and Subnautica calls no unresolved imports at all.
sceKernelGettimeofday truncated to milliseconds on Linux. It went through
DateTime::FromSystemUTC, which keeps only whole milliseconds, then round-tripped the result
through a double of roughly 1.75e9 seconds. It now reads clock_gettime(CLOCK_REALTIME)
directly, giving the microsecond resolution the real API has. The Windows branch, which already
used GetSystemTimePreciseAsFileTime, is untouched.
sceRtcGetCurrentTick had the same millisecond truncation while sceRtcGetTickResolution
already advertised 1 µs to the guest. The tick is now derived from a single microsecond
reading anchored on the existing RTC_UNIX_EPOCH_TICKS constant, so the calendar and sub-second
parts cannot disagree across a second boundary.
The unresolved-import thunk restored the caller's xmm0 and returned, so a float-returning
unresolved import handed the guest back its own first floating-point argument. It now clears
xmm0 on the fall-through path, matching the integer return that was already zeroed.
Unresolved-import logging now reports the first call per symbol rather than the first 1024
calls overall, so a single hot stub can no longer exhaust the budget and hide every other
unresolved import.
Testing
Proven causal by bisect on the same binary: with the zeroing disabled the failure returns at
61 s with the original signature; with it enabled the same session ran 248 s clean, and an
earlier variant ran 511 s. Six recorded failures before the fix fell between 45 s and 229 s.
Subnautica: audio survives sustained movement, water transitions and scene changes, with no
NaN in any of 437 measured one-second windows and no trace of the underwater buzz.
PowerWash Simulator: buzz gone, healthy 8-channel mix.
Cat Quest III and Dreaming Sarah: no regression — full-rate submission, no drops, no underruns
beyond ordinary jitter.
Note that Dreaming Sarah has a pre-existing visual defect, floor tiles alternating between
correct and broken and benches failing to render. It reproduces identically on stock HEAD with
every change here reverted, and is unrelated.
Tests
game — no available title churns ports — so both needed a direct test. It compiles
libAudio2.cpp plus loader/timer.cpp and stubs the audio backend and kernel clock, so it
needs no SDL and no Vulkan device and builds in seconds.
concurrent creates never return the same handle — passed 20/20 against the bug, because handles
come from an atomic counter and are unique whether or not two threads share a slot. The test
instead asserts entry reachability and device open/close balance, which fail 20/20 against the
defect and pass 30/30 against the fix.
Platform impact
#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS, leaving the original EINVAL return in place
there; winpthreads does not validate priority against policy, so Windows never hit the failure.
The AudioOut2, port-table, BedWrite and sceKernelSyncOnAddress changes are
platform-independent.
backend SDL actually selected and the period size it granted, since SDL falls back through its
driver list silently.
Not addressed here
Testing
Built on Linux with Clang/Ninja, both with and without KYTY_ENABLE_HLE_TRACE. Cat Quest III, Subnautica, Cult of the lamb, Jack & Joe Caveman Ninja, Minecraft and Dreaming Sarah confirmed audible on hardware output. ctest -R audio_out2_port passes, 11 checks.
@StefanosCosta on GitHub · 2026-08-01 23:48 UTC · original
Some games listed as having been used for testing don't work on current main. I decided to split performance/deadlocks/blockers and sound into 2 PRs, so performance changes and fixes will come after this PR is merged.
@Nmzik on GitHub · 2026-08-02 01:35 UTC · original
@StefanosCosta Thanks for finding these bugs, especially the unknown sceKernelSyncOnAddress NIDs (Hc4CaR6JBL0 and q2y-wDIVWZA) and the audio. I’ll cherry-pick the commits one at a time.
@StefanosCosta on GitHub · 2026-08-02 01:53 UTC · original
Hi there @Nmzik ! Happy to be here! Best way to prove the second commit is to only have first commit and go in-game on free play on powerwash simulator. Don't wear headphones because the buzz is quite loud and obnoxious! Once the second commit is added the buzz should be gone :).
@Nmzik on GitHub · 2026-08-02 03:23 UTC · original
@StefanosCosta Thanks again.
Bugs:
@StefanosCosta on GitHub · 2026-08-02 04:15 UTC · original
Hey @Nmzik. Apologies for the mistakes. I'll try to be more careful and dig deeper next time. Can you please explain how you know the struct is wrong? It was the only attempt that worked for me. Regarding the shim - it was the only way I could think that could "grab onto" it as it would initialize itself and had no other way to interact with it as far as I could see. Please let me know what you need from me so I could fix these bugs
@Nmzik on GitHub · 2026-08-02 04:39 UTC · original
@StefanosCosta You can disassemble some games to see what they expect - specifically, which structure members they write to. AudioOut2ContextParamis definitely incorrect.
No further changes are needed from you. I’ve already cherry-picked some of your changes and I’ll review the other changes to make sure they don’t cause regressions in other games.
@StefanosCosta on GitHub · 2026-08-02 04:46 UTC · original
@Nmzik thanks for the tip! I have no excuse. Hope all goes well.
@Nmzik on GitHub · 2026-08-02 23:35 UTC · original
@StefanosCosta Ive cherry-picked the change. It should be good to go with the latest commit. I wont close the PR for now, though. Please make sure the sound is working on the main branch.
@StefanosCosta on GitHub · 2026-08-03 03:42 UTC · original · edited 2026-08-03 03:45 UTC
Hey there @Nmzik . It looks like issues mostly occur on game states that main cannot reach yet, as I am adding some of my fixes to reach the in-game state. That being said, even though my fixes should not affect the audio, it's going to be hard to test on both sides, so let's wrap this one up, and I'll make another PR for the current optimizations I added, which will include any audio fixes that may be needed, if any. Apologies for the inconvenience. Wish you a great week
Pull request closed