NGS2: Mastering effects, PCM/VAG waveforms, custom DSP modules and expanded API surface #2493

Open
github-bot wants to merge 10 commits from github-bot/gh-2493 into main AGit
Owner

@⁠Ekt0re on GitHub · 2026-11-21 15:25 UTC · original
Ekt0re:NGS2-improvement → main · +5625 −290 · 5 files · 10 commits · open

NGS2: Mastering effects, PCM/VAG waveforms, custom DSP modules and expanded API surface

Summary

Trackmania (PPSA02195) stopped at boot with:

unsupported mastering control: 0x30000002 in src/libs/ngs2.cpp:3006

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.

Screenshot 2026-11-21 153113

Root cause fix: mastering voice controls

In Ngs2VoiceControl, the mastering rack (0x3000 block) previously supported only a few parameter IDs and hit EXIT("unsupported mastering control") for anything else. Three new controls are now handled:

Param ID Name Behavior
0x30000002 MASTERING_VOICE_PARAM_LFE Enables an LFE low-pass filter on channel index 3. Cutoff is 80 Hz if value <= 80, otherwise 120 Hz.
0x30000003 MASTERING_VOICE_PARAM_LIMITER Hard-clamps all channels to ±threshold. The threshold is a float stored in value and clamped to [0, 1]; non-finite values disable the limiter.
0x30000006 MASTERING_VOICE_PARAM_PEAK_METER enable_flag 1 = peak mode, 2 = RMS mode. The measured level is kept in the voice state (peak_height).

LFE filter details. ConfigureMasteringLfe designs 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 in Ngs2RenderVoice right 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, the SCE_NGS2_MASTERING_VOICE_PARAM_* constants) live in ngs2.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):

Type Format
0x11 8-bit unsigned
0x12 16-bit signed
0x14 24-bit signed
0x16 32-bit signed
0x18 32-bit float
0x1a 64-bit double

Helpers: Ngs2PcmSampleSize() and Ngs2ReadPcmSample(). Sample-size assumptions that were hard-coded to sizeof(int16_t) (in WaveformData(), Ngs2DecodeFrame, Ngs2CalcWaveformBlock) now use the actual format.

2. VAG (PlayStation ADPCM) codec

  • New waveform type SCE_NGS2_WAVEFORM_TYPE_VAG (0x1c).
  • Ngs2ParseVag: parses the VAGp header (big-endian size and sample rate, channel byte at 0x1e), detects loop start/end flags (6 / 3) and splits the waveform into up to three blocks (pre-loop, infinite loop, post-loop).
  • Decoder in 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).
  • Ngs2CalcWaveformBlock and Ngs2GetWaveformFrameInfo handle VAG.

3. Generalized RIFF/WAVE parser

Ngs2ParseAtrac9Riff became Ngs2ParseRiffWaveform and now handles:

  • ATRAC9 (as before, via WAVE_FORMAT_EXTENSIBLE + ATRAC9 GUID);

  • PCM and IEEE float (fmt tags 1, 3 and extensible with the PCM GUID);

  • smpl chunk loop points, translated into pre-loop / infinite-loop / post-loop blocks.
    Ngs2ParseWaveformData dispatches 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. Ngs2GetWaveformFrameInfo

Returns 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:

Module ID Module Notes
0x13 Filter Reuses Ngs2SamplerFilter (Process now takes a raw float* overload).
0x15 Gain Per-channel gain with a linear ramp across the grain from the previous to the new target. The first configuration is applied immediately.
0x17 Channel Mixer Now accepts variable-size parameter blocks (copies at most 37×37 levels) instead of requiring an exact size.
0x20 Pitch Shift See below.

Pitch 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:

  • Custom control index resolution accepts an index shifted by one when the module ID matches.
  • Mastering/submixer setup (0x2000) now also accepts CustomSubmixer racks, using the proper max_channels field.

5. System, rack and voice API expansion

New exports registered in libAudio.cpp (InitAudio_1_Ngs2) and implemented in ngs2.cpp:

System

  • Ngs2SystemSetUserData / Ngs2SystemGetUserData
  • Ngs2SystemSetSampleRate (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, Ngs2SystemEnumRackHandles
    Rack
  • Ngs2RackSetUserData / Ngs2RackGetUserData
  • Ngs2RackRunCommands, Ngs2RackQueryInfo, Ngs2RackGetInfo (including active voice and channel counts)
  • Ngs2CustomRackGetModuleInfo
  • Ngs2RackLock / Ngs2RackUnlock now track lock depth and owner thread, and return an error code instead of exiting on bad handles.
    Voice
  • Ngs2VoiceGetOwner, Ngs2VoiceGetMatrixInfo
    Supporting changes: Ngs2RackInternal and Ngs2Internal gained fields (rack_id, uid, name, user_data, lock tracking, slot storage); new error constants (NGS2_ERROR_INVALID_RACK_HANDLE, ..._VOICE_HANDLE, ..._SAMPLE_RATE, etc.); new Ngs2FindRack and Ngs2VoiceFromHandle helpers.

6. FFT

Ngs2FftQuerySize, Ngs2FftInit and Ngs2FftProcess for lengths 8 to 12 (256 to 4096 points as per 1 << length). flags & 2 selects the trigonometric-table mode: forward and inverse real FFT, with either natural or internal bin ordering and optional 1/N scaling. flags == 0 is a pass-through copy. Implemented with a radix-2 Cooley-Tukey FFT.

7. Stream API, scheduler, module enumeration, reporting

Export Status
Ngs2StreamResetOption, Ngs2StreamQueryBufferSize Implemented, with option validation and buffer size computation.
Ngs2StreamCreate, Ngs2StreamCreateWithAllocator, Ngs2StreamDestroy Implemented: argument validation, handle tracking, allocator callbacks.
Ngs2StreamRunCommands, Ngs2StreamQueryInfo Validation of commands, sizes and handles only; no actual streaming.
Ngs2JobSchedulerResetOption Writes default option.
Ngs2ModuleArrayEnumItems, Ngs2ModuleQueueEnumItems Implemented (the queue variant uses a spin lock with back-off).
Ngs2ModuleEnumConfigs, Ngs2ReportRegisterHandler, Ngs2ReportUnregisterHandler Stubs returning 0.

Guest memory access goes through small helpers (ReadGuestBytes, WriteGuest, ...) that check pointer plausibility.


Header changes (ngs2.h)

  • Ngs2ContextBufferInfo, Ngs2BufferAllocator and Ngs2VoiceParamHeader are now fully defined in the header (removed from ngs2.cpp).
  • Added constants and parameter structs for mastering, custom modules, VAG, stream options and error codes, with static_assert size checks.
  • Declarations for all the new functions.

Tests

tests/Ngs2SamplerTests.cpp:

  • Check() now flushes stderr before 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:

  • GuardedMemory uses _aligned_malloc / _aligned_free on Windows instead of std::aligned_alloc / std::free, which are not available there.


Formatting-only changes

clang-format style cleanups with no functional effect: include ordering in libAudio.cpp, constant alignment, line wrapping in several ngs2.cpp functions, and re-wrapped error constants. They add to the diff size but can be skipped during review.


Review notes and known limitations

  • Handle lookup is more permissive. Ngs2FindSystem now falls back to casting the handle to a pointer when it is not in the system list (after rejecting values below 0x10000), and Ngs2FindRack does the same for racks. This helps titles whose handles were not created through the tracked list, but it can dereference an invalid handle.
  • Partial or stub features: stream commands and queries only validate; Ngs2ModuleEnumConfigs and the report handlers are no-ops. The peak meter value is stored but this PR does not expose it through additional state queries.
  • Pitch shift is skipped for grains that are not a multiple of 64 samples.
  • The implementations are based on behavior observed in AnyPS5 and on the title's usage, not on a full specification, so edge cases may still differ from real hardware.

Verification

  • Trackmania (PPSA02195) boots and plays audio correctly.
  • New unit tests added in tests/Ngs2SamplerTests.cpp.
  • I also tested other titles to make sure there were no regressions

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

**@⁠Ekt0re** on GitHub · 2026-11-21 15:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493) `Ekt0re:NGS2-improvement` → `main` · +5625 −290 · 5 files · 10 commits · open # NGS2: Mastering effects, PCM/VAG waveforms, custom DSP modules and expanded API surface ## Summary Trackmania (PPSA02195) stopped at boot with: ``` unsupported mastering control: 0x30000002 in src/libs/ngs2.cpp:3006 ``` 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](https://github.com/boykopovar/AnyPS5) already covers. **Result:** Trackmania now boots and its audio works correctly. I'm attaching a screenshot for illustration purposes. <img width="1372" height="802" alt="Screenshot 2026-11-21 153113" src="https://github.com/user-attachments/assets/c2c10812-8c7b-4e3a-9d62-e00d9e63d705" /> --- ## Root cause fix: mastering voice controls In `Ngs2VoiceControl`, the mastering rack (`0x3000` block) previously supported only a few parameter IDs and hit `EXIT("unsupported mastering control")` for anything else. Three new controls are now handled: | Param ID | Name | Behavior | |---|---|---| | `0x30000002` | `MASTERING_VOICE_PARAM_LFE` | Enables an LFE low-pass filter on channel index 3. Cutoff is 80 Hz if `value <= 80`, otherwise 120 Hz. | | `0x30000003` | `MASTERING_VOICE_PARAM_LIMITER` | Hard-clamps all channels to `±threshold`. The threshold is a float stored in `value` and clamped to `[0, 1]`; non-finite values disable the limiter. | | `0x30000006` | `MASTERING_VOICE_PARAM_PEAK_METER` | `enable_flag` 1 = peak mode, 2 = RMS mode. The measured level is kept in the voice state (`peak_height`). | **LFE filter details.** `ConfigureMasteringLfe` designs 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 in `Ngs2RenderVoice` right 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`, the `SCE_NGS2_MASTERING_VOICE_PARAM_*` constants) live in `ngs2.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): | Type | Format | |---|---| | `0x11` | 8-bit unsigned | | `0x12` | 16-bit signed | | `0x14` | 24-bit signed | | `0x16` | 32-bit signed | | `0x18` | 32-bit float | | `0x1a` | 64-bit double | Helpers: `Ngs2PcmSampleSize()` and `Ngs2ReadPcmSample()`. Sample-size assumptions that were hard-coded to `sizeof(int16_t)` (in `WaveformData()`, `Ngs2DecodeFrame`, `Ngs2CalcWaveformBlock`) now use the actual format. ### 2. VAG (PlayStation ADPCM) codec - New waveform type `SCE_NGS2_WAVEFORM_TYPE_VAG` (`0x1c`). - `Ngs2ParseVag`: parses the `VAGp` header (big-endian size and sample rate, channel byte at `0x1e`), detects loop start/end flags (`6` / `3`) and splits the waveform into up to three blocks (pre-loop, infinite loop, post-loop). - Decoder in `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). - `Ngs2CalcWaveformBlock` and `Ngs2GetWaveformFrameInfo` handle VAG. ### 3. Generalized RIFF/WAVE parser `Ngs2ParseAtrac9Riff` became `Ngs2ParseRiffWaveform` and now handles: - ATRAC9 (as before, via `WAVE_FORMAT_EXTENSIBLE` + ATRAC9 GUID); - PCM and IEEE float (`fmt` tags 1, 3 and extensible with the PCM GUID); - `smpl` chunk loop points, translated into pre-loop / infinite-loop / post-loop blocks. `Ngs2ParseWaveformData` dispatches 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. `Ngs2GetWaveformFrameInfo` Returns 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: | Module ID | Module | Notes | |---|---|---| | `0x13` | Filter | Reuses `Ngs2SamplerFilter` (`Process` now takes a raw `float*` overload). | | `0x15` | Gain | Per-channel gain with a linear ramp across the grain from the previous to the new target. The first configuration is applied immediately. | | `0x17` | Channel Mixer | Now accepts variable-size parameter blocks (copies at most 37×37 levels) instead of requiring an exact size. | | `0x20` | Pitch Shift | See below. | **Pitch 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: - Custom control index resolution accepts an index shifted by one when the module ID matches. - Mastering/submixer setup (`0x2000`) now also accepts `CustomSubmixer` racks, using the proper `max_channels` field. ### 5. System, rack and voice API expansion New exports registered in `libAudio.cpp` (`InitAudio_1_Ngs2`) and implemented in `ngs2.cpp`: **System** - `Ngs2SystemSetUserData` / `Ngs2SystemGetUserData` - `Ngs2SystemSetSampleRate` (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`, `Ngs2SystemEnumRackHandles` **Rack** - `Ngs2RackSetUserData` / `Ngs2RackGetUserData` - `Ngs2RackRunCommands`, `Ngs2RackQueryInfo`, `Ngs2RackGetInfo` (including active voice and channel counts) - `Ngs2CustomRackGetModuleInfo` - `Ngs2RackLock` / `Ngs2RackUnlock` now track lock depth and owner thread, and return an error code instead of exiting on bad handles. **Voice** - `Ngs2VoiceGetOwner`, `Ngs2VoiceGetMatrixInfo` Supporting changes: `Ngs2RackInternal` and `Ngs2Internal` gained fields (`rack_id`, `uid`, `name`, `user_data`, lock tracking, slot storage); new error constants (`NGS2_ERROR_INVALID_RACK_HANDLE`, `..._VOICE_HANDLE`, `..._SAMPLE_RATE`, etc.); new `Ngs2FindRack` and `Ngs2VoiceFromHandle` helpers. ### 6. FFT `Ngs2FftQuerySize`, `Ngs2FftInit` and `Ngs2FftProcess` for lengths 8 to 12 (256 to 4096 points as per `1 << length`). `flags & 2` selects the trigonometric-table mode: forward and inverse real FFT, with either natural or internal bin ordering and optional 1/N scaling. `flags == 0` is a pass-through copy. Implemented with a radix-2 Cooley-Tukey FFT. ### 7. Stream API, scheduler, module enumeration, reporting | Export | Status | |---|---| | `Ngs2StreamResetOption`, `Ngs2StreamQueryBufferSize` | Implemented, with option validation and buffer size computation. | | `Ngs2StreamCreate`, `Ngs2StreamCreateWithAllocator`, `Ngs2StreamDestroy` | Implemented: argument validation, handle tracking, allocator callbacks. | | `Ngs2StreamRunCommands`, `Ngs2StreamQueryInfo` | Validation of commands, sizes and handles only; no actual streaming. | | `Ngs2JobSchedulerResetOption` | Writes default option. | | `Ngs2ModuleArrayEnumItems`, `Ngs2ModuleQueueEnumItems` | Implemented (the queue variant uses a spin lock with back-off). | | `Ngs2ModuleEnumConfigs`, `Ngs2ReportRegisterHandler`, `Ngs2ReportUnregisterHandler` | Stubs returning 0. | Guest memory access goes through small helpers (`ReadGuestBytes`, `WriteGuest`, ...) that check pointer plausibility. --- ## Header changes (`ngs2.h`) - `Ngs2ContextBufferInfo`, `Ngs2BufferAllocator` and `Ngs2VoiceParamHeader` are now fully defined in the header (removed from `ngs2.cpp`). - Added constants and parameter structs for mastering, custom modules, VAG, stream options and error codes, with `static_assert` size checks. - Declarations for all the new functions. --- ## Tests `tests/Ngs2SamplerTests.cpp`: - `Check()` now flushes `stderr` before 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`: - `GuardedMemory` uses `_aligned_malloc` / `_aligned_free` on Windows instead of `std::aligned_alloc` / `std::free`, which are not available there. --- ## Formatting-only changes `clang-format` style cleanups with no functional effect: include ordering in `libAudio.cpp`, constant alignment, line wrapping in several `ngs2.cpp` functions, and re-wrapped error constants. They add to the diff size but can be skipped during review. --- ## Review notes and known limitations - **Handle lookup is more permissive.** `Ngs2FindSystem` now falls back to casting the handle to a pointer when it is not in the system list (after rejecting values below `0x10000`), and `Ngs2FindRack` does the same for racks. This helps titles whose handles were not created through the tracked list, but it can dereference an invalid handle. - **Partial or stub features:** stream commands and queries only validate; `Ngs2ModuleEnumConfigs` and the report handlers are no-ops. The peak meter value is stored but this PR does not expose it through additional state queries. - **Pitch shift** is skipped for grains that are not a multiple of 64 samples. - The implementations are based on behavior observed in AnyPS5 and on the title's usage, not on a full specification, so edge cases may still differ from real hardware. ## Verification - Trackmania (PPSA02195) boots and plays audio correctly. - New unit tests added in `tests/Ngs2SamplerTests.cpp`. - I also tested other titles to make sure there were no regressions # 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 ](https://github.com/boykopovar/AnyPS5 )and @⁠simonbronk
Add PCM and VAG waveform parsing and decoding, custom sampler DSP modules, mastering effects, FFT utilities, and system, rack, and stream APIs. Extend NGS2 tests and use platform-correct aligned allocation in VdecswTests on Windows.

Co-Authored-By: simonbronk <[email protected]>
- test: Ngs2FillDefaultRackOption ora usa Ngs2RackOptionUnion (overflow stack)
- stream: user_data passato all'allocatore, buffer parziale rilasciato una
  volta, fallback interno mai passato al free handler del chiamante
- custom module filter: stato history resettato ai cambi di layout canali
- ParseWaveformFile: lettura limitata all'extent dichiarato RIFF/VAG
- VAG block math in uint64 con reject su overflow dei campi destinazione
- Ngs2FftLengthValid: confronto diretto, niente length-8 con INT_MIN
- test: INT_MIN FFT, matrice 1370 livelli riporta 1369 copiati

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- Ngs2RackGetVoiceHandle ora risolve il rack via registry: handle distrutti
  o non registrati tornano NGS2_ERROR_INVALID_RACK_HANDLE
- test: enum dopo destroy, unlock rack non owner, free handler annidato
- verificati gia' corretti: lookup stream solo-registry, unlink sistema dal
  registry in destroy, owner check in RackUnlock, scritture comandi di
  sistema sotto mutex, detach stream prima del free handler, header coda
  letto dopo il lock, destroy dei rack nei test custom

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- history del predittore VAG confrontata con la posizione di decode
  (block.data + data_cursor) invece della base del blocco
- lookahead: cursore di inizio frame preservato insieme al frame in
  staging (next_frame_cursor), senza rewind del frame in riproduzione
- ClearWaveformBlocks non azzera piu' is_vag: la selezione del formato
  cambia solo nel setup del sampler (incluso quello differito)
- CalcWaveformBlock VAG riporta num_samples richiesto; data_size resta
  allineato ai frame; aritmetica byte in uint64
- test: history nel blocco, continuita' 24->48 kHz al confine frame,
  CLEAR che mantiene il decoder VAG

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- filtro modulo custom progettato alla sample rate di sistema (audio
  post-resampling) invece della sample rate della sorgente; i
  coefficienti vengono ridisegnati quando cambia il sample rate di
  sistema (anche per i filtri del sampler)
- filtro LFE mastering: la chiave di design include il cutoff, non solo
  il sample rate
- pitch shift: ProcessOrDrain svuota la coda ritardata con silenzio a
  fine stream invece di troncare l'audio; canali in bypass e voci
  pause/stop restano sul percorso diretto
- WAVE_FORMAT_EXTENSIBLE: riconosciuto il sottotipo IEEE float e
  instradato agli stessi controlli di larghezza del tag 3
- geometria ATRAC9: il limite di 8 canali si applica solo ai formati
  non-ATRAC9; canali e sample rate validati contro il codec in entrambe
  le API
- test: design rate del filtro custom, redesign su cambio rate, cutoff
  LFE, drain della coda pitch shift, WAVE estensibile float, ATRAC9 a
  12 canali

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- PackNatural: lo scaling 1/N ora copre tutti i 2*points float
  dell'output (prima solo points)
- DECISIONE: l'inversa in ordine naturale fa l'unpack dello stesso
  layout a quattro blocchi prodotto dal forward (Ngs2FftUnpackNatural),
  cosi' forward+inverse restituisce il segnale; il layout forward non
  cambia per coerenza con l'ABI guest. Copia di input dimensionata sul
  layout (points vs points*2)
- test: round trip naturale 256 punti con tono al bin 96; asserzioni
  NaN-safe nelle comparazioni di errore

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- Ngs2StreamQueryInfo: le query riconosciute ma non implementate
  ritornano SCE_NGS2_ERROR_INVALID_STREAM_QUERY_ID invece di OK senza
  scrivere l'output
- Ngs2ParseWaveformFile: il path guest passa da
  FileSystem::GetRealFilename come le altre API file; i percorsi non
  montati non ricadono sul filesystem host
- Ngs2SystemGetInfo: accetta buffer piu' grandi di Ngs2SystemInfo e
  scrive solo sizeof(Ngs2SystemInfo)
- Ngs2SystemRender: render_count del rack incrementato una volta per
  rack per render, non per voce
- test: query stream non implementata, path guest vs host, buffer
  info sovradimensionato, render_count del rack

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:21:20 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 15:35 UTC · original · edited 2026-11-21 19:54 UTC

Explain Change →

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, mrbigbritches

Change: Feature

Merge Risk: Moderate · up to 1de75

This 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: Passed 4

