Repository navigation
hle, docs: add XTP_APU_DUMP and Windows Opus MFT parity test - #48
Conversation
|
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.
This comment is kept up to date automatically and removed when the overlap ends. |
simnJS
left a comment
There was a problem hiding this comment.
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:
- Captures from different runs get mixed (
apu.rs~152, 222-229): the counter restarts at00each run andappend_capture_packetappends to an existing file, so a second run into the same folder concatenates unrelated streams (and the old header's channel count wins). CouldStreamDump::opencreate/truncate the file and write the header, withrecordonly appending? opus_reference.rs~598-606: whenLocksucceeds withcur_len < 4, the buffer is never unlocked.- Optional hardening:
MFT_ENUM_FLAG_SYNCMFT | LOCALMFT | SORTANDFILTERinstead ofALL, aCOMMAND_DRAINat end of stream (and treatMF_E_TRANSFORM_STREAM_CHANGEexplicitly), andLoadLibraryExA(..., LOAD_LIBRARY_SEARCH_SYSTEM32)for the system DLLs (also free both module handles on the early-return paths). - 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.)
|
Thanks for the review, @simnJS! Addressed all five points in
Verified locally with |
simnJS
left a comment
There was a problem hiding this comment.
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::recordreopens the file for every packet while the connection lock is held; keeping theFileinStreamDumpwould avoid that.MFTEnumExcan 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
left a comment
There was a problem hiding this comment.
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
- 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 atApplication::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 == 0returns infinity,~672).
Fix: parameterisesynth_packetsover 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
-
COM is initialised on every load and never uninitialised.
opus_reference.rs:~222-224:CoInitializeEx(NULL, MULTITHREADED)runs for
eachMfApi::load()(once per stream in the sample test, so once per
file), its result is ignored, and there is noCoUninitialize. On a
libtest worker thread that already has an apartment of the other kind the
call returnsRPC_E_CHANGED_MODE, harmlessly. Media Foundation does not
need COM initialised forMFTEnumEx/MFStartup, so the simplest fix is to
delete the call; otherwise callCoUninitializeinMfApi::droponly when
the result wasS_OKorS_FALSE. -
A few HRESULTs are dropped.
~639(AddBufferresult),~598
(Unlock/SetCurrentLength),drain()~535(ProcessMessageresult),
select_output_type's fallbacklet _ = a && b && ...(~420-440: if
setting the float type's attributes fails,SetOutputTypeis attempted
anyway on a half-built type, and the failure is reported only as a generic
false). A failingAddBufferwould give an empty sample and an obscure
"sample count mismatch". Fix: check each and return the HRESULT. -
Blocking file I/O under the connection lock, per packet.
apu.rs:243-249recordcallsappend_capture_packet(apu.rs:157),
which doespath.exists()plusOpenOptions::openplus two writes for each
of up to 256 packets per stream, insideXApuEnqueueCommand'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 aBufWriter<File>in
StreamDump(opened once inopen) and flush at the cap or on drop. -
MF_E_TRANSFORM_STREAM_CHANGEcan loop forever.
opus_reference.rs:~609-617retries withcontinueand no bound. A broken
MFT that keeps answeringSTREAM_CHANGEwould hang the test run instead of
failing it. Fix: allow two retries, then returnErr(hr). -
End of stream: send
NOTIFY_END_OF_STREAMbeforeCOMMAND_DRAIN. The
documented MFT shutdown sequence isNOTIFY_END_OF_STREAM, then
COMMAND_DRAIN, then pull untilNEED_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 settingSetSampleTime/SetSampleDuration(960 samples = 200000 x
100 ns per 20 ms packet) would make the test independent of that behaviour. -
The synthetic test can pass without testing anything.
compare_stream(~690-692) returns afterskip("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.ymlsetXTP_REQUIRE: no-opus-mfton thetestjob
(a follow-up, not this PR's job, if the maintainer agrees). -
Docs.
XTP_SAMPLE_OPUSis documented only inside theXTP_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 thediagprofile build (the README's own table header
says diagnostics, but the row itself does not).
Also:XTP_APU_DUMP=(set but empty) becomesPathBuf::from(""), which
ensure_outside_reporesolves to the current directory, so captures would be
written into whatever the working directory is. Treat an empty value as unset
(apu.rs:222). -
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), noxcl/AnyPS5reading, AI
assistance disclosed, no game or SDK material.
Test gaps
StreamDumpitself 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 thatXApuEnqueueCommand
produces a file. The integration test only exercises thepubhelper
functions. A#[cfg(feature = "diagnostics")]unit test inapu.rs(the
existing Opus test there already activates a stream and processes a packet)
withXTP_APU_DUMPpointed at atempfiledirectory 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:463records before
decode), and the parity test then panics onexpect("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_fileand
CAPTURE_MAGICarepubin 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.
What and why
Add an optional Opus packet capture switch (
XTP_APU_DUMP=<dir>) and a test-only parity check comparingopus-purewith 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
windowsfeatures. 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 throughXTP_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
windowsfeatures.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
cargo xtask pr-checkpasses on my machine (the contributor reported the unrelated hardware GPU failure tracked in gpu: UAV texture clear test differs on hardware and WARP #41).Contributor-reported Windows verification:
cargo test -p xtp-hle --test opus_reference --locked -- --nocapturecargo test -p xtp-hle apu --lockedxtp-hle.cargo xtask policyandcargo xtask conventions.XTP_SAMPLE_OPUSwas unset.CI on head
991ef67f2062834209f97d3cc2c3dc47335c8d16passed, including workspace tests andgpu-debug-layer.Provenance
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 readxclorAnyPS5source 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
<area>: <summary>; one topic; the reason for exceeding 400 changed lines is above.