Skip to content

hle, docs: add XTP_APU_DUMP and Windows Opus MFT parity test - #48

Merged
fogydes merged 3 commits into
MiamiGame:mainfrom
PrivacyOnion:hle/opus-mft-check
Nov 25, 2026
Merged

fogydes merged 3 commits into
MiamiGame:mainfrom
PrivacyOnion:hle/opus-mft-check

Conversation

@PrivacyOnion

@PrivacyOnion PrivacyOnion commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What and why

Add an optional Opus packet capture switch (XTP_APU_DUMP=<dir>) and a test-only parity check comparing opus-pure with the Windows Opus Media Foundation Transform (MFT).

The diagnostics-only capture writes up to 32 activated streams, with at most 256 packets per stream, outside the repository. Each stream creates or truncates its capture and writes the header once; recording only appends packets.

The reference test dynamically loads the system Media Foundation DLLs without new dependencies or windows features. It checks synthetic mono and stereo streams at 48 kHz, capture round-tripping, and a signal-to-noise ratio of at least 60 dB. An optional test checks real captures supplied through XTP_SAMPLE_OPUS=<dir>.

Size note: +947/-6, or 953 changed lines. Most of the change is the test-only Media Foundation wrapper, which uses raw COM vtables to avoid adding runtime dependencies or windows features.

Part of #9. Real-capture validation remains outstanding and will be run by the core team.

Depends on: none.

Area

  • crates/xtp-hle/src/modules/apu.rs: bounded diagnostics capture and capture-file helpers.
  • crates/xtp-hle/tests/opus_reference.rs: synthetic and optional real-capture parity tests.
  • README.md: capture configuration.

Tests

Contributor-reported Windows verification:

  • cargo test -p xtp-hle --test opus_reference --locked -- --nocapture
  • cargo test -p xtp-hle apu --locked
  • Default and all-feature Clippy for xtp-hle.
  • cargo xtask policy and cargo xtask conventions.
  • Synthetic mono/stereo parity passed against the Windows Opus MFT with SNR >=60 dB, including stale capture replacement and round-tripping.
  • The real-capture test visibly skipped because XTP_SAMPLE_OPUS was unset.

CI on head 991ef67f2062834209f97d3cc2c3dc47335c8d16 passed, including workspace tests and gpu-debug-layer.

Provenance

  • I wrote all of this change myself for XTP, or it only moves code already in XTP.
  • Some of it comes from elsewhere. Each source, its licence and the files concerned are listed here, and every licence is compatible with GPL-3.0-or-later:

Written for XTP using public Microsoft Learn documentation for Media Foundation (MFTEnumEx, MFAudioFormat_Opus, IMFTransform) and RFC 7845 (OpusHead). The contributor reports that neither they nor the AI assistant read xcl or AnyPS5 source code.

AI assistance: Antigravity (Gemini) assisted with the Windows Media Foundation Opus MFT wrapper, capture helper, and tests. The contributor reviewed and verified the changes locally. Codex subsequently reviewed the change and repaired this description's formatting and size note.

Checklist

  • No game data, keys, console SDK code or headers, and nothing that circumvents DRM (asset policy).
  • No code copied from xcl or AnyPS5.
  • I agree to license this contribution under GPL-3.0-or-later.
  • Title and every commit follow <area>: <summary>; one topic; the reason for exceeding 400 changed lines is above.
  • Docs updated where behaviour, commands or variables changed.

@github-actions github-actions Bot added area/hle touches crates/xtp-hle area/docs docs/, Markdown size/L 400 to 999 changed lines overlap another open PR changes the same files labels Nov 25, 2026
@github-actions

Copy link
Copy Markdown

Other open pull requests change the same files. Check that they do not do the same work, and agree with their authors on which lands first: the other one will then need a rebase.

Pull request Files changed by both
#26 README.md

This comment is kept up to date automatically and removed when the overlap ends.

@simnJS simnJS left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this, @PrivacyOnion. The MFT plumbing is careful work, and it's good to see the synthetic parity test actually run (and pass) on the CI runner.