Check name Status Explanation
Title check Passed 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 con…
Description check Passed 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, c…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
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](https://github.com/KytyPS5/KytyPS5/pull/2493#issuecomment-7064994080) · edited 2026-11-21 19:54 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/2493?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> 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`, `mrbigbritches` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"1de75dc05a8bc270c20795c9f283e3ac1016165c" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · up to <code>1de75</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `1de75` --> <!-- final_review_risk_coverage:{"sourceCommitId":"1de75dc05a8bc270c20795c9f283e3ac1016165c","coveredCommitId":"1de75dc05a8bc270c20795c9f283e3ac1016165c","kind":"reviewed"} --> This 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. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | 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 con… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | 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, c… | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> <br> **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. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> <br> **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. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2493)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>Share</strong></summary> <dl> <dd> <br> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 15:35 UTC · original · reviewed

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Major comments: 21

src/libs/ngs2.cpp: 20

2220-2225: Major · Stability & Availability · Heavy lift

Unlock only the rack acquired by the calling thread.

If one thread locks rack A and unlocks rack B on the same system, B has zero depth. The code skips B's bookkeeping but still releases the system mutex. A then reports that it is locked even though another thread can enter. Check the rack and owner before changing depth or releasing the mutex. Keep the normal lock/unlock pair balanced.


2340-2340: Major · Functional Correctness · Heavy lift

Do not change the current playback cursor during VAG lookahead.

At 24 kHz on a 48 kHz system, playback looks ahead from sample 27 to interpolate across the frame boundary. Decoding the next frame sets voice.frame_cursor to zero even when there is no skip. Interpolation then reads the start of the old frame. Keep each decoded frame's start cursor with that frame, or stage only playable samples at index zero.


1586-1588: Major · Stability & Availability · Quick win

Reject rack handles that are not in the registry.

If a caller destroys a rack and then queries its old handle, the lookup misses the registry and reads ngs from the former rack object. The pointer check does not establish that the object is still live. Return the invalid-rack error on a registry miss. Use registered racks in the tests that currently depend on the fallback.


4550-4550: Major · Stability & Availability · Heavy lift

Remove destroyed systems from the handle registry.

Ngs2SystemDestroy returns success without unlinking the system. The new enumerator therefore returns a destroyed handle if its storage is still live, or reads released storage if the caller freed it. Unlink the system before destroy returns. Synchronize enumeration and lookup with registry updates so live systems remain enumerable.


2780-2781: Major · Stability & Availability · Quick win

Keep custom filter history in sync with voice setup.

A custom submixer can configure an enabled filter with one channel and then be set up with two channels. Setup clears voice.filters, but leaves the module filter enabled with one history entry. The next render accesses history[1]. Reset or rebuild module filter history when the layout changes, before processing the new channels.


1255-1255: Major · Functional Correctness · Quick win

Preserve the selected VAG format when clearing the queue.

AddWaveformBlocks calls ClearWaveformBlocks for CLEAR. This resets is_vag, so a replacement block on a configured VAG voice reaches the PCM decoder. Keep the VAG history and cursor resets in the queue clear. Reset is_vag only when sampler setup selects a new format, including deferred setup.


4801-4803: Major · Data Integrity & Integration · Quick win

Do not report more matrix levels than the query returns.

The existing matrix setter can store 1,370 levels. This query reports all 1,370 but copies only 1,369 into info->levels. A caller cannot use the returned count to read the result safely. Report the number copied, or reject a matrix that exceeds the ABI capacity if truncation is not allowed.


4460-4462: Major · Stability & Availability · Heavy lift

Synchronize system command writes with rendering.

The supplied test updates the rate and grain after its explicit unlock. These are accepted commands, but their stores do not take the mutex that protects the render reads. If rendering overlaps either store, the accesses race. Route ordinary mutations through the same synchronization as the direct setter and renderer. Preserve the behavior of explicit lock and unlock commands.


5584-5584: Major · Data Integrity & Integration · Heavy lift

Do not return success without writing the stream query result.

A live stream and an eight-byte output buffer pass query 0xf24001, but the buffer is left unchanged. The caller can treat its previous contents as fresh query data. Write the defined result for supported queries. If a result is not implemented yet, return a defined failure instead of reporting success.


2306-2307: Major · Functional Correctness · Quick win

Preserve VAG predictor history within a block.

After decoding the first frame, vag_next_data points to the second frame. The next iteration compares it with the block base and clears the predictor history. A predicted frame with zero residual then loses the expected decay. Compare vag_next_data with block.data + block.data_cursor. This preserves history for contiguous frames and still resets it after a discontinuity.


5484-5487: Major · Stability & Availability · Quick win

Release the stream registry lock before calling the free handler.

If a free handler destroys another stream, a nonrecursive registry mutex blocks reentry. With a recursive mutex, deleting an earlier stream invalidates the iterator that the outer call still uses. Move the stream out of the registry and erase its entry under the lock. Then release the lock and call the handler with the detached stream's buffer information.


3987-3988: Major · Functional Correctness · Quick win

Design the custom filter at the rate it processes.

The custom module runs after sampler resampling. A 22.05 kHz custom sampler on a 48 kHz system therefore processes 48 kHz samples with coefficients designed for 22.05 kHz. A custom submixer also uses the fixed 48 kHz fallback on a 44.1 kHz system. Use the system rate and redesign the coefficients when that rate changes.


3293-3296: Major · Performance & Scalability · Quick win

Bound file reads to the waveform at the requested offset.

If a small RIFF waveform is near the start of an asset archive, this function allocates and reads the entire remaining archive. The parser then ignores the bytes beyond the RIFF extent. Read the header first and limit subsequent reads to the declared waveform extent. Return an error for a failed size query or an extent outside the file before allocating.


2702-2702: Major · Functional Correctness · Heavy lift

Drain buffered pitch-shift audio after the source ends.

An active pitch-shift channel outputs silence until more than 1,984 input samples arrive. A finite 1,024-sample clip ends before that point. Once the source stops producing samples, the render guard stops calling the module, so the entire clip is silent. Track pending audio separately from current-grain input and drain it at end of stream. Keep bypassed channels on the existing direct path.


5639-5639: Major · Stability & Availability · Quick win

Read queue metadata only after acquiring the queue lock.

The first header copy reads mutable ring metadata and the lock word before acquisition. If another thread updates the queue, this copy bypasses the synchronization used by the second copy. No value from the first copy is used. Remove it and take the snapshot only after the lock is acquired.


5048-5050: Major · Functional Correctness · Quick win

Scale every bin in natural-order FFT output.

Ngs2FftPackNatural writes 2 * points floats. The scaling loop visits only points floats. For a 256-point transform, a tone at bin 96 is stored at float index 384 and is returned without the requested 1/256 factor. Scale the entire packed output, as the internal-order branch does.


5453-5461: Major · Stability & Availability · Quick win

Keep fallback storage out of the caller's free handler.

If the allocation callback fails without supplying a buffer, creation installs vector-owned storage but leaves has_allocator set. Destroy then passes that storage to the caller's free handler, and the vector releases it again. Propagate the allocation error, or mark the fallback as internally owned. Keep calling the caller's free handler exactly once for a successful caller allocation.


5406-5409: Major · Data Integrity & Integration · Quick win

Require a registered system before creating a stream.

Ngs2FindSystem returns a cast pointer for an unregistered handle above the low-address cutoff. Ngs2StreamCreate and Ngs2StreamCreateWithAllocator accept that pointer and can return success without a live owner. Use a registry-only lookup for stream creation. Keep the existing success path for a live system.


3319-3321: Major · Data Integrity & Integration · Quick win

Keep ATRAC9 geometry queries compatible with parsed formats.

The RIFF parser accepts codec-matched channel counts, including the 12-channel ATRAC9 format covered by the codec test. Both geometry APIs reject that format before reading its codec configuration. Apply the eight-channel limit only to the formats that require it. Validate ATRAC9 channels and rate against the codec result in both APIs.

Also applies to: 5112-5114


3285-3285: Major · Data Integrity & Integration · Quick win

Resolve guest paths through the kernel mount table before Ngs2ParseWaveformFile opens the file.

Ngs2ParseWaveformFile passes path directly to std::ifstream. A guest path such as /app0/... therefore resolves as a host path, not through the /app0 mount. The open fails, and the function returns NGS2_ERROR_INVALID_WAVEFORM_DATA for assets that exist only in the guest mount. Other guest file APIs translate paths through the kernel mount resolver before host access. Apply the same translation here, for example with the existing FileSystem::GetRealFilename helper, before the open.

tests/Ngs2SamplerTests.cpp: 1

3571-3571: Major · Stability & Availability · Quick win

Destroy registered racks before their test buffers expire.

TestCustomFilterModule releases rBuf without calling Ngs2RackDestroy. The next system render traverses g_racks_list, which still contains the freed rack. The VAG, gain, mixer, and pitch tests repeat this teardown pattern. Use RenderRack or explicitly destroy each rack before releasing its storage. Where a test does not need to exercise system creation, use the existing stack-system fixture so it does not leave a system registry entry either.

Minor comments: 10

src/libs/ngs2.cpp: 8

3347-3353: Minor · Data Integrity & Integration · Quick win

Widen VAG block arithmetic before computing the endpoints.

For an eight-channel VAG block above 4 GiB in encoded data, the start offset is computed in 64 bits, but past * frame_bytes wraps in 32 bits. Subtracting the start offset then produces a very large data_size for a short request. The sample endpoint can also wrap before division. Compute both endpoints and encoded offsets in 64 bits. Reject any result that cannot fit its destination field.


2663-2663: Minor · Functional Correctness · Quick win

Redesign the LFE filter when the cutoff changes.

If a voice renders with an 80 Hz cutoff and then receives a 120 Hz cutoff at the same system rate, the design-rate check keeps the 80 Hz coefficients. Include the cutoff in the design key. Repeated controls that do not change the cutoff can still reuse the coefficients.


4499-4499: Minor · Data Integrity & Integration · Quick win

Accept oversized buffers in the system-info query.

A 192-byte output buffer passes the query's 184-byte minimum check, but Ngs2SystemGetInfo rejects it because it requires exactly 184 bytes. After checking capacity, pass sizeof(Ngs2SystemInfo) to the fixed-size helper. This accepts both buffer sizes without writing into the extra bytes.


4814-4814: Minor · Functional Correctness · Quick win

Validate FFT length before subtracting.

Ngs2FftInit accepts a signed length. If it is INT_MIN, length - 8 overflows before the cast. Compare the signed value directly with 8 and 12. This rejects the extreme value and preserves the supported range.


3063-3065: Minor · Functional Correctness · Quick win

Recognize the IEEE float subtype in extensible WAVE files.

A valid 32-bit float waveform can use WAVE_FORMAT_EXTENSIBLE with the IEEE float subtype. The parser rejects that subtype before it reaches the float width mapping. Recognize the float subtype and pass it through the same width checks as tag 3. Keep extensible integer PCM and ATRAC9 on their existing branches. (learn.microsoft.com)

Also applies to: 3070-3070


4688-4688: Minor · Data Integrity & Integration · Quick win

Update the rack render count when the rack renders.

Ngs2RackGetInfo returns rack->render_count, but rendering only increments the system count. A rack still reports zero after it has rendered multiple grains. Increment the count once per rack at the corresponding render boundary, not once per voice.


5058-5069: Minor · Data Integrity & Integration · Heavy lift

Natural-order inverse FFT does not accept natural-order forward output.

With mode bit 2 clear, Ngs2FftProcess writes forward output in four blocks spaced points / 2 floats apart. Each block holds data in its first points / 4 floats, and odd blocks are reversed. The natural inverse path (src/libs/ngs2.cpp:5064-5069) reads the first points floats as contiguous bin pairs. For a 256-point transform, a tone at bin 96 is written at float 384, which the inverse never reads. Bins 32 through 127 also come back from the wrong positions. A forward (0x1) followed by inverse (0x8) round trip in natural order therefore does not return the input.

The internal-order path (bit 2 set) uses matching pack and unpack helpers and round-trips correctly. The tests cover only internal order, so this natural-order mismatch is not caught.

Decide the layout the guest ABI requires for the natural inverse input. If the ABI expects the forward layout, change the inverse to unpack the block layout. If it expects contiguous pairs, change the forward natural pack to write contiguous pairs. Add a natural-order round-trip test for a 256-point tone at bin 96.


3353-3353: Minor · Data Integrity & Integration · Quick win

Return the requested sample count from the VAG branch of Ngs2CalcWaveformBlock.

The VAG branch sets num_samples to the frame-aligned count (84 for sample_pos=10, num_samples=50). The decoder treats num_samples as the playback duration after num_skip_samples is removed. A block queued unchanged therefore plays 74 samples instead of 50. The ATRAC9 and PCM branches already return the requested count, so the VAG branch should match them. The aligned count does not affect data_size, which stays aligned to whole frames.

Suggested fix

-		block->num_samples      = num_samples == 0 ? 0 : (past - first) * VAG_FRAME_SAMPLES;
+		block->num_samples      = num_samples;

Update the expectation at tests/Ngs2SamplerTests.cpp:3155 to num_samples == 50. The current assertion of 84 encodes the over-length count.

tests/Ngs2SamplerTests.cpp: 2

2700-2704: Minor · Functional Correctness · Quick win

Use a voice allocated by its rack in the owner-index test.

Fixture::voice is a separate member, not an element of the rack's voice array. Ngs2VoiceGetOwner computes an index by subtracting the rack's array base from that pointer. The test depends on undefined pointer subtraction even if adjacent storage produces zero. Create the rack with RenderRack and obtain the voice through Ngs2RackGetVoiceHandle.


2865-2865: Minor · Functional Correctness · Quick win

Make the FFT assertions reject NaN.

Both tests reject an error only when it is greater than the tolerance. A NaN error does not satisfy that comparison, so both tests can accept nonfinite output for a finite input. Require the error to be at or below the tolerance, or check finiteness before comparing.

Also applies to: 2879-2879

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 39936ffa39 and f9c405865d.

Files selected for processing: 5

  • src/libs/libAudio.cpp
  • src/libs/ngs2.cpp
  • src/libs/ngs2.h
  • tests/Ngs2SamplerTests.cpp
  • tests/VdecswTests.cpp

Included 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 15:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6006320579) · **reviewed** <!-- coderabbit-ai-generated:v1 --> > [!NOTE] > Due to the large number of review comments, Critical severity comments were prioritized as inline comments. <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major comments: 21</summary><blockquote> <dl> <dd> <br> <details> <summary>src/libs/ngs2.cpp: 20</summary><blockquote> <dl> <dd> <br> `2220-2225`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Unlock only the rack acquired by the calling thread.** If one thread locks rack A and unlocks rack B on the same system, B has zero depth. The code skips B's bookkeeping but still releases the system mutex. A then reports that it is locked even though another thread can enter. Check the rack and owner before changing depth or releasing the mutex. Keep the normal lock/unlock pair balanced. <!-- cr-comment:v1:e1e55849f63d4b55a2c6b0a7 --> --- `2340-2340`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Do not change the current playback cursor during VAG lookahead.** At 24 kHz on a 48 kHz system, playback looks ahead from sample 27 to interpolate across the frame boundary. Decoding the next frame sets `voice.frame_cursor` to zero even when there is no skip. Interpolation then reads the start of the old frame. Keep each decoded frame's start cursor with that frame, or stage only playable samples at index zero. <!-- cr-comment:v1:ff7c45a791ccd8e1610d2768 --> --- `1586-1588`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Reject rack handles that are not in the registry.** If a caller destroys a rack and then queries its old handle, the lookup misses the registry and reads `ngs` from the former rack object. The pointer check does not establish that the object is still live. Return the invalid-rack error on a registry miss. Use registered racks in the tests that currently depend on the fallback. <!-- cr-comment:v1:e09f79fd006294c9ec0b26a4 --> --- `4550-4550`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Remove destroyed systems from the handle registry.** `Ngs2SystemDestroy` returns success without unlinking the system. The new enumerator therefore returns a destroyed handle if its storage is still live, or reads released storage if the caller freed it. Unlink the system before destroy returns. Synchronize enumeration and lookup with registry updates so live systems remain enumerable. <!-- cr-comment:v1:fd1efde461b8dd81b696cc81 --> --- `2780-2781`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Keep custom filter history in sync with voice setup.** A custom submixer can configure an enabled filter with one channel and then be set up with two channels. Setup clears `voice.filters`, but leaves the module filter enabled with one history entry. The next render accesses `history[1]`. Reset or rebuild module filter history when the layout changes, before processing the new channels. <!-- cr-comment:v1:1405ee0aaa2b0114272616ed --> --- `1255-1255`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Preserve the selected VAG format when clearing the queue.** `AddWaveformBlocks` calls `ClearWaveformBlocks` for CLEAR. This resets `is_vag`, so a replacement block on a configured VAG voice reaches the PCM decoder. Keep the VAG history and cursor resets in the queue clear. Reset `is_vag` only when sampler setup selects a new format, including deferred setup. <!-- cr-comment:v1:c4aeb776d90d51aa8d3ab5c2 --> --- `4801-4803`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Do not report more matrix levels than the query returns.** The existing matrix setter can store 1,370 levels. This query reports all 1,370 but copies only 1,369 into `info->levels`. A caller cannot use the returned count to read the result safely. Report the number copied, or reject a matrix that exceeds the ABI capacity if truncation is not allowed. <!-- cr-comment:v1:287927674f21618671ebd86a --> --- `4460-4462`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** **Synchronize system command writes with rendering.** The supplied test updates the rate and grain after its explicit unlock. These are accepted commands, but their stores do not take the mutex that protects the render reads. If rendering overlaps either store, the accesses race. Route ordinary mutations through the same synchronization as the direct setter and renderer. Preserve the behavior of explicit lock and unlock commands. <!-- cr-comment:v1:553c26c8585d23dfd43131c6 --> --- `5584-5584`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** **Do not return success without writing the stream query result.** A live stream and an eight-byte output buffer pass query `0xf24001`, but the buffer is left unchanged. The caller can treat its previous contents as fresh query data. Write the defined result for supported queries. If a result is not implemented yet, return a defined failure instead of reporting success. <!-- cr-comment:v1:215312e7b139c0e64db78495 --> --- `2306-2307`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Preserve VAG predictor history within a block.** After decoding the first frame, `vag_next_data` points to the second frame. The next iteration compares it with the block base and clears the predictor history. A predicted frame with zero residual then loses the expected decay. Compare `vag_next_data` with `block.data + block.data_cursor`. This preserves history for contiguous frames and still resets it after a discontinuity. <!-- cr-comment:v1:cc19936066d49ff456d20f0a --> --- `5484-5487`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Release the stream registry lock before calling the free handler.** If a free handler destroys another stream, a nonrecursive registry mutex blocks reentry. With a recursive mutex, deleting an earlier stream invalidates the iterator that the outer call still uses. Move the stream out of the registry and erase its entry under the lock. Then release the lock and call the handler with the detached stream's buffer information. <!-- cr-comment:v1:5b5fd7d206578bb060ed44ee --> --- `3987-3988`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Design the custom filter at the rate it processes.** The custom module runs after sampler resampling. A 22.05 kHz custom sampler on a 48 kHz system therefore processes 48 kHz samples with coefficients designed for 22.05 kHz. A custom submixer also uses the fixed 48 kHz fallback on a 44.1 kHz system. Use the system rate and redesign the coefficients when that rate changes. <!-- cr-comment:v1:3693deace5c5b57b693c1868 --> --- `3293-3296`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Performance & Scalability** · **Quick win** **Bound file reads to the waveform at the requested offset.** If a small RIFF waveform is near the start of an asset archive, this function allocates and reads the entire remaining archive. The parser then ignores the bytes beyond the RIFF extent. Read the header first and limit subsequent reads to the declared waveform extent. Return an error for a failed size query or an extent outside the file before allocating. <!-- cr-comment:v1:6a840a70c959ec6971d1dd63 --> --- `2702-2702`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Drain buffered pitch-shift audio after the source ends.** An active pitch-shift channel outputs silence until more than 1,984 input samples arrive. A finite 1,024-sample clip ends before that point. Once the source stops producing samples, the render guard stops calling the module, so the entire clip is silent. Track pending audio separately from current-grain input and drain it at end of stream. Keep bypassed channels on the existing direct path. <!-- cr-comment:v1:b597b109c41a9222f402c583 --> --- `5639-5639`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Read queue metadata only after acquiring the queue lock.** The first header copy reads mutable ring metadata and the lock word before acquisition. If another thread updates the queue, this copy bypasses the synchronization used by the second copy. No value from the first copy is used. Remove it and take the snapshot only after the lock is acquired. <!-- cr-comment:v1:bf714457fc5e54e7515d3344 --> --- `5048-5050`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** **Scale every bin in natural-order FFT output.** `Ngs2FftPackNatural` writes `2 * points` floats. The scaling loop visits only `points` floats. For a 256-point transform, a tone at bin 96 is stored at float index 384 and is returned without the requested `1/256` factor. Scale the entire packed output, as the internal-order branch does. <!-- cr-comment:v1:77543ca4345e514b550fbf5c --> --- `5453-5461`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Keep fallback storage out of the caller's free handler.** If the allocation callback fails without supplying a buffer, creation installs vector-owned storage but leaves `has_allocator` set. Destroy then passes that storage to the caller's free handler, and the vector releases it again. Propagate the allocation error, or mark the fallback as internally owned. Keep calling the caller's free handler exactly once for a successful caller allocation. <!-- cr-comment:v1:96f4342957ac5176d8ed1844 --> --- `5406-5409`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Require a registered system before creating a stream.** `Ngs2FindSystem` returns a cast pointer for an unregistered handle above the low-address cutoff. `Ngs2StreamCreate` and `Ngs2StreamCreateWithAllocator` accept that pointer and can return success without a live owner. Use a registry-only lookup for stream creation. Keep the existing success path for a live system. <!-- cr-comment:v1:6d3c695aa7e97e63612558a4 --> --- `3319-3321`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Keep ATRAC9 geometry queries compatible with parsed formats.** The RIFF parser accepts codec-matched channel counts, including the 12-channel ATRAC9 format covered by the codec test. Both geometry APIs reject that format before reading its codec configuration. Apply the eight-channel limit only to the formats that require it. Validate ATRAC9 channels and rate against the codec result in both APIs. Also applies to: 5112-5114 <!-- cr-comment:v1:431828b963c49d8b202ae2fa --> --- `3285-3285`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Resolve guest paths through the kernel mount table before `Ngs2ParseWaveformFile` opens the file.** `Ngs2ParseWaveformFile` passes `path` directly to `std::ifstream`. A guest path such as `/app0/...` therefore resolves as a host path, not through the `/app0` mount. The open fails, and the function returns `NGS2_ERROR_INVALID_WAVEFORM_DATA` for assets that exist only in the guest mount. Other guest file APIs translate paths through the kernel mount resolver before host access. Apply the same translation here, for example with the existing `FileSystem::GetRealFilename` helper, before the open. <!-- cr-comment:v1:be76d52e5b2cbd2200f5f95a --> </dd> </dl> </blockquote></details> <details> <summary>tests/Ngs2SamplerTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `3571-3571`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Destroy registered racks before their test buffers expire.** `TestCustomFilterModule` releases `rBuf` without calling `Ngs2RackDestroy`. The next system render traverses `g_racks_list`, which still contains the freed rack. The VAG, gain, mixer, and pitch tests repeat this teardown pattern. Use `RenderRack` or explicitly destroy each rack before releasing its storage. Where a test does not need to exercise system creation, use the existing stack-system fixture so it does not leave a system registry entry either. <!-- cr-comment:v1:844bab15c235c8e21f6c26ae --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor comments: 10</summary><blockquote> <dl> <dd> <br> <details> <summary>src/libs/ngs2.cpp: 8</summary><blockquote> <dl> <dd> <br> `3347-3353`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Widen VAG block arithmetic before computing the endpoints.** For an eight-channel VAG block above 4 GiB in encoded data, the start offset is computed in 64 bits, but `past * frame_bytes` wraps in 32 bits. Subtracting the start offset then produces a very large `data_size` for a short request. The sample endpoint can also wrap before division. Compute both endpoints and encoded offsets in 64 bits. Reject any result that cannot fit its destination field. <!-- cr-comment:v1:b8f2a24762a12ac41715af8e --> --- `2663-2663`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Redesign the LFE filter when the cutoff changes.** If a voice renders with an 80 Hz cutoff and then receives a 120 Hz cutoff at the same system rate, the design-rate check keeps the 80 Hz coefficients. Include the cutoff in the design key. Repeated controls that do not change the cutoff can still reuse the coefficients. <!-- cr-comment:v1:50f1596d8d9a4b75f9d3a03a --> --- `4499-4499`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Accept oversized buffers in the system-info query.** A 192-byte output buffer passes the query's 184-byte minimum check, but `Ngs2SystemGetInfo` rejects it because it requires exactly 184 bytes. After checking capacity, pass `sizeof(Ngs2SystemInfo)` to the fixed-size helper. This accepts both buffer sizes without writing into the extra bytes. <!-- cr-comment:v1:e51cd3548bfcf544d8dfdc8f --> --- `4814-4814`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Validate FFT length before subtracting.** `Ngs2FftInit` accepts a signed `length`. If it is `INT_MIN`, `length - 8` overflows before the cast. Compare the signed value directly with 8 and 12. This rejects the extreme value and preserves the supported range. <!-- cr-comment:v1:e0c76394ffffaae6be5ded75 --> --- `3063-3065`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Recognize the IEEE float subtype in extensible WAVE files.** A valid 32-bit float waveform can use `WAVE_FORMAT_EXTENSIBLE` with the IEEE float subtype. The parser rejects that subtype before it reaches the float width mapping. Recognize the float subtype and pass it through the same width checks as tag 3. Keep extensible integer PCM and ATRAC9 on their existing branches. ([learn.microsoft.com](https://learn.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible?utm_source=openai)) Also applies to: 3070-3070 <!-- cr-comment:v1:ea014f76abfbb752d4bacb51 --> --- `4688-4688`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Update the rack render count when the rack renders.** `Ngs2RackGetInfo` returns `rack->render_count`, but rendering only increments the system count. A rack still reports zero after it has rendered multiple grains. Increment the count once per rack at the corresponding render boundary, not once per voice. <!-- cr-comment:v1:52a4e4498e430910d675732f --> --- `5058-5069`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Heavy lift** **Natural-order inverse FFT does not accept natural-order forward output.** With mode bit 2 clear, `Ngs2FftProcess` writes forward output in four blocks spaced `points / 2` floats apart. Each block holds data in its first `points / 4` floats, and odd blocks are reversed. The natural inverse path (`src/libs/ngs2.cpp:5064-5069`) reads the first `points` floats as contiguous bin pairs. For a 256-point transform, a tone at bin 96 is written at float 384, which the inverse never reads. Bins 32 through 127 also come back from the wrong positions. A forward (`0x1`) followed by inverse (`0x8`) round trip in natural order therefore does not return the input. The internal-order path (bit 2 set) uses matching pack and unpack helpers and round-trips correctly. The tests cover only internal order, so this natural-order mismatch is not caught. Decide the layout the guest ABI requires for the natural inverse input. If the ABI expects the forward layout, change the inverse to unpack the block layout. If it expects contiguous pairs, change the forward natural pack to write contiguous pairs. Add a natural-order round-trip test for a 256-point tone at bin 96. <!-- cr-comment:v1:5aa1b26d148d64d9ddc41f69 --> --- `3353-3353`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Return the requested sample count from the VAG branch of `Ngs2CalcWaveformBlock`.** The VAG branch sets `num_samples` to the frame-aligned count (84 for `sample_pos=10, num_samples=50`). The decoder treats `num_samples` as the playback duration after `num_skip_samples` is removed. A block queued unchanged therefore plays 74 samples instead of 50. The ATRAC9 and PCM branches already return the requested count, so the VAG branch should match them. The aligned count does not affect `data_size`, which stays aligned to whole frames. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff - block->num_samples = num_samples == 0 ? 0 : (past - first) * VAG_FRAME_SAMPLES; + block->num_samples = num_samples; ``` </dd> </dl> </details> Update the expectation at `tests/Ngs2SamplerTests.cpp:3155` to `num_samples == 50`. The current assertion of 84 encodes the over-length count. <!-- cr-comment:v1:0e995ad689e53e57d2852dcf --> </dd> </dl> </blockquote></details> <details> <summary>tests/Ngs2SamplerTests.cpp: 2</summary><blockquote> <dl> <dd> <br> `2700-2704`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Use a voice allocated by its rack in the owner-index test.** `Fixture::voice` is a separate member, not an element of the rack's voice array. `Ngs2VoiceGetOwner` computes an index by subtracting the rack's array base from that pointer. The test depends on undefined pointer subtraction even if adjacent storage produces zero. Create the rack with `RenderRack` and obtain the voice through `Ngs2RackGetVoiceHandle`. <!-- cr-comment:v1:3a0f85a39cbc4bfee1f17969 --> --- `2865-2865`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Make the FFT assertions reject NaN.** Both tests reject an error only when it is greater than the tolerance. A NaN error does not satisfy that comparison, so both tests can accept nonfinite output for a finite input. Require the error to be at or below the tolerance, or check finiteness before comparing. Also applies to: 2879-2879 <!-- cr-comment:v1:548d8722d125f8c8ede97155 --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `41c1ea08-c063-44db-be68-29104538892f` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 39936ffa39237997080f8d169370667ca63d12fa and f9c405865dc289a85691b77f97c1f8cf23ef6df8. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 5</summary> <dl> <dd> <br> * `src/libs/libAudio.cpp` * `src/libs/ngs2.cpp` * `src/libs/ngs2.h` * `tests/Ngs2SamplerTests.cpp` * `tests/VdecswTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=777df9bf-4b3a-41cf-b4e8-c5685be3cb12 attempt=3a0dc429-4dc2-44dd-a562-ecc34df3494e batch=1/1 -->
@ -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);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · edited 2026-11-21 17:07 UTC

Major · Data Integrity & Integration · Quick win

Pass the allocator context to stream allocation.

stream->buffer_info.user_data is still zero when the allocation callback runs. An allocator that uses Ngs2BufferAllocator::user_data to 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_data before allocation. Preserve the callback's resulting buffer information for destruction.

