Skip to content

obs-output: Port the encoder lifecycle decisions - #2521

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

zackees merged 6 commits into
obs-rust:masterfrom
rdoupe:port/encoder-lifecycle

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Fixes #2512

What and why

Ports the encoder callback and connection lifecycle decisions of libobs/obs-encoder.c.h to rust/obs-output, as a new module encoder_lifecycle, next to encoder_bind. Every recording, stream and replay buffer passes through these when an output starts or stops its encoders, when an encoder connects to (or disconnects from) the canvas video or the audio mix, and for every encoded packet an encoder hands an output:

  • obs_encoder_start_internal(): the first callback (the encoder connects), and whether the callback is already there (not added again, no keyframe request);
  • obs_encoder_stop(): whether the callback was found, whether it was the last (the encoder disconnects), and whether the group is destroyed;
  • add_connection() and remove_connection(): the encoder group's counts (the divisor LCM starting at 1, the started count, ready when every encoder started, and the reset when the last one stops);
  • gpu_encode_available() (which full_stop() asks): the texture cap;
  • send_first_video_packet(): whether the SEI goes in front of the first keyframe.

The type tests are reused, not copied. The connection route (the audio mix, or else the GPU encode or the raw video) asks obs_encoder_bind_not_audio() (#2511), negated. The keyframe request for a video encoder that gains an output, and send_packet()'s first packet route, ask obs_encoder_audio_start_not_video(), negated. encoder_lifecycle re-exports both.

One function per decision, asked where the C made it. Ten functions cross the C ABI: obs_encoder_lifecycle_first(), _found(), _last(), _pass_texture(), _lcm_unset(), _started_inc(), _group_ready(), _started_dec(), _group_idle() and _prepend_sei(). The plan's combined steps (skip, first, join and keyframe as one start plan; the connect route together with the GPU test; the send route) would read media, info.type, request_keyframe, the mix's texture flags or sent_first_packet on paths where the C's ||, && and early returns never read them. info is rewritten when an encoder is initialized or rerouted, and the mix flags by a video reset. So the steps are split: the comparisons are functions, and the single-field tests stay C, in their order. full_stop() has nothing else to decide (the active test and the texture early return are single values).

What stays C, at its point and under its condition:

  • init_mutex, callbacks_mutex, outputs_mutex and the group mutex, with every section they guard. No section is merged. first is still read under callbacks_mutex from the count before the add. The group's ready is computed under its mutex and acted on after it is released, as before;
  • the darrays (the callback push and erase, the SEI copy) and get_callback_idx() (a walk; its result is passed);
  • the context.data, media, request_keyframe, destroy_on_stop, keyframe, sent_first_packet, mix and texture flag tests, and each output's obs_output_active();
  • lcm() (it divides by gcd(), the held frame rate 0 class; C still computes and stores it);
  • the audio connect and disconnect, the GPU and raw starts and stops, get_audio_info(), get_video_info(), get_mix_for_video(), add_ready_encoder_group(), the group destroy, obs_encoder_shutdown(), set_encoder_active(), pause_reset(), request_keyframe(), get_sei(), obs_output_force_stop() and the NULL packet, the callbacks and the profiler, and every write.

Nothing divides. The header copies OBS_ENCODER_CAP_PASS_TEXTURE and DARRAY_INVALID, and obs-encoder.c.h checks both with _Static_assert. Only counts, an index, the caps and three SEI values cross, by value; no pointer crosses.

Two small changes, both behaviour-neutral:

  • The group counts go through a local: num_encoders_started is read, stepped, written back and the local tested, where the C stepped the field and tested it. It is the same value, under the same mutex.
  • send_first_video_packet()'s sei and size now start as NULL and 0, and get_sei()'s result goes into a local. So _prepend_sei() never reads an unset local. The C read them only after get_sei() returned true.

Six commits:

  1. Move (behaviour-neutral, d4b618aaa): the decisions go to libobs/obs-encoder-lifecycle.c.h, declared in the new obs-encoder-lifecycle.h without EXPORT, so they are hidden. The file joins libobs.core-output. git blame on the moved lines shows upstream commits and one of the fork's (4b811b1, the keyframe request when an output joins).

    The move was checked against the original code. A scratch harness (not committed) compiles origin/master's eleven functions verbatim (gpu_encode_available(), get_callback_idx(), add_connection(), remove_connection(), obs_encoder_start_internal(), obs_encoder_start(), obs_encoder_stop(), get_sei(), send_first_video_packet(), send_packet() and full_stop()) next to this branch's. In both, every pointer-chain field access is rewritten the same way into a logged access, which records the field's value at the next event:

    • every lock and unlock, the validity checks, get_mix_for_video(), the audio and video info, the connects, disconnects and GPU and raw starts and stops, lcm(), the ready add, the group destroy, the shutdown, set_encoder_active(), pause_reset(), each atomic store, the profiler, obs_output_active() and the force stop, the NULL packet, request_keyframe(), get_sei_data() and every callback (with the packet's bytes) are logged in order;
    • between calls, another "thread" flips an output's active flag, a mix's NV12 flag, initialized, the group's started count or the SEI the plugin returns;
    • the inputs cover audio, video and unknown types; four cap words; no media, or media with no mix, NV12, P010 or neither; with and without context.data, request_keyframe and get_sei_data; six SEI answers; divisors 0 to 3; 0 to 3 callbacks; 0 to 3 outputs; no group, or groups of 0 to 3 encoders with 0 to 3 or UINT32_MAX started and LCMs of 0, 1 and 6; NULL encoders and callbacks; 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): all 312,182,644 logged events match, and so does the end state after each run. Every branch of origin/master's functions is reached both ways (gcov, 90 of 90). The full check was rerun after the rebase onto obs-output: Port the encoder binding checks #2511.

    27 deliberately broken moves were tried, and all 27 fail the harness. 14 are moved or reordered reads:

    • the mix flags read before the cap, or the cap read before the mix test;
    • sent_first_packet read before the type; request_keyframe or the type read before added;
    • first taken from the count after the add, or outside callbacks_mutex; last taken for a missing callback;
    • the destroy test's order swapped; the started count read again after the reset; ready read after the unlock;
    • the SEI asked before the keyframe wait; the send or connection route not negated.

    The other 13 are changed decisions.

  2. Characterization (752ccf05e): test_encoder_lifecycle_steps, 12 cases. It compiles the moved file, obs-encoder-bind.c.h and obs-encoder-audio-start.c.h with ASan and UBSan, and calls only their functions. It pins every decision over edge values. It also copies the start, stop, connect, disconnect, GPU test, full stop and both sends onto a stand-in encoder and group, and checks end to end:

    • the start with 0, 1 and 2 callbacks and with a duplicate, for audio and video encoders with and without request_keyframe, and with no data or no media;
    • the stop of a missing, a non-last and the last callback;
    • every connect route;
    • a group of two with divisors 2 and 3 through 0, 1 and 2 started and back, destroy_on_stop both ways;
    • the full stop of an idle output between two active ones (only the active ones are force stopped, the fork's fix) and of a texture encoder;
    • the first packets for six SEI answers, keyframe or not, and a second output waiting for its own keyframe.

    It is in the test graph, sorted, with the three headers as watch inputs. No assert_in_range or fail_msg, and no comparison between two enum types (MSVC C5287).

  3. RED (cc0fbf6fb): Tier 1 against todo!(). It ports the 12 C cases 1:1 and adds 7 edge tests against the origin/master expressions inline:

    • every type from -1,000 to 1,000 and the extremes;
    • every cap word of the low 16 bits;
    • counts and indexes at both ends of usize and u32;
    • the SEI table;
    • the stand-in through a fixed run of every caller for 6,144 encoder states;
    • proptests over full-range values, and over call sequences with another thread flipping state between calls.
  4. GREEN (a5e8dd38a): the safe core (ten functions) and ten #[no_mangle] shims, in a new libobs.ported-encoder-lifecycle group whose PCH is only the new header.

    • The commit updates source-sets.json, the unity lists, the three export lists and ci/test_ported_sources.py, each in sorted place.
    • test_encoder_lifecycle_steps has no _rust variant, as for test_encoder_audio_start_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 (b41a29bbe): a C oracle of the unchanged file, the parity tests and a mutation check.

  6. Docs (73b6deaec): the README rows and a port_comparison bench file in the sorted lists. docs/rust-port/naming.md maps the file in the move commit. The port changes nothing a user can see, so docs/features.md has no line.

The core denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints. It keeps no state, takes no lock and does not divide. The counts wrap as the C's uint32_t does.

  • Kept, characterized, not endorsed (current behaviour, unchanged):

    • a stop with none started wraps the count to UINT32_MAX, so the group is never reset or destroyed again;
    • a divisor of 0 (the setter refuses it) leaves an LCM of 0, which the next start takes as unset;
    • the GPU route is asked again at the stop, so a mix that lost its textures in between would stop on the raw path an encoder that started on the GPU;
    • the stop of a missing callback still clears the packet times.

    No path I could find reaches the first or the third: full_stop() frees the callbacks, so a later stop finds none, and obs_reset_video() refuses while outputs are active.

  • Intentional differences: none.

Mutation check (once, not committed), failing tests per tier:

mutant Tier 1 Tier 3
first: != 0 9 4
first: <= 1 5 3
found: == 10 4
found: != 0 9 3
last: != 0 7 4
last: false 6 3
pass_texture: any cap 6 4
pass_texture: bit 0 7 4
lcm_unset: == 1 5 3
started_inc: saturating 3 3
started_inc: + 0 6 4
group_ready: > 5 3
group_ready: == 4 3
started_dec: saturating 4 3
started_dec: + 1 6 4
group_idle: != 0 6 4
group_idle: <= 1 5 3
prepend_sei: || 6 4
prepend_sei: ignores size 5 3
prepend_sei: ignores got 6 4
prepend_sei: ignores has_sei 6 4
shim first inverted 0 4
shim last: index - 1 0 3
shim found: last 0 3
shim pass_texture: caps >> 1 0 4
shim lcm_unset inverted 0 4
shim started_inc: dec 0 4
shim group_ready: count - 1 0 2
shim started_dec: inc 0 4
shim group_idle inverted 0 4
shim prepend_sei: size - 1 0 3

Tier 1 kills all 21 core mutants, Tier 3 all 31.

port_comparison bench (encoder_lifecycle/start_send_stop/1024, release, x86_64 Linux, GCC, median, load average about 5): Rust 12.41 µs, C 31.35 µs (0.40x), about 12 ns a round. That is next to a single mutex lock or one of the callbacks the C makes around it.

RED → GREEN

  • RED commit: cc0fbf6fb. soldr cargo test -p obs-data --test obs-tests-core -- output::encoder_lifecycle passes 3 of 19 and fails 16 with "not yet implemented". The 3 that pass are the constants and the two type tests, already ported (steps_constants, steps_routes, edge_routes_every_type). local_gate.py --test-diff origin/master fails exactly those 16 and nothing else (4,522 run, 4,506 passed). --lane lint passes.
  • GREEN: 19 of 19 at a5e8dd38a, and 28 of 28 (19 Tier 1, 9 Tier 3) at the head.
    • Full ctest on the GREEN tree (private Xvfb and D-Bus, own HOME, no sound): 538 of 538 on the C libobs, 570 of 570 on the hybrid libobs and 570 of 570 on libobs-c-reference, with the same 3 environment skips on each (a PulseAudio default sink and the v4l2 vivid module).
    • Among those runs: test_encoder_lifecycle_steps, test_encoder_join_keyframe, test_encoder_error_stop, test_encoder_group_null, test_multitrack_ladder, test_output_interleave_e2e, test_output_interleave_restart, test_texture_encoder_raw_format, test_output_delay_restart and test_encoder_bind_steps.
    • Exported symbol sets are identical (1766) on the C, hybrid and C reference libobs, with libobs-c-reference rebuilt first. The ten functions are local, and the hybrid libobs has no C object for the group.
    • At the head (73b6deaec, on bf3ff380d), --lane lint passes. local_gate.py --test-diff origin/master (4,531 of 4,531) and --lane cross (Windows MSVC and macOS clippy) pass on the same tree, before a message-only amend. MSVC clippy also passes over all targets of obs-output, obs-data and obs-c-oracle (the tests and the bench), with SOLDR_RUSTC_WRAPPER=none.
  • Real app (UI, protocol output or logging changes): N/A, no user-visible change. The real-libobs tests above drive the start, the join keyframe, the stop, the group, the full stop and the first packets through the hybrid libobs.

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): not applicable, none
  • Intentional differences from C listed in the parity test header and rust/README.md (ports): none

Behaviour-neutral extraction before the Rust port. The decisions of
obs_encoder_start_internal(), obs_encoder_stop(), add_connection(),
remove_connection(), gpu_encode_available() (which full_stop() asks) and
send_first_video_packet() move to libobs/obs-encoder-lifecycle.c.h, as
ten functions on plain values declared in the new
libobs/obs-encoder-lifecycle.h without EXPORT (hidden, as
-fvisibility=hidden keeps them):

- obs_encoder_start_internal(), under callbacks_mutex: _first() (no
  callback before this one) and _found() (get_callback_idx()'s result
  is not DARRAY_INVALID: the callback is not added again);
- obs_encoder_stop(), under callbacks_mutex: _found() (the callback is
  erased) and _last() (none is left); under the group mutex,
  _group_idle() after destroy_on_stop (the group is destroyed);
- add_connection() and remove_connection(), under the group mutex:
  _lcm_unset() (the divisor LCM starts at 1), _started_inc() and
  _group_ready() (every encoder started), _started_dec() and
  _group_idle() (the last started encoder stopped: the group reset);
- gpu_encode_available(): _pass_texture() (the texture cap);
- send_first_video_packet(): _prepend_sei() (get_sei() returned true
  with a pointer and a size, so the SEI goes in front of the keyframe).

The type tests are the ones already ported, so they share one
implementation: the connection route of add_connection() and
remove_connection() (the audio mix, else the GPU encode or the raw
video) asks obs_encoder_bind_not_audio() (obs-rust#2511), the audio setter's
refusal, negated; the keyframe request in obs_encoder_start_internal()
and the first packet route in send_packet() ask
obs_encoder_audio_start_not_video(), the video setters' refusal,
negated. obs-encoder-bind.h and obs-encoder-audio-start.h note the new
callers.

One function per decision, asked where the C made it, so every read
stays where it was. The plan's combined steps (skip, first, join and
keyframe as one start plan; the connect route with the GPU test; the
send route) would read media, info.type, request_keyframe, the mix's
texture flags or sent_first_packet where the C's ||, && and early
returns do not (info is rewritten when the encoder is initialized or
rerouted, and the mix flags by a video reset), so they are split: the
comparisons are functions, and the single-field tests stay C in their
order (context.data, media, request_keyframe, destroy_on_stop, keyframe,
sent_first_packet, the mix and its texture flags, the outputs'
obs_output_active()). full_stop() has nothing else to decide (the active
test and the texture early return are single values), so apart from
gpu_encode_available() it is unchanged.

C keeps init_mutex, callbacks_mutex, outputs_mutex and the group mutex
with every section they guard, the darrays (the callback push and erase,
the SEI copy), get_callback_idx() (a walk; its result is passed), lcm()
(it divides by gcd(), the held fps-0 class; its result is stored as
before), audio_output_connect() and _disconnect(), start_gpu_encode()
and stop_gpu_encode(), start_raw_video() and stop_raw_video(),
get_audio_info(), get_video_info(), get_mix_for_video(),
add_ready_encoder_group(), the group destroy, obs_encoder_shutdown(),
set_encoder_active(), pause_reset(), request_keyframe(), get_sei(),
obs_output_force_stop() and the NULL packet, the callbacks and the
profiler, and every write. No lock section is merged and nothing
divides.

Two small changes, both behaviour-neutral:
- the group counters take a local: num_encoders_started is read, the
  stepped value written back and the local tested, where the C stepped
  the field and tested it (the same value, under the same mutex);
- send_first_video_packet()'s sei and size start NULL and 0 and
  get_sei()'s result goes into a local, so _prepend_sei() never reads
  an unset local; the C read them only after get_sei() returned true.

Checked in a scratch harness (not committed). It compiles
origin/master's eleven functions (gpu_encode_available(),
get_callback_idx(), add_connection(), remove_connection(),
obs_encoder_start_internal(), obs_encoder_start(), obs_encoder_stop(),
get_sei(), send_first_video_packet(), send_packet() and full_stop())
verbatim, and this branch's with the moved file,
obs_encoder_audio_start_not_video() and obs_encoder_bind_not_audio(),
with every pointer-chain field access rewritten the same way into a
logged access (with the field's value at the next event; a run of
accesses to one field with nothing between them counts as one, which
covers the counters' local), over a stand-in encoder, group, mixes,
outputs and callbacks. It logs every lock and unlock,
obs_encoder_valid() and obs_ptr_valid(), get_mix_for_video(), the audio
and video info, the connects, disconnects and GPU and raw starts and
stops, lcm(), the ready add, the group destroy, the shutdown,
set_encoder_active(), pause_reset(), each atomic store, the profiler,
obs_output_active() and the force stop, the NULL packet,
request_keyframe(), get_sei_data() and every callback with the packet's
bytes, in order. Between calls another "thread" flips an output's active
flag, a mix's NV12 flag, initialized, the group's started count or the
SEI the plugin returns.
- Inputs: audio, video and unknown types; caps 0, 1, the texture cap
  and 0xff; no media or one of four (no mix, NV12, P010, neither);
  with or without context.data, request_keyframe and get_sei_data;
  six SEI answers (false, true with no pointer, true with size 0, true
  with data, false with data set); divisors 0 to 3; 0 to 3 callbacks
  of two functions and three params, sent or not; 0 to 3 outputs,
  active or not; no group or one of 0 to 3 encoders with 0 to 3 or
  UINT32_MAX started, an LCM of 0, 1 or 6 and destroy_on_stop both
  ways; NULL encoders and callbacks; one to six calls of start, stop,
  full stop and send (keyframes or not) 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, callback, group
  and output field and every mutex): 312,182,644 events.
