Skip to content

rust: Port the PulseAudio monitor format and volume code to obs-audio-monitoring #1697

Closed

Description

@rdoupe

Port the PulseAudio monitor's sample format, channel map and volume code to the existing crate rust/obs-audio-monitoring as a new module, pulse_format. On Linux and FreeBSD, audio monitoring plays every monitored source on the chosen sink through PulseAudio (also with pipewire-pulse). The monitor asks the sink for its spec and plays in that spec where OBS can produce it, which is U8, S16LE, S32LE or FLOAT32LE with 1-6 or 8 channels. Any other spec plays as FLOAT32LE or stereo, and the server converts. The resampler hands the monitor interleaved samples in that format, and the monitor applies the source's volume to them itself.

From libobs/audio-monitoring/pulse/pulseaudio-output.c.h:

  • pulseaudio_channels_to_obs_speakers, pulseaudio_to_obs_audio_format and pulseaudio_channel_map;
  • the spec choice in pulseaudio_sink_info: an unsupported format falls back to FLOAT32LE, and an unsupported channel count to 2;
  • process_byte, process_s16, process_s32, process_float and process_volume. process_volume is the one non-static function. Its entry point gets a prefixed name, pulseaudio_monitor_process_volume, and takes the format and channel count instead of the file-local struct audio_monitor;
  • the arithmetic of drop_backlog, without the pa_stream_* calls: what the server holds (write index - read index, less what it has played since the last timing update), plus what is not written yet; and the bytes to drop, rounded down to whole frames and split between what is not written yet and the rewind.

From libobs/audio-monitoring/pulse/pulseaudio-wrapper.c.h: the feedback-loop match in devices_match, with the default sink's name passed in.

About 200 lines. These stay C:

  • everything that calls pa_*: the mainloop, the context, the stream, the sink info callbacks and sink events;
  • get_default_id, which asks the server. devices_match keeps calling it lazily, only when one of the ids is "default";
  • bytes_per_sec, the tlength choice, the deque, the resampler, logging and audio_monitor_init.

Phase and position