✅ Addressed in commits b2cf3b5 to bb303ad

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 16:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653633535) · edited 2026-11-21 17:07 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Quick win** **Pass the allocator context to stream allocation.** `stream->buffer_info.user_data` is still zero when the allocation callback runs. An allocator that uses `Ngs2BufferAllocator::user_data` to 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_data` before allocation. Preserve the callback's resulting buffer information for destruction. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:aa86367ce1dc1851f244dc84 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits b2cf3b5 to bb303ad
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · edited 2026-11-21 17:07 UTC
On tests/Ngs2SamplerTests.cpp line 2717 (outdated):

@@ -2437,6 +2507,1339 @@ void TestFiniteFilterTail() {
 	Check(!split.voice.has_samples, "completed finite filter tail still produced samples");
 }
 
+void TestSystemRunCommandsAndQueries() {
+	Ngs2SystemOption opt {};
+	Ngs2SystemResetOption(&opt);
+	Check(opt.sample_rate == 48000, "reset option failed");
+
+	Ngs2Internal system;
+	system.option = opt;
+	const auto sys_handle = reinterpret_cast<uintptr_t>(&system);
+
+	// User data
+	uintptr_t ud = 0;
+	Check(Ngs2SystemSetUserData(sys_handle, 0x12345678) == OK, "set user data failed");
+	Check(Ngs2SystemGetUserData(sys_handle, &ud) == OK && ud == 0x12345678, "get user data failed");
+
+	// Sample rate
+	Check(Ngs2SystemSetSampleRate(sys_handle, 44100) == OK && system.option.sample_rate == 44100, "set sample rate failed");
+	Check(Ngs2SystemSetSampleRate(sys_handle, 12345) == NGS2_ERROR_INVALID_SAMPLE_RATE, "invalid sample rate accepted");
+
+	// Lock & Unlock
+	Check(Ngs2SystemLock(sys_handle) == OK, "system lock failed");
+	Check(Ngs2SystemUnlock(sys_handle) == OK, "system unlock failed");
+
+	// Commands
+	struct Cmd {
+		uint32_t id;
+		uint8_t  flags, type;
+		uint16_t count;
+		union {
+			uint64_t    u64;
+			uint32_t    u32;
+			int32_t     i32;
+			float       f;
+			const void* ptr;
+		} value;
+	};
+
+	Cmd cmds[6] = {};
+	cmds[0].id = 0xf00000; // lock
+	cmds[1].id = 0xf00001; // unlock
+	cmds[2].id = 0xf00002; // userdata
+	cmds[2].value.u64 = 0x8888;
+	cmds[3].id = 0xf00004; // samplerate
+	cmds[3].value.u32 = 96000;
+	cmds[4].id = 0xf00005; // grain
+	cmds[4].value.u32 = 128;
+	cmds[5].id = 0xf00006; // unnamed float
+	cmds[5].value.f = 0.75f;
+
+	Check(Ngs2SystemRunCommands(sys_handle, cmds, 6) == OK, "system run commands failed");
+	Check(system.user_data == 0x8888, "system userdata cmd failed");
+	Check(system.option.sample_rate == 96000, "system samplerate cmd failed");
+	Check(system.option.num_grain_samples == 128, "system grain cmd failed");
+	Check(std::abs(system.unnamed_param - 0.75f) < 1e-6f, "system unnamed param failed");
+
+	// Slot command
+	uint8_t slot_bytes[24] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
+	Cmd slot_cmd {};
+	slot_cmd.id = 0xf00003 | (2u << 24); // slot 2
+	slot_cmd.value.ptr = slot_bytes;
+	Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "slot cmd failed");
+	Check(system.slot_set[2], "slot 2 not set");
+	Check(std::memcmp(system.slot_data[2].data(), slot_bytes, 24) == 0, "slot data mismatch");
+
+	// Clear slot
+	slot_cmd.value.ptr = nullptr;
+	Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "clear slot failed");
+	Check(!system.slot_set[2], "slot 2 not cleared");
+
+	// QueryInfo tests
+	uint64_t query_ud = 0;
+	Check(Ngs2SystemQueryInfo(sys_handle, 0xf04001, &query_ud, sizeof(query_ud)) == OK, "query userdata failed");
+	Check(query_ud == 0x8888, "queried userdata mismatch");
+
+	// Reset slot for query
+	slot_cmd.value.ptr = slot_bytes;
+	Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "re-set slot failed");
+	uint8_t query_slot[24] = {};
+	Check(Ngs2SystemQueryInfo(sys_handle, 0xf04002 | (2u << 24), query_slot, 24) == OK, "query slot failed");
+	Check(std::memcmp(query_slot, slot_bytes, 24) == 0, "queried slot mismatch");
+
+	// Error handling
+	Cmd bad_cmd {};
+	bad_cmd.id = 0xdeadbeef;
+	Check(Ngs2SystemRunCommands(sys_handle, &bad_cmd, 1) == NGS2_ERROR_INVALID_PARAM_ID, "bad cmd allowed");
+	Check(Ngs2SystemQueryInfo(sys_handle, 0xdeadbeef, &query_ud, sizeof(query_ud)) == NGS2_ERROR_INVALID_SYSTEM_QUERY_ID, "bad query allowed");
+}
+
+void TestRackRunCommandsAndQueries() {
+	Ngs2Internal system;
+	system.option.sample_rate = 48000;
+	system.option.num_grain_samples = 256;
+	Ngs2CustomSamplerRackOption c_opt {};
+	c_opt.custom_rack_option.rack_option.size = sizeof(c_opt);
+	c_opt.custom_rack_option.rack_option.max_grain_samples = 512;
+	c_opt.custom_rack_option.rack_option.max_voices = 1;
+	c_opt.custom_rack_option.rack_option.max_ports = 1;
+	c_opt.custom_rack_option.rack_option.max_matrices = 1;
+	c_opt.custom_rack_option.num_buffers = 1;
+	c_opt.custom_rack_option.num_modules = 2;
+	c_opt.custom_rack_option.module[0].module_id = 0x15;
+	c_opt.custom_rack_option.module[0].source_buffer_id = 0;
+	c_opt.custom_rack_option.module[0].dest_buffer_id = 0;
+	c_opt.custom_rack_option.module[0].state_size = 64;
+	c_opt.custom_rack_option.state_size = sizeof(Ngs2CustomSamplerVoiceState);
+	c_opt.max_waveform_blocks = 4;
+
+	RenderRack renderRack(system, 0x4001, c_opt.custom_rack_option.rack_option);
+	const auto rack_handle = renderRack.handle;
+	auto* rack_ptr = reinterpret_cast<Ngs2RackInternal*>(rack_handle);
+	std::memcpy(rack_ptr->name, "CustomTestRack", 15);
+	rack_ptr->uid = 42;
+	auto& rack = *rack_ptr;
+
+	// User data
+	uintptr_t ud = 0;
+	Check(Ngs2RackSetUserData(rack_handle, 0x9999) == OK, "rack set user data failed");
+	Check(Ngs2RackGetUserData(rack_handle, &ud) == OK && ud == 0x9999, "rack get user data failed");
+
+	// Lock & Unlock
+	Check(Ngs2RackLock(rack_handle) == OK, "rack lock failed");
+	Check(rack.lock_depth == 1, "rack lock depth mismatch");
+	Check(Ngs2RackUnlock(rack_handle) == OK, "rack unlock failed");
+	Check(rack.lock_depth == 0, "rack lock depth after unlock mismatch");
+
+	// RackRunCommands
+	struct Cmd {
+		uint32_t id;
+		uint8_t  flags, type;
+		uint16_t count;
+		union {
+			uint64_t    u64;
+			uint32_t    u32;
+			int32_t     i32;
+			float       f;
+			const void* ptr;
+		} value;
+	};
+	Cmd cmds[3] = {};
+	cmds[0].id = 0xf10000; // lock
+	cmds[1].id = 0xf10001; // unlock
+	cmds[2].id = 0xf10002; // user data
+	cmds[2].value.u64 = 0x7777;
+	Check(Ngs2RackRunCommands(rack_handle, cmds, 3) == OK, "rack run commands failed");
+	Check(rack.user_data == 0x7777, "rack run commands user data failed");
+
+	// RackGetInfo
+	Ngs2RackInfo info {};
+	Check(Ngs2RackGetInfo(rack_handle, &info, sizeof(info)) == OK, "rack get info failed");
+	Check(std::strcmp(info.name, "CustomTestRack") == 0, "rack get info name mismatch");
+	Check(info.rack_id == 0x4001, "rack get info rack_id mismatch");
+	Check(info.uid == 42, "rack get info uid mismatch");
+	Check(info.type == 0, "rack get info type mismatch"); // sampler/custom_sampler is 0
+	Check(info.num_modules == 2, "rack get info num_modules mismatch");
+	Check(info.active_voice_count == 0, "rack get info active voices mismatch");
+
+	// Test created rack with active voice
+	Ngs2Internal sys {};
+	sys.option.max_grain_samples = 512;
+	sys.option.num_grain_samples = 256;
+	sys.option.sample_rate = 48000;
+	Ngs2RackOptionUnion r_opt {};
+	r_opt.sampler.rack_option.size = sizeof(Ngs2SamplerRackOption);
+	r_opt.sampler.rack_option.max_grain_samples = 512;
+	r_opt.sampler.rack_option.max_voices = 2;
+	r_opt.sampler.rack_option.max_ports = 8;
+	r_opt.sampler.rack_option.max_matrices = 1;
+	r_opt.sampler.max_waveform_blocks = 4;
+	std::vector<uint8_t> r_buf(sizeof(Ngs2RackInternal) + 2 * sizeof(Ngs2VoiceInternal) + 16384);
+	Ngs2ContextBufferInfo c_buf {};
+	c_buf.host_buffer = r_buf.data();
+	c_buf.host_buffer_size = r_buf.size();
+	uintptr_t cr_handle = 0;
+	Check(Ngs2RackCreate(reinterpret_cast<uintptr_t>(&sys), 0x1000, &r_opt.common, &c_buf, &cr_handle) == OK, "create rack failed");
+	auto* cr_voices = reinterpret_cast<Ngs2VoiceInternal*>(reinterpret_cast<Ngs2RackInternal*>(cr_handle) + 1);
+	cr_voices[0].state = Ngs2VoicePlayState::Playing;
+	cr_voices[0].channels = 2;
+	Ngs2RackInfo cr_info {};
+	Check(Ngs2RackGetInfo(cr_handle, &cr_info, sizeof(cr_info)) == OK, "get info for created rack failed");
+	Check(cr_info.active_voice_count == 1, "created rack active voice count mismatch");
+	Check(cr_info.active_channel_work_count == 2, "created rack active channel count mismatch");
+	Check(Ngs2RackDestroy(cr_handle, nullptr) == OK, "destroy created rack failed");
+
+	// RackQueryInfo
+	Ngs2RackInfo qinfo {};
+	Check(Ngs2RackQueryInfo(rack_handle, 0xf14000, &qinfo, sizeof(qinfo)) == OK, "rack query info failed");
+	Check(qinfo.rack_id == 0x4001, "queried rack info mismatch");
+
+	uint64_t q_ud = 0;
+	Check(Ngs2RackQueryInfo(rack_handle, 0xf14001, &q_ud, sizeof(q_ud)) == OK && q_ud == 0x7777, "rack query ud failed");
+
+	Ngs2CustomModuleInfo q_mod {};
+	Check(Ngs2RackQueryInfo(rack_handle, 0xf14002 | (0u << 24), &q_mod, sizeof(q_mod)) == OK, "rack query mod failed");
+	Check(q_mod.module_id == 0x15 && q_mod.state_size == 64, "queried mod mismatch");
+
+	// CustomRackGetModuleInfo
+	Ngs2CustomModuleInfo mod_info {};
+	Check(Ngs2CustomRackGetModuleInfo(rack_handle, 0, &mod_info, sizeof(mod_info)) == OK, "custom rack get module info failed");
+	Check(mod_info.module_id == 0x15 && mod_info.state_size == 64, "module info mismatch");
+	Check(Ngs2CustomRackGetModuleInfo(rack_handle, 99, &mod_info, sizeof(mod_info)) == NGS2_ERROR_INVALID_RACK_MODULE_INDEX, "out of range module allowed");
+}
+
+void TestVoiceOwnerAndMatrixInfo() {
+	Ngs2Internal system;
+	system.option                   = Ngs2DefaultSystemOption();
+	system.option.sample_rate = 48000;
+	system.option.num_grain_samples = 256;
+	Ngs2SamplerRackOption option {};
+	Ngs2FillDefaultRackOption(0x1000, reinterpret_cast<Ngs2RackOptionUnion*>(&option));

Major · Stability & Availability · Quick win

Allocate a full option union before filling defaults.

option is a Ngs2SamplerRackOption, but Ngs2FillDefaultRackOption first assigns an entire Ngs2RackOptionUnion. The union contains much larger custom-rack options. This call overwrites the stack beyond option and can crash the test or fail under AddressSanitizer.

Declare a Ngs2RackOptionUnion, fill that object, and use its sampler member.

✅ Addressed in commits b2cf3b5 to bb303ad

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 16:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653633538) · edited 2026-11-21 17:07 UTC On `tests/Ngs2SamplerTests.cpp` line 2717 (outdated): ```diff @@ -2437,6 +2507,1339 @@ void TestFiniteFilterTail() { Check(!split.voice.has_samples, "completed finite filter tail still produced samples"); } +void TestSystemRunCommandsAndQueries() { + Ngs2SystemOption opt {}; + Ngs2SystemResetOption(&opt); + Check(opt.sample_rate == 48000, "reset option failed"); + + Ngs2Internal system; + system.option = opt; + const auto sys_handle = reinterpret_cast<uintptr_t>(&system); + + // User data + uintptr_t ud = 0; + Check(Ngs2SystemSetUserData(sys_handle, 0x12345678) == OK, "set user data failed"); + Check(Ngs2SystemGetUserData(sys_handle, &ud) == OK && ud == 0x12345678, "get user data failed"); + + // Sample rate + Check(Ngs2SystemSetSampleRate(sys_handle, 44100) == OK && system.option.sample_rate == 44100, "set sample rate failed"); + Check(Ngs2SystemSetSampleRate(sys_handle, 12345) == NGS2_ERROR_INVALID_SAMPLE_RATE, "invalid sample rate accepted"); + + // Lock & Unlock + Check(Ngs2SystemLock(sys_handle) == OK, "system lock failed"); + Check(Ngs2SystemUnlock(sys_handle) == OK, "system unlock failed"); + + // Commands + struct Cmd { + uint32_t id; + uint8_t flags, type; + uint16_t count; + union { + uint64_t u64; + uint32_t u32; + int32_t i32; + float f; + const void* ptr; + } value; + }; + + Cmd cmds[6] = {}; + cmds[0].id = 0xf00000; // lock + cmds[1].id = 0xf00001; // unlock + cmds[2].id = 0xf00002; // userdata + cmds[2].value.u64 = 0x8888; + cmds[3].id = 0xf00004; // samplerate + cmds[3].value.u32 = 96000; + cmds[4].id = 0xf00005; // grain + cmds[4].value.u32 = 128; + cmds[5].id = 0xf00006; // unnamed float + cmds[5].value.f = 0.75f; + + Check(Ngs2SystemRunCommands(sys_handle, cmds, 6) == OK, "system run commands failed"); + Check(system.user_data == 0x8888, "system userdata cmd failed"); + Check(system.option.sample_rate == 96000, "system samplerate cmd failed"); + Check(system.option.num_grain_samples == 128, "system grain cmd failed"); + Check(std::abs(system.unnamed_param - 0.75f) < 1e-6f, "system unnamed param failed"); + + // Slot command + uint8_t slot_bytes[24] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; + Cmd slot_cmd {}; + slot_cmd.id = 0xf00003 | (2u << 24); // slot 2 + slot_cmd.value.ptr = slot_bytes; + Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "slot cmd failed"); + Check(system.slot_set[2], "slot 2 not set"); + Check(std::memcmp(system.slot_data[2].data(), slot_bytes, 24) == 0, "slot data mismatch"); + + // Clear slot + slot_cmd.value.ptr = nullptr; + Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "clear slot failed"); + Check(!system.slot_set[2], "slot 2 not cleared"); + + // QueryInfo tests + uint64_t query_ud = 0; + Check(Ngs2SystemQueryInfo(sys_handle, 0xf04001, &query_ud, sizeof(query_ud)) == OK, "query userdata failed"); + Check(query_ud == 0x8888, "queried userdata mismatch"); + + // Reset slot for query + slot_cmd.value.ptr = slot_bytes; + Check(Ngs2SystemRunCommands(sys_handle, &slot_cmd, 1) == OK, "re-set slot failed"); + uint8_t query_slot[24] = {}; + Check(Ngs2SystemQueryInfo(sys_handle, 0xf04002 | (2u << 24), query_slot, 24) == OK, "query slot failed"); + Check(std::memcmp(query_slot, slot_bytes, 24) == 0, "queried slot mismatch"); + + // Error handling + Cmd bad_cmd {}; + bad_cmd.id = 0xdeadbeef; + Check(Ngs2SystemRunCommands(sys_handle, &bad_cmd, 1) == NGS2_ERROR_INVALID_PARAM_ID, "bad cmd allowed"); + Check(Ngs2SystemQueryInfo(sys_handle, 0xdeadbeef, &query_ud, sizeof(query_ud)) == NGS2_ERROR_INVALID_SYSTEM_QUERY_ID, "bad query allowed"); +} + +void TestRackRunCommandsAndQueries() { + Ngs2Internal system; + system.option.sample_rate = 48000; + system.option.num_grain_samples = 256; + Ngs2CustomSamplerRackOption c_opt {}; + c_opt.custom_rack_option.rack_option.size = sizeof(c_opt); + c_opt.custom_rack_option.rack_option.max_grain_samples = 512; + c_opt.custom_rack_option.rack_option.max_voices = 1; + c_opt.custom_rack_option.rack_option.max_ports = 1; + c_opt.custom_rack_option.rack_option.max_matrices = 1; + c_opt.custom_rack_option.num_buffers = 1; + c_opt.custom_rack_option.num_modules = 2; + c_opt.custom_rack_option.module[0].module_id = 0x15; + c_opt.custom_rack_option.module[0].source_buffer_id = 0; + c_opt.custom_rack_option.module[0].dest_buffer_id = 0; + c_opt.custom_rack_option.module[0].state_size = 64; + c_opt.custom_rack_option.state_size = sizeof(Ngs2CustomSamplerVoiceState); + c_opt.max_waveform_blocks = 4; + + RenderRack renderRack(system, 0x4001, c_opt.custom_rack_option.rack_option); + const auto rack_handle = renderRack.handle; + auto* rack_ptr = reinterpret_cast<Ngs2RackInternal*>(rack_handle); + std::memcpy(rack_ptr->name, "CustomTestRack", 15); + rack_ptr->uid = 42; + auto& rack = *rack_ptr; + + // User data + uintptr_t ud = 0; + Check(Ngs2RackSetUserData(rack_handle, 0x9999) == OK, "rack set user data failed"); + Check(Ngs2RackGetUserData(rack_handle, &ud) == OK && ud == 0x9999, "rack get user data failed"); + + // Lock & Unlock + Check(Ngs2RackLock(rack_handle) == OK, "rack lock failed"); + Check(rack.lock_depth == 1, "rack lock depth mismatch"); + Check(Ngs2RackUnlock(rack_handle) == OK, "rack unlock failed"); + Check(rack.lock_depth == 0, "rack lock depth after unlock mismatch"); + + // RackRunCommands + struct Cmd { + uint32_t id; + uint8_t flags, type; + uint16_t count; + union { + uint64_t u64; + uint32_t u32; + int32_t i32; + float f; + const void* ptr; + } value; + }; + Cmd cmds[3] = {}; + cmds[0].id = 0xf10000; // lock + cmds[1].id = 0xf10001; // unlock + cmds[2].id = 0xf10002; // user data + cmds[2].value.u64 = 0x7777; + Check(Ngs2RackRunCommands(rack_handle, cmds, 3) == OK, "rack run commands failed"); + Check(rack.user_data == 0x7777, "rack run commands user data failed"); + + // RackGetInfo + Ngs2RackInfo info {}; + Check(Ngs2RackGetInfo(rack_handle, &info, sizeof(info)) == OK, "rack get info failed"); + Check(std::strcmp(info.name, "CustomTestRack") == 0, "rack get info name mismatch"); + Check(info.rack_id == 0x4001, "rack get info rack_id mismatch"); + Check(info.uid == 42, "rack get info uid mismatch"); + Check(info.type == 0, "rack get info type mismatch"); // sampler/custom_sampler is 0 + Check(info.num_modules == 2, "rack get info num_modules mismatch"); + Check(info.active_voice_count == 0, "rack get info active voices mismatch"); + + // Test created rack with active voice + Ngs2Internal sys {}; + sys.option.max_grain_samples = 512; + sys.option.num_grain_samples = 256; + sys.option.sample_rate = 48000; + Ngs2RackOptionUnion r_opt {}; + r_opt.sampler.rack_option.size = sizeof(Ngs2SamplerRackOption); + r_opt.sampler.rack_option.max_grain_samples = 512; + r_opt.sampler.rack_option.max_voices = 2; + r_opt.sampler.rack_option.max_ports = 8; + r_opt.sampler.rack_option.max_matrices = 1; + r_opt.sampler.max_waveform_blocks = 4; + std::vector<uint8_t> r_buf(sizeof(Ngs2RackInternal) + 2 * sizeof(Ngs2VoiceInternal) + 16384); + Ngs2ContextBufferInfo c_buf {}; + c_buf.host_buffer = r_buf.data(); + c_buf.host_buffer_size = r_buf.size(); + uintptr_t cr_handle = 0; + Check(Ngs2RackCreate(reinterpret_cast<uintptr_t>(&sys), 0x1000, &r_opt.common, &c_buf, &cr_handle) == OK, "create rack failed"); + auto* cr_voices = reinterpret_cast<Ngs2VoiceInternal*>(reinterpret_cast<Ngs2RackInternal*>(cr_handle) + 1); + cr_voices[0].state = Ngs2VoicePlayState::Playing; + cr_voices[0].channels = 2; + Ngs2RackInfo cr_info {}; + Check(Ngs2RackGetInfo(cr_handle, &cr_info, sizeof(cr_info)) == OK, "get info for created rack failed"); + Check(cr_info.active_voice_count == 1, "created rack active voice count mismatch"); + Check(cr_info.active_channel_work_count == 2, "created rack active channel count mismatch"); + Check(Ngs2RackDestroy(cr_handle, nullptr) == OK, "destroy created rack failed"); + + // RackQueryInfo + Ngs2RackInfo qinfo {}; + Check(Ngs2RackQueryInfo(rack_handle, 0xf14000, &qinfo, sizeof(qinfo)) == OK, "rack query info failed"); + Check(qinfo.rack_id == 0x4001, "queried rack info mismatch"); + + uint64_t q_ud = 0; + Check(Ngs2RackQueryInfo(rack_handle, 0xf14001, &q_ud, sizeof(q_ud)) == OK && q_ud == 0x7777, "rack query ud failed"); + + Ngs2CustomModuleInfo q_mod {}; + Check(Ngs2RackQueryInfo(rack_handle, 0xf14002 | (0u << 24), &q_mod, sizeof(q_mod)) == OK, "rack query mod failed"); + Check(q_mod.module_id == 0x15 && q_mod.state_size == 64, "queried mod mismatch"); + + // CustomRackGetModuleInfo + Ngs2CustomModuleInfo mod_info {}; + Check(Ngs2CustomRackGetModuleInfo(rack_handle, 0, &mod_info, sizeof(mod_info)) == OK, "custom rack get module info failed"); + Check(mod_info.module_id == 0x15 && mod_info.state_size == 64, "module info mismatch"); + Check(Ngs2CustomRackGetModuleInfo(rack_handle, 99, &mod_info, sizeof(mod_info)) == NGS2_ERROR_INVALID_RACK_MODULE_INDEX, "out of range module allowed"); +} + +void TestVoiceOwnerAndMatrixInfo() { + Ngs2Internal system; + system.option = Ngs2DefaultSystemOption(); + system.option.sample_rate = 48000; + system.option.num_grain_samples = 256; + Ngs2SamplerRackOption option {}; + Ngs2FillDefaultRackOption(0x1000, reinterpret_cast<Ngs2RackOptionUnion*>(&option)); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Allocate a full option union before filling defaults.** `option` is a `Ngs2SamplerRackOption`, but `Ngs2FillDefaultRackOption` first assigns an entire `Ngs2RackOptionUnion`. The union contains much larger custom-rack options. This call overwrites the stack beyond `option` and can crash the test or fail under AddressSanitizer. Declare a `Ngs2RackOptionUnion`, fill that object, and use its `sampler` member. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:189cda3ed22a4d697acbc953 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commits b2cf3b5 to bb303ad
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 16:20 UTC · original · reviewed

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f9c405865d and 6776f8dff3.

Files selected for processing: 2

  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp

Included 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 16:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6006548508) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 2** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `c77c9e77-f975-45d9-b56c-cd1f4ed1ca4a` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between f9c405865dc289a85691b77f97c1f8cf23ef6df8 and 6776f8dff3f0baf53832918d97b957acc43a66f4. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/libs/ngs2.cpp` * `tests/Ngs2SamplerTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=1a40a5bd-438c-46b6-ab53-197d437f8726 attempt=181d99c8-c035-40d1-94f1-275e68da8869 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On src/libs/ngs2.cpp line 2575 (outdated):

@@ -2004,7 +2563,19 @@ static void Ngs2ConsumeSamples(Ngs2VoiceInternal& voice, uint32_t grain) {
 				if (voice.next_decoded_frame.empty()) {
 					voice.next_decoded_frame.resize(voice.decoded_frame.size());
 				}
+				// The decode reports the staged frame's start cursor through
+				// frame_cursor/frame_samples; keep them with the staged frame
+				// and restore the cursor of the frame still being played.
+				const auto saved_cursor  = voice.frame_cursor;
+				const auto saved_samples = voice.frame_samples;
+				voice.frame_cursor       = 0;
+				voice.frame_samples      = 0;
 				Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples);
+				if (voice.source_generation == generation) {
+					voice.next_frame_cursor = voice.frame_cursor;

Minor · Functional Correctness · Quick win

Do not stage a fully skipped VAG frame as lookahead.

When a VAG block has only skipped samples left, Ngs2DecodeFrame returns false. It still sets frame_samples to the skip count. The lookahead at lines 2573-2577 stores that count as next_frame_samples and 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

-				Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples);
+				const bool staged = Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples);
 				if (voice.source_generation == generation) {
 					voice.next_frame_cursor = voice.frame_cursor;
 					voice.frame_cursor      = saved_cursor;
 					voice.frame_samples     = saved_samples;
+					if (!staged) {
+						voice.next_frame_samples = 0;
+					}
 				}