A few things before merging:

  1. Captures from different runs get mixed (apu.rs ~152, 222-229): the counter restarts at 00 each run and append_capture_packet appends to an existing file, so a second run into the same folder concatenates unrelated streams (and the old header's channel count wins). Could StreamDump::open create/truncate the file and write the header, with record only appending?
  2. opus_reference.rs ~598-606: when Lock succeeds with cur_len < 4, the buffer is never unlocked.
  3. Optional hardening: MFT_ENUM_FLAG_SYNCMFT | LOCALMFT | SORTANDFILTER instead of ALL, a COMMAND_DRAIN at end of stream (and treat MF_E_TRANSFORM_STREAM_CHANGE explicitly), and LoadLibraryExA(..., LOAD_LIBRARY_SEARCH_SYSTEM32) for the system DLLs (also free both module handles on the early-return paths).
  4. Small one: in StreamDump::open, check the 32-stream cap before the repository walk, so the walk and its warning don't repeat on every activation.

Since the real-capture criterion in #9 hasn't been run on the title yet, could you change "Fixes: #9" to "Part of #9"? We'll run XTP_APU_DUMP → XTP_SAMPLE_OPUS on our side and close the issue once it passes.

(The red gpu-debug-layer comes from two xtp-gpu tests on main and isn't caused by this PR; a fix is in progress.)

@PrivacyOnion

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @simnJS! Addressed all five points in d136729:

  • Capture truncation per run (apu.rs): added create_capture_file and called it in StreamDump::open so each run creates/truncates <n>-s<stream>-<ch>ch.opuscap and writes the 8-byte XOPU header once, while record only appends packets (also covered by the synthetic capture round-trip test).
  • 32-stream cap check (apu.rs): moved the MAX_DUMP_STREAMS check before ensure_outside_repo so the repository walk and warning do not repeat after the cap is hit.
  • Buffer unlock (opus_reference.rs): always call Unlock whenever Lock succeeds, even when cur_len < 4.
  • MFT hardening (opus_reference.rs):
    • switched MFTEnumEx flags to MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_LOCALMFT | MFT_ENUM_FLAG_SORTANDFILTER;
    • added MFT_MESSAGE_COMMAND_DRAIN at end of stream and explicit MF_E_TRANSFORM_STREAM_CHANGE handling via select_output_type();
    • loaded mfplat.dll / ole32.dll via LoadLibraryExA(..., LOAD_LIBRARY_SEARCH_SYSTEM32) wrapped in an RAII DllGuard so both module handles are freed on every early-return path.
  • PR description: changed Fixes: #9 to Part of #9.

Verified locally with cargo test -p xtp-hle --test opus_reference --locked -- --nocapture, cargo test -p xtp-hle apu --locked, cargo clippy -p xtp-hle --all-targets (default & --all-features), cargo xtask policy, and cargo xtask conventions.

@simnJS simnJS left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the quick follow-up. Every point from the last review is addressed: StreamDump::open truncates and writes the header while record only appends (and the synthetic test covers a stale file); the buffer is unlocked whenever Lock succeeds; the enumeration flags, the drain at end of stream, MF_E_TRANSFORM_STREAM_CHANGE, System32-only loading and DllGuard are in; the stream cap comes before the repository walk; and the description says "Part of #9".

I checked the vtable slots, GUIDs and struct layouts against the public Media Foundation documentation and found no mismatch. The test downloads nothing and loads only System32 DLLs.

CI: the red gpu-debug-layer is two known xtp-gpu failures from main (missing_first_target_preserves_the_second_slot, rectangle_geometry_obeys_depth_bounds), fixed there since; I'm updating the branch from main for a clean run. The earlier conventions failure came from a description edit that lost its line breaks, so ## Provenance no longer started a line; the latest run passes.

Before merge, please restore the description's formatting: it is now one long line under the first heading, with a second Provenance section appended. The size note also says ~690 lines; the diff is +947/−6.

Optional:

  • StreamDump::record reopens the file for every packet while the connection lock is held; keeping the File in StreamDump would avoid that.
  • MFTEnumEx can also return a third-party Opus MFT; logging the chosen MFT's friendly name would show which decoder a comparison used.

Approving. Thanks for the careful work.

@fogydes fogydes left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review of PR #48: XTP_APU_DUMP and Windows Opus MFT parity test

Reviewed head d136729 (two commits), by reading gh pr diff 48 and
origin/main. Nothing was built or run, so every
statement about behaviour comes from reading code. CI on the PR: all green
except gpu-debug-layer, which the maintainer said is a main-branch problem
(it passes on #52).

Verdict: ready to approve, with four small follow-ups (none blocking)

The maintainer's change request is fully addressed. I found no correctness bug
that makes the dump unsafe or the parity test wrong. The weaknesses are test
strength (the synthetic stream is narrow) and a few cosmetic or hygiene items.

Maintainer's points

# Point Addressed? Where
1 Captures from runs get mixed: open should create/truncate and write the header; record only appends Yes apu.rs:235 create_capture_file(&path, channels) in StreamDump::open (File::create truncates, apu.rs:146); record (apu.rs:243) only appends. Test seeds a stale 2-channel capture and checks it is replaced (opus_reference.rs:~758)
2 Lock ok with cur_len < 4 never unlocked Yes opus_reference.rs:~645: unlock is outside the if cur_len >= 4
3a SYNCMFT|LOCALMFT|SORTANDFILTER instead of ALL Yes opus_reference.rs:~244 (constants 0x1, 0x10, 0x40 are the right values)
3b COMMAND_DRAIN at end of stream Yes (partly) drain() ~534, called once after the last packet (~700). The ProcessMessage result is ignored and NOTIFY_END_OF_STREAM is not sent first (finding 6)
3c Treat MF_E_TRANSFORM_STREAM_CHANGE explicitly Yes ~609: releases buffers, re-selects the output type, retries. Unbounded retry (finding 5)
3d LoadLibraryExA(..., LOAD_LIBRARY_SEARCH_SYSTEM32) and free both handles on early return Yes DllGuard ~164-190; both guards are fields of MfApi/locals in load(), so every return path frees them
4 Check the 32-stream cap before the repository walk Yes apu.rs:224 precedes ensure_outside_repo at apu.rs:227
5 Fixes: #9 becomes Part of #9 Yes PR body says "Part of #9" (the body text is mangled, see finding 9)

The areas you asked about

APU dump. Off by default: StreamDump::open returns None when
XTP_APU_DUMP is unset (apu.rs:222, before the counter is touched), and the
whole feature is #[cfg(feature = "diagnostics")], so it is absent from normal
builds. Never inside the repository: xtp_core::ensure_outside_repo runs
(apu.rs:227) before create_dir_all and any write, and on refusal logs a
warning and records nothing. That helper resolves relative paths against the
current directory, canonicalises the longest existing prefix, and also looks
for .xtp-root in every ancestor, so other clones are caught too. Size is
bounded: 32 streams x 256 packets x at most one Opus packet each (a few KB at
most), so under about 10 MB. Threading: The StreamDump lives in the stream slot,
and record is called from process(), which XApuEnqueueCommand runs with
the connection's Mutex<State> held. So there is no race, and the global
COUNT is atomic. The cost is blocking file I/O under that lock (finding 4).

Media Foundation use. I checked every hand-written constant and vtable slot
against the public headers, and found no error: GUID values, MF_VERSION
(0x20070), MFSTARTUP_FULL, the MFT_MESSAGE_* values, the two MF_E_*
HRESULTs, the IMFAttributes slots (GetGUID 10, SetUINT32 21, SetGUID 24,
SetBlob 26), IMFActivate::ActivateObject 33, IMFMediaBuffer Lock/Unlock/
SetCurrentLength 3/4/6, IMFSample ConvertToContiguousBuffer/AddBuffer 41/42,
and the IMFTransform slots 7, 14, 15, 16, 23, 24, 25. Teardown order is
correct: WindowsOpusMft::drop releases the transform, then MfApi::drop calls
MFShutdown, then the DllGuards call FreeLibrary. HRESULTs are checked on
every call except those listed in findings 2, 3 and 6. Output ownership handles
both MFT-provided and caller-provided samples, and releases the events
collection.

Parity test tolerance. MIN_SNR_DB = 60 over the whole stream, after
asserting both decoders produced exactly the same number of samples
(opus_reference.rs:~689-720). 60 dB is what the A1 task in
docs/analysis/hle.md asks for. Two float decoders of the same standard
normally agree to well over 80 dB, so 60 is lenient but meaningful, and the
sample-count equality assertion also makes a latency or pre-skip difference
fail loudly instead of being absorbed. Weaknesses are in finding 1.

Skips cleanly. opus_pure_matches_windows_mft_on_sample_captures returns
via xtp_testkit::skip("no-sample XTP_SAMPLE_OPUS") when the variable is unset,
prints the SKIPPED marker, and panics if the variable is set but the folder is
unreadable or holds no .opuscap file (matches the convention in
docs/analysis/tooling.md). The test file is #![cfg(windows)].
XTP_SAMPLE_OPUS is named in the test's doc comment, in the README row for
XTP_APU_DUMP, and in docs/analysis/hle.md A1; XTP_APU_DUMP has a README
row. XTP_SAMPLE_OPUS has no row of its own and no "how to run" line (finding
8). The synthetic test also skips (no-opus-mft) when the MFT is missing, and
XTP_REQUIRE=no-opus-mft turns that into a failure; CI does not set it, so a
Windows runner that lacks the MFT would pass silently (finding 7).

Findings, by severity

None is critical or high.

Medium

  1. The synthetic stream covers one narrow case, so a green CI run says less than it seems to.
    opus_reference.rs:~724-745 (synth_packets) encodes 10 packets of 20 ms
    of a pure 440 Hz (and 660 Hz) tone at Application::Audio. That exercises
    CELT 20 ms frames only, probably on a handful of bands. It never reaches
    SILK or hybrid mode, 2.5/5/10/40/60 ms frames, multi-frame packets, a
    transient, or packet-loss concealment. The aggregate SNR also lets a loud
    passage hide an error in a quiet one, and an all-silent capture passes
    (err == 0 returns infinity, ~672).
    Fix: parameterise synth_packets over frame size (480, 960, 1920, 2880 in
    48 kHz samples) and signal (add a noise burst and a decaying chirp, plus
    Application::Voip) and run all combinations; compute the SNR per packet
    as well and assert the worst packet, not only the total.

Low

  1. COM is initialised on every load and never uninitialised.
    opus_reference.rs:~222-224: CoInitializeEx(NULL, MULTITHREADED) runs for
    each MfApi::load() (once per stream in the sample test, so once per
    file), its result is ignored, and there is no CoUninitialize. On a
    libtest worker thread that already has an apartment of the other kind the
    call returns RPC_E_CHANGED_MODE, harmlessly. Media Foundation does not
    need COM initialised for MFTEnumEx/MFStartup, so the simplest fix is to
    delete the call; otherwise call CoUninitialize in MfApi::drop only when
    the result was S_OK or S_FALSE.

  2. A few HRESULTs are dropped. ~639 (AddBuffer result), ~598
    (Unlock/SetCurrentLength), drain() ~535 (ProcessMessage result),
    select_output_type's fallback let _ = a && b && ... (~420-440: if
    setting the float type's attributes fails, SetOutputType is attempted
    anyway on a half-built type, and the failure is reported only as a generic
    false). A failing AddBuffer would give an empty sample and an obscure
    "sample count mismatch". Fix: check each and return the HRESULT.

  3. Blocking file I/O under the connection lock, per packet.
    apu.rs:243-249 record calls append_capture_packet (apu.rs:157),
    which does path.exists() plus OpenOptions::open plus two writes for each
    of up to 256 packets per stream, inside XApuEnqueueCommand's
    Mutex<State>. Only diagnostics builds with the variable set pay for it,
    and the title's audio thread would stall for a few tens of microseconds per
    packet, so this is acceptable but not tidy. Fix: keep a BufWriter<File> in
    StreamDump (opened once in open) and flush at the cap or on drop.

  4. MF_E_TRANSFORM_STREAM_CHANGE can loop forever.
    opus_reference.rs:~609-617 retries with continue and no bound. A broken
    MFT that keeps answering STREAM_CHANGE would hang the test run instead of
    failing it. Fix: allow two retries, then return Err(hr).

  5. End of stream: send NOTIFY_END_OF_STREAM before COMMAND_DRAIN. The
    documented MFT shutdown sequence is NOTIFY_END_OF_STREAM, then
    COMMAND_DRAIN, then pull until NEED_MORE_INPUT (drain(), ~534).
    Input samples also carry no sample time or duration (decode_packet,
    ~475-520); the Opus MFT works without, and equal sample counts are checked,
    but setting SetSampleTime/SetSampleDuration (960 samples = 200000 x
    100 ns per 20 ms packet) would make the test independent of that behaviour.

  6. The synthetic test can pass without testing anything.
    compare_stream (~690-692) returns after skip("no-opus-mft"). Fine
    locally, but in CI a missing MFT (a Server Core image, for example) passes
    silently. The maintainer said it runs on the CI runner today. Fix: in
    .github/workflows/ci.yml set XTP_REQUIRE: no-opus-mft on the test job
    (a follow-up, not this PR's job, if the maintainer agrees).

  7. Docs. XTP_SAMPLE_OPUS is documented only inside the XTP_APU_DUMP
    README row. Add a sentence there with the command
    (XTP_SAMPLE_OPUS=<dir> cargo test -p xtp-hle --test opus_reference) and
    that the dump needs the diag profile build (the README's own table header
    says diagnostics, but the row itself does not).
    Also: XTP_APU_DUMP= (set but empty) becomes PathBuf::from(""), which
    ensure_outside_repo resolves to the current directory, so captures would be
    written into whatever the working directory is. Treat an empty value as unset
    (apu.rs:222).

  8. PR description is mangled. The body has lost its line breaks in the
    first half ("## What and whyAdd an Opus ...", "Part of #9Depends on: none"),
    keeps the unticked "Some of it comes from elsewhere" box with the sentence
    under it, has two Provenance sections, and still says "~690 changed lines"
    (the PR is about 950 changed lines: size/L, reason given). Ask the author to
    tidy it. The provenance statements themselves are fine: written from
    Microsoft Learn docs and RFC 7845 (public), no xcl/AnyPS5 reading, AI
    assistance disclosed, no game or SDK material.

Test gaps

  • StreamDump itself has no test: no unit test checks that the dump is off
    when the variable is unset, that a path inside the repository is refused,
    that the 32-stream and 256-packet caps hold, or that XApuEnqueueCommand
    produces a file. The integration test only exercises the pub helper
    functions. A #[cfg(feature = "diagnostics")] unit test in apu.rs (the
    existing Opus test there already activates a stream and processes a packet)
    with XTP_APU_DUMP pointed at a tempfile directory would cover all of it.
    The sample-captures test is also never run with a real file in CI, and the
    author notes the real-title run has not happened (hence "Part of #9").
  • Packets that fail to decode are recorded too (apu.rs:463 records before
    decode), and the parity test then panics on expect("opus-pure decode")
    (~700). That may be wanted, but a capture with one bad packet fails the
    whole file with no hint which packet; say so in the panic message (packet
    index).
  • create_capture_file, append_capture_packet, read_capture_file and
    CAPTURE_MAGIC are pub in every build (not only diagnostics) only so the
    integration test can reach them. Acceptable; a #[doc(hidden)] would say so.

What I did not do

No build, no test run, no GitHub comment. The claim "passed against Windows' real
Opus MFT" comes from the author and from the maintainer's own remark about
the CI runner.


Review drafted with Claude Code; findings checked against the PR head by reading the code.

@github-actions github-actions Bot mentioned this pull request Nov 25, 2026
8 of 9 tasks
@fogydes
fogydes merged commit b1d443a into MiamiGame:main Nov 25, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/docs docs/, Markdown area/hle touches crates/xtp-hle overlap another open PR changes the same files size/L 400 to 999 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants