Skip to content

libobs: Port the PulseAudio monitor open and write steps to Rust - #2472

Merged
zackees merged 6 commits into
obs-rust:masterfrom
rdoupe:port/pulse-monitor
Oct 26, 2026
Merged

zackees merged 6 commits into
obs-rust:masterfrom
rdoupe:port/pulse-monitor

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Fixes #2470

What and why

Round 9 unit 10: the last of the PulseAudio monitor's decision logic still in C. The decisions of do_stream_write(), on_audio_playback(), pulseaudio_sink_info(), audio_monitor_init(), on_sink_event(), audio_monitor_reset() and audio_monitor_destroy() in libobs/audio-monitoring/pulse/pulseaudio-output.c.h move to the new pulseaudio-monitor-steps.c.h, then to obs-audio-monitoring::pulse_monitor (next to pulse_format and pulse_stream_flags), in six commits, as #2457 and #2448 did:

  1. 9e20dc2a0 libobs: Move the PulseAudio monitor steps. Behaviour-neutral move into twenty hidden functions on plain values, one per decision, each asked where the C made it (the obs-source: Port the deinterlace draw decisions #2153 split-decision pattern).
  2. c5ae6b748 test: Characterize the PulseAudio monitor steps. test_pulse_monitor_steps (ASan + UBSan, no server).
  3. bd6d8429f obs-audio-monitoring: Test the pulse monitor port. Tier 1 RED against todo!().
  4. e5cd70b69 obs-audio-monitoring: Port the pulse monitor steps. GREEN: the safe core plus src/ffi/pulse_monitor.rs, in the new libobs.ported-pulse-monitor group, and test_pulse_monitor_steps_rust.
  5. 3b530f2e1 obs-audio-monitoring: Compare pulse monitor to C. Tier 3: C oracle, parity tests and a mutation table.
  6. dcc948136 docs: Record the pulse monitor steps port. rust/README.md row, crate description and lib.rs, and a port_comparison bench.

The twenty decisions:

  • do_stream_write(): grow the server buffer when more than twice tlength is queued, and the new tlength; stay corked until a whole tlength is queued; the write loop; cancel and wait when the server asks for more than is queued.
  • on_audio_playback(): skip a source with no activate refs; the bytes pushed; the volume step unless the volume is 1 within EPSILON.
  • pulseaudio_sink_info(): error, end of list, or a sink.
  • audio_monitor_init(): no device; the feedback-loop check (OBS_SOURCE_DO_NOT_SELF_MONITOR); "default"; falling back to the default sink when the chosen one is gone; the default sink has a name; the invalid format; the 25 ms buffer; the fallback stream's flags.
  • on_sink_event(): only new and remove events are queued.
  • audio_monitor_reset(): PA_CONTEXT_IS_GOOD.
  • audio_monitor_destroy(): the last monitor stops the sink events.

C keeps pulseaudio_lock()/_unlock(), the playback mutex and its trylock, the monitoring mutex, every read of the monitor, source and settings at its place, every pa_* call, pulseaudio_get_server_info()/_get_sink_info(), get_default_id(), devices_match(), the resampler, the deque, the buffer attributes, the task queue, every allocation and every log. The core takes no lock, keeps no state and does not divide. The plan sketched a single write_plan(), open_route() and reset_route(). Each would hoist a read or a call: the queue and tlength read before pa_stream_set_buffer_attr() and pa_stream_is_corked(), the settings read before the flag check, and the context state read before the NULL check. So every step is its own function.

Characterized, not endorsed (pinned in C and Rust):

  • tlength * 2 is a uint32_t product, so it wraps from 2^31.
  • The new tlength is the queue truncated to uint32_t, so a queue past 4 GiB shrinks the buffer.
  • A NaN volume is applied.
  • Negative activate refs are not idle.
  • An empty monitoring device ("") falls back like a name.

The byte count is a product in the host's uint_fast32_t (64 bits on glibc, 32 on FreeBSD), and the shim keeps that width.

Intentional difference: a NULL id passed to is_default(), or to fallback() with an invalid format, is not "default" and does not fall back. The C dereferences it. pulseaudio-output.c asks both only after has_device(). This is listed in the parity test header and in rust/README.md.

The port changes nothing a user can see, so docs/features.md has no line.

RED → GREEN

  • Move (9e20dc2a0): checked with a scratch harness (not committed). It compiles origin/master's pulseaudio-output.c.h verbatim and the branch's version with the moved file, as separate translation units, over stubs that log every call with its arguments: both locks, the trylock, every pa_* and wrapper call, the deque, the resampler, the settings, the callbacks, allocations, the task queue and every log line. Another thread moves the queue size, tlength, the format and the activate refs around the calls, and adds monitors when the list is unlocked. Results:
    • 2,600,000 runs (GCC and Clang -O2, GCC -O0, gcov, and ASan+UBSan under GCC and Clang) produced equal events and equal state: 215,904,226 events.
    • Every branch of master's moved-from functions was reached both ways.
    • Of 32 planted broken moves, 31 were caught. The survivor is equivalent: the same read twice with no call in between.
  • RED commit bd6d8429f: soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring::pulse_monitor passes 1 of 31 (the constants) and fails 30, all with "not yet implemented". On that commit, local_gate --lane lint passed and --test-diff origin/master ran 4276 tests: 4246 passed, 6 skipped, and the only 30 failures were the new stubs.
  • GREEN (e5cd70b69):
    • Tier 1: 31 of 31.
    • Characterization: test_pulse_monitor_steps passes 20 of 20 on the C build, the hybrid and the C reference. test_pulse_monitor_steps_rust, linked against libobs_rust-static alone, also passes 20 of 20.
  • Tier 3 (3b530f2e1): 12 parity tests compare the oracle, the shims and the core: constants, exhaustive and strided ranges, 139,968 open routes, 980 write loops and 20,000-case proptests. Tier 1 + Tier 3 together: 43 of 43.
  • Mutation check: 30 mutants (23 core, 7 shims). Tier 1 kills 22 of the 23 core mutants. Tier 3 kills 28 of 30. Both survivors are explained in the commit:
    • needs_volume with < is equivalent: no f32 lands exactly 1e-4f from 1.
    • "Bytes always 64-bit" is identical on 64-bit glibc. Tier 1 kills it.
  • Real-libobs Tier 2 on the rebased head dcc948136, against a private pipewire-pulse (own runtime dir and HOME, no hardware, no audio output):
    • The PulseAudio suite passes 18 of 18 on the C build, and 19 of 19 on the hybrid and on libobs-c-reference (ninja libobs-c-reference built first).
    • test_pulse_default_follow skips on all three because it needs a PulseAudio daemon (not installed here). Its PipeWire variant test_pulse_default_follow_pipewire passes.
  • Exports: 1766 on all three lanes, the same set as master. The twenty functions are local (t), and the hybrid's are the Rust shims.
  • Gates on dcc948136 (rebased onto 2fbf34251):
    • local_gate --test-diff origin/master: 4320 passed, 6 skipped.
    • --lane lint: pass.
    • --lane cross: pass.
    • SOLDR_RUSTC_WRAPPER=none soldr cargo clippy --workspace --target x86_64-pc-windows-msvc --all-targets --locked -- -D warnings: clean.
    • The oracle also compiles against the stand-in <pulse/*.h> alone (GCC and Clang -Werror), which is what the MSVC and macOS runners use.
  • Bench (port_comparison, pulse_monitor/stream_write/1024, release, loaded host): Rust 12.25 µs against C 12.24 µs, and Rust 12.03 µs against C 13.61 µs, with matching checksums.
  • Real app: not applicable (no UI, protocol or logging change). The real-stream tests above run the hybrid against a live sound server.

Note on suite counts: rust/obs-build/tests/libobs.rs pins the native graph count. That pin runs only on macOS and Windows, where test_pulse_monitor_steps is not built (it requires Linux or FreeBSD with ENABLE_PULSEAUDIO), so the pin is unchanged. A Linux run with OBS_BUILD_C_TESTS and PulseAudio would count one more test, but nothing sets that variable today.

Checklist

  • Base is master
  • I claimed the issue, or no one else has an open PR for it
  • Characterization test (if the unit had none), then RED, then GREEN commits
  • User-visible change: its line in docs/features.md is added or updated (not applicable: no user-visible change)
  • (Optional) Local gate passed and the pushed head is stamped; otherwise PR CI runs the full suite
  • Warning or flag changes (-W..., ratchets): built with scripting ON (PR CI builds no OBS app: run gh workflow run ci.yml --ref <branch> for the full builds) and cross-checked with clang and MSVC (not applicable)
  • Intentional differences from C listed in the parity test header and rust/README.md (ports)

Behaviour-neutral extraction before the Rust port. The decisions of
do_stream_write(), on_audio_playback(), pulseaudio_sink_info(),
audio_monitor_init(), on_sink_event(), audio_monitor_reset() and
audio_monitor_destroy() in audio-monitoring/pulse/pulseaudio-output.c.h
move to the new pulseaudio-monitor-steps.c.h, as twenty functions on
plain values declared in pulseaudio-monitor-steps.h without EXPORT
(hidden, as -fvisibility=hidden keeps them):

- do_stream_write(): _grow() (more than twice tlength queued, a
  uint32_t product) and _grown_tlength() (the queue as uint32_t),
  _uncork() (a corked stream starts once a whole tlength is queued),
  _write_more() (the write loop) and _write_short() (the server asks
  for more than is queued: cancel and wait);
- on_audio_playback(): _playback_idle() (no activate refs),
  _playback_bytes() (bytes_per_frame * resample_frames, a product in
  uint_fast32_t) and _needs_volume() (not 1 within EPSILON);
- pulseaudio_sink_info(): _sink_result() (error, end of list or a
  sink);
- audio_monitor_init(): _has_device(), _self_monitor_check()
  (OBS_SOURCE_DO_NOT_SELF_MONITOR), _is_default(), _fallback() (no
  format and not "default": play on the default sink), _sink_named()
  (the default sink has a name), _format_invalid(), _tlength_usec()
  (25 ms) and _open_flags() (the fallback stream's flags are those of
  "default");
- on_sink_event(): _event_queued() (new and remove only);
- audio_monitor_reset(): _context_good() (PA_CONTEXT_IS_GOOD);
- audio_monitor_destroy(): _last().

The plan sketched one write_plan() returning grow, uncork and wait, and
one open_route() and reset_route(). Those would read the queue and
tlength before pa_stream_set_buffer_attr() and pa_stream_is_corked(),
the settings before the output flags are checked, and the context state
before the context is known not to be NULL, so each step is its own
function, asked at its own point, as obs-rust#2153 did. The queue size is still
read for each test and again for the new tlength, tlength again after
the cork test, activate_refs once after the trylock, the format after
each pulseaudio_get_sink_info(), and the monitor count under the
monitoring mutex.

C keeps pulseaudio_lock() and _unlock(), the playback mutex and its
trylock, the monitoring mutex, every pa_* call
(pa_stream_set_buffer_attr(), _is_corked(), _cork(), _begin_write(),
_cancel_write(), _write(), _get_context(), pa_context_get_state(),
pa_usec_to_bytes(), pa_sample_spec_valid(), pa_frame_size()),
pulseaudio_get_server_info() and _get_sink_info(), get_default_id(),
devices_match(), obs_source_get_settings(), the resampler, the deque,
the buffer attributes it writes, the task queue, drop_backlog(), every
allocation and every log. The NULL tests of
pointers the C dereferences next (the device, the context, the stream)
stay with them.

The expressions move as they were: the uint32_t tlength * 2, the
size_t comparisons, the (uint32_t) truncation of the new tlength, the
uint_fast32_t product of the bytes (64 bits on glibc, 32 on FreeBSD),
fabsf(vol - 1.0f) <= EPSILON through close_float(), and the masked
event type.

Checked in a scratch harness (not committed). It compiles
origin/master's pulseaudio-output.c.h verbatim and this branch's with
the moved file, each as its own C translation unit, over stubs that log
every call with its arguments, in order: both locks, the trylock, every
pa_* and wrapper call, the deque, the resampler, the settings, the
source callbacks, the allocations, the task queue and every log line.
The stubs answer from one seeded stream in call order. Another thread
moves the queue size, tlength and the format around each lock, pa_*
call and callback, moves activate_refs before each load, and adds a
monitor to the list when it is unlocked; the sink info callback runs
1 to 3 times per call with eol 0, 1, -1, 2, -2, INT_MAX and INT_MIN.
Each run is 1 to 8 operations on up to 8 monitors (create, write,
playback, a direct sink info, sink events, running the queued events,
reset, destroy), with queue sizes and tlengths at 0, 1, around 4800,
around 2 * tlength, around 2^31 and 2^32 and SIZE_MAX; volumes of 1,
1 +- EPSILON and their neighbours, 0, -1, 2, NaN and +-infinity;
activate refs of -1 to 2; any output flags; device ids NULL, "",
"default", "defaults" and names; any format, rate and channel count
from the server; every context state and values outside the enum. The
monitors' state is compared after every run.
- 2,600,000 runs (GCC and Clang -O2, 1,000,000 each; GCC -O0, 300,000;
  GCC -O0 with coverage, 100,000; ASan with UBSan under GCC -O0 and
  Clang -O2, 100,000 each) give equal events and equal state:
  215,904,226 events.
- Every branch of origin/master's do_stream_write(),
  on_audio_playback(), pulseaudio_sink_info(), audio_monitor_init(),
  handle_sink_event(), on_sink_event(), audio_monitor_reset() and
  audio_monitor_destroy() is reached both ways (gcov).
- 32 deliberately broken moves were planted. 31 fail it: 24 changed
  decisions (each comparison moved by one, the uint32_t product done in
  size_t, the new tlength saturated, the bytes in uint32_t and one frame
  over, EPSILON at 1e-3, eol 1 taken as a
  sink, an error as the end, the flag bit moved, "default" as a prefix,
  the fallback also for "default", an empty default sink accepted,
  PA_SAMPLE_MAX taken as invalid, 20 ms, the fallback's flags from the
  chosen id, change events queued, the event type unmasked, a
  terminated context taken as good, the last monitor at one), and 7
  moved reads or calls (tlength read before the cork test, the queue
  read before pa_stream_begin_write() for the short test,
  activate_refs loaded before the trylock, the settings read before the
  flag check, the format read before pulseaudio_get_sink_info(),
  pa_context_get_state() asked of a NULL context, and the monitor count
  read after the mutex is dropped). The 32nd, the queue size read once
  for the grow test and the new tlength, is equivalent: no call comes
  between the two reads, under both locks.

git blame on the moved lines: upstream (b6042d9, bc9eee9,
9de1ffe, 5142a76, 73dea7c, e8a8ac5, 2963959 and formatting)
and the fork's own fixes: the chosen device and its fallback
(9295370), the reset that keeps a live monitor (82fdc46) and the
stall catch-up (3ebc4fd).

OBS_SOURCE_DO_NOT_SELF_MONITOR is copied into the header, so it needs
no core header; pulseaudio-output.c.h checks it with _Static_assert.
The new file joins libobs.pulse, before pulseaudio-output.c.h, with
libobs-pulse.pch.h, which includes the new header and math-defs.h;
os-linux.cmake and os-freebsd.cmake list the header.
docs/rust-port/naming.md already maps libobs/audio-monitoring/ to
rust/obs-audio-monitoring. The exported symbol sets are unchanged
(1766 on the C build, hybrid and C reference); the twenty functions
are local. The 17 PulseAudio tests pass on all three against a private
pipewire-pulse (test_pulse_default_follow skips: it needs a
PulseAudio daemon, and its PipeWire variant passes).

Refs obs-rust#2470
test_pulse_monitor_steps compiles
libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h and
pulseaudio-stream-flags.c.h (for pulseaudio_monitor_stream_flags())
with ASan and UBSan, and calls only their functions through
pulseaudio-monitor-steps.h and pulseaudio-stream-flags.h. No server.
20 cases:

- the copied OBS_SOURCE_DO_NOT_SELF_MONITOR and the sink results;
- do_stream_write(): the grow rule at 2 * tlength - 1, at it and + 1
  (strict >) over six tlengths, its uint32_t wrap at 2^31 and up, the
  new tlength's truncation, the cork rule at tlength - 1, at it and
  + 1, the write loop at 0, 1 and SIZE_MAX, and the short write when
  the server asks for more than, all of and less than the queue;
- on_audio_playback(): activate refs of 0, 1, 2, -1, LONG_MIN and
  LONG_MAX; the bytes of a packet, with the uint_fast32_t product's
  width (64 bits on glibc, 32 on FreeBSD); the volume at 1, at the last floats within EPSILON of 1
  on either side and the next ones, at 1 +- EPSILON (which round past
  it), 0, -0, 0.5, 2, -1, +-infinity and NaN;
- pulseaudio_sink_info(): eol of 0, 1 to INT_MAX and -1 to INT_MIN;
- audio_monitor_init(): no device (NULL), "default" against "",
  "Default", "default ", "defaults", "default.monitor" and a name;
  each of the 32 flag bits alone and cleared; the fallback for a gone
  sink with every kind of id; the default sink's name NULL, "" or set;
  the invalid format against every valid one and -2; the 25 ms buffer;
  the fallback stream's flags (those of "default", whatever the id)
  and the others' (their id's);
- on_sink_event(): new, change, remove and the full type mask on six
  facilities, and high bits;
- audio_monitor_reset(): every context state and two outside the
  enum;
- audio_monitor_destroy(): the last monitor at 0, 1, 2 and SIZE_MAX.

Stand-ins copy the order pulseaudio-output.c asks these in, with each
call replaced by its answer, to pin end to end: the write loop at
25 ms of 48 kHz stereo float (corked one byte short: nothing; a whole
tlength: uncorked and written; asked for more: cancelled, nothing
popped; asked in pieces; a piece then more than is left; past twice
tlength: grown, then uncorked; at exactly twice: not grown), 14 open
routes (no device, the feedback loop prevented for "default" and a
name, the flag or the match alone, "default", "default" with no
format, the fallback and its three failures, and "" both ways), and
the reset routes (replace, keep with no stream or a good context,
ignore with no context or a context in any other state).

Characterized, not endorsed:
- tlength * 2 is a uint32_t product: a tlength of 2^31 or more wraps,
  so the buffer grows for a much smaller queue;
- the new tlength is the queue truncated to uint32_t: past UINT32_MAX
  bytes the buffer shrinks (2^32 + 5 gives 5);
- a NaN volume is not close to 1, so the volume step runs with it;
- negative activate refs are not idle;
- an empty monitoring device ("") is a name: it falls back to the
  default sink when it gives no format.

It is in the native test graph, in name order, on Linux and FreeBSD
with ENABLE_PULSEAUDIO, with both headers as watch inputs. No
assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x.
The real-libobs tests test_pulse_monitor_device,
test_pulse_default_follow, test_pulse_monitor_reset,
test_pulse_stream_restart, test_pulse_two_sources and
test_pulse_monitor_samples cover the callers against a private sound
server.

Refs obs-rust#2470
RED for the port of
libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h to a new
pulse_monitor module of rust/obs-audio-monitoring, next to pulse_format
and pulse_stream_flags. The safe core is a stub (todo!()): grow(),
grown_tlength(), uncork(), write_more(), write_short(),
playback_idle(), playback_bytes(), needs_volume(), sink_result(),
has_device(), self_monitor_check(), is_default(), fallback(),
sink_named(), format_invalid(), tlength_usec(), open_flags(),
event_queued(), context_good() and last(), with
DO_NOT_SELF_MONITOR, EPSILON, TLENGTH_USEC, the PA_CONTEXT_* states and
the SinkResult enum.

tests/audio_monitoring/pulse_monitor.rs ports test_pulse_monitor_steps
1:1: its 20 cases under the same names (steps_*), in the same order,
with the same values and expectations, the characterized-not-endorsed
cases included, and the C test's stand-ins (the write loop, the open
routes and the reset routes) written in Rust over the core.

Edge cases (edge_*) check the core against models of the origin/master
C, its expressions inline: the write rules over every pair of 21 or
more special sizes and 12 special tlengths (around 4800, 9600, 2^31,
2^32, twice each tlength and SIZE_MAX); the bytes over 11 frame sizes,
12 frame counts and both uint_fast32_t widths; activate refs at the
ends of i64; every float within 4096 ulps of 1 and of the two EPSILON
boundaries, and the special floats; every eol edge and format with
three ids; every low 16-bit event word and flag word under four high
words; context states 0 to 64 and the top of u32; ids near "default".
Two proptests (4,096 cases each): every decision over full-range
values, and the write loop over queues and server asks against the
origin/master loop.

soldr cargo test -p obs-data --test obs-tests-core --
audio_monitoring::pulse_monitor passes 1 of 31 (the constants) and
fails 30 with "not yet implemented".

Refs obs-rust#2470
Ports libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h, the
PulseAudio monitor's open and write steps of pulseaudio-output.c, to
the pulse_monitor module of rust/obs-audio-monitoring.
pulseaudio-output.c.h stays C around it: both locks and the trylock,
the monitoring mutex, every read of the monitor, the source and the
settings, every pa_* call, the server and sink info calls,
get_default_id(), devices_match(), the resampler, the deque, the
buffer attributes, the task queue, every allocation and every log. The
hybrid libobs drops the C file and links the Rust shims in its place.

Safe core (src/pulse_monitor.rs):
- grow(): queued > tlength.wrapping_mul(2), widened, as the C's
  uint32_t product; grown_tlength(): the low 32 bits of the queue;
  uncork(), write_more(), write_short(): the C's >=, > 0 and >;
- playback_idle(): refs == 0; playback_bytes(): the product wrapping
  in 64 or 32 bits (uint_fast32_t's width, passed by the shim), then
  the low bits as a usize; needs_volume(): !((vol - 1.0).abs() <=
  EPSILON) in f32, so NaN needs the step;
- sink_result(): eol < 0 Error, > 0 End, else Info;
- has_device(), sink_named() (set and not empty), is_default() (the
  bytes equal "default"), fallback() (invalid and not "default"),
  format_invalid() (PA_SAMPLE_INVALID), self_monitor_check() (bit 9),
  tlength_usec() (25,000) and open_flags() (stream_flags() of
  "default" on the fallback, else of the id);
- event_queued(): the masked type is new or remove; context_good():
  connecting, authorizing, setting the name or ready; last(): 0.
The module denies clippy's arithmetic, as, indexing, unwrap, expect,
panic, todo, unimplemented and unreachable lints, keeps no state, takes
no lock and does not divide.

Shims (src/ffi/pulse_monitor.rs): the twenty functions keep the C
signatures. pa_sample_format_t crosses as int, the other pa_* enums
and the sink result (0 to 2) as unsigned int, long as c_long and
uint_fast32_t as pulse_format's host alias. The id strings are read up
to their NUL; no struct is mirrored.

Intentional difference: a NULL id given to is_default(), or to
fallback() with an invalid format, is not "default" and does not fall
back; the C dereferences it. pulseaudio-output.c asks both only after
has_device().

C side: the file leaves libobs.pulse for its own group,
libobs.ported-pulse-monitor (LIBOBS_PULSE_PORTED_SOURCES), whose PCH is
math-defs.h, pulseaudio-monitor-steps.h and pulseaudio-stream-flags.h;
libobs-pulse.pch.h keeps the header for pulseaudio-output.c. The
functions are not EXPORT, so the shims are hidden: rust-hidden.txt, the
local: list of rust-exports.map and rust-unexports-macos.txt.
libobs-rust already links the crate's ffi. ci/test_ported_sources.py
checks the group on Linux and its absence without PulseAudio.

test_pulse_monitor_steps still compiles the C file into itself,
unchanged. test_pulse_monitor_steps_rust runs the same file against
libobs_rust-static alone (the obs-audio-monitoring member needs nothing
from libobs), on Linux and FreeBSD with ENABLE_PULSEAUDIO: 20 of 20.

soldr cargo test -p obs-data --test obs-tests-core --
audio_monitoring::pulse_monitor passes 31 of 31. The exported symbol
sets stay 1766 on the C build, the hybrid and the C reference; the 19
PulseAudio tests pass on the hybrid and the C reference and 18 on the
C build, against a private pipewire-pulse (test_pulse_default_follow
skips: it needs a PulseAudio daemon; its PipeWire variant passes).

Refs obs-rust#2470
Tier 3 for the pulse_monitor port. The oracle
(rust/obs-c-oracle/oracle/pulse_monitor_steps.c) compiles the unchanged
libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h with its
twenty functions renamed to oracle_*, and its call of
pulseaudio_monitor_stream_flags() renamed to the stream-flags oracle's,
so C answers all the way down. It also gives its constants (the copied
flag, the sink results, the PA_CONTEXT_* states, PA_SAMPLE_INVALID,
sizeof(uint_fast32_t) and sizeof(long)) and a wrapper that converts the
frame size to the host's uint_fast32_t as pulseaudio-output.c's field
does; bound in src/pulse_monitor_steps.rs. Nothing in it divides. The
oracle's stand-in <pulse/def.h> and <pulse/sample.h> (used where
libpulse is not installed: MSVC, macOS) gain pa_context_state_t,
PA_CONTEXT_IS_GOOD() and pa_usec_t, with libpulse's values; the oracle
was also compiled against the stand-ins alone with GCC and Clang
-Werror.

tests/audio_monitoring/pulse_monitor_parity.rs compares the oracle, the
shims and the core exactly, all three sides:
- the fourteen constants and the 25 ms buffer;
- the write rules over every pair of 151 sizes (around 0, 4800, 9600,
  19200, 2^31, 2^32, each special tlength, twice it and its uint32_t
  wrap, and SIZE_MAX) with 14 special tlengths, and every pair of sizes
  for the short write;
- the activate refs at the ends of long, the bytes over 14 frame sizes
  and 14 frame counts;
- the volume at every float within 2^16 ulps of 1 and of both EPSILON
  boundaries, and every 4099th bit pattern of all 2^32 (NaNs,
  infinities, subnormals);
- eol from -1000 to 1000 and a stride through all i32; every low 16-bit
  flag and event word, 256 under each of three high words and a stride
  through all u32; context states 0 to 4096 and the top of u32;
- formats from -1000 to 1000 and the ends of int with 11 ids, the ids
  through every string function, and NULL where the C takes it;
- the callers (the C test's stand-ins) on the oracle and on the shims:
  980 write loops over tlengths, queues, cork states and server asks;
  139,968 open routes over ids (NULL included), flags, the match, the
  formats, the default sink's name and the fallback's format, reaching
  every route; and the reset rule over every context state;
- proptests (20,000 cases each) of every decision over full-range values
  and of the write loop.

Only the intentional difference is excluded: is_default() and
fallback() (with an invalid format) are not called on the oracle with a
NULL id, which the C dereferences.

Mutation check (once, not committed): 30 mutants, 23 in the core and 7
in the shims.

  mutant                                  Tier 1  Tier 3
  grow: >=                                     4       2
  grow: product in usize                       2       2
  grown_tlength: saturating                    4       4
  uncork: >                                    4       3
  write_more: > 1                              2       2
  write_short: >=                              3       3
  playback_idle: <= 0                          3       2
  playback_bytes: always 64-bit                2       0
  playback_bytes: saturating                   2       2
  needs_volume: <                              0       0
  needs_volume: NaN taken as close             3       2
  sink_result: eol 0 as the end                2       1
  has_device: always                           1       2
  self_monitor_check: bit 8                    4       3
  is_default: as a prefix                      3       2
  fallback: also for "default"                 3       2
  sink_named: "" accepted                      4       3
  format_invalid: < 0                          3       3
  tlength_usec: 20 ms                          2       1
  open_flags: the id on the fallback           3       3
  event_queued: change too                     3       2
  context_good: terminated too                 3       2
  last: <= 1                                   2       1
  shim grow: arguments swapped                 0       3
  shim write_short: arguments swapped          0       4
  shim playback_bytes: always 32-bit           0       2
  shim sink_result: error as the end           0       2
  shim open_flags: fallback dropped            0       3
  shim has_device: NULL taken as set           0       2
  shim context_good: state off by one          0       2

(failing tests per tier.) Tier 1 kills 22 of the 23 core mutants and
Tier 3 28 of 30. needs_volume() with < survives both and is equivalent:
no f32 differs from 1 by exactly 1e-4f (steps of 2^-23 above 1 and
2^-24 below never land on it). playback_bytes() always 64-bit survives
Tier 3 only on a host where uint_fast32_t is 64-bit, as here (64-bit
glibc); Tier 1 kills it, and Tier 3 does on FreeBSD and Windows.

soldr cargo test -p obs-data --test obs-tests-core --
audio_monitoring::pulse_monitor passes 43 of 43 (31 Tier 1, 12
Tier 3).

Refs obs-rust#2470
rust/README.md gets the row for
libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h
(obs-audio-monitoring::pulse_monitor): what moved, what stays C and
why, the characterized-not-endorsed behaviours (the uint32_t
tlength * 2 and the truncated new tlength among them), the byte count's
host width, the one intentional difference and the tests that cover
it; the obs-audio-monitoring crate row, its Cargo description and
lib.rs name the new module. docs/rust-port/naming.md already maps
libobs/audio-monitoring/ to rust/obs-audio-monitoring.

rust/obs-c-oracle/benches/port_comparison/pulse_monitor.rs, in the
sorted module list, runs 1024 packets through every decision
on_audio_playback() and do_stream_write() ask (the activate refs, the
bytes, the volume, the grow and cork rules and the write loop), on the
shims and on the oracle, and checks both checksums match; obs-c-oracle
gains obs-audio-monitoring as a dev-dependency (Cargo.lock). Release,
x86_64 Linux, GCC, a loaded host, criterion medians of two runs: Rust
12.25 us, C 12.24 us (1.00x), and Rust 12.03 us, C 13.61 us.

The port changes nothing a user can see, so docs/features.md has no
line.

Fixes obs-rust#2470
@rdoupe
rdoupe requested a review from zackees as a code owner October 26, 2026 11:00
@zackees

zackees commented Oct 26, 2026

Copy link
Copy Markdown
Member

Coordinator review: a decision port in the standard shape. The PulseAudio monitor's open and write steps move into a steps unit, and then to obs-audio-monitoring::pulse_monitor through ffi/. The new tests and the C reference copy are added, and the only existing test file touched is the test-graph.json entry. Lint's platform-boundary Dylint covers the cfg placement. Queuing; it merges when CI is green.

@zackees
zackees enabled auto-merge October 26, 2026 11:02
@zackees
zackees added this pull request to the merge queue Oct 26, 2026
Merged via the queue into obs-rust:master with commit fb85e74 Oct 26, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

rust: Port the PulseAudio monitor steps in pulseaudio-output.c to Rust

2 participants