✅ Addressed in commit 1de75dc

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653931121) · edited 2026-11-21 18:40 UTC On `src/libs/ngs2.cpp` line 2575 (outdated): ```diff @@ -2004,7 +2563,19 @@ static void Ngs2ConsumeSamples(Ngs2VoiceInternal& voice, uint32_t grain) { if (voice.next_decoded_frame.empty()) { voice.next_decoded_frame.resize(voice.decoded_frame.size()); } + // The decode reports the staged frame's start cursor through + // frame_cursor/frame_samples; keep them with the staged frame + // and restore the cursor of the frame still being played. + const auto saved_cursor = voice.frame_cursor; + const auto saved_samples = voice.frame_samples; + voice.frame_cursor = 0; + voice.frame_samples = 0; Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples); + if (voice.source_generation == generation) { + voice.next_frame_cursor = voice.frame_cursor; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Do not stage a fully skipped VAG frame as lookahead.** When a VAG block has only skipped samples left, `Ngs2DecodeFrame` returns `false`. It still sets `frame_samples` to the skip count. The lookahead at lines 2573-2577 stores that count as `next_frame_samples` and 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. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff - Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples); + const bool staged = Ngs2DecodeFrame(voice, voice.next_decoded_frame, voice.next_frame_samples); if (voice.source_generation == generation) { voice.next_frame_cursor = voice.frame_cursor; voice.frame_cursor = saved_cursor; voice.frame_samples = saved_samples; + if (!staged) { + voice.next_frame_samples = 0; + } } ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b41c449bc3a59564acf68361 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1de75dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On src/libs/ngs2.cpp line 3360 (outdated):

@@ -2356,75 +3070,352 @@ static int Ngs2ParseAtrac9Riff(const void* data, size_t data_size, Ngs2WaveformI
 		offset = static_cast<size_t>(next);
 	}
 
-	if (format == nullptr || fact == nullptr || waveform_offset == 0) {
+	if (format == nullptr || format_size < 16 || waveform_offset == 0) {
 		return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
 	}
-	if (Ngs2ReadLe16(format) != 0xfffe ||
-	    std::memcmp(format + 24, ATRAC9_GUID, sizeof(ATRAC9_GUID)) != 0) {
-		return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
-	}
 
-	std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config {};
-	std::memcpy(config.data(), format + 44, config.size());
-	Atrac9CodecInfo codec {};
-	const bool valid_codec = Ngs2GetAtrac9CodecInfo(config, codec);
-	const uint64_t frame_samples =
-	    static_cast<uint64_t>(codec.frameSamples) * static_cast<uint64_t>(codec.framesInSuperframe);
-	if (!valid_codec || codec.channels != Ngs2ReadLe16(format + 2) ||
-	    codec.samplingRate != static_cast<int>(Ngs2ReadLe32(format + 4)) ||
-	    codec.superframeSize != Ngs2ReadLe16(format + 12) ||
-	    frame_samples != Ngs2ReadLe16(format + 18) ||
-	    frame_samples > std::numeric_limits<uint32_t>::max()) {
-		return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+	const uint16_t tag = Ngs2ReadLe16(format);
+	if (tag == 0xfffe) {
+		// WAVE_FORMAT_EXTENSIBLE
+		if (format_size < 40) {
+			return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+		}
+		if (std::memcmp(format + 24, ATRAC9_GUID, sizeof(ATRAC9_GUID)) == 0) {
+			if (format_size < 52 || fact == nullptr || fact_size < 12) {
+				return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+			}
+			std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config {};
+			std::memcpy(config.data(), format + 44, config.size());
+			Atrac9CodecInfo codec {};
+			const bool      valid_codec   = Ngs2GetAtrac9CodecInfo(config, codec);
+			const uint64_t  frame_samples = static_cast<uint64_t>(codec.frameSamples) *
+			                                static_cast<uint64_t>(codec.framesInSuperframe);
+			if (!valid_codec || codec.channels != Ngs2ReadLe16(format + 2) ||
+			    codec.samplingRate != static_cast<int>(Ngs2ReadLe32(format + 4)) ||
+			    codec.superframeSize != Ngs2ReadLe16(format + 12) ||
+			    frame_samples != Ngs2ReadLe16(format + 18) ||
+			    frame_samples > std::numeric_limits<uint32_t>::max()) {
+				return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+			}
+
+			info->format.waveform_type = NGS2_WAVEFORM_TYPE_ATRAC9;
+			info->format.num_channels  = static_cast<uint32_t>(codec.channels);
+			info->format.sample_rate   = static_cast<uint32_t>(codec.samplingRate);
+			info->format.config_data   = (static_cast<uint32_t>(config[0]) << 24u) |
+			                             (static_cast<uint32_t>(config[1]) << 16u) |
+			                             (static_cast<uint32_t>(config[2]) << 8u) | config[3];
+			info->data_offset          = static_cast<uint32_t>(waveform_offset);
+			info->data_size            = waveform_size;
+			info->num_samples          = Ngs2ReadLe32(fact);
+			info->audio_unit_size =
+			    static_cast<uint32_t>(codec.superframeSize / codec.framesInSuperframe);
+			info->num_audio_unit_samples     = static_cast<uint32_t>(codec.frameSamples);
+			info->num_audio_unit_per_frame   = static_cast<uint32_t>(codec.framesInSuperframe);
+			info->audio_frame_size           = static_cast<uint32_t>(codec.superframeSize);
+			info->num_audio_frame_samples    = static_cast<uint32_t>(frame_samples);
+			info->num_delay_samples          = Ngs2ReadLe32(fact + 4);
+			info->num_blocks                 = 1;
+			info->blocks[0].data_offset      = waveform_offset;
+			info->blocks[0].data_size        = waveform_size;
+			info->blocks[0].num_skip_samples = Ngs2ReadLe32(fact + 8);
+			info->blocks[0].num_samples      = info->num_samples;
+			return OK;
+		}
+		if (std::memcmp(format + 24, PCM_GUID, sizeof(PCM_GUID)) != 0) {
+			return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+		}
 	}
 
-	info->format.waveform_type = NGS2_WAVEFORM_TYPE_ATRAC9;
-	info->format.num_channels  = static_cast<uint32_t>(codec.channels);
-	info->format.sample_rate   = static_cast<uint32_t>(codec.samplingRate);
-	info->format.config_data = (static_cast<uint32_t>(config[0]) << 24u) |
-	                           (static_cast<uint32_t>(config[1]) << 16u) |
-	                           (static_cast<uint32_t>(config[2]) << 8u) | config[3];
-	info->data_offset              = static_cast<uint32_t>(waveform_offset);
-	info->data_size                = waveform_size;
-	info->num_samples              = Ngs2ReadLe32(fact);
-	info->audio_unit_size          = static_cast<uint32_t>(codec.superframeSize /
-	                                                       codec.framesInSuperframe);
-	info->num_audio_unit_samples   = static_cast<uint32_t>(codec.frameSamples);
-	info->num_audio_unit_per_frame = static_cast<uint32_t>(codec.framesInSuperframe);
-	info->audio_frame_size         = static_cast<uint32_t>(codec.superframeSize);
-	info->num_audio_frame_samples  = static_cast<uint32_t>(frame_samples);
-	info->num_delay_samples        = Ngs2ReadLe32(fact + 4);
-	info->num_blocks               = 1;
-	info->blocks[0].data_offset    = waveform_offset;
-	info->blocks[0].data_size      = waveform_size;
-	info->blocks[0].num_skip_samples = Ngs2ReadLe32(fact + 8);
-	info->blocks[0].num_samples      = info->num_samples;
-	return OK;
-}
+	// PCM or IEEE Float
+	if (tag == 1 || tag == 3 || tag == 0xfffe) {
+		const bool     is_float  = (tag == 3);
+		const uint16_t bits      = Ngs2ReadLe16(format + 14);
+		uint32_t       wave_type = 0;
+		if (is_float) {
+			wave_type = (bits == 32 ? 0x18u : (bits == 64 ? 0x1au : 0u));
+		} else {
+			wave_type =
+			    (bits == 8
+			         ? 0x11u
+			         : (bits == 16 ? 0x12u : (bits == 24 ? 0x14u : (bits == 32 ? 0x16u : 0u))));
+		}
+		if (wave_type == 0) {
+			return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+		}
 
-int KYTY_SYSV_ABI Ngs2ParseWaveformData(const void* data, size_t data_size,
-                                        Ngs2WaveformInfo* info) {
-	PRINT_NAME();
-	LOGF("\t data = 0x%016" PRIx64 ", data_size = 0x%016" PRIx64 "\n",
-	     reinterpret_cast<uint64_t>(data), static_cast<uint64_t>(data_size));
+		const uint32_t channels        = Ngs2ReadLe16(format + 2);
+		const uint32_t sample_rate     = Ngs2ReadLe32(format + 4);
+		const uint32_t bytes_per_frame = channels * (bits / 8u);
+		if (channels == 0 || channels > 8 || sample_rate == 0 || sample_rate > 192000 ||
+		    Ngs2ReadLe16(format + 12) != bytes_per_frame) {
+			return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+		}
+		if (bytes_per_frame == 0 || (waveform_size % bytes_per_frame) != 0) {
+			return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+		}
 
-	if (info == nullptr) {
-		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+		info->format.waveform_type       = wave_type;
+		info->format.num_channels        = channels;
+		info->format.sample_rate         = sample_rate;
+		info->format.config_data         = 0;
+		info->data_offset                = static_cast<uint32_t>(waveform_offset);
+		info->data_size                  = waveform_size;
+		info->num_samples                = waveform_size / bytes_per_frame;
+		info->audio_unit_size            = bytes_per_frame;
+		info->num_audio_unit_samples     = 1;
+		info->num_audio_unit_per_frame   = 1;
+		info->audio_frame_size           = bytes_per_frame;
+		info->num_audio_frame_samples    = 1;
+		info->num_delay_samples          = 0;
+		info->num_blocks                 = 1;
+		info->blocks[0].data_offset      = waveform_offset;
+		info->blocks[0].data_size        = waveform_size;
+		info->blocks[0].num_skip_samples = 0;
+		info->blocks[0].num_samples      = info->num_samples;
+
+		if (smpl != nullptr && smpl_size >= 36) {
+			const uint32_t num_loops = Ngs2ReadLe32(smpl + 28);
+			if (num_loops > 0 && smpl_size >= 52) {
+				const uint32_t loop_start = Ngs2ReadLe32(smpl + 44);
+				const uint32_t loop_end   = Ngs2ReadLe32(smpl + 48) + 1u;
+				info->loop_begin_position = loop_start;
+				info->loop_end_position   = loop_end;
+				if (loop_end > loop_start && loop_end <= info->num_samples) {
+					info->num_blocks = 0;
+					if (loop_start != 0) {
+						auto& b       = info->blocks[info->num_blocks++];
+						b.data_offset = waveform_offset;
+						b.data_size   = static_cast<uint64_t>(loop_start) * bytes_per_frame;
+						b.num_samples = loop_start;
+					}
+					auto& b_loop = info->blocks[info->num_blocks++];
+					b_loop.data_offset =
+					    waveform_offset + static_cast<uint64_t>(loop_start) * bytes_per_frame;
+					b_loop.data_size =
+					    static_cast<uint64_t>(loop_end - loop_start) * bytes_per_frame;
+					b_loop.num_repeats = UINT32_MAX;
+					b_loop.num_samples = loop_end - loop_start;
+					if (loop_end != info->num_samples) {
+						auto& b_end = info->blocks[info->num_blocks++];
+						b_end.data_offset =
+						    waveform_offset + static_cast<uint64_t>(loop_end) * bytes_per_frame;
+						b_end.data_size =
+						    static_cast<uint64_t>(info->num_samples - loop_end) * bytes_per_frame;
+						b_end.num_samples = info->num_samples - loop_end;
+					}
+				}
+			}
+		}
+		return OK;
 	}
 
-	std::memset(info, 0, sizeof(Ngs2WaveformInfo));
-	return Ngs2ParseAtrac9Riff(data, data_size, info);
+	return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
 }
 
-int KYTY_SYSV_ABI Ngs2CalcWaveformBlock(const Ngs2WaveformFormat* format, uint32_t sample_pos,
-                                        uint32_t num_samples, Ngs2WaveformBlock* block) {
-	PRINT_NAME();
-	LOGF("\t format = 0x%016" PRIx64 ", sample_pos = %" PRIu32 ", num_samples = %" PRIu32 "\n",
-	     reinterpret_cast<uint64_t>(format), sample_pos, num_samples);
+static int Ngs2ParseVag(const void* data, size_t data_size, Ngs2WaveformInfo* info) {
+	static constexpr uint32_t VAG_FRAME_SAMPLES   = 28;
+	static constexpr uint32_t VAG_FRAME_BYTES     = 16;
+	static constexpr uint32_t VAG_HEADER_SIZE     = 0x30;
+	static constexpr uint8_t  VAG_FLAG_LOOP_END   = 3;
+	static constexpr uint8_t  VAG_FLAG_LOOP_START = 6;
 
-	EXIT_NOT_IMPLEMENTED(block == nullptr);
+	const auto* bytes = static_cast<const uint8_t*>(data);
+	if (bytes == nullptr || data_size < VAG_HEADER_SIZE) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+	if (std::memcmp(bytes, "VAGp", 4) != 0) {
+		return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+	}
 
-	std::memset(block, 0, sizeof(Ngs2WaveformBlock));
+	const uint32_t channels    = bytes[0x1e] != 0 ? bytes[0x1e] : 1u;
+	const uint32_t frame_bytes = VAG_FRAME_BYTES * channels;
+	const uint32_t data_size_val =
+	    (static_cast<uint32_t>(bytes[0x0c]) << 24u) | (static_cast<uint32_t>(bytes[0x0d]) << 16u) |
+	    (static_cast<uint32_t>(bytes[0x0e]) << 8u) | static_cast<uint32_t>(bytes[0x0f]);
+	const uint32_t sample_rate =
+	    (static_cast<uint32_t>(bytes[0x10]) << 24u) | (static_cast<uint32_t>(bytes[0x11]) << 16u) |
+	    (static_cast<uint32_t>(bytes[0x12]) << 8u) | static_cast<uint32_t>(bytes[0x13]);
+
+	const size_t payload = data_size - VAG_HEADER_SIZE;
+	if (data_size_val > payload || payload < static_cast<size_t>(frame_bytes) + VAG_FRAME_BYTES) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+	if (channels > 8 || sample_rate == 0 || sample_rate > 192000 ||
+	    (data_size_val % frame_bytes) != 0) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+
+	const bool     drops_frame = (bytes[VAG_HEADER_SIZE + frame_bytes + 1] & 2) == 0;
+	const uint64_t last_frame  = data_size_val != 0 ? (data_size_val - 1u) / frame_bytes : 0;
+	const uint64_t scan_bytes  = last_frame * frame_bytes + VAG_FRAME_BYTES;
+	if (!drops_frame && data_size_val != 0 && scan_bytes > payload) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+
+	info->format.waveform_type     = SCE_NGS2_WAVEFORM_TYPE_VAG;
+	info->format.num_channels      = channels;
+	info->format.sample_rate       = sample_rate;
+	info->format.config_data       = 0;
+	info->data_offset              = VAG_HEADER_SIZE;
+	info->data_size                = data_size_val;
+	info->num_samples              = (data_size_val / frame_bytes) * VAG_FRAME_SAMPLES;
+	info->audio_unit_size          = frame_bytes;
+	info->num_audio_unit_samples   = VAG_FRAME_SAMPLES;
+	info->num_audio_unit_per_frame = 1;
+	info->audio_frame_size         = frame_bytes;
+	info->num_audio_frame_samples  = VAG_FRAME_SAMPLES;
+	info->num_delay_samples        = 0;
+
+	if (drops_frame) {
+		if (info->num_samples < VAG_FRAME_SAMPLES) {
+			return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+		}
+		info->num_samples -= VAG_FRAME_SAMPLES;
+	} else if (data_size_val != 0) {
+		const auto* frames = bytes + VAG_HEADER_SIZE;
+		for (uint64_t frame = 0; frame <= last_frame; ++frame) {
+			const uint8_t flag = frames[frame * frame_bytes + 1] & 0x0fu;
+			if (flag == VAG_FLAG_LOOP_END) {
+				info->loop_end_position = static_cast<uint32_t>(frame + 1) * VAG_FRAME_SAMPLES;
+			} else if (flag == VAG_FLAG_LOOP_START) {
+				info->loop_begin_position = static_cast<uint32_t>(frame) * VAG_FRAME_SAMPLES;
+			}
+		}
+	}
+
+	const auto make_vag_block = [&](uint32_t pos, uint32_t count, uint32_t repeats) {
+		const uint64_t first = pos / VAG_FRAME_SAMPLES;
+		const uint64_t past  = (uint64_t(pos) + count + VAG_FRAME_SAMPLES - 1u) / VAG_FRAME_SAMPLES;
+		const uint64_t offset = first * frame_bytes;
+		Ngs2WaveformBlock b {};
+		b.data_offset      = VAG_HEADER_SIZE + offset;
+		b.data_size        = past * frame_bytes - offset;
+		b.num_samples      = static_cast<uint32_t>(std::min<uint64_t>(
+		    (past - first) * VAG_FRAME_SAMPLES, std::numeric_limits<uint32_t>::max()));
+		b.num_skip_samples = 0;
+		b.num_repeats      = repeats;
+		return b;
+	};
+
+	const uint32_t begin = info->loop_begin_position;
+	const uint32_t end   = info->loop_end_position;
+	info->num_blocks     = 0;
+	if (end <= begin || end > info->num_samples) {
+		info->blocks[info->num_blocks++] = make_vag_block(0, info->num_samples, 0);
+		return OK;
+	}
+	if (begin != 0) {
+		info->blocks[info->num_blocks++] = make_vag_block(0, begin, 0);
+	}
+	info->blocks[info->num_blocks++] = make_vag_block(begin, end - begin, UINT32_MAX);
+	if (end != info->num_samples) {
+		info->blocks[info->num_blocks++] = make_vag_block(end, info->num_samples - end, 0);
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2ParseWaveformData(const void* data, size_t data_size,
+                                        Ngs2WaveformInfo* info) {
+	PRINT_NAME();
+	LOGF("\t data = 0x%016" PRIx64 ", data_size = 0x%016" PRIx64 "\n",
+	     reinterpret_cast<uint64_t>(data), static_cast<uint64_t>(data_size));
+
+	if (info == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+
+	std::memset(info, 0, sizeof(Ngs2WaveformInfo));
+	if (data != nullptr && data_size >= 4 && std::memcmp(data, "VAGp", 4) == 0) {
+		return Ngs2ParseVag(data, data_size, info);
+	}
+	return Ngs2ParseRiffWaveform(data, data_size, info);
+}
+
+int KYTY_SYSV_ABI Ngs2ParseWaveformFile(const char* path, uint32_t offset, Ngs2WaveformInfo* info) {
+	PRINT_NAME();
+	LOGF("\t path = %s, offset = %" PRIu32 "\n", path != nullptr ? path : "(null)", offset);
+
+	if (info == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	std::memset(info, 0, sizeof(Ngs2WaveformInfo));
+
+	if (path == nullptr) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+
+	std::ifstream file(path, std::ios::binary | std::ios::ate);
+	if (!file) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+	const auto file_size = static_cast<uint64_t>(file.tellg());
+	if (static_cast<uint64_t>(offset) > file_size) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+
+	// Read the leading header first and bound the payload read to the extent
+	// declared by the container instead of copying the whole remaining file.
+	uint8_t header[0x30] {};
+	file.seekg(static_cast<std::streamoff>(offset));
+	file.read(reinterpret_cast<char*>(header), sizeof(header));

Minor · Functional Correctness · Quick win

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 second seekg clears eofbit, not failbit, 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](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653931128) · edited 2026-11-21 18:40 UTC On `src/libs/ngs2.cpp` line 3360 (outdated): ```diff @@ -2356,75 +3070,352 @@ static int Ngs2ParseAtrac9Riff(const void* data, size_t data_size, Ngs2WaveformI offset = static_cast<size_t>(next); } - if (format == nullptr || fact == nullptr || waveform_offset == 0) { + if (format == nullptr || format_size < 16 || waveform_offset == 0) { return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; } - if (Ngs2ReadLe16(format) != 0xfffe || - std::memcmp(format + 24, ATRAC9_GUID, sizeof(ATRAC9_GUID)) != 0) { - return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; - } - std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config {}; - std::memcpy(config.data(), format + 44, config.size()); - Atrac9CodecInfo codec {}; - const bool valid_codec = Ngs2GetAtrac9CodecInfo(config, codec); - const uint64_t frame_samples = - static_cast<uint64_t>(codec.frameSamples) * static_cast<uint64_t>(codec.framesInSuperframe); - if (!valid_codec || codec.channels != Ngs2ReadLe16(format + 2) || - codec.samplingRate != static_cast<int>(Ngs2ReadLe32(format + 4)) || - codec.superframeSize != Ngs2ReadLe16(format + 12) || - frame_samples != Ngs2ReadLe16(format + 18) || - frame_samples > std::numeric_limits<uint32_t>::max()) { - return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + const uint16_t tag = Ngs2ReadLe16(format); + if (tag == 0xfffe) { + // WAVE_FORMAT_EXTENSIBLE + if (format_size < 40) { + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } + if (std::memcmp(format + 24, ATRAC9_GUID, sizeof(ATRAC9_GUID)) == 0) { + if (format_size < 52 || fact == nullptr || fact_size < 12) { + return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + } + std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config {}; + std::memcpy(config.data(), format + 44, config.size()); + Atrac9CodecInfo codec {}; + const bool valid_codec = Ngs2GetAtrac9CodecInfo(config, codec); + const uint64_t frame_samples = static_cast<uint64_t>(codec.frameSamples) * + static_cast<uint64_t>(codec.framesInSuperframe); + if (!valid_codec || codec.channels != Ngs2ReadLe16(format + 2) || + codec.samplingRate != static_cast<int>(Ngs2ReadLe32(format + 4)) || + codec.superframeSize != Ngs2ReadLe16(format + 12) || + frame_samples != Ngs2ReadLe16(format + 18) || + frame_samples > std::numeric_limits<uint32_t>::max()) { + return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + } + + info->format.waveform_type = NGS2_WAVEFORM_TYPE_ATRAC9; + info->format.num_channels = static_cast<uint32_t>(codec.channels); + info->format.sample_rate = static_cast<uint32_t>(codec.samplingRate); + info->format.config_data = (static_cast<uint32_t>(config[0]) << 24u) | + (static_cast<uint32_t>(config[1]) << 16u) | + (static_cast<uint32_t>(config[2]) << 8u) | config[3]; + info->data_offset = static_cast<uint32_t>(waveform_offset); + info->data_size = waveform_size; + info->num_samples = Ngs2ReadLe32(fact); + info->audio_unit_size = + static_cast<uint32_t>(codec.superframeSize / codec.framesInSuperframe); + info->num_audio_unit_samples = static_cast<uint32_t>(codec.frameSamples); + info->num_audio_unit_per_frame = static_cast<uint32_t>(codec.framesInSuperframe); + info->audio_frame_size = static_cast<uint32_t>(codec.superframeSize); + info->num_audio_frame_samples = static_cast<uint32_t>(frame_samples); + info->num_delay_samples = Ngs2ReadLe32(fact + 4); + info->num_blocks = 1; + info->blocks[0].data_offset = waveform_offset; + info->blocks[0].data_size = waveform_size; + info->blocks[0].num_skip_samples = Ngs2ReadLe32(fact + 8); + info->blocks[0].num_samples = info->num_samples; + return OK; + } + if (std::memcmp(format + 24, PCM_GUID, sizeof(PCM_GUID)) != 0) { + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } } - info->format.waveform_type = NGS2_WAVEFORM_TYPE_ATRAC9; - info->format.num_channels = static_cast<uint32_t>(codec.channels); - info->format.sample_rate = static_cast<uint32_t>(codec.samplingRate); - info->format.config_data = (static_cast<uint32_t>(config[0]) << 24u) | - (static_cast<uint32_t>(config[1]) << 16u) | - (static_cast<uint32_t>(config[2]) << 8u) | config[3]; - info->data_offset = static_cast<uint32_t>(waveform_offset); - info->data_size = waveform_size; - info->num_samples = Ngs2ReadLe32(fact); - info->audio_unit_size = static_cast<uint32_t>(codec.superframeSize / - codec.framesInSuperframe); - info->num_audio_unit_samples = static_cast<uint32_t>(codec.frameSamples); - info->num_audio_unit_per_frame = static_cast<uint32_t>(codec.framesInSuperframe); - info->audio_frame_size = static_cast<uint32_t>(codec.superframeSize); - info->num_audio_frame_samples = static_cast<uint32_t>(frame_samples); - info->num_delay_samples = Ngs2ReadLe32(fact + 4); - info->num_blocks = 1; - info->blocks[0].data_offset = waveform_offset; - info->blocks[0].data_size = waveform_size; - info->blocks[0].num_skip_samples = Ngs2ReadLe32(fact + 8); - info->blocks[0].num_samples = info->num_samples; - return OK; -} + // PCM or IEEE Float + if (tag == 1 || tag == 3 || tag == 0xfffe) { + const bool is_float = (tag == 3); + const uint16_t bits = Ngs2ReadLe16(format + 14); + uint32_t wave_type = 0; + if (is_float) { + wave_type = (bits == 32 ? 0x18u : (bits == 64 ? 0x1au : 0u)); + } else { + wave_type = + (bits == 8 + ? 0x11u + : (bits == 16 ? 0x12u : (bits == 24 ? 0x14u : (bits == 32 ? 0x16u : 0u)))); + } + if (wave_type == 0) { + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } -int KYTY_SYSV_ABI Ngs2ParseWaveformData(const void* data, size_t data_size, - Ngs2WaveformInfo* info) { - PRINT_NAME(); - LOGF("\t data = 0x%016" PRIx64 ", data_size = 0x%016" PRIx64 "\n", - reinterpret_cast<uint64_t>(data), static_cast<uint64_t>(data_size)); + const uint32_t channels = Ngs2ReadLe16(format + 2); + const uint32_t sample_rate = Ngs2ReadLe32(format + 4); + const uint32_t bytes_per_frame = channels * (bits / 8u); + if (channels == 0 || channels > 8 || sample_rate == 0 || sample_rate > 192000 || + Ngs2ReadLe16(format + 12) != bytes_per_frame) { + return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + } + if (bytes_per_frame == 0 || (waveform_size % bytes_per_frame) != 0) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } - if (info == nullptr) { - return NGS2_ERROR_INVALID_OUT_ADDRESS; + info->format.waveform_type = wave_type; + info->format.num_channels = channels; + info->format.sample_rate = sample_rate; + info->format.config_data = 0; + info->data_offset = static_cast<uint32_t>(waveform_offset); + info->data_size = waveform_size; + info->num_samples = waveform_size / bytes_per_frame; + info->audio_unit_size = bytes_per_frame; + info->num_audio_unit_samples = 1; + info->num_audio_unit_per_frame = 1; + info->audio_frame_size = bytes_per_frame; + info->num_audio_frame_samples = 1; + info->num_delay_samples = 0; + info->num_blocks = 1; + info->blocks[0].data_offset = waveform_offset; + info->blocks[0].data_size = waveform_size; + info->blocks[0].num_skip_samples = 0; + info->blocks[0].num_samples = info->num_samples; + + if (smpl != nullptr && smpl_size >= 36) { + const uint32_t num_loops = Ngs2ReadLe32(smpl + 28); + if (num_loops > 0 && smpl_size >= 52) { + const uint32_t loop_start = Ngs2ReadLe32(smpl + 44); + const uint32_t loop_end = Ngs2ReadLe32(smpl + 48) + 1u; + info->loop_begin_position = loop_start; + info->loop_end_position = loop_end; + if (loop_end > loop_start && loop_end <= info->num_samples) { + info->num_blocks = 0; + if (loop_start != 0) { + auto& b = info->blocks[info->num_blocks++]; + b.data_offset = waveform_offset; + b.data_size = static_cast<uint64_t>(loop_start) * bytes_per_frame; + b.num_samples = loop_start; + } + auto& b_loop = info->blocks[info->num_blocks++]; + b_loop.data_offset = + waveform_offset + static_cast<uint64_t>(loop_start) * bytes_per_frame; + b_loop.data_size = + static_cast<uint64_t>(loop_end - loop_start) * bytes_per_frame; + b_loop.num_repeats = UINT32_MAX; + b_loop.num_samples = loop_end - loop_start; + if (loop_end != info->num_samples) { + auto& b_end = info->blocks[info->num_blocks++]; + b_end.data_offset = + waveform_offset + static_cast<uint64_t>(loop_end) * bytes_per_frame; + b_end.data_size = + static_cast<uint64_t>(info->num_samples - loop_end) * bytes_per_frame; + b_end.num_samples = info->num_samples - loop_end; + } + } + } + } + return OK; } - std::memset(info, 0, sizeof(Ngs2WaveformInfo)); - return Ngs2ParseAtrac9Riff(data, data_size, info); + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; } -int KYTY_SYSV_ABI Ngs2CalcWaveformBlock(const Ngs2WaveformFormat* format, uint32_t sample_pos, - uint32_t num_samples, Ngs2WaveformBlock* block) { - PRINT_NAME(); - LOGF("\t format = 0x%016" PRIx64 ", sample_pos = %" PRIu32 ", num_samples = %" PRIu32 "\n", - reinterpret_cast<uint64_t>(format), sample_pos, num_samples); +static int Ngs2ParseVag(const void* data, size_t data_size, Ngs2WaveformInfo* info) { + static constexpr uint32_t VAG_FRAME_SAMPLES = 28; + static constexpr uint32_t VAG_FRAME_BYTES = 16; + static constexpr uint32_t VAG_HEADER_SIZE = 0x30; + static constexpr uint8_t VAG_FLAG_LOOP_END = 3; + static constexpr uint8_t VAG_FLAG_LOOP_START = 6; - EXIT_NOT_IMPLEMENTED(block == nullptr); + const auto* bytes = static_cast<const uint8_t*>(data); + if (bytes == nullptr || data_size < VAG_HEADER_SIZE) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + if (std::memcmp(bytes, "VAGp", 4) != 0) { + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } - std::memset(block, 0, sizeof(Ngs2WaveformBlock)); + const uint32_t channels = bytes[0x1e] != 0 ? bytes[0x1e] : 1u; + const uint32_t frame_bytes = VAG_FRAME_BYTES * channels; + const uint32_t data_size_val = + (static_cast<uint32_t>(bytes[0x0c]) << 24u) | (static_cast<uint32_t>(bytes[0x0d]) << 16u) | + (static_cast<uint32_t>(bytes[0x0e]) << 8u) | static_cast<uint32_t>(bytes[0x0f]); + const uint32_t sample_rate = + (static_cast<uint32_t>(bytes[0x10]) << 24u) | (static_cast<uint32_t>(bytes[0x11]) << 16u) | + (static_cast<uint32_t>(bytes[0x12]) << 8u) | static_cast<uint32_t>(bytes[0x13]); + + const size_t payload = data_size - VAG_HEADER_SIZE; + if (data_size_val > payload || payload < static_cast<size_t>(frame_bytes) + VAG_FRAME_BYTES) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + if (channels > 8 || sample_rate == 0 || sample_rate > 192000 || + (data_size_val % frame_bytes) != 0) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + + const bool drops_frame = (bytes[VAG_HEADER_SIZE + frame_bytes + 1] & 2) == 0; + const uint64_t last_frame = data_size_val != 0 ? (data_size_val - 1u) / frame_bytes : 0; + const uint64_t scan_bytes = last_frame * frame_bytes + VAG_FRAME_BYTES; + if (!drops_frame && data_size_val != 0 && scan_bytes > payload) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + + info->format.waveform_type = SCE_NGS2_WAVEFORM_TYPE_VAG; + info->format.num_channels = channels; + info->format.sample_rate = sample_rate; + info->format.config_data = 0; + info->data_offset = VAG_HEADER_SIZE; + info->data_size = data_size_val; + info->num_samples = (data_size_val / frame_bytes) * VAG_FRAME_SAMPLES; + info->audio_unit_size = frame_bytes; + info->num_audio_unit_samples = VAG_FRAME_SAMPLES; + info->num_audio_unit_per_frame = 1; + info->audio_frame_size = frame_bytes; + info->num_audio_frame_samples = VAG_FRAME_SAMPLES; + info->num_delay_samples = 0; + + if (drops_frame) { + if (info->num_samples < VAG_FRAME_SAMPLES) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + info->num_samples -= VAG_FRAME_SAMPLES; + } else if (data_size_val != 0) { + const auto* frames = bytes + VAG_HEADER_SIZE; + for (uint64_t frame = 0; frame <= last_frame; ++frame) { + const uint8_t flag = frames[frame * frame_bytes + 1] & 0x0fu; + if (flag == VAG_FLAG_LOOP_END) { + info->loop_end_position = static_cast<uint32_t>(frame + 1) * VAG_FRAME_SAMPLES; + } else if (flag == VAG_FLAG_LOOP_START) { + info->loop_begin_position = static_cast<uint32_t>(frame) * VAG_FRAME_SAMPLES; + } + } + } + + const auto make_vag_block = [&](uint32_t pos, uint32_t count, uint32_t repeats) { + const uint64_t first = pos / VAG_FRAME_SAMPLES; + const uint64_t past = (uint64_t(pos) + count + VAG_FRAME_SAMPLES - 1u) / VAG_FRAME_SAMPLES; + const uint64_t offset = first * frame_bytes; + Ngs2WaveformBlock b {}; + b.data_offset = VAG_HEADER_SIZE + offset; + b.data_size = past * frame_bytes - offset; + b.num_samples = static_cast<uint32_t>(std::min<uint64_t>( + (past - first) * VAG_FRAME_SAMPLES, std::numeric_limits<uint32_t>::max())); + b.num_skip_samples = 0; + b.num_repeats = repeats; + return b; + }; + + const uint32_t begin = info->loop_begin_position; + const uint32_t end = info->loop_end_position; + info->num_blocks = 0; + if (end <= begin || end > info->num_samples) { + info->blocks[info->num_blocks++] = make_vag_block(0, info->num_samples, 0); + return OK; + } + if (begin != 0) { + info->blocks[info->num_blocks++] = make_vag_block(0, begin, 0); + } + info->blocks[info->num_blocks++] = make_vag_block(begin, end - begin, UINT32_MAX); + if (end != info->num_samples) { + info->blocks[info->num_blocks++] = make_vag_block(end, info->num_samples - end, 0); + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2ParseWaveformData(const void* data, size_t data_size, + Ngs2WaveformInfo* info) { + PRINT_NAME(); + LOGF("\t data = 0x%016" PRIx64 ", data_size = 0x%016" PRIx64 "\n", + reinterpret_cast<uint64_t>(data), static_cast<uint64_t>(data_size)); + + if (info == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + + std::memset(info, 0, sizeof(Ngs2WaveformInfo)); + if (data != nullptr && data_size >= 4 && std::memcmp(data, "VAGp", 4) == 0) { + return Ngs2ParseVag(data, data_size, info); + } + return Ngs2ParseRiffWaveform(data, data_size, info); +} + +int KYTY_SYSV_ABI Ngs2ParseWaveformFile(const char* path, uint32_t offset, Ngs2WaveformInfo* info) { + PRINT_NAME(); + LOGF("\t path = %s, offset = %" PRIu32 "\n", path != nullptr ? path : "(null)", offset); + + if (info == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + std::memset(info, 0, sizeof(Ngs2WaveformInfo)); + + if (path == nullptr) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + const auto file_size = static_cast<uint64_t>(file.tellg()); + if (static_cast<uint64_t>(offset) > file_size) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + + // Read the leading header first and bound the payload read to the extent + // declared by the container instead of copying the whole remaining file. + uint8_t header[0x30] {}; + file.seekg(static_cast<std::streamoff>(offset)); + file.read(reinterpret_cast<char*>(header), sizeof(header)); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **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 second `seekg` clears `eofbit`, not `failbit`, so the payload read fails before the parser runs. ([eel.is](https://eel.is/c%2B%2Bdraft/istream.unformatted)) 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. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fe29059a210b0d478f62fa77 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1de75dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 19:46 UTC
On src/libs/ngs2.cpp line 3814 (outdated):

@@ -2801,8 +3811,11 @@ int KYTY_SYSV_ABI Ngs2RackGetVoiceHandle(uintptr_t rack_handle, uint32_t voice_i
 
 	LOGF("\t voice_id = %u\n", voice_id);
 
-	auto* rack   = reinterpret_cast<Ngs2RackInternal*>(rack_handle);
-	auto* voices = reinterpret_cast<Ngs2VoiceInternal*>(rack_handle + sizeof(Ngs2RackInternal));
+	auto* rack = Ngs2FindRack(rack_handle);

Major · Stability & Availability · Quick win

Hold the rack registry lock while Ngs2RackGetVoiceHandle reads the rack.

Ngs2FindRack releases g_racks_mutex before the caller reads rack->option and voices[]. A concurrent Ngs2RackDestroy can 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 one g_racks_mutex hold. A destroy that starts first makes the lookup return NGS2_ERROR_INVALID_RACK_HANDLE, as the existing rejection path intends.

Suggested fix

-	auto* rack = Ngs2FindRack(rack_handle);
-	if (rack == nullptr) {
+	Common::LockGuard racks_lock(g_racks_mutex);
+	Ngs2RackInternal* rack = nullptr;
+	for (auto* current = g_racks_list; current != nullptr; current = current->next) {
+		if (reinterpret_cast<uintptr_t>(current) == rack_handle) {
+			rack = current;
+			break;
+		}
+	}
+	if (rack == nullptr) {

✅ Addressed in commit 1de75dc

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653931145) · edited 2026-11-21 19:46 UTC On `src/libs/ngs2.cpp` line 3814 (outdated): ```diff @@ -2801,8 +3811,11 @@ int KYTY_SYSV_ABI Ngs2RackGetVoiceHandle(uintptr_t rack_handle, uint32_t voice_i LOGF("\t voice_id = %u\n", voice_id); - auto* rack = reinterpret_cast<Ngs2RackInternal*>(rack_handle); - auto* voices = reinterpret_cast<Ngs2VoiceInternal*>(rack_handle + sizeof(Ngs2RackInternal)); + auto* rack = Ngs2FindRack(rack_handle); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Hold the rack registry lock while `Ngs2RackGetVoiceHandle` reads the rack.** `Ngs2FindRack` releases `g_racks_mutex` before the caller reads `rack->option` and `voices[]`. A concurrent `Ngs2RackDestroy` can 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 one `g_racks_mutex` hold. A destroy that starts first makes the lookup return `NGS2_ERROR_INVALID_RACK_HANDLE`, as the existing rejection path intends. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff - auto* rack = Ngs2FindRack(rack_handle); - if (rack == nullptr) { + Common::LockGuard racks_lock(g_racks_mutex); + Ngs2RackInternal* rack = nullptr; + for (auto* current = g_racks_list; current != nullptr; current = current->next) { + if (reinterpret_cast<uintptr_t>(current) == rack_handle) { + rack = current; + break; + } + } + if (rack == nullptr) { ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8bfd15a58edcb9b7a432f5c0 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1de75dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 18:40 UTC
On src/libs/ngs2.cpp line 5582 (outdated):

@@ -3363,6 +4465,1385 @@ int KYTY_SYSV_ABI Ngs2SystemUnlock(uintptr_t system_handle) {
 	return OK;
 }
 
+int KYTY_SYSV_ABI Ngs2SystemSetUserData(uintptr_t system_handle, uintptr_t user_data) {
+	PRINT_NAME();
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	Common::LockGuard lock(ngs->mutex);
+	ngs->user_data = user_data;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2SystemGetUserData(uintptr_t system_handle, uintptr_t* user_data) {
+	PRINT_NAME();
+	if (user_data == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	Common::LockGuard lock(ngs->mutex);
+	*user_data = ngs->user_data;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2SystemSetSampleRate(uintptr_t system_handle, uint32_t sample_rate) {
+	PRINT_NAME();
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	if (!Ngs2IsValidSampleRate(sample_rate)) {
+		return NGS2_ERROR_INVALID_SAMPLE_RATE;
+	}
+	Common::LockGuard lock(ngs->mutex);
+	ngs->option.sample_rate = sample_rate;
+	return OK;
+}
+
+struct Ngs2CommandRecord {
+	uint32_t id;
+	uint8_t  flags;
+	uint8_t  type;
+	uint16_t count;
+	union {
+		uint64_t    u64;
+		uint32_t    u32;
+		int32_t     i32;
+		float       f;
+		const void* ptr;
+	} value;
+};
+static_assert(sizeof(Ngs2CommandRecord) == 16);
+
+int KYTY_SYSV_ABI Ngs2SystemRunCommands(uintptr_t system_handle, const void* commands,
+                                        size_t count) {
+	PRINT_NAME();
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	if (count == 0) {
+		return OK;
+	}
+	if (commands == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	const auto* records = static_cast<const Ngs2CommandRecord*>(commands);
+	for (size_t i = 0; i < count; ++i) {
+		const auto&    rec = records[i];
+		const uint32_t cmd = rec.id & 0x00ffffffu;
+		if (cmd == 0xf00000 || cmd == 0xf00001 || cmd == 0xf00002 || cmd == 0xf00006) {
+			continue;
+		}
+		if (cmd == 0xf00003) {
+			if (rec.id >= 0x20000000u) {
+				return NGS2_ERROR_SYSTEM_INDEX_RANGE;
+			}
+		} else if (cmd == 0xf00004) {
+			if (!Ngs2IsValidSampleRate(rec.value.u32)) {
+				return NGS2_ERROR_INVALID_SAMPLE_RATE;
+			}
+		} else if (cmd == 0xf00005) {
+			const uint32_t grain = rec.value.u32;
+			if (grain < 64 || grain > ngs->option.max_grain_samples || (grain % 64) != 0) {
+				return NGS2_ERROR_INVALID_NUM_GRAIN_SAMPLES;
+			}
+		} else {
+			return NGS2_ERROR_INVALID_PARAM_ID;
+		}
+	}
+
+	for (size_t i = 0; i < count; ++i) {
+		const auto&    rec = records[i];
+		const uint32_t cmd = rec.id & 0x00ffffffu;
+		if (cmd == 0xf00000) {
+			ngs->mutex.Lock();
+		} else if (cmd == 0xf00001) {
+			ngs->mutex.Unlock();
+		} else if (cmd == 0xf00002) {
+			Common::LockGuard lock(ngs->mutex);
+			ngs->user_data = rec.value.u64;
+		} else if (cmd == 0xf00004) {
+			Common::LockGuard lock(ngs->mutex);
+			ngs->option.sample_rate = rec.value.u32;
+		} else if (cmd == 0xf00005) {
+			Common::LockGuard lock(ngs->mutex);
+			ngs->option.num_grain_samples = rec.value.u32;
+		} else if (cmd == 0xf00006) {
+			Common::LockGuard lock(ngs->mutex);
+			ngs->unnamed_param = rec.value.f;
+		} else if (cmd == 0xf00003) {
+			const uint32_t slot = rec.id >> 24;
+			if (slot < ngs->slot_data.size()) {
+				Common::LockGuard lock(ngs->mutex);
+				if (rec.value.ptr == nullptr) {
+					ngs->slot_set[slot] = false;
+					ngs->slot_data[slot].fill(0);
+				} else {
+					uint64_t leading_word = 0;
+					std::memcpy(&leading_word, rec.value.ptr, sizeof(leading_word));
+					if (leading_word == 0) {
+						ngs->slot_set[slot] = false;
+						ngs->slot_data[slot].fill(0);
+					} else {
+						ngs->slot_set[slot] = true;
+						std::memcpy(ngs->slot_data[slot].data(), rec.value.ptr, 24);
+					}
+				}
+			}
+		}
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2SystemQueryInfo(uintptr_t system_handle, uint32_t info_id, void* info,
+                                      size_t info_size) {
+	PRINT_NAME();
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	switch (info_id & 0x00ffffffu) {
+		case 0xf04000: {
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			if (info_size < sizeof(Ngs2SystemInfo)) return NGS2_ERROR_INVALID_OUT_SIZE;
+			return Ngs2SystemGetInfo(system_handle, static_cast<Ngs2SystemInfo*>(info), info_size);
+		}
+		case 0xf04001: {
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			if (info_size < sizeof(uint64_t)) return NGS2_ERROR_INVALID_OUT_SIZE;
+			Common::LockGuard lock(ngs->mutex);
+			std::memcpy(info, &ngs->user_data, sizeof(uint64_t));
+			return OK;
+		}
+		case 0xf04002: {
+			if (info_id >= 0x20000000u) return NGS2_ERROR_SYSTEM_INDEX_RANGE;
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			if (info_size < 24) return NGS2_ERROR_INVALID_OUT_SIZE;
+			const uint32_t          slot = info_id >> 24;
+			std::array<uint8_t, 24> out_data {};
+			{
+				Common::LockGuard lock(ngs->mutex);
+				if (slot < ngs->slot_data.size() && ngs->slot_set[slot]) {
+					std::memcpy(out_data.data(), ngs->slot_data[slot].data(), 24);
+				}
+			}
+			std::memcpy(info, out_data.data(), 24);
+			return OK;
+		}
+		case 0xf04003: {
+			if (info == nullptr && info_size >= sizeof(uintptr_t))
+				return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			uint32_t count = 0;
+			{
+				Common::LockGuard lock(g_racks_mutex);
+				for (auto* r = g_racks_list; r != nullptr; r = r->next) {
+					if (r->ngs == ngs) {
+						if (info != nullptr && count < (info_size / sizeof(uintptr_t))) {
+							reinterpret_cast<uintptr_t*>(info)[count] =
+							    reinterpret_cast<uintptr_t>(r);
+						}
+						++count;
+					}
+				}
+			}
+			return static_cast<int>(count);
+		}
+		default: return NGS2_ERROR_INVALID_SYSTEM_QUERY_ID;
+	}
+}
+
+int KYTY_SYSV_ABI Ngs2SystemEnumHandles(uintptr_t* out_handles, uint32_t max_handles) {
+	PRINT_NAME();
+	constexpr int32_t invalid_argument = static_cast<int32_t>(0x804a0053u);
+	if (max_handles != 0 && out_handles == nullptr) return invalid_argument;
+	uint32_t          count = 0;
+	Common::LockGuard lock(g_ngs_mutex);
+	for (auto* ngs = g_ngs_list; ngs != nullptr; ngs = ngs->next) {
+		if (out_handles != nullptr && count < max_handles) {
+			out_handles[count] = reinterpret_cast<uintptr_t>(ngs);
+		}
+		++count;
+	}
+	return static_cast<int>(count);
+}
+
+int KYTY_SYSV_ABI Ngs2SystemEnumRackHandles(uintptr_t system_handle, uintptr_t* out_handles,
+                                            uint32_t max_handles) {
+	PRINT_NAME();
+	constexpr int32_t invalid_argument      = static_cast<int32_t>(0x804a0053u);
+	constexpr int32_t invalid_system_handle = static_cast<int32_t>(0x804a0230u);
+	if (max_handles != 0 && out_handles == nullptr) return invalid_argument;
+	auto* ngs = Ngs2FindSystem(system_handle);
+	if (ngs == nullptr) return invalid_system_handle;
+	uint32_t          count = 0;
+	Common::LockGuard lock(g_racks_mutex);
+	for (auto* rack = g_racks_list; rack != nullptr; rack = rack->next) {
+		if (rack->ngs == ngs) {
+			if (out_handles != nullptr && count < max_handles) {
+				out_handles[count] = reinterpret_cast<uintptr_t>(rack);
+			}
+			++count;
+		}
+	}
+	return static_cast<int>(count);
+}
+
+int KYTY_SYSV_ABI Ngs2RackSetUserData(uintptr_t rack_handle, uintptr_t user_data) {
+	PRINT_NAME();
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr) {
+		return NGS2_ERROR_INVALID_RACK_HANDLE;
+	}
+	rack->user_data = user_data;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2RackGetUserData(uintptr_t rack_handle, uintptr_t* user_data) {
+	PRINT_NAME();
+	if (user_data == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr) {
+		return NGS2_ERROR_INVALID_RACK_HANDLE;
+	}
+	*user_data = rack->user_data;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2RackRunCommands(uintptr_t rack_handle, const void* commands, size_t count) {
+	PRINT_NAME();
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr) {
+		return NGS2_ERROR_INVALID_RACK_HANDLE;
+	}
+	if (count == 0) {
+		return OK;
+	}
+	if (commands == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	const auto* records = static_cast<const Ngs2CommandRecord*>(commands);
+	for (size_t i = 0; i < count; ++i) {
+		const uint32_t cmd = records[i].id & 0x00ffffffu;
+		if (cmd < 0xf10000 || cmd > 0xf10002) {
+			return NGS2_ERROR_INVALID_PARAM_ID;
+		}
+	}
+	for (size_t i = 0; i < count; ++i) {
+		const auto&    rec = records[i];
+		const uint32_t cmd = rec.id & 0x00ffffffu;
+		if (cmd == 0xf10000) {
+			int lock_res = Ngs2RackLock(rack_handle);
+			if (lock_res != OK) return lock_res;
+		} else if (cmd == 0xf10001) {
+			int unlock_res = Ngs2RackUnlock(rack_handle);
+			if (unlock_res != OK) return unlock_res;
+		} else if (cmd == 0xf10002) {
+			rack->user_data = rec.value.u64;
+		}
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2RackGetInfo(uintptr_t rack_handle, Ngs2RackInfo* info, size_t info_size) {
+	PRINT_NAME();
+	if (info == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	if (info_size < sizeof(Ngs2RackInfo)) {
+		return NGS2_ERROR_INVALID_OUT_SIZE;
+	}
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr || rack->ngs == nullptr) {
+		return NGS2_ERROR_INVALID_RACK_HANDLE;
+	}
+	Common::LockGuard lock(rack->ngs->mutex);
+
+	*info = {};
+	std::memcpy(info->name, rack->name, sizeof(info->name));
+	info->rack_handle         = rack_handle;
+	info->buffer_info         = rack->buffer_info;
+	info->owner_system_handle = reinterpret_cast<uintptr_t>(rack->ngs);
+	info->type =
+	    (rack->type == Ngs2RackType::Sampler || rack->type == Ngs2RackType::CustomSampler) ? 0
+	    : (rack->type == Ngs2RackType::Mastering || rack->type == Ngs2RackType::CustomMastering)
+	        ? 2
+	        : 1;
+	info->rack_id           = rack->rack_id;
+	info->uid               = rack->uid;
+	info->min_grain_samples = 64;
+	info->max_grain_samples = rack->option.common.max_grain_samples;
+	info->max_voices        = rack->option.common.max_voices;
+	info->max_channel_works = (rack->type == Ngs2RackType::Sampler)
+	                              ? rack->option.sampler.max_channel_works
+	                          : (rack->type == Ngs2RackType::CustomSampler)
+	                              ? rack->option.custom_sampler.max_channel_works
+	                              : 0;
+	info->max_inputs =
+	    (rack->type == Ngs2RackType::Submixer)          ? rack->option.submixer.max_inputs
+	    : (rack->type == Ngs2RackType::CustomSubmixer)  ? rack->option.custom_submixer.max_inputs
+	    : (rack->type == Ngs2RackType::CustomMastering) ? rack->option.custom_mastering.max_inputs
+	                                                    : 0;
+	info->max_matrices        = rack->option.common.max_matrices;
+	info->max_ports           = rack->option.common.max_ports;
+	info->max_voice_channels  = rack->option.common.max_voice_channels;
+	info->max_output_channels = rack->option.common.max_output_channels;
+	info->num_modules         = Ngs2RackIsCustom(rack->type)
+	                                ? rack->option.custom_sampler.custom_rack_option.num_modules
+	                                : 0;
+	info->num_buffers         = rack->NumBuffers();
+	info->state_flags         = (rack->lock_depth == 0) ? 1 : 5;
+	info->last_process_ratio  = 0.0f;
+	info->last_processed_tick = 0;
+	info->render_count        = rack->render_count;
+	info->active_voice_count  = 0;
+	info->active_channel_work_count = 0;
+
+	auto* voices = reinterpret_cast<Ngs2VoiceInternal*>(rack + 1);
+	for (uint32_t i = 0; i < rack->option.common.max_voices; ++i) {
+		if (voices[i].state == Ngs2VoicePlayState::Playing ||
+		    voices[i].state == Ngs2VoicePlayState::Paused) {
+			++info->active_voice_count;
+			info->active_channel_work_count += voices[i].channels;
+		}
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2RackQueryInfo(uintptr_t rack_handle, uint32_t info_id, void* info,
+                                    size_t info_size) {
+	PRINT_NAME();
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr) {
+		return NGS2_ERROR_INVALID_RACK_HANDLE;
+	}
+	switch (info_id & 0x00ffffffu) {
+		case 0xf14000: {
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			if (info_size < sizeof(Ngs2RackInfo)) return NGS2_ERROR_INVALID_OUT_SIZE;
+			return Ngs2RackGetInfo(rack_handle, static_cast<Ngs2RackInfo*>(info), info_size);
+		}
+		case 0xf14001: {
+			if (info_size < sizeof(uint64_t)) return NGS2_ERROR_INVALID_OUT_SIZE;
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			std::memcpy(info, &rack->user_data, sizeof(uint64_t));
+			return OK;
+		}
+		case 0xf14002: {
+			if (info_size < sizeof(Ngs2CustomModuleInfo)) return NGS2_ERROR_INVALID_OUT_SIZE;
+			if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+			const uint32_t module_idx = info_id >> 24;
+			if (!Ngs2RackIsCustom(rack->type) ||
+			    module_idx >= rack->option.custom_sampler.custom_rack_option.num_modules) {
+				return NGS2_ERROR_INVALID_RACK_MODULE_INDEX;
+			}
+			const auto& mod = rack->option.custom_sampler.custom_rack_option.module[module_idx];
+			auto*       out = static_cast<Ngs2CustomModuleInfo*>(info);
+			out->module_id  = mod.module_id;
+			out->source_buffer_id = mod.source_buffer_id;
+			out->extra_buffer_id  = mod.extra_buffer_id;
+			out->dest_buffer_id   = mod.dest_buffer_id;
+			out->state_offset     = mod.state_offset;
+			out->state_size       = mod.state_size;
+			out->reserved         = 0;
+			out->reserved2        = 0;
+			return OK;
+		}
+		default: return NGS2_ERROR_INVALID_RACK_QUERY_ID;
+	}
+}
+
+int KYTY_SYSV_ABI Ngs2CustomRackGetModuleInfo(uintptr_t rack_handle, uint32_t module_index,
+                                              Ngs2CustomModuleInfo* info, size_t info_size) {
+	PRINT_NAME();
+	if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	if (info_size < sizeof(Ngs2CustomModuleInfo)) return NGS2_ERROR_INVALID_OUT_SIZE;
+	auto* rack = Ngs2FindRack(rack_handle);
+	if (rack == nullptr) return NGS2_ERROR_INVALID_RACK_HANDLE;
+	if (!Ngs2RackIsCustom(rack->type) ||
+	    module_index >= rack->option.custom_sampler.custom_rack_option.num_modules) {
+		return NGS2_ERROR_INVALID_RACK_MODULE_INDEX;
+	}
+	const auto& mod        = rack->option.custom_sampler.custom_rack_option.module[module_index];
+	info->module_id        = mod.module_id;
+	info->source_buffer_id = mod.source_buffer_id;
+	info->extra_buffer_id  = mod.extra_buffer_id;
+	info->dest_buffer_id   = mod.dest_buffer_id;
+	info->state_offset     = mod.state_offset;
+	info->state_size       = mod.state_size;
+	info->reserved         = 0;
+	info->reserved2        = 0;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2VoiceGetOwner(uintptr_t voice_handle, uintptr_t* owner_rack,
+                                    uint32_t* voice_index) {
+	PRINT_NAME();
+	if (voice_handle == 0) return NGS2_ERROR_INVALID_VOICE_HANDLE;
+	if (owner_rack == nullptr || voice_index == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+
+	auto* voice = Ngs2VoiceFromHandle(voice_handle);
+	if (voice == nullptr || voice->rack == nullptr) return NGS2_ERROR_INVALID_VOICE_HANDLE;
+
+	auto* rack              = voice->rack;
+	*owner_rack             = reinterpret_cast<uintptr_t>(rack);
+	const auto* voices_base = reinterpret_cast<const Ngs2VoiceInternal*>(rack + 1);
+	*voice_index            = static_cast<uint32_t>(voice - voices_base);
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2VoiceGetMatrixInfo(uintptr_t voice_handle, uint32_t matrix_id,
+                                         Ngs2VoiceMatrixInfo* info, size_t info_size) {
+	PRINT_NAME();
+	if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	if (info_size < sizeof(Ngs2VoiceMatrixInfo)) return NGS2_ERROR_INVALID_OUT_SIZE;
+	if (voice_handle == 0) return NGS2_ERROR_INVALID_VOICE_HANDLE;
+
+	auto* voice = Ngs2VoiceFromHandle(voice_handle);
+	if (voice == nullptr) return NGS2_ERROR_INVALID_VOICE_HANDLE;
+
+	Common::LockGuard lock(voice->rack->ngs->mutex);
+	if (matrix_id >= voice->matrices.size()) return NGS2_ERROR_INVALID_PARAM_ID;
+
+	const auto& m = voice->matrices[matrix_id];
+	*info         = {};
+	if (!m.empty()) {
+		const auto count = std::min(m.size(), size_t(37 * 37));
+		info->num_levels = static_cast<uint32_t>(count);
+		std::memcpy(info->levels, m.data(), count * sizeof(float));
+	}
+	return OK;
+}
+
+// DSP FFT & Waveform Frame Info / ParseWaveformUser
+
+// Size Chart FFT: length 8..12 -> samples 64, 128, 256, 512, 1024
+static constexpr uint32_t kFftSamples[5] = {64u, 128u, 256u, 512u, 1024u};
+
+static bool Ngs2FftLengthValid(int length) {
+	return length >= 8 && length <= 12;
+}
+
+// Radix-2 Cooley-Tukey in-place FFT on complex data (double).
+// inverse=false -> forward transform (negative sign and exponent),
+// inverse=true  -> inverse transform (positive sign, unnormalized).
+static void Ngs2Radix2Fft(std::vector<std::complex<double>>& data, bool inverse) {
+	const size_t n = data.size();
+	// Bit-reversal permutation
+	for (size_t i = 1, j = 0; i < n; ++i) {
+		size_t bit = n >> 1u;
+		for (; j & bit; bit >>= 1u) {
+			j ^= bit;
+		}
+		j ^= bit;
+		if (i < j) {
+			std::swap(data[i], data[j]);
+		}
+	}
+	// Butterfly stages
+	const double sign = inverse ? 1.0 : -1.0;
+	for (size_t len = 2; len <= n; len <<= 1u) {
+		const double angle = sign * (2.0 * std::numbers::pi) / static_cast<double>(len);
+		const std::complex<double> step(std::cos(angle), std::sin(angle));
+		for (size_t i = 0; i < n; i += len) {
+			std::complex<double> w(1.0, 0.0);
+			const size_t         half = len >> 1u;
+			for (size_t j2 = 0; j2 < half; ++j2) {
+				const std::complex<double> u = data[i + j2];
+				const std::complex<double> v = data[i + j2 + half] * w;
+				data[i + j2]                 = u + v;
+				data[i + j2 + half]          = u - v;
+				w *= step;
+			}
+		}
+	}
+}
+
+// Calculate the index in the “internal order” buffer used by sceNgs2FftProcess.
+static size_t Ngs2FftInternalBinIndex(size_t q, size_t r, size_t j, size_t quarterBins) {
+	switch (r) {
+		case 0: return 4 * q + j;
+		case 1: return (q == 0 && j == 0) ? quarterBins : (2 * quarterBins - 4 * q - j);
+		case 2: return 2 * quarterBins + 4 * q + j;
+		default: return (q == 0 && j == 0) ? 3 * quarterBins : (4 * quarterBins - 4 * q - j);
+	}
+}
+
+// Serialize bins in “internal order” (flags=2, mode bit2=1).
+static void Ngs2FftPackInternal(const std::vector<std::pair<float, float>>& bins, size_t points,
+                                std::vector<float>& out) {
+	const size_t quarterBins = points / 8u;
+	const size_t quadGroups  = quarterBins / 4u;
+	out.assign(points, 0.0f);
+	for (size_t q = 0; q < quadGroups; ++q) {
+		for (size_t r = 0; r < 4; ++r) {
+			const size_t base = (4 * q + r) * 8u;
+			for (size_t j = 0; j < 4; ++j) {
+				const size_t bin  = Ngs2FftInternalBinIndex(q, r, j, quarterBins);
+				out[base + j]     = bins[bin].first;
+				out[base + 4 + j] = bins[bin].second;
+			}
+		}
+	}
+}
+
+// Deserialize bins in “internal order.”
+static void Ngs2FftUnpackInternal(const std::vector<float>& in, size_t points,
+                                  std::vector<std::pair<float, float>>& bins) {
+	const size_t quarterBins = points / 8u;
+	const size_t quadGroups  = quarterBins / 4u;
+	bins.assign(points / 2u, {0.0f, 0.0f});
+	for (size_t q = 0; q < quadGroups; ++q) {
+		for (size_t r = 0; r < 4; ++r) {
+			const size_t base = (4 * q + r) * 8u;
+			for (size_t j = 0; j < 4; ++j) {
+				const size_t bin = Ngs2FftInternalBinIndex(q, r, j, quarterBins);
+				bins[bin]        = {in[base + j], in[base + 4 + j]};
+			}
+		}
+	}
+}
+
+// Serialize bins in “natural order” (flags=2, mode bit2=0).
+static void Ngs2FftPackNatural(const std::vector<std::pair<float, float>>& bins, size_t points,
+                               std::vector<float>& out) {
+	const size_t quarterBins = points / 8u;
+	const size_t blockStride = points / 2u;
+	out.assign(points * 2u, 0.0f);
+	for (size_t q = 0; q < 4; ++q) {
+		const size_t binStart  = q * quarterBins;
+		const size_t blockBase = q * blockStride;
+		for (size_t r = 0; r < quarterBins; ++r) {
+			const size_t dstOffset             = ((q & 1u) != 0 && r > 0) ? (quarterBins - r) : r;
+			const auto&  bin                   = bins[binStart + r];
+			out[blockBase + dstOffset * 2]     = bin.first;
+			out[blockBase + dstOffset * 2 + 1] = bin.second;
+		}
+	}
+}
+
+// ---- Public FFT APIs ----
+
+int KYTY_SYSV_ABI Ngs2FftQuerySize(uint32_t length, uint32_t flags, uint64_t* out_size) {
+	PRINT_NAME();
+	if (out_size == nullptr || length < 8 || length > 12) {
+		return -1;
+	}
+	uint32_t count = kFftSamples[length - 8];
+	if ((flags & 2u) != 0) {
+		count /= 2u;
+	}
+	// Formula: count * 32 + 64 (each 32-byte entry = 2 float pairs × 2 channels × 4 bytes)
+	*out_size = static_cast<uint64_t>(count) * 32u + 64u;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2FftInit(void* work, size_t size, int length, uint32_t flags,
+                              void** out_handle) {
+	PRINT_NAME();
+	if (!Ngs2FftLengthValid(length) || work == nullptr || out_handle == nullptr) {
+		return -1;
+	}
+	uint32_t count = kFftSamples[static_cast<size_t>(length - 8)];
+	if ((flags & 2u) != 0) {
+		count /= 2u;
+	}
+	const size_t required = static_cast<size_t>(count) * 32u + 64u;
+	if (size < required) {
+		return -1;
+	}
+
+	auto* bytes = static_cast<uint8_t*>(work);
+	std::memset(bytes, 0, required);
+
+	// 64-byte table alignment
+	const uintptr_t base      = reinterpret_cast<uintptr_t>(work);
+	const uintptr_t tableAddr = (base + 0x57u) & ~uintptr_t {0x3fu};
+	const size_t    tableOff  = static_cast<size_t>(tableAddr - base);
+	const uintptr_t secondAddr =
+	    tableAddr + (((flags & 2u) != 0) ? static_cast<size_t>(count) * 16u : 0u);
+
+	// Header with an offset of 0x00..0x17
+	std::memcpy(bytes + 0x00, &tableAddr, sizeof(uint64_t));
+	std::memcpy(bytes + 0x08, &secondAddr, sizeof(uint64_t));
+	const int32_t len32 = static_cast<int32_t>(length);
+	std::memcpy(bytes + 0x10, &len32, sizeof(int32_t));
+	std::memcpy(bytes + 0x14, &flags, sizeof(uint32_t));
+
+	// Pre-calculated sine/cosine table
+	if (tableOff < required) {
+		const size_t points    = size_t {1} << length;
+		const size_t maxFloats = (required - tableOff) / sizeof(float);
+		for (size_t idx = 0; idx + 1 < maxFloats; idx += 2) {
+			const size_t k = idx / 2u;
+			const double angle =
+			    (-2.0 * std::numbers::pi * static_cast<double>(k)) / static_cast<double>(points);
+			const float c = static_cast<float>(std::cos(angle));
+			const float s = static_cast<float>(std::sin(angle));
+			std::memcpy(bytes + tableOff + idx * sizeof(float), &c, sizeof(float));
+			std::memcpy(bytes + tableOff + (idx + 1) * sizeof(float), &s, sizeof(float));
+		}
+	}
+
+	*out_handle = work;
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2FftProcess(void* handle, const float* in, float* out, float* work_buf,
+                                 uintptr_t unused, uint32_t mode) {
+	(void)unused;
+	PRINT_NAME();
+	if (handle == nullptr || in == nullptr || out == nullptr) {
+		return -1;
+	}
+
+	const auto* hdr    = static_cast<const uint8_t*>(handle);
+	int32_t     length = 0;
+	uint32_t    flags  = 0;
+	std::memcpy(&length, hdr + 0x10, sizeof(length));
+	std::memcpy(&flags, hdr + 0x14, sizeof(flags));
+	if (!Ngs2FftLengthValid(length)) {
+		return -1;
+	}
+
+	const size_t points = size_t {1} << length;
+
+	// flags=0: “pass-through” mode — copies work_buf to out (or to in if work_buf==nullptr)
+	if ((flags & 2u) == 0) {
+		const size_t totalFloats = points * 2u;
+		if (work_buf != nullptr) {
+			std::memcpy(out, work_buf, totalFloats * sizeof(float));
+		} else {
+			std::memcpy(out, in, totalFloats * sizeof(float));
+		}
+		return OK;
+	}
+
+	// flags=2: trigonometric table mode; supports direct and inverse FFT.
+	const float scale = 1.0f / static_cast<float>(points);
+
+	if ((mode & 1u) != 0) {
+		// ---- Forward FFT: real -> compressed spectrum ----
+		std::vector<float> input(points);
+		std::memcpy(input.data(), in, points * sizeof(float));
+
+		std::vector<std::complex<double>> spectrum(points);
+		for (size_t n2 = 0; n2 < points; ++n2) {
+			spectrum[n2] = {static_cast<double>(input[n2]), 0.0};
+		}
+		Ngs2Radix2Fft(spectrum, false);
+
+		const size_t                         half = points / 2u;
+		std::vector<std::pair<float, float>> bins(half);
+		bins[0] = {static_cast<float>(spectrum[0].real()),
+		           static_cast<float>(spectrum[half].real())};
+		for (size_t k = 1; k < half; ++k) {
+			bins[k] = {static_cast<float>(spectrum[k].real()),
+			           static_cast<float>(spectrum[k].imag())};
+		}
+
+		std::vector<float> output;
+		if ((mode & 4u) != 0) {
+			// internal order
+			Ngs2FftPackInternal(bins, points, output);
+			if ((mode & 8u) != 0) {
+				for (float& v: output) {
+					v *= scale;
+				}
+			}
+		} else {
+			// natural order
+			Ngs2FftPackNatural(bins, points, output);
+			if ((mode & 8u) != 0) {
+				for (size_t i = 0; i < points; ++i) {
+					output[i] *= scale;
+				}
+			}
+		}
+		std::memcpy(out, output.data(), output.size() * sizeof(float));
+		return OK;
+	}
+
+	// ---- Inverse FFT: compressed spectrum -> real ----
+	std::vector<float> input(points);
+	std::memcpy(input.data(), in, points * sizeof(float));
+
+	std::vector<std::pair<float, float>> bins;
+	if ((mode & 4u) != 0) {
+		Ngs2FftUnpackInternal(input, points, bins);
+	} else {
+		const size_t half = points / 2u;
+		bins.resize(half);
+		for (size_t k = 0; k < half; ++k) {
+			bins[k] = {input[k * 2], input[k * 2 + 1]};
+		}
+	}
+
+	const size_t                      half = points / 2u;
+	std::vector<std::complex<double>> spectrum(points);
+	spectrum[0]    = {static_cast<double>(bins[0].first), 0.0};
+	spectrum[half] = {static_cast<double>(bins[0].second), 0.0};
+	for (size_t k = 1; k < half; ++k) {
+		const std::complex<double> v(static_cast<double>(bins[k].first),
+		                             static_cast<double>(bins[k].second));
+		spectrum[k]          = v;
+		spectrum[points - k] = std::conj(v);
+	}
+	Ngs2Radix2Fft(spectrum, true);
+
+	std::vector<float> output(points);
+	for (size_t n2 = 0; n2 < points; ++n2) {
+		float v = static_cast<float>(spectrum[n2].real());
+		if ((mode & 8u) != 0) {
+			v *= scale;
+		}
+		output[n2] = v;
+	}
+	std::memcpy(out, output.data(), points * sizeof(float));
+	return OK;
+}
+
+// Ngs2GetWaveformFrameInfo Retrieves frame size, num_frame_samples, units_per_frame,
+// and num_delay_samples from the waveform format (PCM or ATRAC9).
+
+int KYTY_SYSV_ABI Ngs2GetWaveformFrameInfo(const Ngs2WaveformFormat* format,
+                                           uint32_t*                 out_frame_size,
+                                           uint32_t*                 out_num_frame_samples,
+                                           uint32_t*                 out_units_per_frame,
+                                           uint32_t*                 out_num_delay_samples) {
+	PRINT_NAME();
+
+	// All output pointers must be valid (AnyPS5: SCE_NGS2_ERROR_INVALID_OUT_ADDRESS)
+	if (out_frame_size == nullptr || out_num_frame_samples == nullptr ||
+	    out_units_per_frame == nullptr || out_num_delay_samples == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	// If the format itself is null or invalid
+	if (format == nullptr || format->num_channels == 0 || format->num_channels > 8 ||
+	    format->sample_rate == 0 || format->sample_rate > 192000) {
+		return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+	}
+
+	uint32_t frameSize     = 0;
+	uint32_t frameSamples  = 0;
+	uint32_t unitsPerFrame = 0;
+	uint32_t delaySamples  = 0;
+
+	if (format->waveform_type == NGS2_WAVEFORM_TYPE_ATRAC9) {
+		// ATRAC9: Extracting information from the codec
+		std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config {
+		    static_cast<uint8_t>(format->config_data >> 24u),
+		    static_cast<uint8_t>(format->config_data >> 16u),
+		    static_cast<uint8_t>(format->config_data >> 8u),
+		    static_cast<uint8_t>(format->config_data)};
+		Atrac9CodecInfo codec {};
+		if (!Ngs2GetAtrac9CodecInfo(config, codec)) {
+			return NGS2_ERROR_INVALID_WAVEFORM_FORMAT;
+		}
+		frameSize     = static_cast<uint32_t>(codec.superframeSize);
+		frameSamples  = static_cast<uint32_t>(static_cast<uint64_t>(codec.frameSamples) *
+		                                      codec.framesInSuperframe);
+		unitsPerFrame = static_cast<uint32_t>(codec.framesInSuperframe);
+		delaySamples  = static_cast<uint32_t>(codec.frameSamples);
+	} else if (format->waveform_type == SCE_NGS2_WAVEFORM_TYPE_VAG) {
+		frameSize     = format->num_channels * 16u;
+		frameSamples  = 28;
+		unitsPerFrame = 1;
+		delaySamples  = 0;
+	} else {
+		// PCM (all linear types): frame = one sample for all channels
+		uint32_t bytesPerSample = 0;
+		switch (format->waveform_type) {
+			case 0x11u: bytesPerSample = 1; break; // 8-bit PCM
+			case 0x12u: bytesPerSample = 2; break; // 16-bit PCM (I16L)
+			case 0x14u: bytesPerSample = 3; break; // 24-bit PCM
+			case 0x16u: bytesPerSample = 4; break; // 32-bit PCM int
+			case 0x18u: bytesPerSample = 4; break; // 32-bit float
+			case 0x1au: bytesPerSample = 8; break; // 64-bit double
+			default: return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+		}
+		frameSize     = format->num_channels * bytesPerSample;
+		frameSamples  = 1;
+		unitsPerFrame = 1;
+		delaySamples  = 0;
+	}
+
+	*out_frame_size        = frameSize;
+	*out_num_frame_samples = frameSamples;
+	*out_units_per_frame   = unitsPerFrame;
+	*out_num_delay_samples = delaySamples;
+	return OK;
+}
+
+// Ngs2ParseWaveformUser Calls a handler (PS5 callback) to read RIFF/WAVE data
+// and extract Ngs2WaveformInfo (delegates to Ngs2ParseWaveformData).
+// Callback signature: int32_t handler(uintptr_t user_data, uint32_t offset, void* buf, size_t size)
+
+// Type for the reading callback
+using Ngs2ParseReadHandler = int32_t(KYTY_SYSV_ABI*)(uintptr_t user_data, uint32_t offset,
+                                                     void* data, size_t size);
+
+int KYTY_SYSV_ABI Ngs2ParseWaveformUser(uintptr_t handler, uintptr_t user_data,
+                                        Ngs2WaveformInfo* out_info) {
+	PRINT_NAME();
+
+	if (out_info == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	if (handler == 0) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE; // Null handler = invalid handle
+	}
+
+	const auto read = reinterpret_cast<Ngs2ParseReadHandler>(handler);
+
+	// Read the first bytes of the header
+	uint8_t header[48] = {};
+	if (read(user_data, 0, header, 12) < 0) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+	if (std::memcmp(header, "VAGp", 4) == 0) {
+		if (read(user_data, 12, header + 12, 36) < 0) {
+			return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+		}
+		const uint32_t     vag_size          = (static_cast<uint32_t>(header[0x0c]) << 24u) |
+		                                       (static_cast<uint32_t>(header[0x0d]) << 16u) |
+		                                       (static_cast<uint32_t>(header[0x0e]) << 8u) |
+		                                       static_cast<uint32_t>(header[0x0f]);
+		constexpr uint64_t kMaxWaveformBytes = 256ull * 1024 * 1024;
+		if (vag_size > kMaxWaveformBytes) {
+			return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+		}
+		const size_t         total = 48 + vag_size;
+		std::vector<uint8_t> bytes(total);
+		std::memcpy(bytes.data(), header, 48);
+		if (vag_size > 0 && read(user_data, 48, bytes.data() + 48, vag_size) < 0) {
+			return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+		}
+		return Ngs2ParseWaveformData(bytes.data(), total, out_info);
+	}
+	if (!Ngs2FourCcEquals(header, "RIFF") || !Ngs2FourCcEquals(header + 8, "WAVE")) {
+		return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT;
+	}
+
+	const uint32_t     riff_size         = Ngs2ReadLe32(header + 4);
+	const uint64_t     riff_end          = 8ull + riff_size;
+	constexpr uint64_t kMaxWaveformBytes = 256ull * 1024 * 1024; // 256 MiB
+	if (riff_end < 12 || riff_end > kMaxWaveformBytes) {
+		return NGS2_ERROR_INVALID_WAVEFORM_DATA;
+	}
+
+	// Read the entire RIFF file into a local buffer
+	const size_t         total = static_cast<size_t>(riff_end);
+	std::vector<uint8_t> bytes(total);
+	if (read(user_data, 0, bytes.data(), total) < 0) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+
+	// Delegate to the existing RIFF parser
+	return Ngs2ParseWaveformData(bytes.data(), total, out_info);
+}
+
+// Stream API & Scheduler / Modules
+static inline bool IsValidPointer(const void* ptr, size_t size = 1) {
+	if (ptr == nullptr) return false;
+	const uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
+	if (addr < 0x10000) return false;
+	if (addr + size < addr) return false;
+	return true;
+}
+
+static inline bool ReadGuestBytes(void* local, const void* guest, size_t bytes) {
+	if (bytes == 0) return true;
+	if (!IsValidPointer(guest, bytes) || local == nullptr) return false;
+	std::memcpy(local, guest, bytes);
+	return true;
+}
+
+static inline bool WriteGuestBytes(void* guest, const void* local, size_t bytes) {
+	if (bytes == 0) return true;
+	if (!IsValidPointer(guest, bytes) || local == nullptr) return false;
+	std::memcpy(guest, local, bytes);
+	return true;
+}
+
+template <typename T>
+static inline bool ReadGuest(const T* guest, T& local) {
+	return ReadGuestBytes(&local, guest, sizeof(local));
+}
+
+template <typename T>
+static inline bool WriteGuest(T* guest, const T& local) {
+	return WriteGuestBytes(guest, &local, sizeof(local));
+}
+
+static int CheckStreamOption(const void* option, Ngs2StreamOption& checked) {
+	if (option == nullptr) {
+		checked               = {};
+		checked.size          = sizeof(Ngs2StreamOption);
+		checked.num_blocks    = 4;
+		checked.buffer_size_1 = 0x100;
+		checked.buffer_size_2 = 0x10;
+		checked.buffer_size_3 = 0x10000;
+		checked.default_param = 0.5f;
+		return 0;
+	}
+	Ngs2StreamOption opt {};
+	if (!ReadGuest(static_cast<const Ngs2StreamOption*>(option), opt)) {
+		return SCE_NGS2_ERROR_INVALID_OPTION_SIZE;
+	}
+	if (opt.num_blocks < 1 || opt.num_blocks > 32) {
+		return SCE_NGS2_ERROR_INVALID_NUM_BLOCKS;
+	}
+	if (opt.buffer_size_3 == 0) {
+		return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_3_ZERO;
+	}
+	if (opt.buffer_size_1 == 0) {
+		return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_1_ZERO;
+	}
+	if (opt.buffer_size_2 == 0) {
+		return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_2_ZERO;
+	}
+	if (opt.size != sizeof(Ngs2StreamOption)) {
+		return SCE_NGS2_ERROR_INVALID_OPTION_SIZE;
+	}
+	checked = opt;
+	return 0;
+}
+
+static uint64_t ComputeStreamBufferSize(const Ngs2StreamOption& opt) {
+	auto         align8 = [](size_t val) -> size_t { return (val + 7u) & ~size_t {7u}; };
+	const size_t guard  = (opt.flags & 0x80000000u) ? 16u : 0u;
+	const size_t n      = opt.num_blocks;
+	const size_t total  = align8(0x368 + guard) + align8(0x28 * n + guard) +
+	                      align8(0x28 * n + guard) + align8(opt.buffer_size_3 + guard) +
+	                      align8(opt.buffer_size_2 + guard) + align8(opt.buffer_size_1 + guard) +
+	                      align8(opt.buffer_size_1 + guard) + 8;
+	return static_cast<uint64_t>(total);
+}
+
+struct Ngs2StreamInternal {
+	uintptr_t             handle = 0;
+	Ngs2Internal*         system = nullptr;
+	Ngs2StreamOption      option {};
+	Ngs2ContextBufferInfo buffer_info {};
+	Ngs2BufferAllocator   allocator {};
+	bool                  has_allocator = false;
+	std::vector<uint8_t>  managed_buffer;
+	Common::Mutex         mutex;
+};
+
+static Common::Mutex                                    g_ngs2_streams_mutex;
+static std::vector<std::unique_ptr<Ngs2StreamInternal>> g_ngs2_streams;
+
+static Ngs2StreamInternal* Ngs2FindStream(uintptr_t handle) {
+	if (handle == 0) return nullptr;
+	Common::LockGuard lock(g_ngs2_streams_mutex);
+	for (auto& s: g_ngs2_streams) {
+		if (s && s->handle == handle) {
+			return s.get();
+		}
+	}
+	return nullptr;
+}
+
+int KYTY_SYSV_ABI Ngs2StreamResetOption(void* option) {
+	PRINT_NAME();
+	if (option == nullptr) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	Ngs2StreamOption opt {};
+	opt.size = sizeof(Ngs2StreamOption);
+	std::memset(opt.name, 0, sizeof(opt.name));
+	opt.flags         = 0;
+	opt.num_blocks    = 4;
+	opt.buffer_size_1 = 0x100;
+	opt.reserved1     = 0;
+	opt.buffer_size_2 = 0x10;
+	opt.reserved2     = 0;
+	opt.buffer_size_3 = 0x10000;
+	opt.reserved3     = 0;
+	opt.default_param = 0.5f;
+	opt.reserved4     = 0;
+	std::memset(opt.reserved_tail, 0, sizeof(opt.reserved_tail));
+	if (!WriteGuest(static_cast<Ngs2StreamOption*>(option), opt)) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2StreamQueryBufferSize(const void* option, void* buffer_info) {
+	PRINT_NAME();
+	if (buffer_info == nullptr || !IsValidPointer(buffer_info, sizeof(Ngs2ContextBufferInfo))) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	const Ngs2ContextBufferInfo cleared {};
+	if (!WriteGuestBytes(buffer_info, &cleared, offsetof(Ngs2ContextBufferInfo, user_data))) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	Ngs2StreamOption checked {};
+	const int        error = CheckStreamOption(option, checked);
+	if (error != 0) {
+		return error;
+	}
+	const uint64_t size = ComputeStreamBufferSize(checked);
+	if (!WriteGuestBytes(static_cast<uint8_t*>(buffer_info) +
+	                         offsetof(Ngs2ContextBufferInfo, host_buffer_size),
+	                     &size, sizeof(size))) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2StreamCreate(uintptr_t system_handle, const void* option,
+                                   const void* buffer_info, uintptr_t* handle) {
+	PRINT_NAME();
+	if (buffer_info == nullptr) {
+		return SCE_NGS2_ERROR_INVALID_BUFFER_INFO;
+	}
+	Ngs2ContextBufferInfo localBufferInfo {};
+	if (!ReadGuest(static_cast<const Ngs2ContextBufferInfo*>(buffer_info), localBufferInfo) ||
+	    localBufferInfo.host_buffer == nullptr) {
+		return SCE_NGS2_ERROR_INVALID_BUFFER_INFO;
+	}
+	if (handle == nullptr || !IsValidPointer(handle, sizeof(uintptr_t))) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	Ngs2StreamOption checked {};
+	const int        optError = CheckStreamOption(option, checked);
+	if (optError != 0) {
+		return optError;
+	}
+	auto* system = Ngs2FindRegisteredSystem(system_handle);
+	if (system == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+
+	auto stream         = std::make_unique<Ngs2StreamInternal>();
+	stream->system      = system;
+	stream->option      = checked;
+	stream->buffer_info = localBufferInfo;
+	stream->handle      = reinterpret_cast<uintptr_t>(stream.get());
+
+	*handle = stream->handle;
+	{
+		Common::LockGuard lock(g_ngs2_streams_mutex);
+		g_ngs2_streams.push_back(std::move(stream));
+	}
+	return OK;
+}
+
+int KYTY_SYSV_ABI Ngs2StreamCreateWithAllocator(uintptr_t system_handle, const void* option,
+                                                const void* allocator, uintptr_t* handle) {
+	PRINT_NAME();
+	if (allocator == nullptr) {
+		return SCE_NGS2_ERROR_INVALID_BUFFER_ALLOCATOR;
+	}
+	Ngs2BufferAllocator localAllocator {};
+	if (!ReadGuest(static_cast<const Ngs2BufferAllocator*>(allocator), localAllocator) ||
+	    localAllocator.alloc_handler == nullptr) {
+		return SCE_NGS2_ERROR_INVALID_BUFFER_ALLOCATOR;
+	}
+	if (handle == nullptr || !IsValidPointer(handle, sizeof(uintptr_t))) {
+		return NGS2_ERROR_INVALID_OUT_ADDRESS;
+	}
+	Ngs2StreamOption checked {};
+	const int        optError = CheckStreamOption(option, checked);
+	if (optError != 0) {
+		return optError;
+	}
+	auto* system = Ngs2FindRegisteredSystem(system_handle);
+	if (system == nullptr) {
+		return NGS2_ERROR_INVALID_SYSTEM_HANDLE;
+	}
+
+	auto stream           = std::make_unique<Ngs2StreamInternal>();
+	stream->system        = system;
+	stream->option        = checked;
+	stream->allocator     = localAllocator;
+	stream->has_allocator = true;
+
+	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);
+	if (alloc_res < 0 || stream->buffer_info.host_buffer == nullptr) {
+		if (stream->buffer_info.host_buffer != nullptr && localAllocator.free_handler != nullptr) {
+			localAllocator.free_handler(&stream->buffer_info);
+		}
+		stream->has_allocator = false;
+		stream->managed_buffer.resize(req_size, 0);
+		stream->buffer_info.host_buffer = stream->managed_buffer.data();
+		stream->buffer_info.user_data   = localAllocator.user_data;

Minor · Data Integrity & Integration · Quick win

Set the fallback buffer size from the managed allocation.

If the allocation callback clears host_buffer_size and returns no buffer, the fallback creates req_size bytes but keeps the callback's zero size. Ngs2StreamDestroy then reports that zero size to callers that request buffer information. Rebuild the fallback metadata from managed_buffer after callback cleanup. Preserve the callback's metadata when caller allocation succeeds.

✅ Addressed in commit 1de75dc

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653931154) · edited 2026-11-21 18:40 UTC On `src/libs/ngs2.cpp` line 5582 (outdated): ```diff @@ -3363,6 +4465,1385 @@ int KYTY_SYSV_ABI Ngs2SystemUnlock(uintptr_t system_handle) { return OK; } +int KYTY_SYSV_ABI Ngs2SystemSetUserData(uintptr_t system_handle, uintptr_t user_data) { + PRINT_NAME(); + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + Common::LockGuard lock(ngs->mutex); + ngs->user_data = user_data; + return OK; +} + +int KYTY_SYSV_ABI Ngs2SystemGetUserData(uintptr_t system_handle, uintptr_t* user_data) { + PRINT_NAME(); + if (user_data == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + Common::LockGuard lock(ngs->mutex); + *user_data = ngs->user_data; + return OK; +} + +int KYTY_SYSV_ABI Ngs2SystemSetSampleRate(uintptr_t system_handle, uint32_t sample_rate) { + PRINT_NAME(); + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + if (!Ngs2IsValidSampleRate(sample_rate)) { + return NGS2_ERROR_INVALID_SAMPLE_RATE; + } + Common::LockGuard lock(ngs->mutex); + ngs->option.sample_rate = sample_rate; + return OK; +} + +struct Ngs2CommandRecord { + uint32_t id; + uint8_t flags; + uint8_t type; + uint16_t count; + union { + uint64_t u64; + uint32_t u32; + int32_t i32; + float f; + const void* ptr; + } value; +}; +static_assert(sizeof(Ngs2CommandRecord) == 16); + +int KYTY_SYSV_ABI Ngs2SystemRunCommands(uintptr_t system_handle, const void* commands, + size_t count) { + PRINT_NAME(); + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + if (count == 0) { + return OK; + } + if (commands == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + const auto* records = static_cast<const Ngs2CommandRecord*>(commands); + for (size_t i = 0; i < count; ++i) { + const auto& rec = records[i]; + const uint32_t cmd = rec.id & 0x00ffffffu; + if (cmd == 0xf00000 || cmd == 0xf00001 || cmd == 0xf00002 || cmd == 0xf00006) { + continue; + } + if (cmd == 0xf00003) { + if (rec.id >= 0x20000000u) { + return NGS2_ERROR_SYSTEM_INDEX_RANGE; + } + } else if (cmd == 0xf00004) { + if (!Ngs2IsValidSampleRate(rec.value.u32)) { + return NGS2_ERROR_INVALID_SAMPLE_RATE; + } + } else if (cmd == 0xf00005) { + const uint32_t grain = rec.value.u32; + if (grain < 64 || grain > ngs->option.max_grain_samples || (grain % 64) != 0) { + return NGS2_ERROR_INVALID_NUM_GRAIN_SAMPLES; + } + } else { + return NGS2_ERROR_INVALID_PARAM_ID; + } + } + + for (size_t i = 0; i < count; ++i) { + const auto& rec = records[i]; + const uint32_t cmd = rec.id & 0x00ffffffu; + if (cmd == 0xf00000) { + ngs->mutex.Lock(); + } else if (cmd == 0xf00001) { + ngs->mutex.Unlock(); + } else if (cmd == 0xf00002) { + Common::LockGuard lock(ngs->mutex); + ngs->user_data = rec.value.u64; + } else if (cmd == 0xf00004) { + Common::LockGuard lock(ngs->mutex); + ngs->option.sample_rate = rec.value.u32; + } else if (cmd == 0xf00005) { + Common::LockGuard lock(ngs->mutex); + ngs->option.num_grain_samples = rec.value.u32; + } else if (cmd == 0xf00006) { + Common::LockGuard lock(ngs->mutex); + ngs->unnamed_param = rec.value.f; + } else if (cmd == 0xf00003) { + const uint32_t slot = rec.id >> 24; + if (slot < ngs->slot_data.size()) { + Common::LockGuard lock(ngs->mutex); + if (rec.value.ptr == nullptr) { + ngs->slot_set[slot] = false; + ngs->slot_data[slot].fill(0); + } else { + uint64_t leading_word = 0; + std::memcpy(&leading_word, rec.value.ptr, sizeof(leading_word)); + if (leading_word == 0) { + ngs->slot_set[slot] = false; + ngs->slot_data[slot].fill(0); + } else { + ngs->slot_set[slot] = true; + std::memcpy(ngs->slot_data[slot].data(), rec.value.ptr, 24); + } + } + } + } + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2SystemQueryInfo(uintptr_t system_handle, uint32_t info_id, void* info, + size_t info_size) { + PRINT_NAME(); + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + switch (info_id & 0x00ffffffu) { + case 0xf04000: { + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < sizeof(Ngs2SystemInfo)) return NGS2_ERROR_INVALID_OUT_SIZE; + return Ngs2SystemGetInfo(system_handle, static_cast<Ngs2SystemInfo*>(info), info_size); + } + case 0xf04001: { + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < sizeof(uint64_t)) return NGS2_ERROR_INVALID_OUT_SIZE; + Common::LockGuard lock(ngs->mutex); + std::memcpy(info, &ngs->user_data, sizeof(uint64_t)); + return OK; + } + case 0xf04002: { + if (info_id >= 0x20000000u) return NGS2_ERROR_SYSTEM_INDEX_RANGE; + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < 24) return NGS2_ERROR_INVALID_OUT_SIZE; + const uint32_t slot = info_id >> 24; + std::array<uint8_t, 24> out_data {}; + { + Common::LockGuard lock(ngs->mutex); + if (slot < ngs->slot_data.size() && ngs->slot_set[slot]) { + std::memcpy(out_data.data(), ngs->slot_data[slot].data(), 24); + } + } + std::memcpy(info, out_data.data(), 24); + return OK; + } + case 0xf04003: { + if (info == nullptr && info_size >= sizeof(uintptr_t)) + return NGS2_ERROR_INVALID_OUT_ADDRESS; + uint32_t count = 0; + { + Common::LockGuard lock(g_racks_mutex); + for (auto* r = g_racks_list; r != nullptr; r = r->next) { + if (r->ngs == ngs) { + if (info != nullptr && count < (info_size / sizeof(uintptr_t))) { + reinterpret_cast<uintptr_t*>(info)[count] = + reinterpret_cast<uintptr_t>(r); + } + ++count; + } + } + } + return static_cast<int>(count); + } + default: return NGS2_ERROR_INVALID_SYSTEM_QUERY_ID; + } +} + +int KYTY_SYSV_ABI Ngs2SystemEnumHandles(uintptr_t* out_handles, uint32_t max_handles) { + PRINT_NAME(); + constexpr int32_t invalid_argument = static_cast<int32_t>(0x804a0053u); + if (max_handles != 0 && out_handles == nullptr) return invalid_argument; + uint32_t count = 0; + Common::LockGuard lock(g_ngs_mutex); + for (auto* ngs = g_ngs_list; ngs != nullptr; ngs = ngs->next) { + if (out_handles != nullptr && count < max_handles) { + out_handles[count] = reinterpret_cast<uintptr_t>(ngs); + } + ++count; + } + return static_cast<int>(count); +} + +int KYTY_SYSV_ABI Ngs2SystemEnumRackHandles(uintptr_t system_handle, uintptr_t* out_handles, + uint32_t max_handles) { + PRINT_NAME(); + constexpr int32_t invalid_argument = static_cast<int32_t>(0x804a0053u); + constexpr int32_t invalid_system_handle = static_cast<int32_t>(0x804a0230u); + if (max_handles != 0 && out_handles == nullptr) return invalid_argument; + auto* ngs = Ngs2FindSystem(system_handle); + if (ngs == nullptr) return invalid_system_handle; + uint32_t count = 0; + Common::LockGuard lock(g_racks_mutex); + for (auto* rack = g_racks_list; rack != nullptr; rack = rack->next) { + if (rack->ngs == ngs) { + if (out_handles != nullptr && count < max_handles) { + out_handles[count] = reinterpret_cast<uintptr_t>(rack); + } + ++count; + } + } + return static_cast<int>(count); +} + +int KYTY_SYSV_ABI Ngs2RackSetUserData(uintptr_t rack_handle, uintptr_t user_data) { + PRINT_NAME(); + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr) { + return NGS2_ERROR_INVALID_RACK_HANDLE; + } + rack->user_data = user_data; + return OK; +} + +int KYTY_SYSV_ABI Ngs2RackGetUserData(uintptr_t rack_handle, uintptr_t* user_data) { + PRINT_NAME(); + if (user_data == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr) { + return NGS2_ERROR_INVALID_RACK_HANDLE; + } + *user_data = rack->user_data; + return OK; +} + +int KYTY_SYSV_ABI Ngs2RackRunCommands(uintptr_t rack_handle, const void* commands, size_t count) { + PRINT_NAME(); + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr) { + return NGS2_ERROR_INVALID_RACK_HANDLE; + } + if (count == 0) { + return OK; + } + if (commands == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + const auto* records = static_cast<const Ngs2CommandRecord*>(commands); + for (size_t i = 0; i < count; ++i) { + const uint32_t cmd = records[i].id & 0x00ffffffu; + if (cmd < 0xf10000 || cmd > 0xf10002) { + return NGS2_ERROR_INVALID_PARAM_ID; + } + } + for (size_t i = 0; i < count; ++i) { + const auto& rec = records[i]; + const uint32_t cmd = rec.id & 0x00ffffffu; + if (cmd == 0xf10000) { + int lock_res = Ngs2RackLock(rack_handle); + if (lock_res != OK) return lock_res; + } else if (cmd == 0xf10001) { + int unlock_res = Ngs2RackUnlock(rack_handle); + if (unlock_res != OK) return unlock_res; + } else if (cmd == 0xf10002) { + rack->user_data = rec.value.u64; + } + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2RackGetInfo(uintptr_t rack_handle, Ngs2RackInfo* info, size_t info_size) { + PRINT_NAME(); + if (info == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + if (info_size < sizeof(Ngs2RackInfo)) { + return NGS2_ERROR_INVALID_OUT_SIZE; + } + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr || rack->ngs == nullptr) { + return NGS2_ERROR_INVALID_RACK_HANDLE; + } + Common::LockGuard lock(rack->ngs->mutex); + + *info = {}; + std::memcpy(info->name, rack->name, sizeof(info->name)); + info->rack_handle = rack_handle; + info->buffer_info = rack->buffer_info; + info->owner_system_handle = reinterpret_cast<uintptr_t>(rack->ngs); + info->type = + (rack->type == Ngs2RackType::Sampler || rack->type == Ngs2RackType::CustomSampler) ? 0 + : (rack->type == Ngs2RackType::Mastering || rack->type == Ngs2RackType::CustomMastering) + ? 2 + : 1; + info->rack_id = rack->rack_id; + info->uid = rack->uid; + info->min_grain_samples = 64; + info->max_grain_samples = rack->option.common.max_grain_samples; + info->max_voices = rack->option.common.max_voices; + info->max_channel_works = (rack->type == Ngs2RackType::Sampler) + ? rack->option.sampler.max_channel_works + : (rack->type == Ngs2RackType::CustomSampler) + ? rack->option.custom_sampler.max_channel_works + : 0; + info->max_inputs = + (rack->type == Ngs2RackType::Submixer) ? rack->option.submixer.max_inputs + : (rack->type == Ngs2RackType::CustomSubmixer) ? rack->option.custom_submixer.max_inputs + : (rack->type == Ngs2RackType::CustomMastering) ? rack->option.custom_mastering.max_inputs + : 0; + info->max_matrices = rack->option.common.max_matrices; + info->max_ports = rack->option.common.max_ports; + info->max_voice_channels = rack->option.common.max_voice_channels; + info->max_output_channels = rack->option.common.max_output_channels; + info->num_modules = Ngs2RackIsCustom(rack->type) + ? rack->option.custom_sampler.custom_rack_option.num_modules + : 0; + info->num_buffers = rack->NumBuffers(); + info->state_flags = (rack->lock_depth == 0) ? 1 : 5; + info->last_process_ratio = 0.0f; + info->last_processed_tick = 0; + info->render_count = rack->render_count; + info->active_voice_count = 0; + info->active_channel_work_count = 0; + + auto* voices = reinterpret_cast<Ngs2VoiceInternal*>(rack + 1); + for (uint32_t i = 0; i < rack->option.common.max_voices; ++i) { + if (voices[i].state == Ngs2VoicePlayState::Playing || + voices[i].state == Ngs2VoicePlayState::Paused) { + ++info->active_voice_count; + info->active_channel_work_count += voices[i].channels; + } + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2RackQueryInfo(uintptr_t rack_handle, uint32_t info_id, void* info, + size_t info_size) { + PRINT_NAME(); + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr) { + return NGS2_ERROR_INVALID_RACK_HANDLE; + } + switch (info_id & 0x00ffffffu) { + case 0xf14000: { + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < sizeof(Ngs2RackInfo)) return NGS2_ERROR_INVALID_OUT_SIZE; + return Ngs2RackGetInfo(rack_handle, static_cast<Ngs2RackInfo*>(info), info_size); + } + case 0xf14001: { + if (info_size < sizeof(uint64_t)) return NGS2_ERROR_INVALID_OUT_SIZE; + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + std::memcpy(info, &rack->user_data, sizeof(uint64_t)); + return OK; + } + case 0xf14002: { + if (info_size < sizeof(Ngs2CustomModuleInfo)) return NGS2_ERROR_INVALID_OUT_SIZE; + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + const uint32_t module_idx = info_id >> 24; + if (!Ngs2RackIsCustom(rack->type) || + module_idx >= rack->option.custom_sampler.custom_rack_option.num_modules) { + return NGS2_ERROR_INVALID_RACK_MODULE_INDEX; + } + const auto& mod = rack->option.custom_sampler.custom_rack_option.module[module_idx]; + auto* out = static_cast<Ngs2CustomModuleInfo*>(info); + out->module_id = mod.module_id; + out->source_buffer_id = mod.source_buffer_id; + out->extra_buffer_id = mod.extra_buffer_id; + out->dest_buffer_id = mod.dest_buffer_id; + out->state_offset = mod.state_offset; + out->state_size = mod.state_size; + out->reserved = 0; + out->reserved2 = 0; + return OK; + } + default: return NGS2_ERROR_INVALID_RACK_QUERY_ID; + } +} + +int KYTY_SYSV_ABI Ngs2CustomRackGetModuleInfo(uintptr_t rack_handle, uint32_t module_index, + Ngs2CustomModuleInfo* info, size_t info_size) { + PRINT_NAME(); + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < sizeof(Ngs2CustomModuleInfo)) return NGS2_ERROR_INVALID_OUT_SIZE; + auto* rack = Ngs2FindRack(rack_handle); + if (rack == nullptr) return NGS2_ERROR_INVALID_RACK_HANDLE; + if (!Ngs2RackIsCustom(rack->type) || + module_index >= rack->option.custom_sampler.custom_rack_option.num_modules) { + return NGS2_ERROR_INVALID_RACK_MODULE_INDEX; + } + const auto& mod = rack->option.custom_sampler.custom_rack_option.module[module_index]; + info->module_id = mod.module_id; + info->source_buffer_id = mod.source_buffer_id; + info->extra_buffer_id = mod.extra_buffer_id; + info->dest_buffer_id = mod.dest_buffer_id; + info->state_offset = mod.state_offset; + info->state_size = mod.state_size; + info->reserved = 0; + info->reserved2 = 0; + return OK; +} + +int KYTY_SYSV_ABI Ngs2VoiceGetOwner(uintptr_t voice_handle, uintptr_t* owner_rack, + uint32_t* voice_index) { + PRINT_NAME(); + if (voice_handle == 0) return NGS2_ERROR_INVALID_VOICE_HANDLE; + if (owner_rack == nullptr || voice_index == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + + auto* voice = Ngs2VoiceFromHandle(voice_handle); + if (voice == nullptr || voice->rack == nullptr) return NGS2_ERROR_INVALID_VOICE_HANDLE; + + auto* rack = voice->rack; + *owner_rack = reinterpret_cast<uintptr_t>(rack); + const auto* voices_base = reinterpret_cast<const Ngs2VoiceInternal*>(rack + 1); + *voice_index = static_cast<uint32_t>(voice - voices_base); + return OK; +} + +int KYTY_SYSV_ABI Ngs2VoiceGetMatrixInfo(uintptr_t voice_handle, uint32_t matrix_id, + Ngs2VoiceMatrixInfo* info, size_t info_size) { + PRINT_NAME(); + if (info == nullptr) return NGS2_ERROR_INVALID_OUT_ADDRESS; + if (info_size < sizeof(Ngs2VoiceMatrixInfo)) return NGS2_ERROR_INVALID_OUT_SIZE; + if (voice_handle == 0) return NGS2_ERROR_INVALID_VOICE_HANDLE; + + auto* voice = Ngs2VoiceFromHandle(voice_handle); + if (voice == nullptr) return NGS2_ERROR_INVALID_VOICE_HANDLE; + + Common::LockGuard lock(voice->rack->ngs->mutex); + if (matrix_id >= voice->matrices.size()) return NGS2_ERROR_INVALID_PARAM_ID; + + const auto& m = voice->matrices[matrix_id]; + *info = {}; + if (!m.empty()) { + const auto count = std::min(m.size(), size_t(37 * 37)); + info->num_levels = static_cast<uint32_t>(count); + std::memcpy(info->levels, m.data(), count * sizeof(float)); + } + return OK; +} + +// DSP FFT & Waveform Frame Info / ParseWaveformUser + +// Size Chart FFT: length 8..12 -> samples 64, 128, 256, 512, 1024 +static constexpr uint32_t kFftSamples[5] = {64u, 128u, 256u, 512u, 1024u}; + +static bool Ngs2FftLengthValid(int length) { + return length >= 8 && length <= 12; +} + +// Radix-2 Cooley-Tukey in-place FFT on complex data (double). +// inverse=false -> forward transform (negative sign and exponent), +// inverse=true -> inverse transform (positive sign, unnormalized). +static void Ngs2Radix2Fft(std::vector<std::complex<double>>& data, bool inverse) { + const size_t n = data.size(); + // Bit-reversal permutation + for (size_t i = 1, j = 0; i < n; ++i) { + size_t bit = n >> 1u; + for (; j & bit; bit >>= 1u) { + j ^= bit; + } + j ^= bit; + if (i < j) { + std::swap(data[i], data[j]); + } + } + // Butterfly stages + const double sign = inverse ? 1.0 : -1.0; + for (size_t len = 2; len <= n; len <<= 1u) { + const double angle = sign * (2.0 * std::numbers::pi) / static_cast<double>(len); + const std::complex<double> step(std::cos(angle), std::sin(angle)); + for (size_t i = 0; i < n; i += len) { + std::complex<double> w(1.0, 0.0); + const size_t half = len >> 1u; + for (size_t j2 = 0; j2 < half; ++j2) { + const std::complex<double> u = data[i + j2]; + const std::complex<double> v = data[i + j2 + half] * w; + data[i + j2] = u + v; + data[i + j2 + half] = u - v; + w *= step; + } + } + } +} + +// Calculate the index in the “internal order” buffer used by sceNgs2FftProcess. +static size_t Ngs2FftInternalBinIndex(size_t q, size_t r, size_t j, size_t quarterBins) { + switch (r) { + case 0: return 4 * q + j; + case 1: return (q == 0 && j == 0) ? quarterBins : (2 * quarterBins - 4 * q - j); + case 2: return 2 * quarterBins + 4 * q + j; + default: return (q == 0 && j == 0) ? 3 * quarterBins : (4 * quarterBins - 4 * q - j); + } +} + +// Serialize bins in “internal order” (flags=2, mode bit2=1). +static void Ngs2FftPackInternal(const std::vector<std::pair<float, float>>& bins, size_t points, + std::vector<float>& out) { + const size_t quarterBins = points / 8u; + const size_t quadGroups = quarterBins / 4u; + out.assign(points, 0.0f); + for (size_t q = 0; q < quadGroups; ++q) { + for (size_t r = 0; r < 4; ++r) { + const size_t base = (4 * q + r) * 8u; + for (size_t j = 0; j < 4; ++j) { + const size_t bin = Ngs2FftInternalBinIndex(q, r, j, quarterBins); + out[base + j] = bins[bin].first; + out[base + 4 + j] = bins[bin].second; + } + } + } +} + +// Deserialize bins in “internal order.” +static void Ngs2FftUnpackInternal(const std::vector<float>& in, size_t points, + std::vector<std::pair<float, float>>& bins) { + const size_t quarterBins = points / 8u; + const size_t quadGroups = quarterBins / 4u; + bins.assign(points / 2u, {0.0f, 0.0f}); + for (size_t q = 0; q < quadGroups; ++q) { + for (size_t r = 0; r < 4; ++r) { + const size_t base = (4 * q + r) * 8u; + for (size_t j = 0; j < 4; ++j) { + const size_t bin = Ngs2FftInternalBinIndex(q, r, j, quarterBins); + bins[bin] = {in[base + j], in[base + 4 + j]}; + } + } + } +} + +// Serialize bins in “natural order” (flags=2, mode bit2=0). +static void Ngs2FftPackNatural(const std::vector<std::pair<float, float>>& bins, size_t points, + std::vector<float>& out) { + const size_t quarterBins = points / 8u; + const size_t blockStride = points / 2u; + out.assign(points * 2u, 0.0f); + for (size_t q = 0; q < 4; ++q) { + const size_t binStart = q * quarterBins; + const size_t blockBase = q * blockStride; + for (size_t r = 0; r < quarterBins; ++r) { + const size_t dstOffset = ((q & 1u) != 0 && r > 0) ? (quarterBins - r) : r; + const auto& bin = bins[binStart + r]; + out[blockBase + dstOffset * 2] = bin.first; + out[blockBase + dstOffset * 2 + 1] = bin.second; + } + } +} + +// ---- Public FFT APIs ---- + +int KYTY_SYSV_ABI Ngs2FftQuerySize(uint32_t length, uint32_t flags, uint64_t* out_size) { + PRINT_NAME(); + if (out_size == nullptr || length < 8 || length > 12) { + return -1; + } + uint32_t count = kFftSamples[length - 8]; + if ((flags & 2u) != 0) { + count /= 2u; + } + // Formula: count * 32 + 64 (each 32-byte entry = 2 float pairs × 2 channels × 4 bytes) + *out_size = static_cast<uint64_t>(count) * 32u + 64u; + return OK; +} + +int KYTY_SYSV_ABI Ngs2FftInit(void* work, size_t size, int length, uint32_t flags, + void** out_handle) { + PRINT_NAME(); + if (!Ngs2FftLengthValid(length) || work == nullptr || out_handle == nullptr) { + return -1; + } + uint32_t count = kFftSamples[static_cast<size_t>(length - 8)]; + if ((flags & 2u) != 0) { + count /= 2u; + } + const size_t required = static_cast<size_t>(count) * 32u + 64u; + if (size < required) { + return -1; + } + + auto* bytes = static_cast<uint8_t*>(work); + std::memset(bytes, 0, required); + + // 64-byte table alignment + const uintptr_t base = reinterpret_cast<uintptr_t>(work); + const uintptr_t tableAddr = (base + 0x57u) & ~uintptr_t {0x3fu}; + const size_t tableOff = static_cast<size_t>(tableAddr - base); + const uintptr_t secondAddr = + tableAddr + (((flags & 2u) != 0) ? static_cast<size_t>(count) * 16u : 0u); + + // Header with an offset of 0x00..0x17 + std::memcpy(bytes + 0x00, &tableAddr, sizeof(uint64_t)); + std::memcpy(bytes + 0x08, &secondAddr, sizeof(uint64_t)); + const int32_t len32 = static_cast<int32_t>(length); + std::memcpy(bytes + 0x10, &len32, sizeof(int32_t)); + std::memcpy(bytes + 0x14, &flags, sizeof(uint32_t)); + + // Pre-calculated sine/cosine table + if (tableOff < required) { + const size_t points = size_t {1} << length; + const size_t maxFloats = (required - tableOff) / sizeof(float); + for (size_t idx = 0; idx + 1 < maxFloats; idx += 2) { + const size_t k = idx / 2u; + const double angle = + (-2.0 * std::numbers::pi * static_cast<double>(k)) / static_cast<double>(points); + const float c = static_cast<float>(std::cos(angle)); + const float s = static_cast<float>(std::sin(angle)); + std::memcpy(bytes + tableOff + idx * sizeof(float), &c, sizeof(float)); + std::memcpy(bytes + tableOff + (idx + 1) * sizeof(float), &s, sizeof(float)); + } + } + + *out_handle = work; + return OK; +} + +int KYTY_SYSV_ABI Ngs2FftProcess(void* handle, const float* in, float* out, float* work_buf, + uintptr_t unused, uint32_t mode) { + (void)unused; + PRINT_NAME(); + if (handle == nullptr || in == nullptr || out == nullptr) { + return -1; + } + + const auto* hdr = static_cast<const uint8_t*>(handle); + int32_t length = 0; + uint32_t flags = 0; + std::memcpy(&length, hdr + 0x10, sizeof(length)); + std::memcpy(&flags, hdr + 0x14, sizeof(flags)); + if (!Ngs2FftLengthValid(length)) { + return -1; + } + + const size_t points = size_t {1} << length; + + // flags=0: “pass-through” mode — copies work_buf to out (or to in if work_buf==nullptr) + if ((flags & 2u) == 0) { + const size_t totalFloats = points * 2u; + if (work_buf != nullptr) { + std::memcpy(out, work_buf, totalFloats * sizeof(float)); + } else { + std::memcpy(out, in, totalFloats * sizeof(float)); + } + return OK; + } + + // flags=2: trigonometric table mode; supports direct and inverse FFT. + const float scale = 1.0f / static_cast<float>(points); + + if ((mode & 1u) != 0) { + // ---- Forward FFT: real -> compressed spectrum ---- + std::vector<float> input(points); + std::memcpy(input.data(), in, points * sizeof(float)); + + std::vector<std::complex<double>> spectrum(points); + for (size_t n2 = 0; n2 < points; ++n2) { + spectrum[n2] = {static_cast<double>(input[n2]), 0.0}; + } + Ngs2Radix2Fft(spectrum, false); + + const size_t half = points / 2u; + std::vector<std::pair<float, float>> bins(half); + bins[0] = {static_cast<float>(spectrum[0].real()), + static_cast<float>(spectrum[half].real())}; + for (size_t k = 1; k < half; ++k) { + bins[k] = {static_cast<float>(spectrum[k].real()), + static_cast<float>(spectrum[k].imag())}; + } + + std::vector<float> output; + if ((mode & 4u) != 0) { + // internal order + Ngs2FftPackInternal(bins, points, output); + if ((mode & 8u) != 0) { + for (float& v: output) { + v *= scale; + } + } + } else { + // natural order + Ngs2FftPackNatural(bins, points, output); + if ((mode & 8u) != 0) { + for (size_t i = 0; i < points; ++i) { + output[i] *= scale; + } + } + } + std::memcpy(out, output.data(), output.size() * sizeof(float)); + return OK; + } + + // ---- Inverse FFT: compressed spectrum -> real ---- + std::vector<float> input(points); + std::memcpy(input.data(), in, points * sizeof(float)); + + std::vector<std::pair<float, float>> bins; + if ((mode & 4u) != 0) { + Ngs2FftUnpackInternal(input, points, bins); + } else { + const size_t half = points / 2u; + bins.resize(half); + for (size_t k = 0; k < half; ++k) { + bins[k] = {input[k * 2], input[k * 2 + 1]}; + } + } + + const size_t half = points / 2u; + std::vector<std::complex<double>> spectrum(points); + spectrum[0] = {static_cast<double>(bins[0].first), 0.0}; + spectrum[half] = {static_cast<double>(bins[0].second), 0.0}; + for (size_t k = 1; k < half; ++k) { + const std::complex<double> v(static_cast<double>(bins[k].first), + static_cast<double>(bins[k].second)); + spectrum[k] = v; + spectrum[points - k] = std::conj(v); + } + Ngs2Radix2Fft(spectrum, true); + + std::vector<float> output(points); + for (size_t n2 = 0; n2 < points; ++n2) { + float v = static_cast<float>(spectrum[n2].real()); + if ((mode & 8u) != 0) { + v *= scale; + } + output[n2] = v; + } + std::memcpy(out, output.data(), points * sizeof(float)); + return OK; +} + +// Ngs2GetWaveformFrameInfo Retrieves frame size, num_frame_samples, units_per_frame, +// and num_delay_samples from the waveform format (PCM or ATRAC9). + +int KYTY_SYSV_ABI Ngs2GetWaveformFrameInfo(const Ngs2WaveformFormat* format, + uint32_t* out_frame_size, + uint32_t* out_num_frame_samples, + uint32_t* out_units_per_frame, + uint32_t* out_num_delay_samples) { + PRINT_NAME(); + + // All output pointers must be valid (AnyPS5: SCE_NGS2_ERROR_INVALID_OUT_ADDRESS) + if (out_frame_size == nullptr || out_num_frame_samples == nullptr || + out_units_per_frame == nullptr || out_num_delay_samples == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + // If the format itself is null or invalid + if (format == nullptr || format->num_channels == 0 || format->num_channels > 8 || + format->sample_rate == 0 || format->sample_rate > 192000) { + return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + } + + uint32_t frameSize = 0; + uint32_t frameSamples = 0; + uint32_t unitsPerFrame = 0; + uint32_t delaySamples = 0; + + if (format->waveform_type == NGS2_WAVEFORM_TYPE_ATRAC9) { + // ATRAC9: Extracting information from the codec + std::array<uint8_t, ATRAC9_CONFIG_DATA_SIZE> config { + static_cast<uint8_t>(format->config_data >> 24u), + static_cast<uint8_t>(format->config_data >> 16u), + static_cast<uint8_t>(format->config_data >> 8u), + static_cast<uint8_t>(format->config_data)}; + Atrac9CodecInfo codec {}; + if (!Ngs2GetAtrac9CodecInfo(config, codec)) { + return NGS2_ERROR_INVALID_WAVEFORM_FORMAT; + } + frameSize = static_cast<uint32_t>(codec.superframeSize); + frameSamples = static_cast<uint32_t>(static_cast<uint64_t>(codec.frameSamples) * + codec.framesInSuperframe); + unitsPerFrame = static_cast<uint32_t>(codec.framesInSuperframe); + delaySamples = static_cast<uint32_t>(codec.frameSamples); + } else if (format->waveform_type == SCE_NGS2_WAVEFORM_TYPE_VAG) { + frameSize = format->num_channels * 16u; + frameSamples = 28; + unitsPerFrame = 1; + delaySamples = 0; + } else { + // PCM (all linear types): frame = one sample for all channels + uint32_t bytesPerSample = 0; + switch (format->waveform_type) { + case 0x11u: bytesPerSample = 1; break; // 8-bit PCM + case 0x12u: bytesPerSample = 2; break; // 16-bit PCM (I16L) + case 0x14u: bytesPerSample = 3; break; // 24-bit PCM + case 0x16u: bytesPerSample = 4; break; // 32-bit PCM int + case 0x18u: bytesPerSample = 4; break; // 32-bit float + case 0x1au: bytesPerSample = 8; break; // 64-bit double + default: return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } + frameSize = format->num_channels * bytesPerSample; + frameSamples = 1; + unitsPerFrame = 1; + delaySamples = 0; + } + + *out_frame_size = frameSize; + *out_num_frame_samples = frameSamples; + *out_units_per_frame = unitsPerFrame; + *out_num_delay_samples = delaySamples; + return OK; +} + +// Ngs2ParseWaveformUser Calls a handler (PS5 callback) to read RIFF/WAVE data +// and extract Ngs2WaveformInfo (delegates to Ngs2ParseWaveformData). +// Callback signature: int32_t handler(uintptr_t user_data, uint32_t offset, void* buf, size_t size) + +// Type for the reading callback +using Ngs2ParseReadHandler = int32_t(KYTY_SYSV_ABI*)(uintptr_t user_data, uint32_t offset, + void* data, size_t size); + +int KYTY_SYSV_ABI Ngs2ParseWaveformUser(uintptr_t handler, uintptr_t user_data, + Ngs2WaveformInfo* out_info) { + PRINT_NAME(); + + if (out_info == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + if (handler == 0) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; // Null handler = invalid handle + } + + const auto read = reinterpret_cast<Ngs2ParseReadHandler>(handler); + + // Read the first bytes of the header + uint8_t header[48] = {}; + if (read(user_data, 0, header, 12) < 0) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + if (std::memcmp(header, "VAGp", 4) == 0) { + if (read(user_data, 12, header + 12, 36) < 0) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + const uint32_t vag_size = (static_cast<uint32_t>(header[0x0c]) << 24u) | + (static_cast<uint32_t>(header[0x0d]) << 16u) | + (static_cast<uint32_t>(header[0x0e]) << 8u) | + static_cast<uint32_t>(header[0x0f]); + constexpr uint64_t kMaxWaveformBytes = 256ull * 1024 * 1024; + if (vag_size > kMaxWaveformBytes) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + const size_t total = 48 + vag_size; + std::vector<uint8_t> bytes(total); + std::memcpy(bytes.data(), header, 48); + if (vag_size > 0 && read(user_data, 48, bytes.data() + 48, vag_size) < 0) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + return Ngs2ParseWaveformData(bytes.data(), total, out_info); + } + if (!Ngs2FourCcEquals(header, "RIFF") || !Ngs2FourCcEquals(header + 8, "WAVE")) { + return NGS2_ERROR_UNKNOWN_WAVEFORM_FORMAT; + } + + const uint32_t riff_size = Ngs2ReadLe32(header + 4); + const uint64_t riff_end = 8ull + riff_size; + constexpr uint64_t kMaxWaveformBytes = 256ull * 1024 * 1024; // 256 MiB + if (riff_end < 12 || riff_end > kMaxWaveformBytes) { + return NGS2_ERROR_INVALID_WAVEFORM_DATA; + } + + // Read the entire RIFF file into a local buffer + const size_t total = static_cast<size_t>(riff_end); + std::vector<uint8_t> bytes(total); + if (read(user_data, 0, bytes.data(), total) < 0) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + + // Delegate to the existing RIFF parser + return Ngs2ParseWaveformData(bytes.data(), total, out_info); +} + +// Stream API & Scheduler / Modules +static inline bool IsValidPointer(const void* ptr, size_t size = 1) { + if (ptr == nullptr) return false; + const uintptr_t addr = reinterpret_cast<uintptr_t>(ptr); + if (addr < 0x10000) return false; + if (addr + size < addr) return false; + return true; +} + +static inline bool ReadGuestBytes(void* local, const void* guest, size_t bytes) { + if (bytes == 0) return true; + if (!IsValidPointer(guest, bytes) || local == nullptr) return false; + std::memcpy(local, guest, bytes); + return true; +} + +static inline bool WriteGuestBytes(void* guest, const void* local, size_t bytes) { + if (bytes == 0) return true; + if (!IsValidPointer(guest, bytes) || local == nullptr) return false; + std::memcpy(guest, local, bytes); + return true; +} + +template <typename T> +static inline bool ReadGuest(const T* guest, T& local) { + return ReadGuestBytes(&local, guest, sizeof(local)); +} + +template <typename T> +static inline bool WriteGuest(T* guest, const T& local) { + return WriteGuestBytes(guest, &local, sizeof(local)); +} + +static int CheckStreamOption(const void* option, Ngs2StreamOption& checked) { + if (option == nullptr) { + checked = {}; + checked.size = sizeof(Ngs2StreamOption); + checked.num_blocks = 4; + checked.buffer_size_1 = 0x100; + checked.buffer_size_2 = 0x10; + checked.buffer_size_3 = 0x10000; + checked.default_param = 0.5f; + return 0; + } + Ngs2StreamOption opt {}; + if (!ReadGuest(static_cast<const Ngs2StreamOption*>(option), opt)) { + return SCE_NGS2_ERROR_INVALID_OPTION_SIZE; + } + if (opt.num_blocks < 1 || opt.num_blocks > 32) { + return SCE_NGS2_ERROR_INVALID_NUM_BLOCKS; + } + if (opt.buffer_size_3 == 0) { + return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_3_ZERO; + } + if (opt.buffer_size_1 == 0) { + return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_1_ZERO; + } + if (opt.buffer_size_2 == 0) { + return SCE_NGS2_ERROR_STREAM_BUFFER_SIZE_2_ZERO; + } + if (opt.size != sizeof(Ngs2StreamOption)) { + return SCE_NGS2_ERROR_INVALID_OPTION_SIZE; + } + checked = opt; + return 0; +} + +static uint64_t ComputeStreamBufferSize(const Ngs2StreamOption& opt) { + auto align8 = [](size_t val) -> size_t { return (val + 7u) & ~size_t {7u}; }; + const size_t guard = (opt.flags & 0x80000000u) ? 16u : 0u; + const size_t n = opt.num_blocks; + const size_t total = align8(0x368 + guard) + align8(0x28 * n + guard) + + align8(0x28 * n + guard) + align8(opt.buffer_size_3 + guard) + + align8(opt.buffer_size_2 + guard) + align8(opt.buffer_size_1 + guard) + + align8(opt.buffer_size_1 + guard) + 8; + return static_cast<uint64_t>(total); +} + +struct Ngs2StreamInternal { + uintptr_t handle = 0; + Ngs2Internal* system = nullptr; + Ngs2StreamOption option {}; + Ngs2ContextBufferInfo buffer_info {}; + Ngs2BufferAllocator allocator {}; + bool has_allocator = false; + std::vector<uint8_t> managed_buffer; + Common::Mutex mutex; +}; + +static Common::Mutex g_ngs2_streams_mutex; +static std::vector<std::unique_ptr<Ngs2StreamInternal>> g_ngs2_streams; + +static Ngs2StreamInternal* Ngs2FindStream(uintptr_t handle) { + if (handle == 0) return nullptr; + Common::LockGuard lock(g_ngs2_streams_mutex); + for (auto& s: g_ngs2_streams) { + if (s && s->handle == handle) { + return s.get(); + } + } + return nullptr; +} + +int KYTY_SYSV_ABI Ngs2StreamResetOption(void* option) { + PRINT_NAME(); + if (option == nullptr) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + Ngs2StreamOption opt {}; + opt.size = sizeof(Ngs2StreamOption); + std::memset(opt.name, 0, sizeof(opt.name)); + opt.flags = 0; + opt.num_blocks = 4; + opt.buffer_size_1 = 0x100; + opt.reserved1 = 0; + opt.buffer_size_2 = 0x10; + opt.reserved2 = 0; + opt.buffer_size_3 = 0x10000; + opt.reserved3 = 0; + opt.default_param = 0.5f; + opt.reserved4 = 0; + std::memset(opt.reserved_tail, 0, sizeof(opt.reserved_tail)); + if (!WriteGuest(static_cast<Ngs2StreamOption*>(option), opt)) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2StreamQueryBufferSize(const void* option, void* buffer_info) { + PRINT_NAME(); + if (buffer_info == nullptr || !IsValidPointer(buffer_info, sizeof(Ngs2ContextBufferInfo))) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + const Ngs2ContextBufferInfo cleared {}; + if (!WriteGuestBytes(buffer_info, &cleared, offsetof(Ngs2ContextBufferInfo, user_data))) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + Ngs2StreamOption checked {}; + const int error = CheckStreamOption(option, checked); + if (error != 0) { + return error; + } + const uint64_t size = ComputeStreamBufferSize(checked); + if (!WriteGuestBytes(static_cast<uint8_t*>(buffer_info) + + offsetof(Ngs2ContextBufferInfo, host_buffer_size), + &size, sizeof(size))) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2StreamCreate(uintptr_t system_handle, const void* option, + const void* buffer_info, uintptr_t* handle) { + PRINT_NAME(); + if (buffer_info == nullptr) { + return SCE_NGS2_ERROR_INVALID_BUFFER_INFO; + } + Ngs2ContextBufferInfo localBufferInfo {}; + if (!ReadGuest(static_cast<const Ngs2ContextBufferInfo*>(buffer_info), localBufferInfo) || + localBufferInfo.host_buffer == nullptr) { + return SCE_NGS2_ERROR_INVALID_BUFFER_INFO; + } + if (handle == nullptr || !IsValidPointer(handle, sizeof(uintptr_t))) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + Ngs2StreamOption checked {}; + const int optError = CheckStreamOption(option, checked); + if (optError != 0) { + return optError; + } + auto* system = Ngs2FindRegisteredSystem(system_handle); + if (system == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + + auto stream = std::make_unique<Ngs2StreamInternal>(); + stream->system = system; + stream->option = checked; + stream->buffer_info = localBufferInfo; + stream->handle = reinterpret_cast<uintptr_t>(stream.get()); + + *handle = stream->handle; + { + Common::LockGuard lock(g_ngs2_streams_mutex); + g_ngs2_streams.push_back(std::move(stream)); + } + return OK; +} + +int KYTY_SYSV_ABI Ngs2StreamCreateWithAllocator(uintptr_t system_handle, const void* option, + const void* allocator, uintptr_t* handle) { + PRINT_NAME(); + if (allocator == nullptr) { + return SCE_NGS2_ERROR_INVALID_BUFFER_ALLOCATOR; + } + Ngs2BufferAllocator localAllocator {}; + if (!ReadGuest(static_cast<const Ngs2BufferAllocator*>(allocator), localAllocator) || + localAllocator.alloc_handler == nullptr) { + return SCE_NGS2_ERROR_INVALID_BUFFER_ALLOCATOR; + } + if (handle == nullptr || !IsValidPointer(handle, sizeof(uintptr_t))) { + return NGS2_ERROR_INVALID_OUT_ADDRESS; + } + Ngs2StreamOption checked {}; + const int optError = CheckStreamOption(option, checked); + if (optError != 0) { + return optError; + } + auto* system = Ngs2FindRegisteredSystem(system_handle); + if (system == nullptr) { + return NGS2_ERROR_INVALID_SYSTEM_HANDLE; + } + + auto stream = std::make_unique<Ngs2StreamInternal>(); + stream->system = system; + stream->option = checked; + stream->allocator = localAllocator; + stream->has_allocator = true; + + 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); + if (alloc_res < 0 || stream->buffer_info.host_buffer == nullptr) { + if (stream->buffer_info.host_buffer != nullptr && localAllocator.free_handler != nullptr) { + localAllocator.free_handler(&stream->buffer_info); + } + stream->has_allocator = false; + stream->managed_buffer.resize(req_size, 0); + stream->buffer_info.host_buffer = stream->managed_buffer.data(); + stream->buffer_info.user_data = localAllocator.user_data; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** **Set the fallback buffer size from the managed allocation.** If the allocation callback clears `host_buffer_size` and returns no buffer, the fallback creates `req_size` bytes but keeps the callback's zero size. `Ngs2StreamDestroy` then reports that zero size to callers that request buffer information. Rebuild the fallback metadata from `managed_buffer` after callback cleanup. Preserve the callback's metadata when caller allocation succeeds. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:26ee6f793020bd4073cda4fd --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ 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();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · edited 2026-11-21 19:46 UTC

Minor · Functional Correctness · Quick win

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](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4653931163) · edited 2026-11-21 19:46 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **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. <!-- fingerprinting:phantom:medusa:wombat62 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8d259821007bcb6f3324e671 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1de75dc
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:15 UTC · original · reviewed

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (4)

Major · Validate the stream option size before reading the full option. · ngs2.cpp:5397

src/libs/ngs2.cpp:5397
Major · Stability & Availability · Quick win

Validate the stream option size before reading the full option.

CheckStreamOption copies all 0x88 bytes before checking the size field. A caller that supplies only a readable size field for an incompatible layout can fault instead of receiving SCE_NGS2_ERROR_INVALID_OPTION_SIZE. Even with readable padding, zeroed fields can cause SCE_NGS2_ERROR_INVALID_NUM_BLOCKS to take precedence. Read and validate the size field first. Then read and validate the full record for a matching size.

Minor · Reject file offsets that do not fit in Ngs2WaveformInfo::data_offset. · ngs2.cpp:3402

src/libs/ngs2.cpp:3402
Minor · Data Integrity & Integration · Quick win

Reject file offsets that do not fit in Ngs2WaveformInfo::data_offset.

If a WAV starts at 0xfffffff0 and its payload is 44 bytes into the container, the parse returns OK with data_offset == 0x1c. Its first block reports 0x10000001c for the same payload. A caller that uses info.data_offset reads the wrong part of the file. Compute the absolute offset in 64 bits and return an error if it does not fit the ABI field.

Minor · Interpolate toward the first playable sample of the staged frame. · ngs2.cpp:2588

src/libs/ngs2.cpp:2588
Minor · Functional Correctness · Quick win

Interpolate toward the first playable sample of the staged frame.

When a staged VAG frame skips four samples, playback starts at next_frame_cursor == 4, but interpolation still reads sample zero. At 24 kHz on a 48 kHz system, a transition from 0 to 0.5 can output 0 instead of 0.25 at the boundary. Use next_frame_cursor * voice.channels to select the interpolation endpoint. Keep the existing behavior for a staged frame with no skip.

Minor · Synchronize reads of lock_depth and lock_owner in Ngs2RackUnlock. · ngs2.cpp:2265

src/libs/ngs2.cpp:2265
Minor · Stability & Availability · Quick win

Synchronize reads of lock_depth and lock_owner in Ngs2RackUnlock.

Ngs2RackUnlock reads lock_depth and lock_owner at line 2265 without holding rack->ngs->mutex. Ngs2RackLock writes both fields while it holds that mutex. When a thread calls unlock while another thread owns the rack lock, these accesses race, which is undefined behavior in C++. The same unsynchronized read appears in Ngs2RackGetInfo at line 4801.

Make these fields safe for concurrent access, for example with atomic types, and keep the wrong-thread rejection behavior. Apply the same access rule to every read of these fields outside the owner's lock scope.

Nitpick comments: 2

tests/Ngs2SamplerTests.cpp: 2

3956-3959: Trivial · Maintainability & Code Quality · Quick win

Test allocator failure after a buffer is supplied.

The helper always returns a null buffer when g_streamAllocResult is negative. That leaves the new cleanup path untested. Let g_streamAllocGaveBuffer control the pointer independently of the result. Add a case that returns an error with a non-null pointer, then assert one free call during creation and no additional free call when the fallback stream is destroyed.


3872-3873: Trivial · Maintainability & Code Quality · Quick win

Exercise the custom submixer relayout command.

This test uses 0x20000000, which clears the filter through ResetSetupState. The test would still pass if the reset were removed from the changed 0x40020000 branch. Use 0x40020000 with matching input and output channel counts for the second setup. Keep the assertions that the filter is cleared and audio passes through.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 6776f8dff3 and bb303ad063.

Files selected for processing: 2

  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp

Included 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](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6006872130) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 5** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (4)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Validate the stream option size before reading the full option. · <code>ngs2.cpp:5397</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/ngs2.cpp:5397` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** > > **Validate the stream option size before reading the full option.** > > `CheckStreamOption` copies all `0x88` bytes before checking the size field. A caller that supplies only a readable size field for an incompatible layout can fault instead of receiving `SCE_NGS2_ERROR_INVALID_OPTION_SIZE`. Even with readable padding, zeroed fields can cause `SCE_NGS2_ERROR_INVALID_NUM_BLOCKS` to take precedence. Read and validate the size field first. Then read and validate the full record for a matching size. > > <!-- cr-comment:v1:99c9022613565d835892bbad --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Reject file offsets that do not fit in <code>Ngs2WaveformInfo::data_offset</code>. · <code>ngs2.cpp:3402</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/ngs2.cpp:3402` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Data Integrity & Integration** · **Quick win** > > **Reject file offsets that do not fit in `Ngs2WaveformInfo::data_offset`.** > > If a WAV starts at `0xfffffff0` and its payload is 44 bytes into the container, the parse returns `OK` with `data_offset == 0x1c`. Its first block reports `0x10000001c` for the same payload. A caller that uses `info.data_offset` reads the wrong part of the file. Compute the absolute offset in 64 bits and return an error if it does not fit the ABI field. > > <!-- cr-comment:v1:bea1c8a79c628290c52f07b6 --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Interpolate toward the first playable sample of the staged frame. · <code>ngs2.cpp:2588</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/ngs2.cpp:2588` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Interpolate toward the first playable sample of the staged frame.** > > When a staged VAG frame skips four samples, playback starts at `next_frame_cursor == 4`, but interpolation still reads sample zero. At 24 kHz on a 48 kHz system, a transition from `0` to `0.5` can output `0` instead of `0.25` at the boundary. Use `next_frame_cursor * voice.channels` to select the interpolation endpoint. Keep the existing behavior for a staged frame with no skip. > > <!-- cr-comment:v1:b9312c32879da6fe21cd72db --> > > </dd> > </dl> > </blockquote></details> > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Synchronize reads of <code>lock_depth</code> and <code>lock_owner</code> in <code>Ngs2RackUnlock</code>. · <code>ngs2.cpp:2265</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/ngs2.cpp:2265` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** > > **Synchronize reads of `lock_depth` and `lock_owner` in `Ngs2RackUnlock`.** > > `Ngs2RackUnlock` reads `lock_depth` and `lock_owner` at line 2265 without holding `rack->ngs->mutex`. `Ngs2RackLock` writes both fields while it holds that mutex. When a thread calls unlock while another thread owns the rack lock, these accesses race, which is undefined behavior in C++. The same unsynchronized read appears in `Ngs2RackGetInfo` at line 4801. > > Make these fields safe for concurrent access, for example with atomic types, and keep the wrong-thread rejection behavior. Apply the same access rule to every read of these fields outside the owner's lock scope. > > <!-- cr-comment:v1:ed6b012ec1653a054ef9a30a --> > > </dd> > </dl> > </blockquote></details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 2</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/Ngs2SamplerTests.cpp: 2</summary><blockquote> <dl> <dd> <br> `3956-3959`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Test allocator failure after a buffer is supplied.** The helper always returns a null buffer when `g_streamAllocResult` is negative. That leaves the new cleanup path untested. Let `g_streamAllocGaveBuffer` control the pointer independently of the result. Add a case that returns an error with a non-null pointer, then assert one free call during creation and no additional free call when the fallback stream is destroyed. <!-- cr-comment:v1:393a8f143cb26eb46dd47659 --> --- `3872-3873`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Maintainability & Code Quality** · **Quick win** **Exercise the custom submixer relayout command.** This test uses `0x20000000`, which clears the filter through `ResetSetupState`. The test would still pass if the reset were removed from the changed `0x40020000` branch. Use `0x40020000` with matching input and output channel counts for the second setup. Keep the assertions that the filter is cleared and audio passes through. <!-- cr-comment:v1:45b8bcf6ee902c96b476892a --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `e71cd156-78e0-45a3-bdda-6c9db762c512` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 6776f8dff3f0baf53832918d97b957acc43a66f4 and bb303ad063402d4cc97e238b7d63ca1983a34264. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/libs/ngs2.cpp` * `tests/Ngs2SamplerTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=d3ebe552-be44-425c-a32d-2ec0ce27a6d1 attempt=a72e6075-7a7f-4d1e-b5df-8bd3e30c74ab batch=1/1 -->
@ -751,0 +1036,4 @@
drain_remaining -= 64;
} else {
drain_remaining = 0;
inputCount = outputCount = inputTime = outputTime = 0;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original

Major · Stability & Availability · Quick win

Reset the complete pitch-shift pipeline after draining.

Drain completion clears the counts but leaves started true. With zero cents (ratio=1), the next clip adds 64 samples and immediately enters Stretch, which consumes 960 samples. inputCount underflows. The next block writes outside input.

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.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4654069977) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Reset the complete pitch-shift pipeline after draining.** Drain completion clears the counts but leaves `started` true. With zero cents (`ratio=1`), the next clip adds 64 samples and immediately enters `Stretch`, which consumes 960 samples. `inputCount` underflows. The next block writes outside `input`. 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. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:13b448c38b17e7fbd2b76aae --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -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) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original

Major · Functional Correctness · Heavy lift

Allow custom sampler pitch-shift tails to render after source completion.

The Empty transition at lines 2722-2727 ignores pitch-shift pending state. A finite custom sampler clip can reach Empty while its pitch-shift channels still hold delayed audio. The render that sets Empty still 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 the Playing block 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.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4654069979) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** **Allow custom sampler pitch-shift tails to render after source completion.** The `Empty` transition at lines 2722-2727 ignores pitch-shift pending state. A finite custom sampler clip can reach `Empty` while its pitch-shift channels still hold delayed audio. The render that sets `Empty` still 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 the `Playing` block 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. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:024097cc4e7f787145aea50b --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -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);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original

Minor · Functional Correctness · Heavy lift

Pass the upstream pitch-shift output to the next module after source input ends.

had_samples is 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 receives nullptr. 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 nullptr only when no upstream audio remains. A module that holds only its own buffered tail must still drain with nullptr.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 17:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4654069982) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Heavy lift** **Pass the upstream pitch-shift output to the next module after source input ends.** `had_samples` is 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 receives `nullptr`. 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 `nullptr` only when no upstream audio remains. A module that holds only its own buffered tail must still drain with `nullptr`. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8f5809387dd06206d3b1e54d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 17:37 UTC · original · reviewed