- Every branch of origin/master's functions is reached both ways
  (gcov, 90 of 90).
- 27 deliberately broken moves were planted and all 27 fail it: the
  mix flags read before the cap, the cap read before the mix test,
  sent_first_packet read before the type, request_keyframe or the type
  read before added, first taken from the count after the add or
  outside callbacks_mutex, last taken for a missing callback, the
  destroy test's order swapped, the started count read again after the
  reset, ready read after the unlock, the SEI asked before the
  keyframe wait, the send and connection routes not negated, and
  thirteen changed decisions (first and the group test inverted, found
  inverted, last always false, the cap test always true or
  any cap, the LCM test at 1, the count not stepped or stepped up on
  stop, ready as >, and the SEI test with || or ignoring the size or
  get_sei()'s result).

git blame on the moved lines shows upstream commits (fd37d9e,
93ba6e7, 5c91d93, caa5723, 0ed0f2c, 3990c18, 751dbda,
dd1e93f, f53df7d, a1fbf10) and one of the fork's (4b811b1, the
keyframe request when an output joins).

The constants (OBS_ENCODER_CAP_PASS_TEXTURE and DARRAY_INVALID) are
copied into the header, so it needs no core header; obs-encoder.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. docs/rust-port/naming.md maps the
file to rust/obs-output. The exported symbol set of the C libobs is
unchanged (1766); the ten functions are local.

Refs obs-rust#2512
test_encoder_lifecycle_steps compiles libobs/obs-encoder-lifecycle.c.h,
libobs/obs-encoder-bind.c.h (whose audio type test the connection route
asks) and libobs/obs-encoder-audio-start.c.h (whose video type test the
keyframe request and the first packet route ask) with ASan and UBSan,
and calls only their functions through their headers. 12 cases:

- the copied constants (the texture cap 2, DARRAY_INVALID SIZE_MAX and
  the type tests' OBS_ENCODER_AUDIO 0 and OBS_ENCODER_VIDEO 1);
- first, found and last over edge size_t values (only DARRAY_INVALID
  is not found);
- the audio route and the video test over edge int values (an unknown
  type takes the video route but asks no keyframe);
- the texture cap over every low byte, with and without the high bits;
- the group counters over edge uint32_t values: the LCM unset and the
  idle test at 0, the steps wrapping as uint32_t, ready at or past the
  encoder count (a group of none is ready);
- the SEI truth table over edge sizes (data with size 0, a size with
  no data, or data from a plugin that returned false: sent as it is).

The bodies of obs_encoder_start_internal(), obs_encoder_stop(),
add_connection(), remove_connection(), gpu_encode_available(),
full_stop(), send_packet() and send_first_video_packet() are also copied
onto a stand-in encoder (no lock, no output, no darray; the mix,
outputs, group and the plugin's SEI are given, every call counted), to
pin end to end: the start with 0, 1 and 2 callbacks and a duplicate (not
added, no keyframe request), for audio and video encoders with and
without request_keyframe, and with no data or no media; the stop of a
missing, a non-last and the last callback, and again after it; every
connect route (audio; GPU with the cap and an NV12 or P010 mix; raw
otherwise); a group of two with divisors 2 and 3 through 0, 1 and the
encoder count started and back, destroy_on_stop both ways; the full stop
of a raw encoder with an idle output between two active ones (only the
active ones are force stopped, the fork's fix) and of a texture encoder
(flagged, then the early return); the first packets for each of six SEI
answers, keyframe or not, and a second output waiting for its own
keyframe; an audio encoder's plain packets.

Characterized, not endorsed: a stop with none started wraps the count to
UINT32_MAX, so the group is never reset or destroyed again; a divisor of
0 (the setter refuses it) leaves an LCM of 0, which the next start takes
as unset; the route is asked again at the stop, so a mix that lost its
textures in between stops raw what started on the GPU; the stop of a
missing callback still clears the packet times.

It is in the native test graph, in name order, with the three 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). It passes 12 of 12 in the C and the hybrid build
trees. The real-libobs tests test_encoder_join_keyframe,
test_encoder_error_stop, test_encoder_group_null and
test_multitrack_ladder cover the callers.

Refs obs-rust#2512
RED for the port of libobs/obs-encoder-lifecycle.c.h to a new
encoder_lifecycle module of rust/obs-output, next to encoder_size and
encoder_audio_start. The safe core is a stub (todo!()): first(),
found(), last(), pass_texture(), lcm_unset(), started_inc(),
group_ready(), started_dec(), group_idle() and prepend_sei(), with
OBS_ENCODER_CAP_PASS_TEXTURE and NOT_FOUND (DARRAY_INVALID). It
re-exports encoder_bind's not_audio() (the connection route) and
encoder_audio_start's not_video() (the keyframe request and the first
packet route), the type tests the callers share, already ported.

tests/output/encoder_lifecycle.rs ports test_encoder_lifecycle_steps
1:1: its 12 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 and group and their copies of the
start, stop, connect, disconnect, GPU test, full stop and both sends
written in Rust over the core.

Edge cases (edge_*) check the core against the origin/master expressions
inline: every type from -1,000 to 1,000 and the extremes; every cap word
of the low 16 bits under three high words; every count and index to
10,000 and in the top 10,000 of usize, and every group count likewise in
u32, with ready over every pair below 65 and of the edge values; the SEI
truth table; the stand-in through a fixed run of every caller for each
of four types, four caps, four mixes, both requests, six SEI answers,
four groups and destroy_on_stop both ways (6,144 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 an output, the mix's flags, initialized, the SEI answer
and the group count between them.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_lifecycle passes 3 of 19 (the constants and both type
tests, already ported: steps_constants, steps_routes and
edge_routes_every_type) and fails 16 with "not yet implemented".

Refs obs-rust#2512
Ports libobs/obs-encoder-lifecycle.c.h, the encoder callback and
connection lifecycle decisions, to the encoder_lifecycle module of
rust/obs-output. obs-encoder.c.h stays C around it: init_mutex,
callbacks_mutex, outputs_mutex and the group mutex with every section
they guard, the callback push and erase and get_callback_idx(), the
context.data, media, request_keyframe, destroy_on_stop, keyframe,
sent_first_packet, mix and texture flag tests in their order, lcm(), the
connects and disconnects, the GPU and raw starts and stops, get_sei()
and the SEI copy, obs_output_active() and the force stop, and every
write. The hybrid libobs drops the C file and links the Rust shims in
its place.

Safe core (src/encoder_lifecycle.rs):
- first() and last(): no callback (before the add; after the erase);
- found(): the index is not NOT_FOUND (DARRAY_INVALID, usize::MAX);
- pass_texture(): the caps have OBS_ENCODER_CAP_PASS_TEXTURE;
- lcm_unset() and group_idle(): the LCM, or the started count, is 0;
- started_inc() and started_dec(): the count plus or minus one,
  wrapping as the C's uint32_t does;
- group_ready(): the count is at least the encoder count (a count that
  does not fit usize, which no host has, is past every encoder count,
  as the C's conversion to size_t gives);
- prepend_sei(): get_sei() returned true with a pointer and a size;
- not_audio() and not_video() re-exported from encoder_bind and
  encoder_audio_start: the connection route, the keyframe request and
  the first packet route call those shims, so the type tests 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 (lcm() stays C).

Shims (src/ffi/encoder_lifecycle.rs): the ten functions keep the C
signatures (size_t as usize, uint32_t as u32). Only counts, an index,
the caps and three SEI values cross, by value; no pointer crosses.

No intentional differences.

C side: the file leaves libobs.core-output for its own group,
libobs.ported-encoder-lifecycle (LIBOBS_PORTED_SOURCES), whose PCH is
only obs-encoder-lifecycle.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 identical (1766) on the C, hybrid and C reference
libobs, and the ten functions are local in each; the hybrid libobs has
no C object for the group.

test_encoder_lifecycle_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_lifecycle passes 19 of 19. Through ctest (private Xvfb
and D-Bus, own HOME, no sound), the full suite passes against the C
libobs (538 of 538), the hybrid libobs (570 of 570) and the C reference
libobs (570 of 570), the same 3 skipped on each (a PulseAudio default
sink and the v4l2 vivid module, absent here). Among them
test_encoder_lifecycle_steps, test_encoder_join_keyframe,
test_encoder_error_stop, test_encoder_group_null,
test_multitrack_ladder, test_output_interleave_e2e,
test_output_interleave_restart, test_texture_encoder_raw_format,
test_output_delay_restart and test_encoder_bind_steps.

Refs obs-rust#2512
Tier 3 for the encoder_lifecycle port. The oracle
(rust/obs-c-oracle/oracle/encoder_lifecycle.c) compiles the unchanged
libobs/obs-encoder-lifecycle.c.h with its ten functions renamed to
oracle_*, plus its two constants, bound in src/encoder_lifecycle.rs.
Nothing in it divides. The type tests' oracles are encoder_bind's and
encoder_audio_start's.

tests/output/encoder_lifecycle_parity.rs compares the oracle, the shims
and the core exactly, all three sides:
- the constants (the texture cap and DARRAY_INVALID);
- first, found and last over 0 to 1,000,000, the top 1,000,000 of
  usize, a stride through all of it and 29 special values;
- the group counts (the LCM test, the idle test and both steps) over 0
  to 1,000,000, the top 1,000,000 of u32 and a stride through all of
  it, and ready over every pair of counts below 1,024 and of 24 special
  values against encoder counts below 1,024 and 29 special values;
- the texture cap over every word of the low 20 bits under four high
  words;
- the SEI test over both flags and the sizes above;
- both type tests over -100,000 to 100,000, the 100,000 values at each
  extreme and a stride through all of i32;
- the callers on test_encoder_lifecycle_steps' stand-in encoder (shared
  with Tier 1), on the oracle's gates and on the shims: a fixed run of
  every caller for each of six types, five caps, five mixes, both
  requests, six SEI answers, six groups (none, idle, destroy_on_stop,
  one started, of none, UINT32_MAX started) and three output lists
  (32,400 encoders), comparing 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 (the steps
wrap as uint32_t does). Tier 1's stand-in, its gates, the call
strategy and the fixed run are pub(crate), so both tiers run the same
caller bodies. The proptests of both files keep no regression files
(failure_persistence None).

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

  mutant                                 Tier 1  Tier 3
  first: != 0                                 9       4
  first: <= 1                                 5       3
  found: ==                                  10       4
  found: != 0                                 9       3
  last: != 0                                  7       4
  last: false                                 6       3
  pass_texture: any cap                       6       4
  pass_texture: bit 0                         7       4
  lcm_unset: == 1                             5       3
  started_inc: saturating                     3       3
  started_inc: + 0                            6       4
  group_ready: >                              5       3
  group_ready: ==                             4       3
  started_dec: saturating                     4       3
  started_dec: + 1                            6       4
  group_idle: != 0                            6       4
  group_idle: <= 1                            5       3
  prepend_sei: ||                             6       4
  prepend_sei: ignores size                   5       3
  prepend_sei: ignores got                    6       4
  prepend_sei: ignores has_sei                6       4
  shim first inverted                         0       4
  shim last: index - 1                        0       3
  shim found: last                            0       3
  shim pass_texture: caps >> 1                0       4
  shim lcm_unset inverted                     0       4
  shim started_inc: dec                       0       4
  shim group_ready: count - 1                 0       2
  shim started_dec: inc                       0       4
  shim group_idle inverted                    0       4
  shim prepend_sei: size - 1                  0       3

(failing tests per tier.) Tier 1 kills all 21 core mutants and Tier 3
all 31.

soldr cargo test -p obs-data --test obs-tests-core --
output::encoder_lifecycle passes 28 of 28 (19 Tier 1, 9 Tier 3).

Refs obs-rust#2512
rust/README.md gets the row for libobs/obs-encoder-lifecycle.c.h
(obs-output::encoder_lifecycle), after encoder_bind's: what moved, the
type tests shared with encoder_bind and encoder_audio_start, what stays
C and why (every mutex and section, the walk, lcm() and its division,
the single-field tests), the two behaviour-neutral changes (the group
counts through a local, the SEI pointer and size initialized), the
characterized-not-endorsed behaviours (the count wrap, the LCM of a 0
divisor, the route asked again at the stop, the packet times cleared
for a missing callback) 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_lifecycle.rs, in the
sorted module list, runs 1024 rounds over audio and video encoders with
four callback counts, four indexes (one not found), four cap words,
group counts 0 to 2 and SEI answers from a fixed table, asking every
decision a start, a connect, a send, a first keyframe and a stop ask,
on the shims and on the oracle, and checks both checksums match.
Release, x86_64 Linux, GCC, median (load average about 5): Rust
12.41 us, C 31.35 us (0.40x), about 12 ns a round, next to a mutex
lock or one callback the C makes around it.

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

Fixes obs-rust#2512
@rdoupe
rdoupe requested a review from zackees as a code owner October 26, 2026 18:55

@zackees zackees left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed: each C comparison now calls one decision function at the point where the C made it, so the evaluation order and short-circuits are unchanged. The started_inc/started_dec wrapping matches the C's unsigned ++/--, the _Static_asserts pin the copied constants, and the type tests reuse #2511 and audio_start instead of copying them. The C oracle, parity, bench and Tier 2 cmocka are all present, and no existing C test or public header is touched. No ledger line is needed (no behavior change). Queuing.

@zackees
zackees enabled auto-merge October 26, 2026 19:02
@zackees
zackees added this pull request to the merge queue Oct 26, 2026
Merged via the queue into obs-rust:master with commit cbc5574 Oct 26, 2026
36 checks passed
@rdoupe rdoupe mentioned this pull request Oct 26, 2026
6 of 7 tasks
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 connection lifecycle in obs-encoder.c to Rust

2 participants