NGS2: Mastering effects, PCM/VAG waveforms, custom DSP modules and expanded API surface #2493
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!2493
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2493"
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?
@Ekt0re on GitHub · 2026-11-21 15:25 UTC · original
Ekt0re:NGS2-improvement→main· +5625 −290 · 5 files · 10 commits · openNGS2: Mastering effects, PCM/VAG waveforms, custom DSP modules and expanded API surface
Summary
Trackmania (PPSA02195) stopped at boot with:
The title was using the mastering rack's LFE filter control, which the NGS2 implementation did not handle and treated as a fatal
EXIT. Fixing that exposed the larger gap: many NGS2 exports and features were missing altogether.This PR fixes the boot crash and, at the same time, implements a large part of the NGS2 (Next Generation Sound 2) surface that AnyPS5 already covers.
Result: Trackmania now boots and its audio works correctly. I'm attaching a screenshot for illustration purposes.
Root cause fix: mastering voice controls
In
Ngs2VoiceControl, the mastering rack (0x3000block) previously supported only a few parameter IDs and hitEXIT("unsupported mastering control")for anything else. Three new controls are now handled:0x30000002MASTERING_VOICE_PARAM_LFEvalue <= 80, otherwise 120 Hz.0x30000003MASTERING_VOICE_PARAM_LIMITER±threshold. The threshold is a float stored invalueand clamped to[0, 1]; non-finite values disable the limiter.0x30000006MASTERING_VOICE_PARAM_PEAK_METERenable_flag1 = peak mode, 2 = RMS mode. The measured level is kept in the voice state (peak_height).LFE filter details.
ConfigureMasteringLfedesigns a 4th-order Chebyshev (0.1 dB ripple) low-pass as two cascaded biquad sections via bilinear transform. When the system sample rate is 96 kHz the filter is designed at 88.2 kHz. The filter is applied inNgs2RenderVoiceright after the reverb stage, only for mastering voices with at least 4 channels, followed by the limiter and the peak meter.New shared definitions (
Ngs2MasteringVoiceEffectParam, theSCE_NGS2_MASTERING_VOICE_PARAM_*constants) live inngs2.h.New features
1. Additional PCM waveform formats
Previously only 16-bit PCM (
0x12) was supported. Now supported end to end (parse, block calculation, decode, skip computation):0x110x120x140x160x180x1aHelpers:
Ngs2PcmSampleSize()andNgs2ReadPcmSample(). Sample-size assumptions that were hard-coded tosizeof(int16_t)(inWaveformData(),Ngs2DecodeFrame,Ngs2CalcWaveformBlock) now use the actual format.2. VAG (PlayStation ADPCM) codec
SCE_NGS2_WAVEFORM_TYPE_VAG(0x1c).Ngs2ParseVag: parses theVAGpheader (big-endian size and sample rate, channel byte at0x1e), detects loop start/end flags (6/3) and splits the waveform into up to three blocks (pre-loop, infinite loop, post-loop).Ngs2DecodeFrame: 28 samples per 16-byte unit per channel, five predictor filters, per-channel history carried across blocks (reset when the data is not contiguous).Ngs2CalcWaveformBlockandNgs2GetWaveformFrameInfohandle VAG.3. Generalized RIFF/WAVE parser
Ngs2ParseAtrac9RiffbecameNgs2ParseRiffWaveformand now handles:ATRAC9 (as before, via
WAVE_FORMAT_EXTENSIBLE+ ATRAC9 GUID);PCM and IEEE float (
fmttags 1, 3 and extensible with the PCM GUID);smplchunk loop points, translated into pre-loop / infinite-loop / post-loop blocks.Ngs2ParseWaveformDatadispatches to VAG or RIFF based on the magic bytes. Two new entry points were added:Ngs2ParseWaveformFile(path, offset, info): reads a file from the given offset and rebases block offsets.Ngs2ParseWaveformUser(handler, user_data, info): reads through a guest callback (VAG or RIFF, capped at 256 MiB).3b.
Ngs2GetWaveformFrameInfoReturns frame size, samples per frame, units per frame and delay samples for ATRAC9, VAG and all PCM types.
4. Custom rack DSP modules
Custom sampler/submixer racks previously supported only the channel mixer (
0x17) and two internal modules (0x19,0x1f). Added:0x13Ngs2SamplerFilter(Processnow takes a rawfloat*overload).0x150x170x20Pitch shift. A per-channel processor (
Ngs2PitchShiftChannel) combining a 15-tap windowed-sinc low-pass, a WSOLA-style time stretch (overlap search with crossfade, separate paths for ratio < 1 and > 1) and an 8-tap windowed-sinc resampler. Pitch is given in cents (clamped to ±1200) and a per-channel bypass mask is supported. It runs only when the grain size is a multiple of 64 and the voice has fewer than 32 channels.Other custom-rack changes:
0x2000) now also acceptsCustomSubmixerracks, using the propermax_channelsfield.5. System, rack and voice API expansion
New exports registered in
libAudio.cpp(InitAudio_1_Ngs2) and implemented inngs2.cpp:System
Ngs2SystemSetUserData/Ngs2SystemGetUserDataNgs2SystemSetSampleRate(validated against the supported rate list)Ngs2SystemRunCommands(lock, unlock, user data, indexed slot data, sample rate, grain samples, float param; validated first, then applied)Ngs2SystemQueryInfo(system info, user data, slot data, rack handle list)Ngs2SystemEnumHandles,Ngs2SystemEnumRackHandlesRack
Ngs2RackSetUserData/Ngs2RackGetUserDataNgs2RackRunCommands,Ngs2RackQueryInfo,Ngs2RackGetInfo(including active voice and channel counts)Ngs2CustomRackGetModuleInfoNgs2RackLock/Ngs2RackUnlocknow track lock depth and owner thread, and return an error code instead of exiting on bad handles.Voice
Ngs2VoiceGetOwner,Ngs2VoiceGetMatrixInfoSupporting changes:
Ngs2RackInternalandNgs2Internalgained fields (rack_id,uid,name,user_data, lock tracking, slot storage); new error constants (NGS2_ERROR_INVALID_RACK_HANDLE,..._VOICE_HANDLE,..._SAMPLE_RATE, etc.); newNgs2FindRackandNgs2VoiceFromHandlehelpers.6. FFT
Ngs2FftQuerySize,Ngs2FftInitandNgs2FftProcessfor lengths 8 to 12 (256 to 4096 points as per1 << length).flags & 2selects the trigonometric-table mode: forward and inverse real FFT, with either natural or internal bin ordering and optional 1/N scaling.flags == 0is a pass-through copy. Implemented with a radix-2 Cooley-Tukey FFT.7. Stream API, scheduler, module enumeration, reporting
Ngs2StreamResetOption,Ngs2StreamQueryBufferSizeNgs2StreamCreate,Ngs2StreamCreateWithAllocator,Ngs2StreamDestroyNgs2StreamRunCommands,Ngs2StreamQueryInfoNgs2JobSchedulerResetOptionNgs2ModuleArrayEnumItems,Ngs2ModuleQueueEnumItemsNgs2ModuleEnumConfigs,Ngs2ReportRegisterHandler,Ngs2ReportUnregisterHandlerGuest memory access goes through small helpers (
ReadGuestBytes,WriteGuest, ...) that check pointer plausibility.Header changes (
ngs2.h)Ngs2ContextBufferInfo,Ngs2BufferAllocatorandNgs2VoiceParamHeaderare now fully defined in the header (removed fromngs2.cpp).static_assertsize checks.Tests
tests/Ngs2SamplerTests.cpp:Check()now flushesstderrbefore aborting.New cases: mastering LFE/limiter/peak meter controls, PCM waveform formats, system/rack run-commands and queries, voice owner and matrix info, FFT (size, init, process, round trip), waveform frame info,
ParseWaveformUser, VAG (parse, loops, block calculation, ADPCM decode through a real render), custom Gain/Channel Mixer/Pitch Shift/Filter modules, and the Stream/module/report APIs.tests/VdecswTests.cpp:GuardedMemoryuses_aligned_malloc/_aligned_freeon Windows instead ofstd::aligned_alloc/std::free, which are not available there.Formatting-only changes
clang-formatstyle cleanups with no functional effect: include ordering inlibAudio.cpp, constant alignment, line wrapping in severalngs2.cppfunctions, and re-wrapped error constants. They add to the diff size but can be skipped during review.Review notes and known limitations
Ngs2FindSystemnow falls back to casting the handle to a pointer when it is not in the system list (after rejecting values below0x10000), andNgs2FindRackdoes the same for racks. This helps titles whose handles were not created through the tracked list, but it can dereference an invalid handle.Ngs2ModuleEnumConfigsand the report handlers are no-ops. The peak meter value is stored but this PR does not expose it through additional state queries.Verification
tests/Ngs2SamplerTests.cpp.AI Use and inspirations
Claude AI was used to investigate the root cause of the problem and to write this documentation. Testing and code review were done by me personally.
I was also inspired by the structure and work of AnyPS5 and @simonbronk
@coderabbitai[bot] on GitHub · 2026-11-21 15:35 UTC · original · edited 2026-11-21 19:54 UTC
Walkthrough
The change adds NGS2 system, rack, voice, FFT, waveform, stream, module, scheduler, and reporting APIs. Waveform support expands to additional PCM encodings, RIFF/WAVE formats, and VAG parsing and decoding. Voice processing adds mastering effects and custom gain, mixing, pitch-shift, and filter modules. Tests cover these APIs and processing paths. The Vdecsw test helper also selects Windows-specific aligned allocation functions.
Suggested reviewers:
nmzik,cosmo,mrbigbritchesChange: Feature
Merge Risk:
Moderate · up to
1de75This PR adds a large NGS2 audio surface and fixes the Trackmania boot crash. Several lifecycle, synchronization and DSP defects remain, such as a rack destroyed while locked leaving its system mutex held, and a test that never reaches its overflow check. These should be resolved before merging.
Pre-merge checks:
4
Full details: Title check
Explanation
The title names the main themes of the changeset: NGS2 mastering effects, PCM/VAG waveform support, custom DSP modules, and the expanded API surface. The diff adds mastering LFE/limiter/peak meter controls in ngs2.cpp, PCM and VAG formats, custom rack modules, and many new exports. It is somewhat long and lists several areas, but it does not describe anything absent from the changeset.
Full details: Description check
Explanation
The description explains the Trackmania boot crash caused by the unsupported mastering LFE control and the fix in Ngs2VoiceControl. It then details the new PCM and VAG waveform support, RIFF parser, custom rack DSP modules, system/rack/voice/FFT/stream APIs, header changes, and tests. These match the raw summary of libAudio.cpp, ngs2.cpp, ngs2.h, and the test files.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Share
@coderabbitai[bot] on GitHub · 2026-11-21 15:35 UTC · original · reviewed
41c1ea08-c063-44db-be68-29104538892fReviewing files that changed from the base of the PR and between
39936ffa39andf9c405865d.src/libs/libAudio.cppsrc/libs/ngs2.cppsrc/libs/ngs2.htests/Ngs2SamplerTests.cpptests/VdecswTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@ -3366,0 +5796,4 @@const uint64_t req_size = ComputeStreamBufferSize(checked);stream->buffer_info.host_buffer_size = req_size;stream->buffer_info.user_data = localAllocator.user_data;int32_t alloc_res = localAllocator.alloc_handler(&stream->buffer_info);@coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · edited 2026-11-21 17:07 UTC
Pass the allocator context to stream allocation.
stream->buffer_info.user_datais still zero when the allocation callback runs. An allocator that usesNgs2BufferAllocator::user_datato select its heap therefore receives the wrong context. The system and rack allocation paths initialize this field before their callbacks.Set
stream->buffer_info.user_data = localAllocator.user_databefore allocation. Preserve the callback's resulting buffer information for destruction.✅ Addressed in commits
b2cf3b5tobb303ad@coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · edited 2026-11-21 17:07 UTC
On
tests/Ngs2SamplerTests.cppline 2717 (outdated):Allocate a full option union before filling defaults.
optionis aNgs2SamplerRackOption, butNgs2FillDefaultRackOptionfirst assigns an entireNgs2RackOptionUnion. The union contains much larger custom-rack options. This call overwrites the stack beyondoptionand can crash the test or fail under AddressSanitizer.Declare a
Ngs2RackOptionUnion, fill that object, and use itssamplermember.✅ Addressed in commits
b2cf3b5tobb303ad@coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · reviewed
Actionable comments posted: 2
c77c9e77-f975-45d9-b56c-cd1f4ed1ca4aReviewing files that changed from the base of the PR and between
f9c405865dand6776f8dff3.src/libs/ngs2.cpptests/Ngs2SamplerTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On
src/libs/ngs2.cppline 2575 (outdated):Do not stage a fully skipped VAG frame as lookahead.
When a VAG block has only skipped samples left,
Ngs2DecodeFramereturnsfalse. It still setsframe_samplesto the skip count. The lookahead at lines 2573-2577 stores that count asnext_frame_samplesand keeps the cursor, even though the decode failed. The interpolation at line 2588 then uses sample 0 of the staged frame as the endpoint for the last sample before the boundary. That sample is skipped audio.Clear the staged state when the decode returns
false. The boundary sample then holds the current value until playable input arrives.Suggested fix
✅ Addressed in commit
1de75dc@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On
src/libs/ngs2.cppline 3360 (outdated):Do not read past EOF during the header probe.
A valid 46-byte PCM WAV contains enough data to parse, but the 48-byte read sets
failbit. The secondseekgclearseofbit, notfailbit, so the payload read fails before the parser runs. (eel.is)Read at most
min(sizeof(header), file_size - offset)bytes and check that read. Add a test for a one-sample PCM16 WAV with no trailing bytes.✅ Addressed in commit
1de75dc@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 19:46 UTC
On
src/libs/ngs2.cppline 3814 (outdated):Hold the rack registry lock while
Ngs2RackGetVoiceHandlereads the rack.Ngs2FindRackreleasesg_racks_mutexbefore the caller readsrack->optionandvoices[]. A concurrentNgs2RackDestroycan unlink the rack and destroy it, and a guest allocator can free its memory, during those reads. The lookup then touches destroyed or freed memory. Perform the lookup and all reads in oneg_racks_mutexhold. A destroy that starts first makes the lookup returnNGS2_ERROR_INVALID_RACK_HANDLE, as the existing rejection path intends.Suggested fix
✅ Addressed in commit
1de75dc@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On
src/libs/ngs2.cppline 5582 (outdated):Set the fallback buffer size from the managed allocation.
If the allocation callback clears
host_buffer_sizeand returns no buffer, the fallback createsreq_sizebytes but keeps the callback's zero size.Ngs2StreamDestroythen reports that zero size to callers that request buffer information. Rebuild the fallback metadata frommanaged_bufferafter callback cleanup. Preserve the callback's metadata when caller allocation succeeds.✅ Addressed in commit
1de75dc@ -2440,0 +3225,4 @@} dir_guard {dir};g_ngs2GuestRoot = dir;const auto wavPath = (dir / "ngs2_extent_test.wav").string();const auto vagPath = (dir / "ngs2_extent_test.vag").string();@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 19:46 UTC
Give each test run its own temporary paths.
Two runs in the same temporary directory use the same WAV and VAG names. One run can replace the valid WAV with its truncated fixture before the other run reads it. Cleanup can also remove a file that the other run still needs. Create a unique temporary directory for each invocation and clean up only that directory.
✅ Addressed in commit
1de75dc@coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · reviewed
Actionable comments posted: 5
e71cd156-78e0-45a3-bdda-6c9db762c512Reviewing files that changed from the base of the PR and between
6776f8dff3andbb303ad063.src/libs/ngs2.cpptests/Ngs2SamplerTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@ -751,0 +1036,4 @@drain_remaining -= 64;} else {drain_remaining = 0;inputCount = outputCount = inputTime = outputTime = 0;@coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original
Reset the complete pitch-shift pipeline after draining.
Drain completion clears the counts but leaves
startedtrue. With zero cents (ratio=1), the next clip adds 64 samples and immediately entersStretch, which consumes 960 samples.inputCountunderflows. The next block writes outsideinput.Reset the complete channel state after draining, then restore the configured pitch coefficients. Add a regression that drains one clip and plays another through the same module.
@ -2128,0 +2867,4 @@// stay on the direct path.bool pitch_pending = false;if (grain % 64 == 0 && voice.channels < 32 && voice.state != Ngs2VoicePlayState::Paused &&voice.state != Ngs2VoicePlayState::Stopped) {@coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original
Allow custom sampler pitch-shift tails to render after source completion.
The
Emptytransition at lines 2722-2727 ignores pitch-shift pending state. A finite custom sampler clip can reachEmptywhile its pitch-shift channels still hold delayed audio. The render that setsEmptystill evaluates the pending check at lines 2822-2843. That render does not produce delayed output. A 512-sample clip does not fill the pitch-shift startup buffer, so no delayed output is produced. Later renders skip thePlayingblock at line 2710, so the drain never continues.Run pending DSP processing after natural source completion. Keep source consumption disabled, and preserve pause and stop behavior.
@ -2137,0 +2950,4 @@static_cast<size_t>(c) * grain;for (uint32_t i = 0; i < grain; i += 64) {channel.ProcessOrDrain(had_samples ? samples + i : nullptr,samples + i, module.pitch_shift_ratio);@coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original
Pass the upstream pitch-shift output to the next module after source input ends.
had_samplesis captured before the module loop and is not updated when an earlier pitch-shift module writes output. After source input ends, a later pitch-shift module on the same buffer receivesnullptr. It ignores the samples the earlier module wrote, including that module's delayed tail. It then emits only its own buffered output, or silence. The earlier module's tail is lost, so the end of the clip is truncated by roughly one module's latency.Track input availability through the ordered module pipeline as the loop runs. A module must receive the preceding module's output while that output is still produced. It should receive
nullptronly when no upstream audio remains. A module that holds only its own buffered tail must still drain withnullptr.@coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original · reviewed
Actionable comments posted: 3
8d53f017-3c55-418c-a4a6-21a5515c0858Reviewing files that changed from the base of the PR and between
bb303ad063and77bbb3ec18.src/libs/ngs2.cpptests/Ngs2SamplerTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@coderabbitai[bot] on GitHub · 2026-11-21 18:08 UTC · original · reviewed
e43e0b99-ebbb-4751-9c77-b587045bb8fdReviewing files that changed from the base of the PR and between
77bbb3ec18and4683bcfdab.src/libs/ngs2.cpptests/Ngs2SamplerTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
@Ekt0re on GitHub · 2026-11-21 19:46 UTC · original
@coderabbitai review
@coderabbitai[bot] on GitHub · 2026-11-21 19:46 UTC · original · edited 2026-11-21 19:54 UTC
Action performed
Review finished.
@Ekt0re on GitHub · 2026-11-21 19:47 UTC · original
@coderabbitai resume
@ -1771,0 +2334,4 @@// The owner already holds ngs->mutex, so the depth and owner are read// atomically instead of taking the system mutex again.Common::LockGuard racks_lock(g_racks_mutex);auto* rack = Ngs2FindRackLocked(rack_handle);@coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original
Destroying a rack that the calling thread still holds leaves the system mutex locked.
Ngs2RackDestroyacquiresngs->mutexwithout checkingrack->lock_depth. When the same thread already holds the rack lock, the destroy call adds and releases one acquisition, then removes the rack.Ngs2RackUnlockcannot find the rack afterward, so it returns beforengs->mutex.Unlock(). The original acquisition remains held. Other threads that callNgs2RackLockorNgs2RackUnlockon the same system then block onngs->mutexand stay blocked.Define the required behavior before destruction. Either reject destruction while the rack is locked, or release the caller's lock acquisition before the rack is removed. Do not leave any acquisition held after
Ngs2RackDestroyreturns. Add a test that destroys a locked rack and checks that another rack on the same system can still be locked.@ -2440,0 +3299,4 @@const uint64_t big_offset = 0xfffffff0ull;const auto big_path = dir / "ngs2_extent_big.wav";{std::ofstream out(big_path, std::ios::binary | std::ios::in);@coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original
Create the overflow fixture before parsing it.
std::ofstreamaddsoutto these flags. The resultingin|out|binarymode requires an existing file, so opening this new path fails. (eel.is)The unchecked write creates no fixture. The parser then returns
NGS2_ERROR_INVALID_WAVEFORM_DATAfor the missing file, so the test passes without reaching the offset-overflow check.Use
binary|trunc. Check the write and close results, then verify the file size before parsing.@coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original · reviewed
Actionable comments posted: 2
671d1c6f-c5ab-456c-b4a5-18d154db27deReviewing files that changed from the base of the PR and between
4683bcfdaband1de75dc05a.src/libs/ngs2.cpptests/Ngs2SamplerTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original
Action performed
Reviews resumed. No new commits to review.
View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.