Actionable comments posted: 3

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between bb303ad063 and 77bbb3ec18.

Files selected for processing: 2

  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp

Included 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:37 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6007011519) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 3** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `8d53f017-3c55-418c-a4a6-21a5515c0858` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between bb303ad063402d4cc97e238b7d63ca1983a34264 and 77bbb3ec18db3e4605869928fed46bacec2f781d. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/libs/ngs2.cpp` * `tests/Ngs2SamplerTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=2f56b963-005e-49cb-9640-a75f0167d2f2 attempt=f2aeb317-d19e-47f1-b7d5-b4cf114df331 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 18:08 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Keep custom filters running while filter history remains. · ngs2.cpp:2846

src/libs/ngs2.cpp:2846
Minor · Functional Correctness · Quick win

Keep custom filters running while filter history remains.

After an impulse ends, a custom submixer can have nonzero filter history but no input or pending pitch output. This guard skips the module loop. The next render returns silence and leaves the filter history unchanged.

Include custom-filter history in pending-work detection. Process zero input until the history clears. Preserve the pause and stop guards.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 77bbb3ec18 and 4683bcfdab.

Files selected for processing: 2

  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 18:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6007188637) · **reviewed** <!-- coderabbit-ai-generated:v1 --> > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor</strong> · Keep custom filters running while filter history remains. · <code>ngs2.cpp:2846</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/libs/ngs2.cpp:2846` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** > > **Keep custom filters running while filter history remains.** > > After an impulse ends, a custom submixer can have nonzero filter history but no input or pending pitch output. This guard skips the module loop. The next render returns silence and leaves the filter history unchanged. > > Include custom-filter history in pending-work detection. Process zero input until the history clears. Preserve the pause and stop guards. > > <!-- cr-comment:v1:78bd6884e0ba76213be68162 --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `e43e0b99-ebbb-4751-9c77-b587045bb8fd` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 77bbb3ec18db3e4605869928fed46bacec2f781d and 4683bcfdab2620d7dd7d835edba5980268b9fe7b. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/libs/ngs2.cpp` * `tests/Ngs2SamplerTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=50bbb3c0-6ea7-452d-8bd0-c1d934545a2e attempt=b5ba499f-6fd7-44c4-8101-78ba25ea21c5 batch=1/1 -->
Author
Owner

@⁠Ekt0re on GitHub · 2026-11-21 19:46 UTC · original

@⁠coderabbitai review

**@⁠Ekt0re** on GitHub · 2026-11-21 19:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#issuecomment-7068264373) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 19:46 UTC · original · edited 2026-11-21 19:54 UTC

Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 19:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#issuecomment-7068265613) · edited 2026-11-21 19:54 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:483a6869400e28fdd4eaa60add30add0d36a7b9607b8cf6a4b8db3644bfe808a --> <details> <summary>Action performed</summary> <dl> <dd> <br> Review finished. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </dd> </dl> </details>
Author
Owner

@⁠Ekt0re on GitHub · 2026-11-21 19:47 UTC · original

@⁠coderabbitai resume

**@⁠Ekt0re** on GitHub · 2026-11-21 19:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#issuecomment-7068276652) @⁠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);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original

Major · Stability & Availability · Quick win

Destroying a rack that the calling thread still holds leaves the system mutex locked.

Ngs2RackDestroy acquires ngs->mutex without checking rack->lock_depth. When the same thread already holds the rack lock, the destroy call adds and releases one acquisition, then removes the rack. Ngs2RackUnlock cannot find the rack afterward, so it returns before ngs->mutex.Unlock(). The original acquisition remains held. Other threads that call Ngs2RackLock or Ngs2RackUnlock on the same system then block on ngs->mutex and 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 Ngs2RackDestroy returns. Add a test that destroys a locked rack and checks that another rack on the same system can still be locked.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 19:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4654680344) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Destroying a rack that the calling thread still holds leaves the system mutex locked.** `Ngs2RackDestroy` acquires `ngs->mutex` without checking `rack->lock_depth`. When the same thread already holds the rack lock, the destroy call adds and releases one acquisition, then removes the rack. `Ngs2RackUnlock` cannot find the rack afterward, so it returns before `ngs->mutex.Unlock()`. The original acquisition remains held. Other threads that call `Ngs2RackLock` or `Ngs2RackUnlock` on the same system then block on `ngs->mutex` and 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 `Ngs2RackDestroy` returns. Add a test that destroys a locked rack and checks that another rack on the same system can still be locked. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:58935708f34ed7812d7de212 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -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);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original

Minor · Functional Correctness · Quick win

Create the overflow fixture before parsing it.

std::ofstream adds out to these flags. The resulting in|out|binary mode 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_DATA for 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](https://github.com/KytyPS5/KytyPS5/pull/2493#discussion_r4654680346) <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Create the overflow fixture before parsing it.** `std::ofstream` adds `out` to these flags. The resulting `in|out|binary` mode requires an existing file, so opening this new path fails. ([eel.is](https://eel.is/c%2B%2Bdraft/ofstream.cons)) The unchecked write creates no fixture. The parser then returns `NGS2_ERROR_INVALID_WAVEFORM_DATA` for 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. <!-- fingerprinting:phantom:medusa:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:39c464921150375c63add03f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original · reviewed

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4683bcfdab and 1de75dc05a.

Files selected for processing: 2

  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp

Included 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](https://github.com/KytyPS5/KytyPS5/pull/2493#pullrequestreview-6007789011) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 2** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/39936ffa39237997080f8d169370667ca63d12fa/.coderabbit.yaml>) - **Commit**: [39936ff](<https://github.com/KytyPS5/KytyPS5/commit/39936ffa39237997080f8d169370667ca63d12fa>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `671d1c6f-c5ab-456c-b4a5-18d154db27de` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 4683bcfdab2620d7dd7d835edba5980268b9fe7b and 1de75dc05a8bc270c20795c9f283e3ac1016165c. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/libs/ngs2.cpp` * `tests/Ngs2SamplerTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=5627b919-fd76-4dd8-a0f3-cd6be6168ed5 attempt=f0c450a5-36dd-41f8-a2cf-170f1ab16988 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-21 19:54 UTC · original

Action performed

Reviews resumed. No new commits to review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-21 19:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2493#issuecomment-7068366469) <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: 27a7d492-a4a6-46f9-b10e-2317129af264 --> <details> <summary>Action performed</summary> <dl> <dd> <br> Reviews resumed. No new commits to review. </dd> </dl> </details>
This pull request has changes conflicting with the target branch.
  • src/libs/ngs2.cpp
  • tests/Ngs2SamplerTests.cpp
  • tests/VdecswTests.cpp
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.
git fetch -u origin '+refs/pull/2493/head:github-bot/gh-2493'
git switch 'github-bot/gh-2493'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2493'
git switch 'github-bot/gh-2493'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2493'
git switch 'github-bot/gh-2493'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2493'
git switch 'main'
git merge --squash 'github-bot/gh-2493'
git switch 'main'
git merge --ff-only 'github-bot/gh-2493'
git switch 'main'
git merge 'github-bot/gh-2493'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.