Skip to content

obs-output: Port the encoder audio start alignment - #2331

Merged
rdoupe merged 6 commits into
obs-rust:masterfrom
rdoupe:port/encoder-audio-start
Oct 25, 2026
Merged

rdoupe merged 6 commits into
obs-rust:masterfrom
rdoupe:port/encoder-audio-start

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #2320

What and why

Ports the encoder audio start alignment and the setter gates of libobs/obs-encoder.c.h to rust/obs-output, as a new module encoder_audio_start next to encoder_size and encoder_roi. Every recording and stream with audio goes through these decisions: they hold an audio encoder's packets until its paired video encoder has started, then cut the audio at the video's first frame. A wrong answer leaves the audio ahead of or behind the video for the whole recording, or never starts the audio.

What moves:

  • in receive_video():
    • the group start gate: the group's start timestamp equals the frame's;
    • the wait for each paired audio encoder: its first audio is after the frame;
    • the pts step after an encode;
  • in buffer_audio():
    • the packet size;
    • the paired and unpaired branches, and "no video yet";
    • once the video has started, the plan. The audio waits while the packet ends at or before the video's start. Otherwise it starts: truncated if the packet begins before the video, the buffer cleared if it begins at or before it, from the buffer if it begins after it;
  • calc_offset_size(), start_from_buffer() and push_back_audio(): the offset in nanoseconds and bytes, the buffer offset, and the size left to push;
  • the send loop of receive_audio() and the pts step of send_audio_data();
  • obs_encoder_set_gpu_scale_type() and obs_encoder_set_frame_rate_divisor(): the not-a-video-encoder refusal (encoder_size::scaled_gate's rule, reused) and the divisor-0 rule.

The plan's API was adjusted. The port plan sketched one audio_start(in) -> Wait | Start { ... } call and a three-flag setter gate. They became sixteen functions, one per decision, so that obs-encoder.c.h keeps every read where it was:

  • The walk over the paired encoders stays in C and asks _paired_late() for each encoder it reaches that has received audio. It still takes, reads and releases one weak reference at a time and stops at the first late encoder. first_raw_ts is read only after first_received. One plan over all of them would take every reference and read every encoder up front (the obs-source: Port the deinterlace draw decisions #2153 pattern).
  • The group's start timestamp is still read under the group mutex.
  • start_ts is read once per branch condition, as before, and the paired encoder's start_ts once.
  • The packet's duration is computed only after the no-video check.
  • The setters keep their if chain. The active flag is loaded and initialized read only for a video encoder, so the gate is not scaled_gate(type, active, initialized), which would read both up front.

C keeps both util_mul_div64() conversions and passes their results in: the packet's duration (frames * 1e9 / samplerate) and the offset in frames (offset * samplerate / 1e9). On MSVC x64, util_mul_div64() is _udiv128(), which faults on a zero divisor or a quotient past 64 bits. C also keeps:

  • the deques and bfree();
  • obs_weak_encoder_get_encoder() and obs_encoder_release();
  • the group mutex and do_encode();
  • the pause checks and handle_encoder_group_reconfigure_request();
  • the fps_override free and create;
  • every log.

Six commits:

  1. Move (behaviour-neutral) into libobs/obs-encoder-audio-start.c.h: sixteen functions declared in the new obs-encoder-audio-start.h without EXPORT (hidden). The packet plan comes back as struct obs_encoder_audio_start_plan (four bools). The expressions move as they were, with their comments.

    The move was checked against the original code. A scratch harness (not committed) compiles origin/master's ten functions verbatim and the moved ones, as C++, over a stand-in encoder whose fields log every read and write. It also logs, in order:

    • every lock, weak reference and release;
    • every deque push, pop and free, bfree and memset;
    • util_mul_div64(), do_encode() (with the frame) and the pause checks;
    • the reconfigure, encoder_active(), every log line and the fps_override calls.

    Reads with no write or call between them are compared as a sorted run, because the C leaves their operand order unsequenced.

    • 8,000,000 runs: GCC and Clang -O2 (3,000,000 each), GCC -O0 (1,000,000), and ASan with UBSan under GCC -O0 and Clang -O2 (500,000 each).

    • Inputs:

      • audio encoders with 0 to 3 paired encoders (each alive or gone per call), started or not;
      • video starts at, one either side of, and one packet either side of each packet's start and end;
      • rates of 1 Hz to 384 kHz, blocksizes 0 to 32 and 1 to 8 planes;
      • buffered sizes below, at and above a frame, 0-frame packets, and pause checks that drop or move a packet;
      • video encoders in and out of a group, with group starts and paired first timestamps at, before and after each frame, and do_encode() failures;
      • both setters on audio, video and other types, active, initialized, divisor 0, with and without fps_override and media, and a NULL encoder.
    • 780,129,112 recorded events are equal, and so are the returns and the encoders after every run. gcov shows every branch of the original functions reached except one that cannot be (!paired_encoder being false in the unpaired branch).

    • Clang's UBSan ran without its pointer-overflow check. The harness fills each plane's buffer on its own, so master's push_back_audio() can add an offset to an empty plane's NULL data. Real libobs pushes every plane in step, so it never does.

    • 22 deliberately broken moves were tried, and 21 fail the harness:

      • fifteen changed decisions;
      • first_raw_ts read before first_received;
      • the walk not stopping at the first late encoder;
      • the duration computed before the no-video check;
      • start_ts read once for both branches;
      • the active flag loaded before the type check;
      • the group's start read outside the mutex.

      The 22nd, pushing when the offset equals the size, is equivalent: the size left is 0 either way.

    git blame on the moved lines shows only upstream commits (9aa18d3, 6cdfb0a, 03fa9ac, 20d8779 and earlier).

  2. Characterization: test_encoder_audio_start_steps, 20 cases. It compiles the moved file (ASan and UBSan) and calls only its functions. buffer_audio() and its helpers are also copied onto a stand-in encoder that counts the bytes buffered, with the real util_mul_div64(). That pins the start end to end against a video start at 48 kHz, at blocksizes 4 and 8 (mono and stereo float):

    • audio before the video by one sample (one frame dropped) and by one packet (it waits, then is cleared);
    • audio at the video;
    • audio after it by one sample and by one packet (cut at the video from the buffer);
    • a packet ending exactly at the video's start;
    • buffered audio below, at and above the offset;
    • the unpaired start and a started encoder.

    It is in the test graph, sorted, and links libm except on MSVC.

  3. RED: Tier 1 against todo!(). It ports the 20 C cases 1:1 and adds 7 edge tests: models of the C over every edge pair and around the video's start, a 4,096-case proptest of every decision, and a proptest of the stand-in over packet sequences against origin/master's code with its comparisons inline.

  4. GREEN: the safe core and sixteen #[no_mangle] shims, in a new libobs.ported-encoder-audio-start group whose PCH is the new header alone.

    • The commit updates source-sets.json, the three export lists and ci/test_ported_sources.py.
    • There is no _rust variant of the C test, as for test_encoder_size_steps: the shims' archive member also holds the rest of obs-output, which does not link on its own. Its tests.d file says so.
  5. Tier 3: a C oracle of the unchanged file, the parity tests, the proptest regression files and a mutation check.

  6. Docs: the README rows, the crate's description, lib.rs, and a port_comparison bench module in the sorted lists. docs/rust-port/naming.md gets its entry in the move commit.

The core denies clippy's arithmetic, as, indexing, unwrap, expect, panic, todo, unimplemented and unreachable lints. It keeps no state, takes no lock, and cannot panic on any input. Every sum, difference and product wraps as the C's unsigned arithmetic does:

  • size_t products use wrapping_mul;

  • the packet end is a wrapping_add, and the offset a wrapping_sub;

  • the (size_t) cast keeps the low bits;

  • the audio pts step uses wrapping_add_unsigned, which is the C's size_t sum converted back.

  • Kept, characterized, not endorsed:

    • The video pts step's uint32_t product wraps before it is added.
    • The conversion to frames rounds down. An offset under one frame (20,833 ns at 48 kHz) drops nothing, and one packet of 1024 frames is 1023 frames, so one frame of the earlier packet stays.
    • A packet whose end wraps past UINT64_MAX waits.
    • A waiting packet is still buffered whole.
    • A frame of 0 bytes is always ready to send.
  • Intentional difference: the video pts step past INT64_MAX, where the C's int64_t sum is undefined, wraps (wrapping_add). A pts never gets there. Tier 1 pins the wrap. Tier 3 calls the C only where the sum stays in range, which excludes exactly those inputs. This is listed in the parity test header and rust/README.md.

  • MSVC x64: nothing in the port or the oracle divides, and there is no INT64_MIN / -1. Both util_mul_div64() calls stay in C. The parity stand-in uses its own copy of the portable formula with a rate of at least 1, so no input can trap and nothing needs a cfg guard.

  • Tier 3 compares the oracle, the shims and the core exactly:

    • every pair of 34 special timestamps for the two-value decisions, and every triple for the packet plan (39,304 calls);
    • the sizes over every pair of 16 special usize values, 12 frame counts and the 34 timestamps;
    • both pts steps where the C is defined;
    • the setter type over every int from -65,536 to 65,536 and the extremes, and the divisor over 0 to 65,536 and the u32 edges;
    • the callers on the stand-in over 43,008 three-packet sequences around the video's start, comparing every push, clear, start from the buffer and send;
    • proptests (20,000 cases each) over full-range values and packet sequences.

    The oracle wrapper turns off -Wsign-conversion for the size_t pts sum, which libobs builds without, as calldata.c does.

  • Mutation check (not committed): 25 mutants, each run against Tier 1 (27 tests) and Tier 3 (10).

    Area Mutants Tier 1 kills Tier 3 kills Survivors
    core comparisons (group ready, paired late, packet wait, truncate, clear, from buffer, buffer offset, can send, each moved by one) 8 8 8 0
    core arithmetic (pts product widened, frames truncated, packet end, offset and audio pts saturating, offset one frame short) 6 6 6 0
    core branches (paired ignoring start, unpaired ignoring pairing, no_video inverted, push_size keeping Some(0), divisor 0 accepted) 5 5 5 0
    core, equivalent (not_video as "gate is not Check") 1 0 0 1, equivalent: scaled_gate(t, false, false) returns only NotVideo or Check
    shims (Wait also setting clear, truncate and clear swapped, None as the size, pairing flag negated, offset_ns arguments swapped) 5 0 5 0
  • Exported symbols: 1766 on the C backend, the hybrid and libobs-c-reference, with identical sets, unchanged from master. This was checked on the move, on GREEN and on the head. The sixteen functions are local (t) in all three. In the hybrid they come from the Rust archive: the group's object is built only for libobs-c-reference.

  • Performance (port_comparison, x86_64 Linux, GCC, release, not pinned, under load; median per 1024 calls):

    • buffer_audio: Rust 10.3 µs, C 8.3 µs;
    • receive_video: Rust 8.1 µs, C 6.1 µs.

    That is about 2 ns more per audio packet or video frame, at about 47 packets and 60 frames a second.

  • Not changed, noticed: libobs/obs-video-gpu-encode.c.h (the GPU encode thread) has its own copy of the group gate and the paired-encoder wait, with wait_for_audio instead of an early exit. It is out of this unit's scope; a later port could reuse _group_ready and _paired_late.

  • Overlap: round-8 unit 1 (deinterlace, rust/obs-source) is being prepared at the same time. The two share only the prose and bench lists, libobs.pch.h and source-sets.json, each entry in its own sorted place.

  • No user-visible change, so no docs/features.md line.

RED → GREEN

  • RED commit: 5e767df12 (3890091fa before the rebase). soldr cargo test -p obs-data --test obs-tests-core -- output::encoder_audio_start fails 27 of 27 with "not yet implemented". On 3890091fa, ci/local_gate.py --lane lint passed, and --test-diff origin/master failed only those 27.
  • GREEN: 5af15ba94 (a1abac555 before the rebase), Tier 1 27/27. The Tier 3 commit adds 10, for 37/37.
  • The branch was rebased once, onto e389f2fed. No conflicts. libobs/obs-encoder.c.h did not change on master, so the move harness result stands.
  • The runs before the rebase:
    • the move harness and its mutants, on the move commit a6c9cbb67;
    • the Rust mutation check, on Tier 3 4848f39e8;
    • the full ctest on adf224e08 (the head before the rebase; private Xvfb -noreset, dbus-run-session, a fresh HOME, ulimit -c 0, TMPDIR unset): 495/495 on the C backend and 519/519 against the hybrid libobs, each with 3 skips (test_pulse_default_follow, test_v4l2_vivid_replug and test_v4l2_vivid_stall, which need a PulseAudio default device or the vivid module). None of the known load flakes failed;
    • soldr cargo test -p obs-c-oracle --locked --bench port_comparison passes (400 benches);
    • soldr cargo clippy --workspace --target x86_64-pc-windows-msvc --all-targets --locked -- -D warnings passes.
  • The runs on the head a2aea7e3f:
    • both trees and libobs-c-reference rebuilt (ninja libobs-c-reference), all newer than the rebase. Exports are 1766 on all three, with identical sets and the sixteen functions local;
    • the encoder and output tests (test_encoder_audio_start_steps, test_encoder_size_steps, test_output_interleave, test_output_interleave_e2e, test_output_interleave_restart, test_output_delay_e2e, test_encoder_error_stop, test_encoding_lag_rescale, test_encoder_video_reset, test_multitrack_encoder_override, test_encoder_group_null, test_opus_mono_bitrate, test_mp4_mux_multichannel): 13/13 on the C backend, the hybrid libobs and libobs-c-reference, no skips. ldd confirms that the c-ref lane loads libobs-c-reference;
    • ci/local_gate.py --test-diff origin/master runs 3941 Rust tests, all passing (6 skipped, all #[ignore] in master). --lane lint and --lane cross pass;
    • the ci/ checks pass: build groups, ported sources, sorted shared lists, test graph sorted, naming, cmocka includes, cmocka Windows diagnostics, the rust-static guard, the oracle stand-ins and oracle MSVC checks, and the conversion card and measure checks.
  • Real app (UI, protocol output or logging changes): not applicable. There is no UI, protocol or log change.

Checklist

  • Base is master (or the description starts with a Stacked: note)
  • 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 (N/A for docs-only; a focused CI fix may push RED and GREEN together)
  • 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
  • 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
receive_video(), buffer_audio(), calc_offset_size(),
start_from_buffer(), push_back_audio(), receive_audio(),
send_audio_data(), obs_encoder_set_gpu_scale_type() and
obs_encoder_set_frame_rate_divisor() move to
libobs/obs-encoder-audio-start.c.h, as sixteen functions on plain values
declared in the new libobs/obs-encoder-audio-start.h without EXPORT
(hidden, as -fvisibility=hidden keeps them):

- receive_video(): _group_ready() (the group's start timestamp, read
  under the group mutex, equals the frame's), _paired_late() (a paired
  audio encoder's first raw timestamp is after the frame) and
  _video_pts() (cur_pts + timebase_num * frame_rate_divisor);
- buffer_audio(): _size() (frames * blocksize), _paired() and
  _unpaired() (the two branches), _no_video() and _packet(), which
  returns struct obs_encoder_audio_start_plan: wait (the packet ends at
  or before the video's start), truncate, clear and from_buffer;
- calc_offset_size(): _offset_ns() and _offset_size(), around the
  conversion to frames; start_from_buffer(): _buffer_offset();
  push_back_audio(): _push_size() (0 when the offset covers the packet);
- receive_audio(): _can_send() (the send loop); send_audio_data():
  _audio_pts();
- both setters: _not_video() (the first refusal) and _divisor_ok().

The decisions are one function each, not one plan per packet, so that
obs-encoder.c.h keeps every read where it was. The walk over the paired
encoders stays in C and asks _paired_late() for each encoder it reaches
that has received audio, so it still takes, reads and releases the weak
references one at a time and stops at the first late one; first_raw_ts
is read only after first_received. The group's start timestamp is read
under the mutex. start_ts is read once per branch condition, as before,
and the paired encoder's start_ts once. The setters keep their if chain:
the active flag is loaded and initialized read only for a video encoder.

C keeps both util_mul_div64() conversions: the packet's duration
(frames * 1e9 / samplerate) and the offset in frames (offset *
samplerate / 1e9), passed in by value. On MSVC x64 util_mul_div64() is
_udiv128(), which faults on a zero divisor or a quotient past 64 bits.
C also keeps the deques, bfree(), obs_weak_encoder_get_encoder() and
obs_encoder_release(), the group mutex, do_encode(), the pause checks,
handle_encoder_group_reconfigure_request(), the fps_override free and
create, and every log.

The expressions move as they were: the uint32_t product of the video
pts step, the size_t products and the uint64_t sum and difference. The
comments move with them.

Checked in a scratch harness (not committed). It compiles
origin/master's ten functions verbatim and the moved ones, as C++, over
a stand-in encoder whose fields log every read and write. It logs every
lock, weak reference, release, deque push, pop and free, bfree, memset,
util_mul_div64(), do_encode() (with the frame), pause check,
reconfigure, encoder_active(), log line and fps_override call, in
order. Reads with no write or call between them are compared as a
sorted run, since the C leaves their operand order unsequenced.
- Inputs: audio encoders with 0 to 3 paired encoders (each alive or
  gone per call), started or not; video starts at, one either side of
  and one packet either side of each packet's start and end; rates of
  1 Hz to 384 kHz, blocksizes 0 to 32 and 1 to 8 planes; buffered sizes
  below, at and above a frame; 0-frame packets; pause checks that drop
  or move a packet. Video encoders in and out of a group, with group
  starts and paired first timestamps at, one before and one after each
  frame, and do_encode() failures. Both setters on audio, video and
  other types, active, initialized, divisor 0, with and without
  fps_override and media, and a NULL encoder.
- 8,000,000 runs (GCC and Clang -O2, 3,000,000 each; GCC -O0,
  1,000,000; ASan with UBSan under GCC -O0 and Clang -O2, 500,000 each)
  give equal events, equal returns and equal encoders after each run:
  780,129,112 events.
- Clang's UBSan runs without its pointer-overflow check: the harness
  fills each plane's buffer independently, so master's push_back_audio()
  can add an offset to an empty plane's NULL data. Real libobs pushes
  every plane in step, so it never does.
- Every branch of the original functions is reached (gcov) except
  !paired_encoder being false in the unpaired branch, which cannot be.
- 22 deliberately broken moves were planted. 21 fail it: fifteen
  changed decisions (each comparison moved by one, the duration or the
  divisor dropped, a pts off by one, the type and divisor rules
  inverted), first_raw_ts read before first_received, the walk not
  stopping at the first late encoder, the duration computed before the
  no-video check, start_ts read once for both branches, the active flag
  loaded before the type check, and the group's start read outside the
  mutex. The 22nd, pushing when the offset equals the size, is
  equivalent: the size left is 0 either way.

git blame on the moved lines shows only upstream commits (9aa18d3,
6cdfb0a, 03fa9ac, 20d8779 and earlier). The fork has not changed
them.

The constant OBS_ENCODER_VIDEO is copied into the header, so it needs no
core header; obs-encoder.c.h checks it with _Static_assert. The new
file joins libobs.core-output, just before obs-encoder.c.h, with
libobs.pch.h, which includes the new header; source-sets.json lists it.
docs/rust-port/naming.md maps it to rust/obs-output. The exported symbol
sets are unchanged (1766); the sixteen functions are local.

Refs obs-rust#2320
test_encoder_audio_start_steps compiles
libobs/obs-encoder-audio-start.c.h (ASan and UBSan) and calls only its
sixteen functions through obs-encoder-audio-start.h. 20 cases:

- receive_video(): the group gate over every pair of edge timestamps,
  the paired wait (late only when the audio's first timestamp is after
  the frame), and the pts step, whose uint32_t product wraps before it
  is added;
- buffer_audio(): the packet size at blocksizes 4 and 8 and the size_t
  edges, both branches against started and not started, no video, and
  the plan: a packet ending before or exactly at the video's start
  waits; one ending a nanosecond into it starts truncated and cleared;
  at the video it is cleared; after it, it starts from the buffer; a
  0-frame packet; and an end that wraps past UINT64_MAX;
- the offset in nanoseconds and bytes, the buffer offset, the push size
  with the offset below, at and above the packet, the send loop and the
  audio pts step;
- the setters: every type other than OBS_ENCODER_VIDEO refused first
  (outside the enum too), and divisor 0.

buffer_audio(), start_from_buffer(), calc_offset_size() and
push_back_audio() are also copied onto a stand-in encoder that counts
the bytes buffered, with the real util_mul_div64(), to pin the start
end to end against a video start at 48 kHz: audio before it by one
sample (one frame dropped) and by one packet (waits, then is cleared),
at it, after it by one sample and one packet (cut at the video from the
buffer), a packet ending exactly at it, buffered audio below, at and
above the offset, the unpaired start and a started encoder, at
blocksizes 4 and 8 (mono and stereo float).

Characterized, not endorsed:
- the video pts step's uint32_t product wraps;
- an offset of less than one frame (20833 ns at 48 kHz) drops nothing,
  and 21333333 ns (one packet of 1024 frames) is 1023 frames, so one
  frame of the earlier packet stays: the conversion rounds down;
- a packet whose end wraps past UINT64_MAX waits;
- a waiting packet is still buffered whole;
- a frame size of 0 bytes is always ready to send;
- the offset and pts arithmetic wraps in size_t and uint64_t.

It is in the native test graph, in name order, and links libm off MSVC.
No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x.
The real-libobs tests test_output_interleave_e2e,
test_output_interleave_restart, test_output_delay_e2e,
test_encoder_error_stop, test_encoding_lag_rescale,
test_encoder_video_reset and test_multitrack_encoder_override cover the
callers.

Refs obs-rust#2320
RED for the port of libobs/obs-encoder-audio-start.c.h to a new
encoder_audio_start module of rust/obs-output, next to encoder_size and
encoder_roi. The safe core is a stub (todo!()): group_ready(),
paired_late(), video_pts(), packet_size(), paired_start(),
unpaired_start(), no_video(), packet_start() -> PacketStart { Wait,
Start { truncate, clear, from_buffer } }, offset_ns(), offset_size(),
buffer_offset(), push_size() -> Option<usize>, can_send(), audio_pts(),
not_video() and divisor_ok(), with OBS_ENCODER_VIDEO taken from
encoder_size.

tests/output/encoder_audio_start.rs ports test_encoder_audio_start_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, the stand-in encoder written in Rust over the core.

Edge cases (edge_*) check the core against models of the original C:
the packet plan over timestamps around every edge and video start with
seven durations; the plan's flags consistent (exactly one of clear and
from_buffer, truncate only with clear); the setter type over -8..=8 and
the i32 extremes; the pts wraps; every pair of edge sizes and
timestamps for the two-value decisions; a proptest of every decision
over full-range values (4,096 cases); and a proptest of the stand-in
over packet sequences against the origin/master code with its
comparisons inline.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_audio_start fails 27 of 27 with "not yet implemented".

Refs obs-rust#2320
Ports libobs/obs-encoder-audio-start.c.h, the encoder audio start
alignment and the setter gates of obs-encoder.c, to the
encoder_audio_start module of rust/obs-output. obs-encoder.c.h stays C
around it: every read of the encoder, its group and its paired encoders,
the group mutex, the weak references and releases, the deques, bfree(),
do_encode(), the pause checks, the group reconfigure, the active and
initialized checks, the fps_override free and create, the logs and both
util_mul_div64() conversions. The hybrid libobs drops the C file and
links the Rust shims in its place.

Safe core (src/encoder_audio_start.rs):
- group_ready(), paired_late(), buffer_offset() and can_send(): the C's
  ==, >, < and >=;
- paired_start() and unpaired_start(): start_ts 0 with and without a
  paired encoder; no_video(): a video start of 0;
- packet_start(): Wait when timestamp + duration (a wrapping sum) is at
  or before the video's start, else Start { truncate (before), clear
  (at or before), from_buffer (after) };
- packet_size(), offset_size(): size_t products, wrapping; offset_size
  keeps the low bits of the u64 that fit usize, as the C's (size_t)
  cast; offset_ns(): a wrapping difference;
- push_size(): None when the offset covers the size, else the rest
  (never Some(0));
- video_pts(): cur_pts plus the wrapping u32 product, added with
  wrapping_add; audio_pts(): wrapping_add_unsigned, the C's size_t sum
  converted back;
- not_video(): encoder_size::scaled_gate()'s first refusal, reused;
  divisor_ok(): not 0.
The module denies clippy's arithmetic, as, indexing, unwrap, expect,
panic, todo, unimplemented and unreachable lints, keeps no state and
takes no lock.

Shims (src/ffi/encoder_audio_start.rs): the sixteen functions keep the
C signatures. struct obs_encoder_audio_start_plan is mirrored #[repr(C)]
(four bools); Wait sets wait alone. push_size's None is 0. No pointer
crosses.

Intentional difference: the video pts step past INT64_MAX, where the
C's int64_t sum is undefined, wraps. A pts never gets there.

C side: the file leaves libobs.core-output for its own group,
libobs.ported-encoder-audio-start (LIBOBS_PORTED_SOURCES), whose PCH is
only obs-encoder-audio-start.h; libobs.pch.h keeps the header for
obs-encoder.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 every host.

test_encoder_audio_start_steps still compiles the C file into itself,
unchanged. It has no _rust variant, as for test_encoder_size_steps: the
shims' archive member also holds the rest of obs-output, which needs
libobs's hidden seams and obs-util, so it does not link on its own. Its
tests.d file says so.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_audio_start passes 27 of 27.

Refs obs-rust#2320
Tier 3 for the encoder_audio_start port. oracle/encoder_audio_start.c
compiles the unchanged libobs/obs-encoder-audio-start.c.h with its
sixteen functions renamed to oracle_*, plus the constant and the layout
of struct obs_encoder_audio_start_plan as the C sees them. The pts step
of send_audio_data() adds a size_t to an int64_t and converts the sum
back, which trips the oracle's -Wsign-conversion (libobs builds without
it), so the wrapper turns that warning off, as calldata.c and
audio_controls.c do.

tests/output/encoder_audio_start_parity.rs runs every check on three
sides, the oracle, the shims and the core, and compares them exactly:
- the constant, and the plan's size, alignment and field offsets
  against both Rust mirrors;
- every two-value decision over every pair of 34 special u64 values
  (the edges, and timestamps around a packet and a video start);
- the packet plan over every triple of them (39,304 calls);
- the sizes over every pair of 16 special usize values, 12 frame counts
  and the 34 u64 values;
- both pts steps over special values, the video step only where the C
  is defined;
- the setter type over every int from -65,536 to 65,536 and the
  extremes, the divisor over 0 to 65,536 and the u32 edges;
- the callers (buffer_audio(), start_from_buffer(), calc_offset_size(),
  push_back_audio() and the send loop) on the C test's stand-in encoder,
  over every combination of eight flags, six rates (1 Hz to 384 kHz),
  four blocksizes and seven offsets around the video's start (43,008
  three-packet sequences), comparing every push, clear, start from the
  buffer and send;
- proptests, 20,000 cases each, of every decision over full-range
  values and of the callers over packet sequences.

Nothing here divides: both util_mul_div64() conversions stay in C, and
the stand-in uses its own copy of the portable formula with a rate of
at least 1, so the MSVC x64 _udiv128() trap cannot be reached and
nothing needs a cfg guard. No input is INT64_MIN / -1.

Intentional difference, listed in the test header: the video pts step
past INT64_MAX (or below INT64_MIN), where the C's int64_t sum is
undefined, wraps in the port. The oracle is called only where the sum
stays in range, which excludes exactly those inputs; Tier 1 pins the
wrap.

Mutation check (not committed): 25 mutants, each run against Tier 1
(27 tests) and Tier 3 (10).
- 20 in the core: each comparison moved by one, the pts product widened,
  the frame count truncated, the wrapping sums and differences
  saturating, an offset one frame short, push_size keeping Some(0), the
  branches ignoring start_ts or the pairing, no_video inverted and
  divisor 0 accepted. Tier 1 and Tier 3 kill 19. The 20th, not_video()
  as "the gate is not Check", is equivalent: scaled_gate() with both
  flags false returns only NotVideo or Check.
- 5 in the shims: Wait also setting clear, truncate and clear swapped,
  None as the size, the pairing flag negated, offset_ns arguments
  swapped. Tier 3 kills all 5; Tier 1 calls the core and kills none.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_audio_start passes 37 of 37 (Tier 1 27, Tier 3 10).

Refs obs-rust#2320
The rust/README.md rows for the encoder_audio_start port: the
obs-output crate row names libobs/obs-encoder-audio-start.c.h, and its
own row in the ported-units table says what moved, what stays C and
why there is one function per decision, the characterized behaviours,
the intentional difference (the video pts step past INT64_MAX wraps),
the tests that see the swap and what Tier 3 covers. The obs-output
Cargo description and the lib.rs crate docs name the new module.
docs/rust-port/naming.md already maps the file to rust/obs-output (the
move commit).

The port_comparison bench gets an encoder_audio_start module, in the
sorted mod and modules![...] lists: buffer_audio's decisions over 1024
packets around a video start, and receive_video's group gate, paired
walk and pts step over 1024 frames, Rust shims against the C oracle
with a checksum both must match. It allocates nothing, so the module's
bmem check has nothing to free.

No user-visible change, so no docs/features.md line.

Fixes obs-rust#2320
@rdoupe
rdoupe force-pushed the port/encoder-audio-start branch from 3890091 to a2aea7e Compare October 25, 2026 03:58
@rdoupe
rdoupe marked this pull request as ready for review October 25, 2026 03:59
@rdoupe
rdoupe requested a review from zackees as a code owner October 25, 2026 03:59
@rdoupe
rdoupe added this pull request to the merge queue Oct 25, 2026
Merged via the queue into obs-rust:master with commit 539b1c5 Oct 25, 2026
35 checks passed
vpacher pushed a commit to vpacher/obs-studio that referenced this pull request Oct 26, 2026
* libobs: Move the GPU encode thread gates

Behaviour-neutral extraction before the Rust port. The decisions of
gpu_encode_thread() and init_gpu_encoding() move to
libobs/obs-encoder-gpu-gates.c.h, as eleven functions on plain values
declared in the new libobs/obs-encoder-gpu-gates.h without EXPORT
(hidden, as -fvisibility=hidden keeps them):

- for each frame: _warming() and _warm_next() (the frames skipped
  while the thread starts);
- for each encoder: _divisor_inc(), _divisor_wrap() and
  _divisor_skip() (the frame rate divisor counter), _next_key() (the
  keyed mutex key it hands on) and _record_timing() (the frame timing
  entry);
- after the walk: _count_next(), _requeue() and _requeue_ts();
- init_gpu_encoding(): _p010() (P010 or NV12 textures).

The group start, the paired audio wait and the pts step are the gates
receive_video() already asks (obs-rust#2331), so the thread now asks the same
functions: obs_encoder_audio_start_group_ready(), _paired_late() and
_video_pts(). The raw and GPU paths share one implementation.

One function per decision, asked where the C made it, so every read
stays where it was. The divisor counter is still read, written with
the increment, read again and compared, and written 0 at the wrap, in
that order. The group's start_timestamp is still read under the group
mutex for each encoder, after the group and start_ts tests; the walk
over the weak paired encoders still takes and releases each reference
and stops at the first one not ready, and first_raw_ts is read only
after first_received.

C keeps os_sem_wait(), the stop flag, gpu_encoder_mutex and the group
mutex (no section merged), the deques, obs_encoder_get_ref() and
_release(), the weak paired-encoder walk, the failed flag (an atomic
load), the group and first_received tests, video_pause_check(),
handle_encoder_group_reconfigure_request() and info.update, the
start_ts test and write, the NULL test of encode_texture2, both encode
calls, os_gettime_ns(), the timing entry, send_off_encoder_packet(),
the profiler, the texture creates, obs_host_texture_shared_handle(),
stop_gpu_encoding_thread() and free_gpu_encoding(). The truth tests of
a single field (the atomic failed flag, the NULL callback, start_ts)
stay C as in receive_video(); the plan's encode_call() and the failed
skip are those.

The expressions move as they were: the int counts, the uint32_t
counter sum, the uint64_t key and timestamp sums and the uint32_t pts
product. The pts step still follows every encode, failed or not.

The plan named the file obs-video-gpu-encode-gates.c.h; naming.md maps
obs-video-* to rust/obs-core and the encoder files to rust/obs-output,
where this port goes (encoder_gpu_gates, beside encoder_audio_start),
so it is obs-encoder-gpu-gates.c.h.

Checked in a scratch harness (not committed). It compiles
origin/master's gpu_encode_thread() and init_gpu_encoding() verbatim,
and this branch's with the moved file and obs-encoder-audio-start.c.h,
as C++, over a stand-in video and encoders whose fields log every read
and write with the value. It logs every lock and unlock, atomic load,
os_sem_wait(), deque pop and push (with the frame), reference taken
and released, weak reference resolved, video_pause_check(), group
reconfigure, info.update, encode call (with the texture, pts, key and
next key), os_gettime_ns(), timing entry, packet send, profiler call,
texture create, shared handle and init call, in order. The stubs
answer from one seeded stream in call order (encoders may move
next_key, fail, or return a packet); another thread moves the group
start, first_received, first_raw_ts, the failed flag, start_ts, the
reconfigure flag and the stop flag around each lock and call. Reads
with no write or call between them are compared as a sorted run,
since the C leaves their operand order unsequenced.
- Inputs: 0 to 8 frames, 0 to 5 queued frames with counts -1 to 4,
  keys up to full range and timestamps of 0, near UINT64_MAX, around
  2^32 and 2^63 and random, popped or made up; 0 to 5 texture encoders
  and 0 to 2 audio ones, failed or not, in 0 to 2 groups with any
  start, with or without encode_texture2, divisors 0 to 4 and full
  range, counters below, at and past them, timebases to UINT32_MAX,
  0 to 3 paired encoders each (dead weak references among them);
  intervals of one 60 fps frame, random and near UINT64_MAX; every
  video format 0 to VIDEO_FORMAT_R10L; failing texture creates,
  os_sem_init(), os_event_init() and pthread_create().
- 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 an equal end state
  (every encoder's fields and timing entries, both queues, the video's
  flags and the groups): 485,800,492 events.
- Every branch of origin/master's functions is reached both ways
  (gcov).
- 24 deliberately broken moves were planted and all 24 fail it: the
  group start read before the group mutex, first_raw_ts read before
  first_received, the paired walk not stopping, start_ts read before
  the group test, the divisor counter written once, compared without
  the second read, or stepped before the pause check, the reference
  loop merged into the walk's lock section, and sixteen changed
  decisions (each comparison moved by one or inverted, the warm-up and
  counter steps by two, the key not stepped or stepped on the wrong
  count, the pts only after a successful encode, the count not stored,
  the timestamp saturating, the P010 test on NV12, the group and
  paired gates with >=).

git blame on the moved lines shows only upstream commits (93ba6e7,
6cdfb0a, 6a53b89, c288d42, 7e39ee2, a1fbf10). The fork has
not changed them.

The constants NUM_ENCODE_TEXTURE_FRAMES_TO_WAIT and VIDEO_FORMAT_P010
are copied into the header, so it needs no core header;
obs-video-gpu-encode.c.h checks them with _Static_assert. The new file
joins libobs.core-output, just before obs-encoder.c.h, with
libobs.pch.h, which includes the new header; source-sets.json lists
it. obs-encoder-audio-start.h notes the thread as a caller.
docs/rust-port/naming.md maps the file to rust/obs-output. The
exported symbol sets are unchanged (1766) on the C, hybrid and C
reference libobs; the eleven functions are local.

Refs obs-rust#2476

* test: Characterize the GPU encode thread gates

test_encoder_gpu_gates_steps compiles libobs/obs-encoder-gpu-gates.c.h
and libobs/obs-encoder-audio-start.c.h (the gates the thread shares
with receive_video()) with ASan and UBSan, and calls only their
functions through obs-encoder-gpu-gates.h and obs-encoder-audio-start.h.
16 cases:

- the copied constants (one frame skipped, VIDEO_FORMAT_P010);
- the start-up wait over edge int values, and the count of frames it
  skips;
- the divisor counter's sum (UINT32_MAX wraps to 0), wrap and skip
  over every pair of edge uint32_t values;
- the key over every triple of edge counts and keys (the last encoder
  hands on 0, any other the next key, which wraps);
- the timing entry, the count, the requeue and the requeue timestamp
  over edge values (the sum wraps past UINT64_MAX);
- the texture format over every enum video_format value and the int
  extremes;
- the shared gates as the thread asks them.

The per-frame body of gpu_encode_thread() is also copied onto stand-in
encoders (no thread, lock or texture; a failed encode stops the
encoder, as send_off_encoder_packet()'s full_stop() does), to pin end
to end: two encoders started on the same frame with divisors 1, 2 and
3 encode on the same frames (the reason for the explicit counter), and
one a frame in is out of step; the keys when every encoder encodes,
with one encoder and wrapping; the keys when one skips for each of its
four reasons; the group start; the paired audio wait, past a dead weak
reference and on one with no audio yet; the pts after a failed encode;
the timing entry for a frame with and without a timestamp; and frames
with counts 1, 2 and 3, near UINT64_MAX, and with no encoder.

Characterized, not endorsed:
- when an encoder in the list skips the frame, the last key handed on
  is not 0 and the frame keeps it (upstream; the Windows keyed mutex
  code is written around it);
- the pts steps after a failed encode, where receive_video() steps it
  only after a successful one (the failure stops the encoder either
  way);
- a divisor of 0 (the setter refuses it) encodes the first frame, then
  none until the uint32_t counter wraps.

It is in the native test graph, in name order, with both headers as
watch inputs, and links libm off MSVC. No assert_in_range or fail_msg,
so it builds with cmocka 1.x and 2.x, and no comparison between two
enum types (MSVC C5287). The real-libobs tests test_encoder_error_stop,
test_texture_encoder_raw_format and test_encoder_join_keyframe cover
the thread.

Refs obs-rust#2476

* obs-output: Add Tier 1 tests for GPU encode gates

RED for the port of libobs/obs-encoder-gpu-gates.c.h to a new
encoder_gpu_gates module of rust/obs-output, next to
encoder_audio_start. The safe core is a stub (todo!()): warming(),
warm_next(), divisor_inc(), divisor_wrap(), divisor_skip(),
next_key(), record_timing(), count_next(), requeue(), requeue_ts()
and p010(), with WAIT_FRAMES and VIDEO_FORMAT_P010. It re-exports
encoder_audio_start's group_ready(), paired_late() and video_pts(),
the gates the thread shares with receive_video(), already ported.

tests/output/encoder_gpu_gates.rs ports test_encoder_gpu_gates_steps
1:1: its 16 cases under the same names (steps_*), in the same order,
with the same values and expectations, the characterized-not-endorsed
cases included, the stand-in thread pass written in Rust over the
core.

Edge cases (edge_*) check the core against models of the original C:
the int counts at and around i32::MIN and i32::MAX; every divisor
counter and divisor below 64, and the counter sequence of every
divisor up to 64 over 200 frames against the C's post-increment; the
key over every count and encoder number below 16; every format from
-1000 to 1000; a proptest of every decision over full-range values
(4,096 cases); and a proptest of the stand-in over encoder lists and
frame sequences against the origin/master code with its expressions
inline.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_gpu_gates passes 2 of 22 (the constants and the
shared gates, already ported) and fails 20 with "not yet
implemented".

Refs obs-rust#2476

* obs-output: Port the GPU encode thread gates

Ports libobs/obs-encoder-gpu-gates.c.h, the per-frame and per-encoder
gates of the GPU encode thread, to the encoder_gpu_gates module of
rust/obs-output. obs-video-gpu-encode.c.h stays C around it:
os_sem_wait(), the stop flag, gpu_encoder_mutex and the group mutex,
every read of the video, the frame, the encoders, their groups and
paired encoders, the weak paired-encoder walk, the pause check, the
group reconfigure, both encode calls, os_gettime_ns(), the timing
entry, the packet send, the deques, the references, the profiler and
the texture creates. The hybrid libobs drops the C file and links the
Rust shims in its place.

Safe core (src/encoder_gpu_gates.rs):
- warming(), divisor_skip(), record_timing() and requeue(): not 0;
- warm_next() and count_next(): a wrapping i32 difference;
- divisor_inc(): a wrapping u32 sum; divisor_wrap(): the C's ==;
- next_key(): 0 when lock_count equals the number of encoders, else
  the next key (a wrapping u64 sum);
- requeue_ts(): a wrapping u64 sum;
- p010(): the format is VIDEO_FORMAT_P010 (18);
- group_ready(), paired_late() and video_pts() re-exported from
  encoder_audio_start: the thread calls those shims, as receive_video()
  does, so both paths share one implementation.
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/encoder_gpu_gates.rs): the eleven functions keep the C
signatures (int as c_int). No pointer crosses and no struct is
mirrored. The keys are the u64 the C computes, so the Windows keyed
mutex code (obs_host_tex_frame_acquire/_release) is untouched.

Intentional difference: warm_next() and count_next() at INT_MIN, where
the C's int subtraction is undefined, wrap. The thread starts the wait
at 1 and a frame's count at 1 or more.

C side: the file leaves libobs.core-output for its own group,
libobs.ported-encoder-gpu-gates (LIBOBS_PORTED_SOURCES), whose PCH is
only obs-encoder-gpu-gates.h; libobs.pch.h keeps the header for
obs-video-gpu-encode.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 every host. The exported
symbol sets are unchanged (1766) on the C, hybrid and C reference
libobs.

test_encoder_gpu_gates_steps still compiles the C file into itself,
unchanged. It has no _rust variant, as for
test_encoder_audio_start_steps: the shims' archive member also holds
the rest of obs-output, which needs libobs's hidden seams and
obs-util, so it does not link on its own. Its tests.d file says so.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_gpu_gates passes 22 of 22. Through ctest (private
Xvfb and D-Bus, own HOME, no sound), test_encoder_gpu_gates_steps,
test_encoder_audio_start_steps, test_encoder_error_stop (the texture
encoder and its teardown races), test_texture_encoder_raw_format,
test_encoder_join_keyframe (with real x264, VA-API H.264 and HEVC, AOM
and SVT-AV1), test_encoding_lag_rescale,
test_multitrack_encoder_override, test_encoder_video_reset,
test_video_output_step_steps, test_output_interleave_e2e,
test_encoder_group_null and test_encoder_tex_active_null pass, 12 of
12, against the C, hybrid and C reference libobs.

Refs obs-rust#2476

* obs-output: Check the GPU encode gates against C

Tier 3 for the encoder_gpu_gates port. The oracle
(rust/obs-c-oracle/oracle/encoder_gpu_gates.c) compiles the unchanged
libobs/obs-encoder-gpu-gates.c.h with its eleven functions renamed to
oracle_*, plus its two constants, bound in src/encoder_gpu_gates.rs.
Nothing in it divides.

tests/output/encoder_gpu_gates_parity.rs compares the oracle, the
shims and the core exactly, all three sides:
- the two constants;
- the int gates (warming, warm_next, count_next, requeue) over
  -100,000 to 100,000, the 100,000 values above INT_MIN and below
  INT_MAX, and a stride through all of i32 both ways;
- the divisor sum, wrap and skip over every pair of counters and
  divisors below 256 and every pair of 20 special u32 values, and the
  sum over 0 to 1,000,000 and a stride through all u32;
- the key over every count and encoder number below 64 with 16
  special keys, and every pair of 9 special usize values with 24
  special keys;
- the timing entry and the requeue timestamp over every pair of 24
  special u64 values (around 0, 2^32, 2^63, a 60 fps frame and
  u64::MAX); the format over -100,000 to 100,000, the extremes and a
  stride through all i32;
- the per-frame body of gpu_encode_thread() (the C test's stand-in)
  on the oracle, with the oracle's shared group, paired and pts gates,
  and on the shims: every list of one to three encoders with divisors
  and counters 0 to 3 (4,368 lists) through eight frames with counts
  1 to 3 at two intervals, comparing every encode, key, pts, counter,
  timing entry and requeue; each reason a middle encoder skips, fails
  or moves the key;
- proptests (20,000 cases each) of every decision over full-range
  values and of the stand-in over encoder lists and frame sequences
  from any state.

The oracle is called for warm_next() and count_next() only above
INT_MIN, where the C's subtraction is defined; that excludes exactly
the intentional difference. Otherwise no input is excluded.

Mutation check (once, not committed): 21 mutants, 15 in the core and
6 in the shims.

  mutant                                  Tier 1  Tier 3
  warming: > 0                                 3       2
  warm_next: - 2                               3       2
  warm_next: saturating                        1       0
  divisor_inc: saturating                      2       1
  divisor_wrap: >=                             5       4
  divisor_skip: > 1                            5       3
  next_key: >=                                 3       2
  next_key: saturating                         3       1
  next_key: the last keeps the key             5       5
  record_timing: inverted                      4       5
  count_next: never below 0                    4       2
  requeue: > 0                                 4       2
  requeue_ts: saturating                       4       4
  p010: NV12                                   2       1
  WAIT_FRAMES = 2                              2       1
  shim p010 inverted                           0       2
  shim next_key: key + 1                       0       5
  shim requeue_ts: interval - 1                0       4
  shim divisor_skip: skip + 1                  0       4
  shim record_timing: always                   0       2
  shim divisor_wrap: arguments swapped         0       0

(failing tests per tier.) Tier 1 kills all 15 core mutants, Tier 3 19
of 21. The survivors: warm_next() saturating differs only at INT_MIN,
the intentional difference Tier 3 does not ask the C (Tier 1 pins
it), and the shim's divisor_wrap() with the arguments swapped compares
them the same way.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_gpu_gates passes 32 of 32 (22 Tier 1, 10 Tier 3).

Refs obs-rust#2476

* docs: Record the GPU encode thread gates port

rust/README.md gets the row for libobs/obs-encoder-gpu-gates.c.h
(obs-output::encoder_gpu_gates), after encoder_audio_start's: what
moved, the three gates shared with receive_video(), what stays C and
why, the characterized-not-endorsed behaviours (the last key not 0
when an encoder skips, the pts step after a failed encode, a divisor
of 0), the one intentional difference and the tests that cover it;
the obs-output crate row, its Cargo description and lib.rs name the
new module. docs/rust-port/naming.md already maps the file to
rust/obs-output (the move commit).

rust/obs-c-oracle/benches/port_comparison/encoder_gpu_gates.rs, in
the sorted module list, runs 1024 frames (counts 1 to 3) through four
encoders with divisors 1 to 4, asking every decision
gpu_encode_thread() asks for each frame and encoder, on the shims and
on the oracle, and checks both checksums match. Release, x86_64
Linux, GCC, a loaded host (load average about 10), median: Rust
51.28 us, C 47.80 us (1.07x), about 12 ns per frame and encoder
against 11.7 ns, next to an encode call.

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

Fixes obs-rust#2476
@rdoupe rdoupe mentioned this pull request Oct 26, 2026
6 of 7 tasks
vpacher pushed a commit to vpacher/obs-studio that referenced this pull request Oct 26, 2026
* libobs: Move the encoder binding checks

Behaviour-neutral extraction before the Rust port. The decisions of
obs_encoder_set_video(), encoder_set_video(), obs_encoder_set_audio(),
the media getters and obs_encoder_shutdown_unstarted() move to
libobs/obs-encoder-bind.c.h, as six functions on plain values declared
in the new libobs/obs-encoder-bind.h without EXPORT (hidden, as
-fvisibility=hidden keeps them):

- obs_encoder_set_audio() and obs_encoder_audio(): _not_audio() (the
  type refusal);
- encoder_set_video(): _video_timebase() (fps_den over fps_num, or 0
  over 0 with no video) and _divisor_override() (the frame rate
  divisor video is created for a divisor that is not 0);
- obs_encoder_set_audio(): _audio_timebase() (1 over the sample rate,
  or 0 over 0 with no audio);
- obs_encoder_shutdown_unstarted(): _locked() (each
  pthread_mutex_trylock() result) and _shutdown_unstarted() (shut down
  when initialized and not needed).

The video type refusal of obs_encoder_set_video(), obs_encoder_video(),
obs_encoder_parent_video() and obs_encoder_unbind_video() is the one
obs_encoder_set_gpu_scale_type() and obs_encoder_set_frame_rate_divisor()
already ask (obs-rust#2331), obs_encoder_audio_start_not_video(), so they ask
it too; obs-encoder-audio-start.h notes the new callers.

One function per decision, asked where the C made it, so every read
stays where it was. The plan's combined gates (type, active and
initialized in one call; unbind and rebind as one decision each; the
getters' override choice) would read the active flag, initialized,
media or fps_override where the C's && and early returns do not, so
they are split as obs_encoder_set_gpu_scale_type() already is: the
type refusal is a function, and the single-field tests stay C in their
order (the active flag, an atomic, loaded where it always was;
initialized; media; fps_override; context.data). Nothing is left to
decide in obs_encoder_shutdown() (the context.data test and the resets
are single fields and constants) or obs_encoder_rebind_video() (three
single-field tests in an && chain), so they are unchanged.

C keeps init_mutex and outputs_mutex, both pthread_mutex_trylock()
calls (their results are passed) and their unlock order, the walk over
videos (it computes bound and stops at the first match) and the walk
over encoder->outputs (it computes needed and stops at the first output
that needs the encoder), obs_encoder_shutdown() with info.destroy,
maybe_clear_encoder_core_video_mix() and the paired-encoder weak
releases, obs_encoder_set_last_error(), video_output_get_info(),
audio_output_get_sample_rate(), the fps_override free and create,
every warning and every write to the encoder. No lock section is
merged and nothing divides.

One order changes, inside a branch with no lock or call in it: the
timebase reads the video's fps_num and fps_den (and the audio's sample
rate) before it writes timebase_num, where the C wrote timebase_num
between them. Those are the video's and audio's info, which nothing
writes after they are created; the encoder's writes keep their order
(media, timebase_num, timebase_den).

Checked in a scratch harness (not committed). It compiles
origin/master's ten functions (the four setters and getters of each
kind, encoder_set_video(), obs_encoder_shutdown(), _shutdown_unstarted(),
_unbind_video() and _rebind_video()) verbatim, and this branch's with
the moved file and obs-encoder-audio-start.c.h, with every read and
write of an encoder field rewritten the same way into a logged access
(with the value), over a stand-in encoder, videos and audios. It logs
every lock, unlock and trylock (with its result), atomic load,
obs_encoder_valid(), obs_output_needs_encoders(), video_output_get_info()
and the video info reads, the sample rate, the divisor free and create,
info.destroy, the weak releases, the last error, the mix clear and each
warning, in order. Another thread flips the active flag and the
outputs' needs at every lock and call, and initialized and the divisor
while init_mutex is not held. The run from the media write to the
timebase_den write is compared as a sorted run (the reorder above), and
must hold nothing but the info reads and the timebase_num write.
- Inputs: audio, video and unknown encoder types, NULL encoders,
  active or not, initialized or not, with or without context.data,
  media (none, any of six videos or four audios), fps_override and
  divisors 0, 1, 2 and UINT32_MAX; frame rates of 30000/1001, 60/1,
  0/1, 0 and UINT32_MAX; sample rates of 0, 44100, 48000 and
  UINT32_MAX; 0 to 4 outputs, 0 to 3 videos to unbind from, 0 to 2
  paired encoders, busy trylocks; one to six calls in a row.
- 2,900,000 runs (GCC and Clang -O2, 1,000,000 each; GCC -O0, 500,000;
  ASan with UBSan under GCC -O0 and Clang -O2, 200,000 each) give
  equal events and an equal end state (every encoder field, the
  outputs, the mutexes and the stubs' state): 80,633,324 events.
- Every branch of origin/master's functions is reached both ways
  (gcov, 72 of 72).
- 25 deliberately broken moves were planted and all 25 fail it: the
  active flag read before the type refusal (both setters), initialized
  read with the active flag, fps_override read before the type, the
  video info or sample rate read before the media write, the divisor
  read before the timebase write, the trylocks or unlocks swapped,
  initialized read before the outputs walk, the walk not stopping, the
  active flag read before init_mutex in unbind, the rebind && order
  changed, the wrong type refusal in four places, and nine changed
  decisions (the type test inverted, the video timebase not swapped,
  a timebase of 1 with no video or audio, an audio timebase of 0 over
  the rate, a divisor of 1 with no override, the trylock test
  inverted, || for && and needed ignored in the shutdown).

git blame on the moved lines shows upstream commits (eb0d9dc,
f07ce85, f53df7d, dfc20bb, d584aed) and two of the fork's
(7041590, the unstarted shutdown; c651ea2, the unbind and rebind).

OBS_ENCODER_AUDIO is copied into the header, so it needs no core
header; obs-encoder.c.h checks it with _Static_assert. The new file
joins libobs.core-output, just before obs-encoder.c.h, with
libobs.pch.h, which includes the new header; source-sets.json lists
it. docs/rust-port/naming.md maps the file to rust/obs-output. The
exported symbol sets are unchanged (1766) on the C, hybrid and C
reference libobs; the six functions are local.

Refs obs-rust#2496

* test: Characterize the encoder binding checks

test_encoder_bind_steps compiles libobs/obs-encoder-bind.c.h and
libobs/obs-encoder-audio-start.c.h (whose video type refusal the video
setter, the video getters and the unbind ask) with ASan and UBSan, and
calls only their functions through obs-encoder-bind.h and
obs-encoder-audio-start.h. 13 cases:

- the copied constant (OBS_ENCODER_AUDIO, 0);
- the audio and video type refusals over edge int values (an unknown
  type is refused by both);
- the video timebase over every pair of edge uint32_t frame rates
  (fps_den over fps_num; 0 over 0 with no video, whatever is passed),
  with 30000/1001, 60/1 and an fps_num of 0 (a timebase den of 0,
  stored as is: the fps-0 class, pinned and held);
- the audio timebase over edge rates (1 over the rate; 0 over 0 with
  no audio; a rate of 0 gives 1 over 0, characterized, not endorsed);
- the frame rate divisor video, created for any divisor but 0;
- the trylock results (only 0 holds the mutex) and the unstarted
  shutdown truth table.

The bodies of obs_encoder_set_video(), encoder_set_video(),
obs_encoder_set_audio(), obs_encoder_video(), _parent_video() and
_audio(), obs_encoder_shutdown_unstarted(), obs_encoder_unbind_video()
and obs_encoder_rebind_video() are also copied onto a stand-in encoder
(no lock and no video output; the trylock results and the outputs'
states are given), to pin end to end: both setters for audio and video
encoders, active and idle, initialized and not, and an unknown type;
binding NULL; divisors 0 and 1 (the getter gives the divisor video,
the parent getter the media; binding again or unbinding frees it); the
getters, which have no active or initialized gate; the unstarted
shutdown with each mutex busy, active, an output that needs the
encoder (the walk stops there), not initialized and with no outputs;
the unbind with each bound, active and initialized combination, of an
audio encoder, with no media and with no videos; the rebind with each
gate; and an unbind then rebind that keeps the divisor.

Characterized, not endorsed: obs_encoder_set_audio() has no
initialized refusal, so an initialized idle audio encoder takes the
new audio, where obs_encoder_set_video() refuses an initialized video
encoder (upstream).

It is in the native test graph, in name order, with both headers as
watch inputs, and links libm off MSVC. No assert_in_range or fail_msg,
so it builds with cmocka 1.x and 2.x, and no comparison between two
enum types (MSVC C5287). The real-libobs tests
test_encoder_video_reset and test_output_failed_start_encoders cover
the callers.

Refs obs-rust#2496

* obs-output: Add Tier 1 tests for encoder binding

RED for the port of libobs/obs-encoder-bind.c.h to a new encoder_bind
module of rust/obs-output, next to encoder_size and
encoder_audio_start. The safe core is a stub (todo!()): not_audio(),
video_timebase(), audio_timebase(), divisor_override(), locked() and
shutdown_unstarted(), with OBS_ENCODER_AUDIO (encoder_size's) and the
Timebase pair. It re-exports encoder_audio_start's not_video(), the
video type refusal the callers share, already ported.

tests/output/encoder_bind.rs ports test_encoder_bind_steps 1:1: its 13
cases under the same names (steps_*), in the same order, with the same
values and expectations, the characterized-not-endorsed case included,
the stand-in encoder and its copies of the setters, getters, unstarted
shutdown, unbind and rebind written in Rust over the core.

Edge cases (edge_*) check the core against the origin/master
expressions inline: every type and trylock result from -1,000 to 1,000
and the extremes; every pair of frame rates below 257 with and without
a video, and every rate; every divisor to 10,000; the shutdown truth
table; the stand-in through every caller for each type, active and
initialized flag, media, divisor, trylock pair and output list (2,304
encoders); and proptests (4,096 cases each) of every decision over
full-range values and of the stand-in over sequences of up to eleven
calls, with another thread flipping the active flag, initialized and
the divisor between them.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_bind passes 1 of 20 (the constants, already ported)
and fails 19 with "not yet implemented".

Refs obs-rust#2496

* obs-output: Port the encoder binding checks

Ports libobs/obs-encoder-bind.c.h, the encoder media binding and
shutdown checks, to the encoder_bind module of rust/obs-output.
obs-encoder.c.h stays C around it: obs_encoder_valid(), every warning,
the active flag (an atomic load) and the initialized, media,
fps_override and context.data tests in their && order, init_mutex and
outputs_mutex with both trylocks and their unlock order, the walks over
the videos to unbind from and over the encoder's outputs (each stops
where it did), obs_encoder_shutdown(), video_output_get_info(),
audio_output_get_sample_rate(), the divisor video's free and create
and every write to the encoder. The hybrid libobs drops the C file and
links the Rust shims in its place.

Safe core (src/encoder_bind.rs):
- not_audio(): the type is not OBS_ENCODER_AUDIO (encoder_size's 0);
- video_timebase(): fps_den over fps_num with a video, else 0 over 0;
- audio_timebase(): 1 over the sample rate with an audio, else 0 over
  0;
- divisor_override(): the divisor is not 0;
- locked(): the trylock result is 0;
- shutdown_unstarted(): initialized and not needed;
- not_video() re-exported from encoder_audio_start: the video setter,
  the video getters and the unbind call that shim, as
  obs_encoder_set_gpu_scale_type() does, so they share one
  implementation.
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 (the timebase is two copies).

Shims (src/ffi/encoder_bind.rs): the six functions keep the C
signatures (int as c_int). The timebase comes back by value as
obs_encoder_bind_timebase, a #[repr(C)] pair of u32 (Tier 3 checks its
layout against the C). No pointer crosses.

No intentional differences.

C side: the file leaves libobs.core-output for its own group,
libobs.ported-encoder-bind (LIBOBS_PORTED_SOURCES), whose PCH is only
obs-encoder-bind.h; libobs.pch.h keeps the header for obs-encoder.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 every host. The exported symbol sets are unchanged
(1766) on the C, hybrid and C reference libobs, and the six functions
are local in each; the hybrid libobs has no C object for the group.

test_encoder_bind_steps still compiles the C file into itself,
unchanged. It has no _rust variant, as for
test_encoder_audio_start_steps: the shims' archive member also holds
the rest of obs-output, which needs libobs's hidden seams and
obs-util, so it does not link on its own. Its tests.d file says so.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_bind passes 20 of 20. Through ctest (private Xvfb and
D-Bus, own HOME and runtime directory, no sound), the full suite
passes against the C libobs (532 of 532), the hybrid libobs (564 of
564) and the C reference libobs (564 of 564), the same 3 skipped on
each (a PulseAudio default sink and the v4l2 vivid module, absent
here). Among them test_encoder_bind_steps, test_encoder_video_reset,
test_output_failed_start_encoders, test_encoding_lag_rescale,
test_encoder_tex_active_null, test_multitrack_encoder_override,
test_texture_encoder_raw_format, test_encoder_error_stop,
test_encoder_join_keyframe, test_video_reset_fps and
test_raw_output_video_reset.

Refs obs-rust#2496

* obs-output: Check the encoder binding against C

Tier 3 for the encoder_bind port. The oracle
(rust/obs-c-oracle/oracle/encoder_bind.c) compiles the unchanged
libobs/obs-encoder-bind.c.h with its six functions renamed to
oracle_*, plus its constant and the layout of
struct obs_encoder_bind_timebase, bound in src/encoder_bind.rs.
Nothing in it divides. The video type refusal's oracle is
encoder_audio_start's.

tests/output/encoder_bind_parity.rs compares the oracle, the shims and
the core exactly, all three sides:
- the constant, and the timebase struct's size, alignment and offsets
  (and the oracle's mirror of it);
- both type refusals and the trylock result over -100,000 to 100,000,
  the 100,000 values at each extreme and a stride through all of i32;
- the video timebase over every pair of frame rates below 512 and
  every pair of 24 special u32 values (the common rates, 0, 2^16, 2^31
  and around u32::MAX), with and without a video;
- the audio timebase and the divisor over 0 to 1,000,000, the top
  100,000 and a stride through all of u32 (with and without an audio);
- the shutdown truth table;
- the callers on test_encoder_bind_steps' stand-in encoder (shared
  with Tier 1), on the oracle's gates and on the shims: every caller in
  turn for each of six types, the active and initialized flags, five
  medias, four divisors, five trylock pairs and four output lists
  (9,600 encoders), comparing every return and the end state;
- proptests (20,000 cases each) of every decision over full-range
  values and of the stand-in over sequences of up to fifteen calls.

No input is excluded: nothing in the C divides or overflows. Tier 1's
stand-in and its gates become pub(crate), so both tiers run the same
caller bodies. The
proptests of both files keep no regression files (failure_persistence
None), as the delay and interleave parity runners do.

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

  mutant                                  Tier 1  Tier 3
  not_audio: ==                                 7       4
  not_audio: the video type                     6       3
  OBS_ENCODER_AUDIO = 1                         7       4
  video_timebase: not swapped                   7       4
  video_timebase: ignores has_video             3       2
  video_timebase: den at least 1                4       2
  audio_timebase: num 0                         6       3
  audio_timebase: ignores has_audio             5       4
  audio_timebase: den at least 1                2       1
  divisor_override: > 1                         5       3
  divisor_override: always                      5       3
  locked: != 0                                  6       4
  locked: >= 0                                  6       4
  shutdown_unstarted: ||                        6       3
  shutdown_unstarted: ignores needed            6       3
  shim not_audio inverted                       0       4
  shim timebase fields swapped                  0       5
  shim audio_timebase: has_audio true           0       4
  shim video_timebase: rates swapped            0       4
  shim divisor_override: divisor - 1            0       3
  shim locked: <= 0                             0       4
  shim shutdown: arguments swapped              0       3

(failing tests per tier.) Tier 1 kills all 15 core mutants and Tier 3
all 22.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_bind passes 29 of 29 (20 Tier 1, 9 Tier 3).

Refs obs-rust#2496

* docs: Record the encoder binding port

rust/README.md gets the row for libobs/obs-encoder-bind.c.h
(obs-output::encoder_bind), after encoder_gpu_gates': what moved, the
video type refusal shared with the other video setters, what stays C
and why, the one reorder inside the timebase branch, the
characterized-not-endorsed behaviours (the audio setter taking an
initialized encoder, the 0 frame rate and sample rate timebases) and
the tests that cover it; the obs-output crate row names the file. The
crate's Cargo description and lib.rs named the module in the port
commit, and docs/rust-port/naming.md maps the file (the move commit).

rust/obs-c-oracle/benches/port_comparison/encoder_bind.rs, in the
sorted module list, runs 1024 rounds over audio and video encoders
with four frame rates, two sample rates, divisors 0 to 2, a busy
trylock every seventh round and mixed output states, asking every
decision the setters, the getters and the unstarted shutdown ask, on
the shims and on the oracle, and checks both checksums match.
Release, x86_64 Linux, GCC, median (load average about 3): Rust
8.42 us, C 8.18 us (1.03x), about 8 ns a round, next to
a mutex trylock or a video_output_get_info() call.

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

Fixes obs-rust#2496
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 encoder audio start alignment in obs-encoder.c to obs-output

1 participant