Phase 6 (#444), libobs core through opaque seams. It joins rust/obs-audio-monitoring, which holds the stream flags, the sink-event rule and the backlog decision (pulse_stream_flags, #1513). It is part of a larger file, so it goes in through function extraction (testing-policy.md, "Extracting a function before porting it"). Its Rust tests join the crate's existing tests/audio_monitoring/ binary. No new test binary.

Dependencies and existing tests

  • struct audio_monitor is file-local (pulseaudio-output.c.h), not in obs-internal.h. The moved functions take scalars (format, channel count, frames, the timing numbers, the frame size), so no accessor is needed.
  • PulseAudio ABI: the pa_sample_format_t and pa_channel_position_t numbers are stable ABI. The Rust side returns the channel count and [u32; 8] positions, and a C shim fills pa_channel_map, so Rust never mirrors pa_channel_map (uint8_t plus map[PA_CHANNELS_MAX]). The characterization pins the numbers against libpulse's header.
  • process_* writes frames * channels samples into the resampler's buffer. The FFI takes that count from its caller and never computes a larger one.
  • The volume multiply must stay the same f32 operation (int → f32 → multiply → convert), or samples differ by 1 LSB. S32 keeps only 24 bits through the float. U8 is ((int)x - 128) * vol + 128, with the offset added in f32.
  • devices_match builds its names with bzalloc/bstrdup and strcat into buffers sized strlen + 9 (".monitor" and the NUL). The safe core compares without allocating.
  • Today:
    • test_pulse_monitor_flags and test_pulse_monitor_backlog compile pulseaudio-stream-flags.c.h (C only).
    • test_pulse_default_id compiles pulseaudio-wrapper.c.h against a fake libpulse.
    • test_pulse_monitor_device, test_pulse_monitor_reset, test_pulse_two_sources and test_pulse_stream_restart link the real libobs and run a real monitoring stream (they skip with 77 without a sound server), so they reach the format and channel-map code. None of them checks the volume, the channel map or devices_match's "default" rule.
  • PR 1 adds test_pulse_monitor_format, which compiles the moved file.

Plan

  1. Characterization and extraction PR (behaviour-neutral, as in libobs: Move the hotkey binding codec into obs-hotkey-bindings.c #1622):

    • The functions above move verbatim into libobs/audio-monitoring/pulse/pulseaudio-monitor-format.c.h. Their declarations go in pulseaudio-monitor-format.h, without EXPORT, as pulseaudio-stream-flags.h did before libobs: Port the PulseAudio stream flags to obs-audio-monitoring #1513. The file joins the existing libobs.pulse unity group (Linux and FreeBSD, ENABLE_PULSEAUDIO). The exported symbols are unchanged.
    • New test test_pulse_monitor_format (plain C, no server, ASan and UBSan). It pins:
      • every pa_sample_format_t, with the BE, S24, A-law and mu-law formats;
      • every channel count from 0 to 255;
      • every layout's channel map, including the positions past the channel count;
      • the volume at 0, 0.1, 0.25, 0.5, just under 1 and 1 for every format, U8 truncation, S32 precision, and formats left unchanged;
      • that exactly frames * channels samples are written;
      • the queued-bytes and drop arithmetic at every frame remainder;
      • devices_match with "default" on either side or both, an empty default, ids that already end in .monitor, and NULL.
    • Above a volume of 1, only results that stay in the type's range are pinned (bug 1 below).
  2. Fix PR, in C, before the port (RED, then GREEN). It fixes both bugs below. The RED commit adds the out-of-range volume cases, which fail today, or trip UBSan where the compiler checks float casts. The GREEN commit:

    • clamps the scaled sample to the type's range before converting it, in process_byte, process_s16 and process_s32. A full-scale sample then clips, as the FLOAT32LE path does when the server converts its output;
    • logs the channel counts with %u, not %c.

    The fix has to come before the port. Rust's as saturates, but the C conversion is undefined behaviour, so a port first would either change the behaviour silently or need unsafe code to copy the UB. After the fix, the port is a plain parity port, and its tests carry no exceptions.

  3. Port PR (RED, then GREEN):

    • obs_audio_monitoring::pulse_format gets the safe core, and src/ffi/pulse_format.rs the C ABI shims. The C file moves to its own ported group, libobs.ported-pulse-format, with its own .pch.h, source-sets.json entry and export fragment (rust-exports.map, rust-hidden.txt, rust-unexports-macos.txt), as libobs.ported-pulse has. The shims stay hidden (no EXPORT).
    • Tests:
      • Tier 1 ports every test_pulse_monitor_format expectation 1:1.
      • Tier 3 checks parity against an oracle over the moved C (rust/obs-c-oracle/oracle/pulse_format.c), with proptests over (format, channels, frames, vol) on random sample buffers (byte-exact output, for every format), over the backlog numbers, and over the device ids.
      • Tier 2 runs with OBS_LIBOBS_BACKEND=C and in the hybrid with libobs-c-reference, unchanged. The four real-stream tests above see the swap where a sound server is installed.
      • Tier 4 does not apply (no protocol change).
    • Docs: the rust/README.md row. The docs/rust-port/naming.md row for libobs/audio-monitoring/ already covers it.

Behaviour: the move makes no change, and neither does the port. PR 1 pins two behaviours, which PR 2 fixes:

  • A volume above 1 on an integer sink wraps instead of clipping. process_byte, process_s16 and process_s32 multiply each sample by the volume in float and convert it back to the integer type without a clamp. A source's volume can be above 1: Advanced Audio Properties allows up to +26 dB (about 20x), obs-websocket SetInputVolume allows 20x, and a scene collection file can hold any value. With such a volume, a loud sample leaves the type's range, and the conversion is undefined behaviour. In practice, on x86-64 with GCC, S16 and U8 samples wrap (20000 × 2 becomes -25536), and every out-of-range S32 sample becomes INT32_MIN, so a positive peak plays as a full-scale negative one. The result is loud distortion in the monitor only. The recording and the stream are fine, because the main mix is float. FLOAT32LE sinks are fine too, because the server clips. U8, S16LE and S32LE sinks are common: classic PulseAudio defaults to S16LE, and pipewire-pulse reports S32LE for many onboard and HDMI devices. S24 and big-endian sinks play as FLOAT32LE, so they are not affected. Upstream OBS has the same code.
  • The fallback log garbles the channel counts. pulseaudio_sink_info() logs the sink's channel count and the fallback with %c, so a 7-channel sink logs a control character where 7 should be, and the fallback logs \x02 where 2 should be. Upstream OBS has the same code. This is cosmetic.

Activity

  1. rdoupe commented on Oct 22, 2026

    @rdoupe
    CollaboratorAuthor

    Claiming: #1697

    1. Characterization and move PR: the format, channel map, volume and device-match code moved into libobs/audio-monitoring/pulse/pulseaudio-monitor-format.c.h, with test_pulse_monitor_format (12 cases). Opening it now.
    2. One C fix PR: clamp the monitoring volume before the integer conversion (today it wraps on s16/u8/s32 sinks above 100% volume), and the %c channel-count log.
    3. The port, as rust/obs-audio-monitoring's pulse_format module.
  2. added
    claimed
    on Oct 22, 2026
  3. rdoupe commented on Oct 22, 2026

    @rdoupe
    CollaboratorAuthor

    Port notes for #1721 (testing-policy tracking):

    • Intentional differences, each on an input that crashes the C and that its caller never sends: a null sample buffer is a no-op, a zero frame size drops nothing, and a "default" id with a null default sink does not match. They're listed in the parity test header and rust/README.md.
    • pa_channel_map is mirrored as a #[repr(C)] struct with a layout test; map[8..] (never written by the C) is filled with PA_CHANNEL_POSITION_INVALID.
    • Coverage gap found by the deliberate break: none of the real-libobs test_pulse* tests check sample values, so a wrong volume conversion in hybrid passes all of them. Tier 1/3 catch it, and so did a private-PipeWire probe that records the monitor. Promoting that probe to a cmocka test is a follow-up.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    claimed

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions