Skip to content

libobs: Port the output interleaver to obs-output - #1603

Merged
zackees merged 2 commits into
obs-rust:masterfrom
rdoupe:rust/port-output-interleave
Oct 21, 2026
Merged

zackees merged 2 commits into
obs-rust:masterfrom
rdoupe:rust/port-output-interleave

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Fixes #1594 (PR 4 of the plan; #1595 moved the interleaver into libobs/obs-output-interleave.c.h and added the characterization test test_output_interleave, #1599 the hidden accessors and wrappers this port reads the output and its encoders through, #1596 and #1600 the Rust util/darray.h operations it uses in place)

What and why

This PR ports libobs/obs-output-interleave.c.h, the encoded packet interleaver, to the interleave module of rust/obs-output (#1567). It is the encoded packet callback of an output with both video and audio. interleave_packets holds the encoders' packets in one queue sorted by dts_usec until every track has started. It then picks the start where the first video and audio are closest, shifts every track to start at 0, and sends the front of the queue once a packet of the opposing type is ahead of it. Each sent video packet gets its encoder timing and, when one is due, a caption. The function also checks that grouped encoders emit their keyframes together. interleave_packets, get_encoder_index and free_packets are declared in obs-internal.h without EXPORT. obs-output.c calls them, and passes interleave_packets to obs_encoder_start() / obs_encoder_stop() (or to the delay as its delay_callback) by name. The encoder finds its callback again by comparing the function pointer, so the Rust symbol replaces the C one exactly, as process_delay does. libobs-with-rust drops the C file and links the Rust shims.

  • Safe core (src/interleave.rs), in two layers:
    • Pure functions over a slice of packets (a PacketView trait: kind, track, dts, pts, dts_usec, keyframe, time base, encoder). They cover the first and last packet of a track and interleaved_start_idx (closest audio, earlier on a tie, the video if first, the move back for priming audio). premature_prune returns NoVideo, MissingAudio, Keep or Through(idx), with c_value() giving the C's -1/0/idx. The rest: get_encoder_duration, insert_position, apply_offset and packet_dts_usec, Highest::has_higher_opposing and streamable, the catch-up rule sends_for, discard_count, the caption timing (frame_timestamp, caption_due, raw_caption_due), find_packet_time, encoder_slot and group_complete.
    • The functions named after the C ones (interleave_packets, send_interleaved, initialize_interleaved_packets, resort_interleaved_packets, check_encoder_group_keyframe_alignment, ...) are generic over an InterleaveOutput trait, as the delay core is over DelayOutput. The trait covers the fields, the queue and the other darrays, interleaved_mutex, pkt_callbacks_mutex and the caption mutex, the encoders and the libobs calls. The locks are taken exactly where the C takes them: one interleaved_mutex per packet (released before a waiting delayed packet is released), the caption mutex around the caption decision, and pkt_callbacks_mutex around the callbacks.
    • Packet times and keyframe group entries are traits too (PacketTime, KeyframeGroup), so the core runs on the C structs in the shim and on plain structs in Tier 1. No host cfg, no unsafe.
    • Changes from the plan, and why. The keyframe group tracking is generic over the output and not a pure slice function: it erases and inserts entries while it walks the array, as the C does, and only group_complete is pure. The plan's "start plan" is initialize_interleaved_packets itself, built from get_audio_and_video_packets, interleaved_start_idx and apply_offset: the C reads the first packets again after the second discard, which a precomputed plan cannot do. get_encoder_index goes through encoder_slot (an Option) and keeps the C's assert(false) as a debug_assert, then 0, as a build without asserts does.
    • The nine behaviours test_output_interleave marks "characterized, not endorsed" are kept:
      • audio that starts more than one video frame after the first keyframe drops that keyframe;
      • the premature prune decides on the last audio track's difference;
      • get_encoder_duration truncates (20480 us, not 21333 us);
      • the start index follows video track 0 only;
      • a premature prune can start a track on a non-keyframe;
      • a waiting non-keyframe discards other tracks' packets;
      • priming audio keeps offset 0;
      • a delayed packet that reaches an inactive output is not released;
      • a later keyframe of the same track marks an older group entry skipped without a warning.
  • Shim (src/ffi/output_interleave.rs):
    • #[repr(C)] keyframe_group_data, packet_callback, caption_text (its first two fields and the text offset), obs_output_interleave_fields, obs_output_caption_track_fields and obs_encoder_interleave_info, with layout tests; encoder_packet and encoder_packet_time are the delay shim's.
    • It never reads struct obs_output or struct obs_encoder. It goes through obs_output_interleave_fields(), obs_output_caption_track_fields(), obs_encoder_interleave_info(), obs_encoder_group_num_started() and the obs_output_interleave_* wrappers of active(), the two first-encoder-index helpers and add_caption() (libobs: Read the output interleaver fields through hidden accessors #1599), and reads and writes each field where the C does.
    • interleaved_packets, encoder_packet_times[] and keyframe_group_tracking stay the C darrays that obs-output.c resets and frees. They are inserted into, erased, popped and pushed in place with obs_util::ffi::darray (test/cmocka: Characterize the util/darray.h operations the interleaver uses #1596, obs-util: Add the darray.h operations the interleaver uses #1600). The resort moves the queue header out and frees the old buffer after the reinsertion, as the C does. Queued packets are libobs's reference-counted copies (obs_encoder_packet_create_instance, hidden in libobs; it resolves inside libobs-with-rust as for the delay) or the delay's copy.
    • The clock is read once per packet callback call, as the C does. interleave_packets_with_clock and the statics module (the C file's static functions on a live output) are Rust-mangled (hidden by _ZN*), and the parity test drives them with a test clock.
    • The three log lines use the C's formats and arguments.
    • Symbols: the three are in rust-hidden.txt, rust-exports.map and rust-unexports-macos.txt. None is EXPORT, so there is no rust-exports.d fragment. In both libobs.so builds nm shows all three as t.
  • Build group: obs-output-interleave.c.h leaves libobs.core-output for its own group, libobs.ported-output-interleave, listed in source-sets.json (LIBOBS_PORTED_SOURCES). Its PCH, libobs-ported-output-interleave.pch.h, is obs-internal.h alone: since libobs: Read the output interleaver fields through hidden accessors #1599 the file needs nothing else. The comment in tests.d/test_output_interleave.cmake that named the old PCH is updated; the test and its sources are unchanged.
  • Oracle (oracle/output_interleave.c):
    • It renames the three external functions and os_gettime_ns with #defines, includes the original file, and adds oracle_output_interleave_* wrappers around ten of its static functions. Everything else it calls keeps its libobs name and is defined by the test.
    • The include is wrapped in a GCC diagnostic push/ignore/pop for -Wpedantic (__FUNCTION__), -Wsign-conversion (the file's implicit int/size_t conversions) and -Wformat (a size_t printed with %lu, which mingw rejects), none of which libobs warns about. The file is compiled unmodified.
    • It is built with NDEBUG, as libobs is. One of the file's asserts is reachable: discard_to_idx() pops the packet time of each video packet it drops, and darray_pop_front() asserts there is one, then does nothing. A video packet that came without a packet time hits it in an assert-enabled build. The Rust darray does nothing there too.
  • Intentional differences: none. Some differences cannot be observed:
    • a packet type other than OBS_ENCODER_VIDEO reads as audio everywhere;
    • a released queue entry is zeroed in a copy, not in the buffer slot that is erased next;
    • an empty queue, a missing first video packet of track 0 or a null callback aborts where the C reads through a null pointer or past the end. The interleaver never reaches those.

test_output_interleave (30 cases) compiles the C file into itself and is unchanged. It passes in every lane but cannot see the swap, so Tier 3 is the proof of the swap, as the issue planned.

RED → GREEN

  • RED commit: 6c7610309 libobs: Add Tier 1 tests for the output interleaver port. The core is todo!(). soldr cargo test -p obs-data --test obs-tests-core output::interleave:: fails 53 of 53 with "not yet implemented".
    • Tier 1 (tests/output/interleave.rs) mirrors test_output_interleave 1:1: the same thirty names and assertions, in order. It runs on a model output that records what the C test's stubs record: each sent packet with whether interleaved_mutex was held, each packet callback with its packet time and whether pkt_callbacks_mutex was held, each add_caption with whether the caption mutex was held, and every held copy until it is released.
    • 23 new edge cases:
      • the dts_usec and encoder-duration truncation;
      • the first and last packet of a track;
      • the start index and the premature prune without audio, and the duration lookups stopping at the missing track;
      • the insertion position at equal times;
      • the opposing-type test without video encoders, the catch-up boundaries and the discard count;
      • the caption timing at equal times, and the first matching packet time;
      • single-encoder and foreign group entries;
      • one lock per packet and none when inactive, and a delayed waiting packet released after the unlock;
      • a packet time offset after the start, and an audio packet's time going to the same-numbered array;
      • one pir per callback, and a start without video encoders.
    • The tests are a module of the existing core category binary, obs-tests-core. No new test binary: ci/test_binary_cap.py passes (8 of 8).
  • GREEN: dc56bf082 libobs: Port the output interleaver to obs-output. output:: passes 98/98 (40 delay, 53 Tier 1, 5 Tier 2/3), and the whole obs-tests-core binary passes 338/338.
    • Tier 3 (tests/output/interleave_parity.rs). Both sides run on a test output through the same stand-ins: the four accessors, the four obs-output.c wrappers, the output's encoded_packet, its packet callbacks and the two name getters, plus the delay parity's tracked packet copy and release (one definition per test binary).
      • Each stand-in records its call, with whether interleaved_mutex, pkt_callbacks_mutex and the caption mutex were held. add_caption and the callbacks change the packet (and the callbacks the packet time), so a side that passed a copy instead of its packet would show.
      • Tier 2 layout: the size, alignment and every field offset of the six structs, struct darray and the four darray typedefs, plus the nine values the file uses.
      • Thirteen characterization scenarios, step by step, among them the "not endorsed" ones.
      • A proptest of 1024 random runs of up to 80 steps, each over one to two video and audio encoders (time bases, frame sizes). Steps: packets of random tracks with random keyframes, running timestamps with jitter and steps back, and packet times; changes of active, the delay (the packet is then the delay's held copy), the batch limit, the captions, the add_caption result, the callbacks and the encoder group; restarts (reset_packet_data() then free_packets); get_encoder_index; and ten static functions called directly where their C preconditions hold.
      • After every step it compares the return value, the recorded calls, the log line, the held copies made and released, the caller's packet, every queued packet field by field (its encoder and group as an index), the packet times and group entries, the darray capacities and every interleaver field. Over the 1024 runs that is about 41,000 steps, about 3,700 sent packets, 1,900 callbacks with a packet time, 98 captions and 25 missing-keyframe warnings.
      • The log comparison swaps the process-wide log handler, so those two runs re-exec the test binary (testing-policy).
      • The exported entry point with the real clock: the packet time it hands a callback carries a pir between two os_gettime_ns() readings.
    • Deliberate-break check. Three mutants of the Rust core, one at a time, then restored:
      • the premature prune's strict diff > duration_usec made >=: 3 tests failed, 2 Tier 1 (premature_audio_prunes_through_it, premature_prune_widens_to_the_audio_frame) and parity_random_sequences;
      • the catch-up rule never sending the second packet: 4 failed, 2 Tier 1 (one_packet_per_call_then_catch_up, catch_up_rule) and both parity runs;
      • the insertion order with the "video before audio at the same time" rule removed: 10 failed, 7 Tier 1 (insertion_order, resort_reinserts_and_raises_highest, start_offsets_and_resort, ...) and all three parity runs that drive the shim.
      • With libobs-with-rust rebuilt for each mutant, the 48 output, delay, encoder, mux, caption, ffmpeg, record, remux and stream cmocka tests in mode ON caught only the catch-up mutant (test_output_interleave_restart, which checks that limit). The prune and insertion mutants passed 48/48: no real-libobs test starts an output with audio exactly one frame after the keyframe, or queues video and audio at the same dts_usec. test_output_interleave compiles the C itself and cannot see the swap. So the start and the ordering are proven by Tier 3, as the issue planned; step 5 of the plan (an end-to-end multi-track start through real libobs, like test: Run the output stream delay end to end through libobs #1578) is the follow-up for them.
      • After the restore, all of these pass again.
    • ASan: output:: (Tier 1 and 3, both proptests included) passes 98/98 under AddressSanitizer (-Zsanitizer=address on the Rust side; the C oracle is uninstrumented but allocates through the ASan allocator), with no reports. The first run found a use-after-free in the parity test itself, not in the port: with a delay, the caller's packet shares its data with the queued copy, which the same call may send and release, and the snapshot read the caller's bytes. The snapshot now reads them only while they are held.
  • Local, two build trees (ENABLE_RUST_LIBOBS=OFF and ON). Each tree runs the full cmocka suite against libobs (OFF) and against libobs-with-rust (ON):
Lane libobs libobs-with-rust Exported symbols
C (ENABLE_RUST_LIBOBS=OFF) 348/348 348/348 IDENTICAL (1766, same as master)
Rust (ENABLE_RUST_LIBOBS=ON) 347/348, then 3/3 on rerun (see below) 348/348 IDENTICAL (1766)
  • The one failure, test_video_io_hidden in the Rust lane against libobs, was the private Xvfb display going away (XOpenDisplay failed during hotkey initialization, so obs_startup failed). It does not use the interleaver, and it passed three of three reruns. No test was skipped or not run. master on the same trees: 348/348 in all four runs, the same symbol sets.
  • test_output_interleave, test_output_interleave_restart, test_output_delay, test_output_delay_e2e and test_output_delay_restart pass in all four runs.
  • libobs.ported-output-interleave+.h.c is linked into libobs and not into libobs-with-rust.
  • After the final rebase onto master (one new commit, test: verify reconnect policy without exact OS timer assumption #1601, which changes test_output_delay_e2e), both lanes were rebuilt and the 48 output, delay, encoder, mux, caption, ffmpeg, record, remux and stream tests rerun OFF and ON (48/48 each), with the same symbol result, and output:: 98/98.
  • The suites ran with an extracted cmocka 2.0.2 (the build host has no system cmocka package): CMake found it through CMocka_DIR, ctest ran with LD_LIBRARY_PATH pointing at its lib,. test_core_module_load, which clears LD_LIBRARY_PATH, finds that cmocka through its build RUNPATH and passed in every run.
  • Environment: headless (private Xvfb, private D-Bus, fresh HOME).
  • ci/local_gate.py:
    • --lane lint (clang-format, gersemi, rustfmt, clippy -D warnings, Dylints, ifdef ratchet, test-binary cap): passed.
    • --lane cross (clippy and Dylints for x86_64-pc-windows-msvc and aarch64-apple-darwin, plus a link of every test binary, the oracle included): passed.
    • --lane cross-release: passed.
    • --lane rust-test (soldr cargo test --workspace --locked, plus a --no-run link for x86_64-pc-windows-gnu): passed (obs-tests-core 338/338, the obs-util harness 740/740 including export_list). Its first run failed the mingw link: the original file prints a size_t with %lu, which mingw's -Wformat rejects under the oracle's -Werror (libobs builds it with MSVC there). The oracle's pragma now also ignores -Wformat; the shim passes the track as a size_t for that %lu too, as the C does.
  • ci/test_build_groups.py, ci/test_naming.py, ci/test_ported_sources.py, ci/test_rust_scope.py, ci/test_binary_cap.py, ci/test_cmocka_includes.py: OK.
  • Real app: not applicable (no behaviour 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 (characterization test_output_interleave landed in libobs: Move the output packet interleaver into obs-output-interleave.c #1595)
  • 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): not applicable (the oracle's -Wpedantic/-Wsign-conversion/-Wformat pragma covers one include in one test-only file)
  • Intentional differences from C listed in the parity test header and rust/README.md (ports): none

RED for the port of libobs/obs-output-interleave.c.h, the encoded packet
interleaver, to obs-output's new interleave module. The pure parts work
on a slice of packets (a PacketView trait): the first and last packet of
a track, the start index, the premature prune, the insertion position,
the offset arithmetic, the streamable count and the catch-up rule, the
discard count, the caption timing and the packet-time lookup. The
functions named after the C ones are generic over the output
(InterleaveOutput): its fields, the queue and the other darrays, the
locks, the encoders and the libobs calls the C file makes, so the C ABI
shim can run them on the real struct obs_output through the hidden
accessors of obs-rust#1599, and the tests on a model. Every function is a
todo!() stub.

The first thirty cases mirror test_output_interleave 1:1 (same names,
same assertions, in order) on a model output that records what the C
test's stubs record: each sent packet with whether interleaved_mutex was
held, each packet callback call with its packet time and whether
pkt_callbacks_mutex was held, each add_caption call with whether the
track's caption mutex was held, and every held copy until it is
released. The other 23 pin the edges: the dts_usec and encoder duration
truncation, the first and last packet of a track, the start index and
the premature prune without audio, the duration lookups stopping at the
missing track, the insertion position at equal times, the opposing-type
test without video encoders, the catch-up boundaries, the discard
count, the caption timing at equal times, the first matching packet
time, single-encoder and foreign group entries, one lock per packet and
none when inactive, a delayed waiting packet released after the unlock,
a packet time offset after the start, an audio packet's time going to
the same-numbered array, one pir per callback, and a start without video
encoders.

They are a module of obs-tests-core, so no new test binary
(ci/test_binary_cap.py: 8 of 8).

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

Refs obs-rust#1594
libobs/obs-output-interleave.c.h moves to obs_output::interleave. It is
the encoded packet callback of an output with video and audio:
interleave_packets queues the encoders' packets, starts every track
together at timestamp 0 and sends the packets in dts order, with their
encoder timing, captions and the encoder group keyframe check.
interleave_packets, get_encoder_index and free_packets are declared in
obs-internal.h without EXPORT; obs-output.c calls them, and passes
interleave_packets to the encoders by name, so the Rust symbol replaces
the C one the encoder later compares against.

The pure parts work on a slice of packets (PacketView): the first and
last packet of a track, the start index, the premature prune, the
insertion position, the offset arithmetic, the streamable count and the
catch-up rule, the discard count, the caption timing and the packet-time
lookup. The functions named after the C ones are generic over the output
(InterleaveOutput), as the delay core is over DelayOutput, and take
interleaved_mutex, pkt_callbacks_mutex and the caption mutex exactly
where the C does. The nine behaviours test_output_interleave marks
"characterized, not endorsed" are kept, among them the late-audio
keyframe drop, the last-track prune difference, the truncating encoder
duration, the track-0-only start index, the non-keyframe start, the
waiting non-keyframe discard, priming audio at offset 0 and the early
return that does not release a delayed packet.

The shim never reads struct obs_output or struct obs_encoder: it goes
through the hidden accessors and wrappers of obs-rust#1599, and reads and writes
each field where the C does. interleaved_packets, encoder_packet_times[]
and keyframe_group_tracking stay the C darrays obs-output.c resets and
frees; they are changed in place with obs_util::ffi::darray (obs-rust#1596,
obs-rust#1600). Queued packets are libobs's reference-counted copies or the
delay's. The clock is read once per packet callback, as in C; the
*_with_clock entry point and the statics module (the C file's static
functions on a live output) are Rust-mangled and are what the parity
test drives.

The file leaves libobs.core-output for its own group,
libobs.ported-output-interleave, whose PCH is obs-internal.h alone, so
the oracle and test_output_interleave compile it without the core. The
three symbols go in rust-hidden.txt, rust-exports.map and
rust-unexports-macos.txt. The exported symbol sets are unchanged.

Tier 3 (oracle/output_interleave.c) compares the layouts of the
keyframe group entry, the packet callback, the caption text, the darray
and the three accessor structs, the values the file uses, thirteen
characterization scenarios, and 1024 random runs of up to 80 steps over
one to two video and audio encoders: packets with random tracks,
keyframes, running timestamps and packet times, changes of active, the
delay, the batch limit, the captions, add_caption, the callbacks and the
encoder group, restarts, get_encoder_index, and the static functions
where their C preconditions hold. After every step it compares the
return value, every recorded call and whether each lock was held, the
log line, the held copies, the caller's packet, every queued packet,
packet time and group entry, the darray capacities and every
interleaver field. Both sides go through the same accessor and libobs
stand-ins. The oracle builds the file with NDEBUG, as libobs is built:
darray_pop_front asserts when a video packet without a packet time is
discarded, then does nothing, as the Rust darray does. No intentional
differences. test_output_interleave compiles the C into itself and is
unchanged.

Fixes obs-rust#1594
@rdoupe
rdoupe requested a review from zackees as a code owner October 21, 2026 05:10
@zackees
zackees enabled auto-merge October 21, 2026 05:11
@zackees
zackees added this pull request to the merge queue Oct 21, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 21, 2026
@zackees
zackees added this pull request to the merge queue Oct 21, 2026
@zackees

zackees commented Oct 21, 2026

Copy link
Copy Markdown
Member

Coordinator: the merge queue ejected this (run 39549304820, Tier 2 Linux tests ON shard 2/2). test_output_delay_e2e → force_stop_skips_delay failed at test_output_delay_e2e.c:484, assert_int_equal(delivered_count(), n): a packet still reached the output in the 300 ms after obs_output_force_stop, where queued packets should be dropped. It passed in this PR's own CI, so it's intermittent, but it's in the path this PR ports (interleaved packets after a force stop), so worth a look for a race between the stop and a send already in flight. Re-queued; if it fails again it's not a one-off.

Merged via the queue into obs-rust:master with commit a2fc918 Oct 21, 2026
27 checks passed
chriscoveries pushed a commit to chriscoveries/obsrust-fork that referenced this pull request Oct 21, 2026
…1606)

obs-rust#1603 ports obs-output-interleave.c.h to rust/obs-output, and its
deliberate-break check showed that the tests run through a real libobs
catch only the catch-up limit (test_output_interleave_restart).
test_output_interleave compiles the C file into itself, so with the
premature prune made non-strict (>=) or the video-before-audio insertion
rule removed in the Rust core, every real-libobs test still passed
against libobs-with-rust; only Tier 3 caught them.

test_output_interleave_e2e drives an encoded output with one video and
two audio tracks, all registered in the test, through obs_startup() and
real core video, and feeds the media by hand as the restart test does,
so nothing depends on the wall clock. It checks what the output's
encoded_packet callback receives: the first packet is a video keyframe
at dts 0 and each audio track starts after it, near 0; the dts never
decrease across the tracks, with video before audio at an equal dts;
audio exactly one frame after the first keyframe keeps it, and audio two
frames after drops it, so the output starts at the next keyframe (as
test_output_interleave characterizes); and the same output, stopped,
receives nothing and starts afresh the same way. About 2 s.

Refs obs-rust#1594
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 obs-output.c interleaver to obs-output

2 participants