Repository navigation
obs-source: Port the deinterlace draw decisions - #2153
Merged
Merged
Conversation
Member
github-merge-queue
Bot
removed this pull request from the merge queue due to a conflict with the base branch
Oct 24, 2026
…ce-draw.c Behaviour-neutral extraction before the Rust port. The decisions of get_effect(), deinterlace_linear_required(), deinterlace_render() and obs_source_set_deinterlace_mode() in obs-source-deinterlace.c.h move to libobs/obs-source-deinterlace-draw.c.h as ten functions on plain values, declared in the new libobs/obs-source-deinterlace-draw.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_source_deinterlace_draw_effect(): which effect a mode draws with, an enum C maps to the effect slot and file (NONE for DISABLE and for a mode outside the enum); - obs_source_deinterlace_draw_linear_required(): the modes that need linear sRGB input; - obs_source_deinterlace_draw_skip(): the early return of deinterlace_render(); - obs_source_deinterlace_draw_reads_linear_srgb() and obs_source_deinterlace_draw_linear_srgb(): the linear sRGB flag, and whether gs_get_linear_srgb() is read for it; - obs_source_deinterlace_draw_technique(), obs_source_deinterlace_draw_reads_white_level() and obs_source_deinterlace_draw_multiplier(): the technique (an enum C maps to "Draw", "DrawMultiply", "DrawTonemap" or "DrawMultiplyTonemap") and the multiplier for each pair of source and current colour spaces; - obs_source_deinterlace_draw_frame2(): whether the second field is due, video_time >= frame_ts + offset + half_duration - TWOX_TOLERANCE in uint64_t (obs-rust#395, obs-rust#1995, obs-rust#2048); - obs_source_deinterlace_draw_mode_change(): same, enable, disable or switch, a mode outside the enum being DISABLE (obs-rust#2120, which moves here with deinterlace_mode_known()). obs-source-deinterlace.c.h keeps every gs_* call in its order and under the same conditions, obs_load_effect() and the effect slots, convert_video_space(), obs_get_video_sdr_white_level(), enable_deinterlacing(), disable_deinterlacing() and obs_enter_graphics(). The early return still comes before convert_video_space() and gs_get_color_space(), so the decisions are separate calls rather than one plan: gs_get_linear_srgb() is still read only for a GS_CS_SRGB source (the short circuit of the old expression), and obs_get_video_sdr_white_level() only for a pair that multiplies, after gs_get_color_space(). The multiplier is the same single float division, sdr_white_level / 80.0f or 80.0f / sdr_white_level. The frame2 sum is the same uint64_t arithmetic, wrapping where it wrapped; TWOX_TOLERANCE, used only there, is now the pacing header's OBS_SOURCE_DEINTERLACE_PACING_TWOX_TOLERANCE (1000000ULL, which the old int constant converted to). Modes and colour spaces cross as int, so a value outside either enum takes the paths it took before; obs-source-deinterlace.c.h checks that both enums are int-sized. Checked against the unchanged functions of origin/master (outside the tree, not committed): both versions compiled against stubs that log every gs_* and obs_* call with its arguments (floats as their bits), and the traces compared byte for byte, under GCC -O2 and clang -O0. 100,601 effect lookups (modes -300 to 300 and random int), 585,120 renders (every texture and size combination of the early return; 9 source x 9 current spaces, in the enum and out, x the graphics linear flag x 16 modes x 20 white levels, NaNs, infinities, signed zeros and subnormals included; 200,000 random white level bit patterns; every combination of 16 edge u64 values for video_time, frame_ts and offset with 8 half durations; 300,000 random and near-threshold frame2 inputs) and 100,512 mode changes (valid or not x 16 current x 16 new modes, and a random sequence). The traces are identical; a planted change to the linear sRGB read or to the frame2 compare is caught. The new file joins libobs.core-source with libobs.pch.h, which includes the new header. The exported symbol sets are unchanged (1766). Refs obs-rust#2130
test_deinterlace_draw_plan_steps compiles libobs/obs-source-deinterlace-draw.c.h (ASan and UBSan) and calls only its ten hidden functions. 17 cases: - enum_values: the effect, technique and mode change numbers the C maps (and the port will return), and that each enum is int-sized; - effect_every_mode, effect_outside_enum: each mode's effect, RETRO drawing with discard 2x; none for DISABLE, -1, 99, 9 (one past YADIF_2X) and the ends of int; - linear_required_every_mode: blend, linear and yadif (and their 2x) need linear input; disable, discard, retro and modes outside the enum do not; - skip_without_texture_or_size: the early return for every combination of the two textures and widths and heights of 0, 1, 1080 and UINT32_MAX; - reads_linear_srgb_every_space, linear_srgb_every_input: gs_get_linear_srgb() is read for a GS_CS_SRGB source only; the flag is set for any other space (outside the enum included), and for SDR by the graphics flag or the mode; - technique_space_pairs, multiplier_space_pairs: the 4 x 4 pairs of source and current spaces, the technique, whether the white level is read, and the multiplier as float bits at SDR white levels of 80, 300 and 0 (300 / 80 = 3.75, 80 / 300 = 0x3e888889); - technique_outside_enum: a space outside the enum, as source or current, draws with Draw at 1 and reads no white level; - multiplier_any_level: -0, infinity, -80, 480, the smallest subnormal and NaN, each one IEEE division; - frame2_at_threshold: due at frame_ts + offset + half_duration - TWOX_TOLERANCE (>=), not 1 ns before; the half duration counted in full up to UINT32_MAX; - frame2_sum_wraps, frame2_below_tolerance_wraps: the uint64_t wraps; - mode_change_every_pair, mode_change_outside_enum, mode_change_current_outside_enum: same, enable, disable or switch for every pair of modes; a mode outside the enum disables, or does nothing when deinterlacing is off (obs-rust#2120). Characterized, not endorsed: - obs_get_video_sdr_white_level() is not checked: a level of 0 gives a multiplier of +inf from scRGB (80.0f / 0), -0 gives -inf, a negative level a negative multiplier and a NaN a NaN. OBS sets levels from 80 to 480 nits; - the frame2 threshold wraps: when frame_ts + offset + half_duration passes UINT64_MAX it lands near 0 and the second field is due at once; when half_duration is under TWOX_TOLERANCE and frame_ts + offset is smaller than the difference, it lands near UINT64_MAX and the second field is never due (a source has frame_ts and offset 0 only before its first frame, when nothing draws); - a current mode outside the enum, which obs_source_set_deinterlace_mode() no longer stores since obs-rust#2120, is not DISABLE: a mode in the enum switches, and one outside it disables, the same value included. The test is in the native test graph in name order, with libm except on MSVC, in the core suite (no suite size is pinned in rust/obs-build/tests/native.rs). On the C backend it passes 17 of 17, and test_deinterlace_2x_field_order (all five rates), test_deinterlace_pacing_steps, test_deinterlace_mode_load and test_media_restart_first_frame are unchanged and pass. Refs obs-rust#2130
Tests for the port of libobs/obs-source-deinterlace-draw.c.h to the deinterlace_draw module of rust/obs-source, next to deinterlace_pacing. The safe core is a stub (todo!()): - effect() and effect_index() (obs_source_deinterlace_draw_effect(), an Effect or its index, None for no effect), mode_known(), linear_required(), skip(), reads_linear_srgb(), linear_srgb(), technique() (a Technique), reads_white_level(), multiplier() (f32), frame2() and mode_change() (a ModeChange), on plain values: modes and colour spaces as the C's int, sizes as u32, times as u64; - the enum obs_deinterlace_mode and enum gs_color_space values, and Effect, Technique and ModeChange with the C's numbers. tests/source/deinterlace_draw.rs ports test_deinterlace_draw_plan_steps 1:1: its 17 cases under the same names (steps_*), in the same order, with the same inputs and expectations, the multipliers compared as bits. Edge cases (edge_*): the mode functions for every mode from -1000 to 1000 and near the ends of i32; the technique, the white level read and the multiplier for every pair of 260 spaces around the enum and the ends of i32; the multiplier at 26 special f32 bit patterns (zeros, subnormals, the normal ends, OBS's levels, infinities, quiet and signalling NaNs of both signs with payloads) for every pair of 9 spaces, against the one division written out; frame2 over every combination of 16 special u64 values and 8 half durations, and at the threshold -2 to +2, against a model in i128 with the modulo explicit; every mode change for 20 modes. Proptests (4000 cases each): frame2 over full-range u64 times and u32 half durations, half of them at the threshold +-3; the multiplier over any space and any white level bit pattern; the mode functions and the linear flag over any i32. soldr cargo test -p obs-data --test obs-tests-core source::deinterlace_draw fails 27 of 27 with "not yet implemented". Refs obs-rust#2130
Ports libobs/obs-source-deinterlace-draw.c.h, the deinterlace draw decisions of obs-source-deinterlace.c, to the deinterlace_draw module of rust/obs-source. obs-source-deinterlace.c.h stays C: every gs_* call in its order and under its conditions, obs_load_effect() and the effect slots, the technique names, convert_video_space(), obs_get_video_sdr_white_level(), enable_deinterlacing(), disable_deinterlacing() and obs_enter_graphics(). The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/deinterlace_draw.rs): - effect() and effect_index(): a match over the mode's int, the C's numbers (DISCARD 0 to YADIF_2X 7, RETRO drawing with discard 2x), None for DISABLE and any value outside the enum; mode_known() is DISABLE or an effect; - linear_required(): BLEND to YADIF_2X; - skip(): no current or previous texture, or a width or height of 0; - reads_linear_srgb() (GS_CS_SRGB only) and linear_srgb() (not GS_CS_SRGB, the graphics flag, or linear_required()); - technique(), Technique with the C's numbers: DrawMultiply for SDR or 709_EXTENDED into scRGB, DrawTonemap for 709_EXTENDED into SDR, DrawMultiplyTonemap for scRGB into SDR, DrawMultiply for scRGB into 709_EXTENDED, Draw otherwise (spaces outside the enum included); reads_white_level() when it multiplies; - multiplier(): sdr_white_level / 80.0 into scRGB, 80.0 / sdr_white_level out of it, 1.0 otherwise: one f32 division, the same IEEE operation as the C's, so the bits match, NaN payloads and infinities included; - frame2(): video_time >= frame_ts + offset + half_duration - TWOX_TOLERANCE (deinterlace_pacing's), each step wrapping_* as the C's uint64_t (obs-rust#395, obs-rust#1995, obs-rust#2048); - mode_change(): a mode outside the enum is DISABLE (obs-rust#2120), then same, enable from DISABLE, disable to DISABLE, else switch. The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. Shim (src/ffi/source_deinterlace_draw.rs): the ten functions keep the C signatures, plain values in and out. The effect comes back as int (-1 for none), the technique and the mode change as the C's enum values. No intentional differences: there is no pointer to check. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-deinterlace-draw (LIBOBS_PORTED_SOURCES), whose PCH is obs.h (the two enums), obs-source-deinterlace-draw.h and obs-source-deinterlace-pacing.h (TWOX_TOLERANCE). libobs.pch.h keeps the header for obs-source-deinterlace.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the ten are local in all three, and the hybrid's come from the Rust archive. ci/test_ported_sources.py checks the group on every host. test_deinterlace_draw_plan_steps still compiles the C file into itself, unchanged. The new test_deinterlace_draw_plan_steps_rust builds the same test source against libobs_rust-static (and libm except on MSVC): the test calls only the ten functions and includes their header and obs.h for the enum values, so it takes libobs's include directories (SIMDe, obsconfig.h) and links the archive alone. It passes 17 of 17 against the shims. test_deinterlace_2x_field_order, test_deinterlace_mode_load and test_media_restart_first_frame see the swap through the hybrid. Tier 1 source::deinterlace_draw passes 27/27. Refs obs-rust#2130
Oracle (oracle/source_deinterlace_draw.c): the original obs-source-deinterlace-draw.c.h, unmodified, with its ten functions renamed to oracle_*, plus every enum value the port uses (the nine modes, the four colour spaces, the effect, technique and mode change values), TWOX_TOLERANCE and the enum, int, bool and float sizes. The rename macros also rename the three enum tags that share their function's name, so the size table names the renamed tags. The bool results are declared as u8 on the Rust side, the byte the C returns. Tier 3 (tests/source/deinterlace_draw_parity.rs, 12 tests). Every function takes and returns plain values, so each run compares the bytes of the two results: the bools as bytes, the enums as values, the multiplier as its f32 bits. - the values and sizes against the C headers; - modes: every value from -70000 to 70000, every 65521st i32 over the whole range and the ends: 205,551 modes, the effect and the linear rule; every mode change between 41 modes (1,681 pairs); - space pairs: the technique, the white level read and the multiplier for every pair of 649 spaces (-320 to 320 and four near each end of i32): 421,201 pairs; every pair of -3 to 6 at 26 special white levels (zeros, subnormals, the normal ends, 80 to 480 nits, infinities, quiet and signalling NaNs of both signs with payloads); - the linear flag for every space, both graphics flags and the 41 modes (53,218); the early return for both flags each and 18 widths and heights (1,296); - frame2 for every combination of 18 special u64 values and 10 half durations (58,320), and at the threshold -2 to +2 (16,200); - deinterlace_render()'s decisions in its order (the early return, the linear sRGB read and flag, the technique, the white level read, the multiplier only when it is read, frame2), one copy on each side: 51,840 renders; - proptests (20,000 cases each): frame2 over full-range u64 times and u32 half durations, half of them at the threshold +-3; the multiplier and technique over any space and any white level bit pattern (never a float range); the mode functions over any i32; the render decisions over all of it at once. Tier 1 and the parity module passed 10 runs in a row with fresh seeds (39/39 each). No regression file came up; the ones the todo!() stub and the mutants left were deleted. Mutation check (once, not committed): 40 mutants, Tier 1 (27 tests) and Tier 3 (12), failures per mutant. | Mutant | Tier 1 | Tier 3 | |---|---|---| | effect: RETRO as discard / YADIF_2X as yadif / DISABLE as discard | 3 / 3 / 3 | 2 / 2 / 2 | | effect_index: blend 2x is 2 | 2 | 3 | | linear_required: RETRO too / not YADIF_2X | 4 / 4 | 5 / 5 | | skip: height ignored / both textures missing only | 1 / 1 | 3 / 3 | | reads_linear_srgb: SRGB_16F too | 2 | 3 | | linear_srgb: graphics flag ignored / mode ignored | 2 / 2 | 3 / 3 | | SRGB_16F not SDR | 4 | 4 | | technique: 709_EXTENDED into SDR not tonemapped / scRGB into SDR not tonemapped / scRGB into 709_EXTENDED drawn | 2 / 2 / 4 | 4 / 4 / 4 | | reads_white_level: DrawMultiply only | 2 | 3 | | multiplier: into scRGB inverted / 80.00001 / times 1/80 / scRGB into scRGB divides | 4 / 4 / 2 / 5 | 4 / 4 / 4 / 2 | | frame2: > / saturating sum / saturating TWOX / no TWOX / half doubled | 6 / 4 / 3 / 6 / 6 | 2 / 3 / 3 / 3 / 3 | | mode_change: unknown kept (pre-obs-rust#2120) / unknown is same / same before normalizing | 4 / 4 / 3 | 2 / 2 / 2 | | shim: no effect is 0 / tonemap numbers swapped / enable and disable swapped | 0 / 0 / 0 | 3 / 4 / 2 | | shim: graphics flag negated / spaces swapped in multiplier / video_time and frame_ts swapped / modes swapped | 0 / 0 / 0 / 0 | 3 / 4 / 3 / 2 | | mode_known: DISABLE unknown | 2 | 0 | | equivalent: multiplier divided in f64 and rounded / disable tested before enable / shim frame_ts and offset swapped / shim width and height swapped | 0 / 0 / 0 / 0 | 0 / 0 / 0 / 0 | 35 are killed by Tier 3. The other five are equivalent through the C ABI: mode_known() is used only by mode_change(), which maps an unknown mode to DISABLE, so DISABLE counting as unknown changes nothing (Tier 1 kills it, as it tests mode_known() itself); a single f32 division done in f64 and rounded is correctly rounded the same; the disable test can only come first when the current mode is DISABLE and the new one is too, which is "same" before either; the sum and the size test are symmetric. Tier 1 does not reach the shim; test_deinterlace_draw_plan_steps_rust and Tier 3 do. No intentional differences: there is no pointer to check. Refs obs-rust#2130
The rust/README.md crate table now lists libobs/obs-source-deinterlace-draw.c.h among the rust/obs-source units, and its port table has a row for it: the ten functions and what they decide, what stays C (every gs_* call in its order and under its conditions, obs_load_effect() and the effect slots, the technique names, convert_video_space(), obs_get_video_sdr_white_level(), enable_deinterlacing(), disable_deinterlacing() and obs_enter_graphics()), why the decisions are separate calls rather than one plan (the early return comes before convert_video_space() and gs_get_color_space()), the modes and spaces as int, the multiplier as one f32 division matching bit for bit, the frame2 wraps it keeps, no intentional differences, the _rust variant of the characterization, the real-libobs tests and what Tier 3 compares. The crate's description and lib.rs say what it holds. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. port_comparison gets its own bench file, benches/port_comparison/source_deinterlace_draw.rs: 1024 renders (the decisions of deinterlace_render() in its order, over every pair of colour spaces, the nine modes, white levels of 80 to 480 nits and field times either side of the threshold, one in 64 returning early) and 1024 mode changes with the new mode's effect, folded into checksums both sides must match. On x86_64 Linux (GCC, not pinned, load average 13 to 17; median, two runs): render_frame 25.2 and 25.8 us Rust, 13.9 and 13.3 us C per 1024 renders (1.8x to 1.9x), about 12 ns more per render, which runs once a frame for each deinterlaced source; mode_change 4.1 and 5.8 us Rust, 6.0 and 4.2 us C, within the noise. Fixes obs-rust#2130
zackees
force-pushed
the
port/deinterlace-draw
branch
from
October 24, 2026 14:43
d14a4e2 to
616b5e6
Compare
zackees
enabled auto-merge
October 24, 2026 14:43
Member
|
Coordinator: rebased after #2159 landed. #2159 turned the bench calls in |
5 of 7 tasks
This was referenced Oct 24, 2026
rdoupe
added a commit
to rdoupe/obs-studio
that referenced
this pull request
Oct 24, 2026
Behaviour-neutral extraction before the Rust port. The decisions of rotate_async_video(), obs_source_render_async_video() and source_render() in obs-source.c.h move to libobs/obs-source-draw-plan.c.h as eight functions on plain values, declared in the new libobs/obs-source-draw-plan.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_source_draw_plan_rotation_x() and _y(): the translate that moves a rotated async frame back into its box (height or width for 270 and 90, both for 180, nothing for any other angle; the rotation is in 0-359 since obs-rust#2136); - obs_source_draw_plan_async_linear_srgb(): the linear sRGB flag of an async frame, the graphics flag or an SDR frame into anything but GS_CS_SRGB, or an HDR frame tonemapped into SDR; - obs_source_draw_plan_async_nonlinear_alpha(): the non-linear alpha blend, an SDR frame drawn linear whose alpha is not linear; - obs_source_draw_plan_technique(): the technique for each pair of source and current colour spaces, with or without non-linear alpha. source_render()'s conversion uses the same table without it, so both callers share it; - obs_source_draw_plan_reads_white_level() and obs_source_draw_plan_multiplier(): when the SDR white level is read and the multiplier, the level over 80 into scRGB and 80 over the level out of it, the same for both callers; - obs_source_draw_plan_convert(): whether source_render() draws through color_space_texrender, when the source and current spaces are in different classes (SDR, 709_EXTENDED, scRGB). The techniques are a new shared enum obs_source_draw_technique in libobs/obs-source-draw-technique.h, with obs_source_draw_technique_name() mapping it to the effect's technique name. The deinterlace draw decisions (obs-rust#2153) move to it from their own technique enum: the four values keep their numbers (0 to 3) and two are added for the async draw (DrawNonlinearAlpha 4, DrawNonlinearAlphaMultiply 5), so the deinterlace shims, their oracle and test_deinterlace_draw_plan_steps change names only. deinterlace_render() maps the technique with the shared function instead of its own copy, and obs_source_deinterlace_draw_reads_white_level() lists the two new values (it never sees them). obs-source.c.h keeps every gs_* call in its order and under the same conditions, convert_video_space(), obs_get_video_sdr_white_level(), gs_get_format_from_space() and the texrenders. gs_get_linear_srgb() is still read for every async frame, after gs_get_color_space(), and obs_get_video_sdr_white_level() only for a pair that multiplies, after the colour spaces and the linear flag (async) or after gs_get_format_from_space() (source_render()); the decisions are separate calls so neither is hoisted. The multiplier is the same single float division, sdr_white_level / 80.0f or 80.0f / sdr_white_level, and the size converts to float as (float)uint32_t did. The rotation stays a long, so a value outside 0-359 takes the path it took before. Colour spaces cross as int, so a value outside the enum takes the paths it took before; obs-source.c.h already checks that the enum is int-sized. Checked against the unchanged functions of origin/master (outside the tree, not committed): both versions compiled against stubs that log every gs_*, obs_* and texrender call with its arguments (floats as their bits), and the traces compared byte for byte, under GCC -O0 and -O2 and clang -O0 and -O2, one trace hash for all four. 1,112,600 async renders (the eight texture, active and stale gates; 9 source x 9 current spaces, in the enum and out, x both linear flags x both alpha flags x 22 white levels, NaNs, infinities, signed zeros and subnormals included, x 19 rotations, LONG_MIN, LONG_MAX and values past 32 bits included, x 6 sizes, past 2^24 and UINT32_MAX included; 300,000 random) and 328,304 source renders (every pair x 22 white levels x no, a matching or a mismatched texrender x begin failing or not x 0 to 3 passes x 3 base sizes; 200,000 random). The traces are identical (24,697,614 calls); each of 12 planted changes (the 792f847 and 0800957 linear rules, the non-linear alpha rule, the 90 and 270 translates, the multiplier, the white level read and its hoisting, the gs_get_linear_srgb() read, the conversion rule, the non-linear alpha technique, the conversion passing non-linear alpha) is caught. The new file joins libobs.core-source with libobs.pch.h, which includes the new header. The exported symbol sets are unchanged (1766). Refs obs-rust#2187
chriscoveries
pushed a commit
to chriscoveries/obsrust-fork
that referenced
this pull request
Oct 24, 2026
* libobs: Move the source draw decisions into obs-source-draw-plan.c Behaviour-neutral extraction before the Rust port. The decisions of rotate_async_video(), obs_source_render_async_video() and source_render() in obs-source.c.h move to libobs/obs-source-draw-plan.c.h as eight functions on plain values, declared in the new libobs/obs-source-draw-plan.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_source_draw_plan_rotation_x() and _y(): the translate that moves a rotated async frame back into its box (height or width for 270 and 90, both for 180, nothing for any other angle; the rotation is in 0-359 since obs-rust#2136); - obs_source_draw_plan_async_linear_srgb(): the linear sRGB flag of an async frame, the graphics flag or an SDR frame into anything but GS_CS_SRGB, or an HDR frame tonemapped into SDR; - obs_source_draw_plan_async_nonlinear_alpha(): the non-linear alpha blend, an SDR frame drawn linear whose alpha is not linear; - obs_source_draw_plan_technique(): the technique for each pair of source and current colour spaces, with or without non-linear alpha. source_render()'s conversion uses the same table without it, so both callers share it; - obs_source_draw_plan_reads_white_level() and obs_source_draw_plan_multiplier(): when the SDR white level is read and the multiplier, the level over 80 into scRGB and 80 over the level out of it, the same for both callers; - obs_source_draw_plan_convert(): whether source_render() draws through color_space_texrender, when the source and current spaces are in different classes (SDR, 709_EXTENDED, scRGB). The techniques are a new shared enum obs_source_draw_technique in libobs/obs-source-draw-technique.h, with obs_source_draw_technique_name() mapping it to the effect's technique name. The deinterlace draw decisions (obs-rust#2153) move to it from their own technique enum: the four values keep their numbers (0 to 3) and two are added for the async draw (DrawNonlinearAlpha 4, DrawNonlinearAlphaMultiply 5), so the deinterlace shims, their oracle and test_deinterlace_draw_plan_steps change names only. deinterlace_render() maps the technique with the shared function instead of its own copy, and obs_source_deinterlace_draw_reads_white_level() lists the two new values (it never sees them). obs-source.c.h keeps every gs_* call in its order and under the same conditions, convert_video_space(), obs_get_video_sdr_white_level(), gs_get_format_from_space() and the texrenders. gs_get_linear_srgb() is still read for every async frame, after gs_get_color_space(), and obs_get_video_sdr_white_level() only for a pair that multiplies, after the colour spaces and the linear flag (async) or after gs_get_format_from_space() (source_render()); the decisions are separate calls so neither is hoisted. The multiplier is the same single float division, sdr_white_level / 80.0f or 80.0f / sdr_white_level, and the size converts to float as (float)uint32_t did. The rotation stays a long, so a value outside 0-359 takes the path it took before. Colour spaces cross as int, so a value outside the enum takes the paths it took before; obs-source.c.h already checks that the enum is int-sized. Checked against the unchanged functions of origin/master (outside the tree, not committed): both versions compiled against stubs that log every gs_*, obs_* and texrender call with its arguments (floats as their bits), and the traces compared byte for byte, under GCC -O0 and -O2 and clang -O0 and -O2, one trace hash for all four. 1,112,600 async renders (the eight texture, active and stale gates; 9 source x 9 current spaces, in the enum and out, x both linear flags x both alpha flags x 22 white levels, NaNs, infinities, signed zeros and subnormals included, x 19 rotations, LONG_MIN, LONG_MAX and values past 32 bits included, x 6 sizes, past 2^24 and UINT32_MAX included; 300,000 random) and 328,304 source renders (every pair x 22 white levels x no, a matching or a mismatched texrender x begin failing or not x 0 to 3 passes x 3 base sizes; 200,000 random). The traces are identical (24,697,614 calls); each of 12 planted changes (the 792f847 and 0800957 linear rules, the non-linear alpha rule, the 90 and 270 translates, the multiplier, the white level read and its hoisting, the gs_get_linear_srgb() read, the conversion rule, the non-linear alpha technique, the conversion passing non-linear alpha) is caught. The new file joins libobs.core-source with libobs.pch.h, which includes the new header. The exported symbol sets are unchanged (1766). Refs obs-rust#2187 * test: Characterize the source draw decisions test_source_draw_plan_steps compiles libobs/obs-source-draw-plan.c.h (ASan and UBSan) and calls only its eight hidden functions. 17 cases: - enum_values: the technique numbers the C maps (and the port will return), their names, and that the enum and enum gs_color_space are int-sized; - rotation_multiples_of_90: the translate of a 1920 x 1080 frame and of a 1080 x 1920 one at 0, 90, 180 and 270, as float bits; - rotation_other_angles: 1, 45, 89, 91, 135, 179, 181, 269, 271 and 359 are not moved, nor are 360, 450, -90, -180, -270 and the ends of long; - rotation_size_to_float: sizes of 0, past 2^24 (rounded to nearest even) and UINT32_MAX (2^32); - async_linear_srgb_space_pairs, async_linear_srgb_outside_enum: the 4 x 4 pairs with the graphics flag off and on (an SDR frame into anything but GS_CS_SRGB, 792f847; an HDR frame into SDR, 0800957); a space outside the enum keeps the graphics flag; - async_nonlinear_alpha_every_input: only an SDR frame drawn linear whose alpha is not linear; - technique_space_pairs, technique_outside_enum: the 4 x 4 pairs with and without non-linear alpha; Draw for a space outside the enum; - reads_white_level_space_pairs, multiplier_space_pairs, multiplier_outside_enum: the pairs that read the level, and the multiplier as float bits at SDR white levels of 80, 300 and 0 (300 / 80 = 3.75, 80 / 300 = 0x3e888889, 80 / 0 = +inf); - multiplier_any_level: -0, infinity, -80, 480, 203, the smallest subnormal and NaN, each one IEEE division; - convert_space_pairs, convert_outside_enum: source_render() converts between classes (SDR, 709_EXTENDED, scRGB) only; - async_plan_every_input, convert_plan_every_input: the decisions in their callers' order for every pair, both linear flags, both alpha flags and the three white levels. Characterized, not endorsed: - obs_get_video_sdr_white_level() is not checked: a level of 0 gives a multiplier of 0 into scRGB and +inf out of it, -0 gives -inf, a negative level a negative multiplier and a NaN a NaN. OBS sets levels from 80 to 480 nits; - a rotation outside 0-359, which obs_source_set_async_rotation() no longer stores since obs-rust#2136, is not moved, even a multiple of 90; - an SDR frame into a current space outside the enum is drawn linear with non-linear alpha, but with Draw (the space is not GS_CS_SRGB, and the technique switch has no case for it). The test is in the native test graph in name order, with libm except on MSVC, in the core suite (no suite size is pinned in rust/obs-build/tests/native.rs). On the C backend it passes 17 of 17. Refs obs-rust#2187 * obs-source: Add Tier 1 tests for the source draw plan port Tests for the port of libobs/obs-source-draw-plan.c.h to the draw_plan module of rust/obs-source. The safe core is a stub (todo!()): - rotation_x() and rotation_y() (the rotation as the C's long, c_long, the size as u32, the translate as f32), async_linear_srgb(), async_nonlinear_alpha(), technique() (a Technique), reads_white_level(), multiplier() (f32) and convert(), on plain values: colour spaces as the C's int; - Technique, enum obs_source_draw_technique with the C's numbers. The technique enum and the enum gs_color_space values move from deinterlace_draw to a new shared module, draw_technique, with Technique::value() (the C's number) and Technique::name() (the name C maps it to); Technique gains DrawNonlinearAlpha (4) and DrawNonlinearAlphaMultiply (5). deinterlace_draw re-exports them, so its users and tests are unchanged, and its shim returns Technique::value() through the shared ffi type obs_source_draw_technique (src/ffi/source_draw_technique.rs) instead of its own copy. tests/source/draw_plan.rs ports test_source_draw_plan_steps 1:1: its 17 cases under the same names (steps_*), in the same order, with the same inputs and expectations, the floats compared as bits. Edge cases (edge_*): the rotation translate for every angle from -1000 to 1000, the ends of c_long and, where long is 64 bits, 90, 180 and 270 plus 2^32, against a model that converts the size through f64; every size from 0 to 1024 and around 2^24, 2^25, 2^31 and u32::MAX; every decision over every pair of 260 spaces around the enum and the ends of i32 with every flag, against a model written from the space classes; the multiplier at 26 special f32 bit patterns (zeros, subnormals, the normal ends, OBS's levels, infinities, quiet and signalling NaNs of both signs with payloads) for every pair of 9 spaces, against the one division written out; the white level is read exactly when the multiplier at 300 nits is not 1. Proptests (4000 cases each): the rotation over any c_long and u32 sizes, a third of them at 90, 180 or 270; every decision over any space, flag and white level bit pattern. soldr cargo test -p obs-data --test obs-tests-core source::draw_plan fails 23 of 24 with "not yet implemented"; steps_enum_values, which tests only the enum, passes. source::deinterlace_draw still passes 39 of 39. Refs obs-rust#2187 * obs-source: Port the source draw decisions Ports libobs/obs-source-draw-plan.c.h, the source draw decisions of obs-source.c, to the draw_plan module of rust/obs-source. obs-source.c.h stays C: every gs_* call in its order and under its conditions, convert_video_space(), obs_get_video_sdr_white_level(), gs_get_format_from_space(), the texrenders and the technique names. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/draw_plan.rs): - rotation_x() and rotation_y(): a match over the C's long (c_long, never converted, so a value past 32 bits is matched as the C's switch matches it on every target): height or width for 270 and 90, both for 180, 0 otherwise; the size converts to f32 to nearest even, as (float)uint32_t does; - async_linear_srgb(): the graphics flag, or GS_CS_SRGB into anything but GS_CS_SRGB (792f847), or 709_EXTENDED or scRGB into SDR (0800957); async_nonlinear_alpha(): GS_CS_SRGB, linear, alpha not linear; - technique(), Technique with the C's numbers: DrawMultiply (or DrawNonlinearAlphaMultiply) for SDR into scRGB, DrawNonlinearAlpha for GS_CS_SRGB with non-linear alpha into SDR or 709_EXTENDED, DrawTonemap for 709_EXTENDED into SDR, DrawMultiply for it into scRGB, DrawMultiplyTonemap for scRGB into SDR, DrawMultiply for it into 709_EXTENDED, Draw otherwise (spaces outside the enum included); - reads_white_level() and multiplier(): into scRGB from SDR or 709_EXTENDED, sdr_white_level / 80.0; out of scRGB into them, 80.0 / sdr_white_level; 1.0 otherwise: one f32 division, the same IEEE operation as the C's, so the bits match, NaN payloads and infinities included; - convert(): both spaces in the enum, in different classes (SDR, 709_EXTENDED, scRGB). The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints (one as, the size to f32, is allowed on its own helper: there is no From<u32> for f32), keeps no state and takes no lock. Shim (src/ffi/source_draw_plan.rs): the eight functions keep the C signatures, plain values in and out; the technique comes back as Technique::value() through the shared obs_source_draw_technique type. No intentional differences: there is no pointer to check. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-draw-plan (LIBOBS_PORTED_SOURCES), whose PCH is obs.h (the colour space enum) and obs-source-draw-plan.h (which brings obs-source-draw-technique.h). libobs.pch.h keeps the header for obs-source.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the eight are local in all three, and the hybrid's come from the Rust archive (it has no object for the C file). ci/test_ported_sources.py checks the group on every host. test_source_draw_plan_steps still compiles the C file into itself, unchanged. The new test_source_draw_plan_steps_rust builds the same test source against libobs_rust-static (and libm except on MSVC): the test calls only the eight functions and the header's static inline obs_source_draw_technique_name(), and includes their header and obs.h for the enum values, so it takes libobs's include directories (SIMDe, obsconfig.h) and links the archive alone. It passes 17 of 17 against the shims. test_async_rotation_normalize, test_filter_color_space, test_source_color_space_steps, test_color_correction_16f, test_pipewire_cursor_hdr and test_texture_render see the swap through the hybrid. Tier 1 source::draw_plan passes 24/24; source::deinterlace_draw still passes 39/39. Refs obs-rust#2187 * obs-source: Check the source draw plan port against the C Oracle (oracle/source_draw_plan.c): the original obs-source-draw-plan.c.h, unmodified, with its eight functions renamed to oracle_*, plus every enum value the port uses (the four colour spaces and the six techniques), the enum, int, long, bool and float sizes, and obs_source_draw_technique_name() for a technique value. No function shares its name with an enum tag, so the size table names the tags as they are. The bool results are declared as u8 on the Rust side, the byte the C returns. Tier 3 (tests/source/draw_plan_parity.rs, 10 tests). Every function takes and returns plain values, so each run compares the bytes of the two results: the bools as bytes, the technique as its value, the floats as their f32 bits. - the values and sizes against the C headers (long is c_long on every target), and the name C maps each technique the port returns to; - the rotation translate for every angle from -70000 to 70000, a stride over the whole c_long range, its ends and, where long is 64 bits, 90, 180 and 270 plus multiples of 2^32, at 6 sizes (non-square, 0, past 2^24, u32::MAX); every size from 0 to 4096 and +-2000 around 2^24, 2^25, 2^31 and u32::MAX at 0, 90, 180, 270 and 45; - space pairs: both linear flags, both non-linear alpha flags, the white level read, the conversion and the multiplier at 300 nits for every pair of 649 spaces (-320 to 320 and four near each end of i32): 421,201 pairs; every pair of -3 to 6 and the ends of i32 at 26 special white levels (zeros, subnormals, the normal ends, 80 to 480 nits, infinities, quiet and signalling NaNs of both signs with payloads); the non-linear alpha rule for every space and flag; - the decisions of obs_source_render_async_video() (with rotate_async_video()) and source_render() in their order, one copy on each side: the linear flag, the blend, the technique, the white level read, the multiplier only when it is read, and the translate only for a rotation other than 0; 9 x 9 spaces x both flags x both alpha flags x 26 levels x 7 rotations x 2 sizes (235,872 draws); - proptests (20,000 cases each): the rotation over any c_long and any sizes (a third at 90, 180 or 270); every decision over any space and any white level bit pattern (never a float range); both callers' decisions over all of it at once. No input reaches an integer division or a 128-bit multiply on either side (the only division is the f32 multiplier, which cannot trap), so the MSVC x64 _udiv128 and INT_MIN / -1 faults cannot come up and no input is skipped there. Tier 1 and the parity module passed 10 runs in a row with fresh seeds (34/34 each). No regression file came up; the ones the todo!() stub and the mutants left were deleted. soldr cargo clippy --target x86_64-pc-windows-msvc -p obs-source -p obs-data -p obs-c-oracle --all-targets -- -D warnings is clean. Mutation check (once, not committed): 36 mutants, Tier 1 (24 tests) and Tier 3 (10), failures per mutant. | Mutant | Tier 1 | Tier 3 | |---|---|---| | rotation: 270 x is width / 180 x is height / 90 y is height / 180 y not moved / -90 as 270 | 5 / 5 / 5 / 5 / 2 | 5 / 5 / 5 / 5 / 2 | | size truncated to even | 4 | 5 | | linear: SDR into non-SRGB dropped (pre-792f8473e) / tonemap dropped (pre-080095786) / SRGB into SRGB_16F not linear / HDR is 709_EXTENDED only | 6 / 4 / 4 / 4 | 5 / 5 / 5 / 5 | | non-linear alpha: linear ignored / SRGB_16F too | 4 / 4 | 3 / 3 | | technique: flag not masked to SRGB / no NA into 709_EXTENDED / 709_EXTENDED into SDR drawn / scRGB into 709_EXTENDED drawn / NAM is DrawMultiply | 2 / 4 / 5 / 5 / 4 | 3 / 5 / 5 / 5 / 5 | | into scRGB not from 709_EXTENDED / out of scRGB not into 709_EXTENDED | 8 / 8 | 5 / 5 | | multiplier: into scRGB inverted / 80.00001 / times 1/80 | 7 / 7 / 3 | 5 / 5 / 4 | | white level read into scRGB only | 6 | 5 | | convert: SRGB_16F its own class / outside the enum converts / same class converts | 4 / 3 / 4 | 5 / 5 / 5 | | Technique::value: NA and NAM swapped / tonemap numbers swapped | 1 / 1 | 6 / 6 | | shim: rotation width and height swapped / technique ignores the flag / multiplier spaces swapped / graphics flag negated | 0 / 0 / 0 / 0 | 5 / 5 / 5 / 5 | | equivalent: multiplier in f64 and rounded / size through f64 / shim convert spaces swapped / white level read as "multiplier at 300 is not 1" | 0 / 0 / 0 / 0 | 0 / 0 / 0 / 0 | 32 are killed by Tier 3. The other four are equivalent: one f32 division done in f64 and rounded is correctly rounded the same; a u32 is exact in f64, so one rounding to f32 is the same; convert() is symmetric; and every pair that multiplies gives a multiplier other than 1 at 300 nits. Tier 1 does not reach the shims; test_source_draw_plan_steps_rust and Tier 3 do. No intentional differences: there is no pointer to check. Refs obs-rust#2187 * docs: Record the source draw plan port The rust/README.md crate table now lists libobs/obs-source-draw-plan.c.h among the rust/obs-source units, and its port table has a row for it: the eight functions and what they decide, the shared technique enum (obs-source-draw-technique.h, obs-source::draw_technique), what stays C (every gs_* call in its order and under its conditions, convert_video_space(), obs_get_video_sdr_white_level(), gs_get_format_from_space(), the texrenders and the technique names), why the decisions are separate calls rather than one plan (neither gs_get_linear_srgb() nor the white level read is hoisted), the spaces as int and the rotation as long, the multiplier as one f32 division matching bit for bit, what is kept and characterized, no intentional differences, the _rust variant of the characterization, the real-libobs tests and what Tier 3 compares. The deinterlace draw row names the shared enum. The crate's description and lib.rs say what it holds, draw_technique included. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. port_comparison gets its own bench file, benches/port_comparison/source_draw_plan.rs, in the sorted modules! list: 1024 async frames (the decisions of obs_source_render_async_video() in its order and the rotation translate, over every pair of colour spaces, both linear and alpha flags, white levels of 80 to 480 nits and rotations of 0, 90, 180 and 270) and 1024 source_render() conversions, folded into checksums both sides must match. Neither side allocates, and the module passes the bench's per-module allocation check. On x86_64 Linux (GCC, not pinned, load average 6 to 8; median, two runs): async_frame 16.3 and 14.6 us Rust, 13.9 and 13.3 us C per 1024 frames (1.1x to 1.2x), about 2 ns more per async frame drawn; source_render 8.9 and 10.0 us Rust, 7.2 and 7.7 us C (1.2x to 1.3x), about 2 ns more per source drawn. soldr cargo test -p obs-c-oracle --locked --bench port_comparison passes. Fixes obs-rust#2187
6 of 7 tasks
5 of 7 tasks
This was referenced Oct 26, 2026
vpacher
pushed a commit
to vpacher/obs-studio
that referenced
this pull request
Oct 26, 2026
…bs-rust#2457) * libobs: Move the raw output audio decisions Behaviour-neutral extraction before the Rust port. The decisions of prepare_audio(), default_raw_audio_callback(), start_raw_audio() and hook_data_capture() move to libobs/obs-output-raw-audio.c.h, as nineteen functions on plain values declared in the new libobs/obs-output-raw-audio.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - prepare_audio(): _passthrough() (no OBS_OUTPUT_VIDEO flag), _video_unset() (asked before the video start is taken from the pause data, and again after), _before_video(), _ends_before() (the packet ends at or before the video start: dropped) and the front cut: _cut_ns(), _cut_ts(), _cut_bytes() (asked for each plane) and _cut_frames(); - default_raw_audio_callback(): _start_unset(), _block_bytes(), _push_bytes() (asked for each plane), _can_pop() (the block loop), _block_ts(), _paused_ts() (under the pause mutex) and _next_frames(); - start_raw_audio(): _mix_on(), asked for each mix with raw_audio2; - hook_data_capture(): _interleave() (the encoded callback), _delay_on() and _delay_ns(). The plan sketched one admit() returning pass, wait, drop or cut. That would read last_video_ts before the video start check and compute the packet's duration before the before-video check, so each step is its own function, asked at its own point, as obs-rust#2153 did. last_video_ts is still read under the pause mutex only while video_start_ts is 0, and video_start_ts is read again after; the duration and the cut in frames are computed only on the cut path; audio_size is read once per plane; mixer_mask once per mix; audio_start_ts before the pause mutex is taken and ts_offset under it. C keeps data_active(), audio_pause_check(), the deques and each plane's pointer advance, the raw_audio and raw_audio2 callbacks and the NULL test of raw_audio2, get_first_mixer(), audio_output_connect(), get_audio_conversion(), start_raw_video(), reset_packet_data() under interleaved_mutex, obs_encoder_start(), the delay's fields, os_atomic_set_bool() and log, and every conversion that divides by the sample rate: util_mul_div64(frames, 1e9, sample_rate), util_mul_div64(cutoff, sample_rate, 1e9) and audio_frames_to_ns(), passed in by value. On MSVC x64 util_mul_div64() is _udiv128(), which faults on a zero divisor. stop_raw_audio() is unchanged. The expressions move as they were: the uint64_t sums and differences, the size_t products, the (uint32_t) truncation of the cut, the uint32_t frame difference and the uint64_t delay product. Checked in a scratch harness (not committed). It compiles origin/master's prepare_audio(), default_raw_audio_callback(), start_audio_encoders(), start_video_encoders(), start_raw_audio(), preserve_active(), hook_data_capture(), get_first_mixer() and the flag helpers verbatim, and this branch's with the moved file, as C++, over a stand-in output whose fields log every read and write with the value. It logs every lock and unlock, data_active(), audio_pause_check(), deque push and pop (with their sizes), util_mul_div64(), raw_audio and raw_audio2 call (with the block), audio_output_connect(), get_audio_conversion(), start_raw_video(), obs_output_get_video_conversion(), reset_packet_data(), obs_encoder_start() (with the callback), os_atomic_set_bool() and log line, in order. The stubs answer from one seeded stream in call order; another thread moves last_video_ts and ts_offset around each lock and callback, and audio_pause_check() may move the packet. Reads with no write or call between them are compared as a sorted run, since the C leaves their operand order unsequenced. - Inputs: any flag word (the four flags and random high bits), with and without raw_audio2; video starts of 0, at, one either side of, half a packet, a packet and up to three packets either side of the packet, and random; last_video_ts likewise; rates of 1 Hz to about 1 GHz; audio sizes 0 to 8 and 0 to 8 planes; buffered sizes below, at and above one block in every mix and plane; 0 to 5 packets of 0, 1, 480, 1023 to 1025, 2048, 4096 or random frames, including ones ending exactly at the video start; random audio starts and frame totals; mixer masks of the six mixes and full-range ones; every encoder slot set or not; delays of 0, small and full-range. - 2,600,000 runs (GCC and Clang -O2, 1,000,000 each; GCC -O0, 300,000; GCC -O0 with coverage, 100,000; ASan with UBSan under GCC -O0 and Clang -O2, 100,000 each) give equal events and equal outputs after each run: 1,064,380,967 events. - Every branch of origin/master's functions is reached both ways (gcov). - 21 deliberately broken moves were planted. 20 fail it: the passthrough inverted, last_video_ts read with a video start set, the second video start check dropped, the duration computed before the before-video check, push sizes hoisted out of the plane loop (one audio_size read), mixer_mask read once for the loop, audio_start_ts read under the pause mutex, and thirteen changed decisions (each comparison moved by one, the cut reversed, a frame count off by one, the pause offset dropped, the interleave rule as ||, the delay rule inverted and its product in uint32_t). The 21st, the cut in bytes without the (uint32_t) truncation, is equivalent: the cut in frames never exceeds the packet's uint32_t frames. git blame on the moved lines shows only upstream commits (85ca1b6, 153fa63, a1fbf10, b8a3ae1, 6ec0b2d, 0f9376f and earlier). The fork has not changed them. The constants OBS_OUTPUT_VIDEO and AUDIO_OUTPUT_FRAMES are copied into the header, so it needs no core header; obs-output.c.h checks them with _Static_assert. The new file joins libobs.core-output, just before obs-output.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 nineteen functions are local. Refs obs-rust#2449 * test: Characterize the raw output audio steps test_output_raw_audio_steps compiles libobs/obs-output-raw-audio.c.h and libobs/obs-output-video-checks.c.h (for obs_output_first_mixer()) with ASan and UBSan, and calls only their functions through obs-output-raw-audio.h and obs-output-video-checks.h. 19 cases: - the copied constants; - prepare_audio(): the passthrough over every low 16-bit flag word; no video or audio start over the edge timestamps; before the video over every pair of edge timestamps; the drop for a packet ending before or exactly at the video start, one ending a nanosecond after it, a 0-frame packet and an end wrapping past UINT64_MAX, and over every triple of edge timestamps; the cut in nanoseconds, its timestamp, the cut in bytes and the frames left; - default_raw_audio_callback(): the block and push sizes, the block loop's strict >, the block timestamp, the pause offset and the frame count, with their wraps; - start_raw_audio()'s mix rule over every 8-bit mask and index; - hook_data_capture()'s interleave, delay and delay product rules. prepare_audio(), the block loop of default_raw_audio_callback(), start_raw_audio() and hook_data_capture() are also copied onto a stand-in output that counts the bytes buffered, with the real util_mul_div64(), to pin end to end at 48 kHz: audio before the video by one sample (one frame dropped) and by less than one (the timestamp moves, no frame is dropped), a packet ending exactly at the video start (dropped) and one a nanosecond later (one frame kept), at and after the video, no video start yet (waits; then taken from the pause data, and kept), an audio-only output (always whole), the block loop over one, two and three packets and single packets of 1.5, 2.5 and 3 blocks, with the block timestamps and the pause offset; every 8-bit mixer mask with and without raw_audio2; and every flag combination of the hookup with delays of 0, 1, 20 and UINT32_MAX seconds. Characterized, not endorsed: - the block loop pops only while more than one block is buffered, so the last full block is held back, and nothing sends it when the output stops; - a cut of less than one sample moves the timestamp to the video start but drops no frame, and a packet ending a nanosecond into the video keeps one frame: the conversion rounds down; - a packet whose end wraps past UINT64_MAX is dropped; - the cut in frames is truncated to uint32_t; - with no mix in the mask, raw_audio2 connects none and raw_audio mix 0; bits past MAX_AUDIO_MIXES are ignored. 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. The real-libobs tests test_raw_output_video_reset, test_output_before_video, test_output_delay_e2e, test_output_delay_restart, test_output_interleave_e2e, test_output_input_checks, test_replay_buffer_pause_stop and test_ffmpeg_output_drain cover the callers. Refs obs-rust#2449 * obs-output: Add Tier 1 tests for raw audio RED for the port of libobs/obs-output-raw-audio.c.h to a new raw_audio module of rust/obs-output, next to delay and interleave. The safe core is a stub (todo!()): passthrough(), video_unset(), before_video(), ends_before(), cut_ns(), cut_ts(), cut_bytes(), cut_frames(), start_unset(), block_bytes(), push_bytes(), can_pop(), block_ts(), paused_ts(), next_frames(), mix_on(), interleave(), delay_on() and delay_ns(), with OBS_OUTPUT_VIDEO taken from video_checks and AUDIO_OUTPUT_FRAMES. tests/output/raw_audio.rs ports test_output_raw_audio_steps 1:1: its 19 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 output written in Rust over the core, with video_checks::first_mixer() for the first mixer. Edge cases (edge_*) check the core against models of the original C: every pair (and for the drop every triple) of 30 special timestamps around the integer and 48 kHz packet edges; the sizes over edge usize values and frame counts; every low 16-bit flag word under four high words; every mix index of every low 16-bit mask under three high words, and indices past the width; the delay over a stride through all u32; 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 expressions inline. soldr cargo test -p obs-data --test obs-tests-core -- output::raw_audio passes 1 of 24 (the constants) and fails 23 with "not yet implemented". Refs obs-rust#2449 * obs-output: Port the raw output audio steps Ports libobs/obs-output-raw-audio.c.h, the raw output audio admission and the capture hookup of obs-output.c, to the raw_audio module of rust/obs-output. obs-output.c.h stays C around it: data_active(), every read of the output, the pause mutex and its reads, audio_pause_check(), the deques and each plane's pointer advance, the raw_audio and raw_audio2 callbacks, the mixer connections, the encoder starts, the delay's fields and log, and every conversion that divides by the sample rate. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/raw_audio.rs): - passthrough(): no OBS_OUTPUT_VIDEO flag; video_unset() and start_unset(): a timestamp of 0; - before_video(), can_pop(): the C's < and >; ends_before(): the wrapping sum at or before the video start; - cut_ns(), cut_ts(), block_ts(), paused_ts(): wrapping differences and sums; next_frames(): a wrapping usize sum; - cut_bytes(), cut_frames(): the low 32 bits of the cut, as the C's (uint32_t) cast, times audio_size (wrapping usize) or from the frames (wrapping u32); block_bytes(), push_bytes(): wrapping usize products; - mix_on(): bit idx of the mask; interleave(): video and audio; delay_on(): not 0; delay_ns(): a u64 product, which cannot wrap. 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/output_raw_audio.rs): the nineteen functions keep the C signatures. No pointer crosses and no struct is mirrored. Intentional difference: mix_on() with an index at or past the width of size_t, where the C's shift is undefined, says not set. The C asks only 0 to 5. C side: the file leaves libobs.core-output for its own group, libobs.ported-output-raw-audio (LIBOBS_PORTED_SOURCES), whose PCH is only obs-output-raw-audio.h; libobs.pch.h keeps the header for obs-output.c. The functions are not EXPORT, so the shims are hidden: rust-hidden.txt, the local: list of rust-exports.map and rust-unexports-macos.txt. libobs-rust already links the crate's ffi. ci/test_ported_sources.py checks the group on every host. test_output_raw_audio_steps still compiles the C file into itself, unchanged. It has no _rust variant, as for test_output_stop_stats_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::raw_audio passes 24 of 24. Refs obs-rust#2449 * obs-output: Check the raw audio port against C Tier 3 for the raw_audio port. The oracle (rust/obs-c-oracle/oracle/output_raw_audio.c) compiles the unchanged libobs/obs-output-raw-audio.c.h with its nineteen functions renamed to oracle_*, plus its two constants, bound in src/output_raw_audio.rs. Nothing in it divides. tests/output/raw_audio_parity.rs compares the oracle, the shims and the core exactly, all three sides: - the two constants; - every two-value decision over every pair of 30 special u64 values (around 0, 2^32, 2^63, u64::MAX, a video start, one 48 kHz packet and one sample), and the drop over every triple (27,000 calls); - the sizes over every pair of 13 special usize values, 12 special frame counts and the 30 special cut lengths; - the passthrough over every low 20-bit flag word and a stride through all u32; the mix rule over every low 16-bit mask under four high words at every index below the width of usize; the delay over 0 to 100,000 and a stride through all u32; the interleave rule; - the callers (prepare_audio(), the block loop, start_raw_audio() and hook_data_capture(), as the C test's stand-in output) on the oracle and on the shims: 186,624 two-packet sequences over flags, video starts, pause data, rates of 1 Hz to 384 kHz, sizes 1 to 8 and 1, 2 and 8 planes around the video start, comparing every admission, cut, push, block and timestamp; every 12-bit mixer mask with and without raw_audio2; every 6-bit flag word with five delays; - proptests (20,000 cases each) of every decision over full-range values and of the callers over packet sequences from any state. The stand-in's conversions are the file's own copy of util_mul_div64()'s portable formula, shared by both sides, with a rate of at least 1; on MSVC x64 the oracle side asserts the rate before it divides (cfg!(all(target_env = "msvc", target_arch = "x86_64"))). The oracle is called for mix_on() only below the width of usize, where the C's shift is defined; that excludes exactly the intentional difference. Otherwise no input is excluded. Mutation check (once, not committed): 27 mutants, 21 in the core and 6 in the shims. mutant Tier 1 Tier 3 passthrough: flag test inverted 9 4 video_unset: <= 1 2 1 start_unset: inverted 8 4 before_video: <= 2 2 ends_before: < 3 2 ends_before: saturating sum 3 2 cut_ns: reversed 7 4 cut_ts: saturating 3 2 cut_bytes: no u32 truncation 3 2 cut_frames: saturating 3 2 the u32 truncation at 16 bits 3 2 block_bytes: 1023 frames 5 4 push_bytes: saturating 2 2 can_pop: >= 4 3 block_ts: saturating 4 3 paused_ts: offset dropped 5 4 next_frames: saturating 2 1 mix_on: next bit 4 3 interleave: || 4 3 delay_on: inverted 4 3 delay_ns: u32 product 4 3 shim passthrough inverted 0 4 shim ends_before: timestamp and duration 0 0 shim cut_ns: arguments swapped 0 4 shim mix_on: arguments swapped 0 3 shim push_bytes: block size 0 4 shim delay_ns: one second short 0 3 (failing tests per tier.) Tier 1 kills all 21 core mutants, Tier 3 26 of 27. The survivor is equivalent: the shim's ends_before() with the timestamp and the duration swapped adds them the same way. soldr cargo test -p obs-data --test obs-tests-core -- output::raw_audio passes 31 of 31 (24 Tier 1, 7 Tier 3). Refs obs-rust#2449 * docs: Record the raw output audio port rust/README.md gets the row for libobs/obs-output-raw-audio.c.h (obs-output::raw_audio): what moved, what stays C and why, the characterized-not-endorsed behaviours (the held-back last block among them), 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/output_raw_audio.rs, in the sorted module list, runs 1024 packets around a video start through every decision prepare_audio() and default_raw_audio_callback() ask, on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median: Rust 12.57 us, C 12.54 us (1.00x). The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2449
vpacher
pushed a commit
to vpacher/obs-studio
that referenced
this pull request
Oct 26, 2026
…rust#2469) * libobs: Move the source audio placement decisions Behaviour-neutral extraction before the Rust port. The decisions of get_buf_placement(), source_output_audio_place(), source_output_audio_push_back(), the last step of source_output_audio_data() and apply_audio_actions() in obs-source.c.h move to libobs/obs-source-audio-place.c.h, as eleven functions on plain values declared in the new libobs/obs-source-audio-place.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _started() (audio_ts != 0) and _older() (timestamp < audio_ts): the place's reset, the push-back rule and the action clamp; - _size(), _offset(), _fits() and _pop_back(): the packet's bytes, its byte placement (util_mul_div64() of the difference, times sizeof(float)), the drop past MAX_BUF_SIZE for the place and the push back, and the bytes popped off the back of each channel; - _outputs(): nothing for a monitor-only source; - _action_frame(), _action_stops(), _fill_end() and _mix_on(): each action's frame, the stop at AUDIO_OUTPUT_FRAMES, how far the previous volume fills and the mixes multiplied. Split per read, as obs-rust#2153 did, so every read stays at its point and under its condition: the C's || and && stay in obs-source.c.h, so audio_ts is read once or twice for the place's reset as before, again after reset_audio_data() for the placement, and in the route only when push_back is set; the action clamp reads it again when it applies, and the frame once more. get_buf_placement() stays C: it takes the two timestamps, read before it asks audio_output_get_sample_rate() as when their difference was its argument. Each channel's size is read after its deque_place(), the first channel's before a push back, monitoring_type before audio_ts, and audio_mixers once per mix. audio_buf_mutex, audio_actions_mutex, reset_audio_data(), deque_place(), deque_pop_back(), deque_push_back(), the DEBUG_AUDIO log, the stores of last_audio_input_buf_size, da_erase(), apply_audio_action(), every get_source_volume() call (before the loop and after each applied action), the volume array and multiply_vol_data() stay in obs-source.c.h. conv_time_to_frames() had no other caller; its expression is _action_frame()'s, so it goes. The expressions move as they were: the uint64_t differences, the (size_t) casts of util_mul_div64(), the size_t sums and products, and the int shift of the mix bit. Checked in a scratch harness (not committed). It compiles origin/master's get_buf_placement(), conv_time_to_frames(), source_output_audio_place(), source_output_audio_push_back(), source_output_audio_data() (whole) and apply_audio_actions() verbatim next to this branch's and the moved file, as C++, over a stand-in source whose fields are wrappers that log every read and write with its value. Every call is logged in order with its arguments: both mutexes, audio_output_get_sample_rate() and _get_channels(), os_gettime_ns(), the two audio timing steps, handle_ts_jump(), the resampler's compensation, every deque call, reset_audio_data() (shared, with its own field accesses), blog(), da_erase(), apply_audio_action(), get_source_volume(), multiply_vol_data() (with a hash of the whole volume array), source_muted() and the audio signal. The stubs answer from one seeded stream in call order, and a concurrent writer may move audio_ts, monitoring_type, audio_mixers or a channel's size at any call. Inputs: audio_ts of 0 and around the packet; packet timestamps at, one to three ns either side of, whole frames and blocks from, and seconds before audio_ts, the ends of int64 and uint64, and random; frames of 0, 1, 480, 1023 to 1025, 4096, around 1024000 and UINT32_MAX; rates of 8000 to 384000 Hz, 0, 1, 1e9 and UINT32_MAX (and any size_t for the actions); 0 to 8 channels; channel sizes empty, around MAX_BUF_SIZE and random; every monitoring type and 7; 0 to 7 actions of each type at those timestamps; any mixer mask. 25,400,000 runs: 10,000,000 each with GCC and Clang at -O2, 2,000,000 each at -O0, 500,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2) and 400,000 with gcov. All 1,077,683,735 events match, as does the final state. Every branch of origin/master's functions is taken both ways, but the switch default of the timing action, which the stub never returns. 22 deliberately broken moves were planted. 21 fail it: audio_ts read once for the place's reset, the placement taken before the reset, audio_ts read before push_back, monitoring_type read after audio_ts, audio_ts read once for the action clamp, get_source_volume() before the fill, apply_audio_action() dropped, audio_mixers read once, and thirteen changed decisions (started at > 1, older at <=, the size in uint32_t, the placement in frames, rounded up, the fit at < and as a saturating sum, the pop one short, monitor-only for NONE, the frame's rate and duration swapped, the stop at >, the fill one short, the next mix bit). The 22nd, _fill_end() always the new frame, is equivalent: the C's loop condition fills nothing when it is not past frame_num. git blame on the moved lines shows only upstream commits (c1dd156, bc0b85c, d2934ec, 0e4ea14, 2963959, a1fbf10 and earlier); the fork's one line there (cb8ec4b, the DEBUG_AUDIO #if) stays. The constants AUDIO_OUTPUT_FRAMES, MAX_BUF_SIZE and OBS_MONITORING_TYPE_MONITOR_ONLY are copied into the header, so it needs no core header; obs-source.c.h checks them, and that enum obs_monitoring_type is int-sized, with _Static_assert. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol sets are unchanged; the eleven functions are local. Refs obs-rust#2461 * test: Characterize the source audio placement test_source_audio_place_steps compiles libobs/obs-source-audio-place.c.h (ASan and UBSan) and calls only its functions through obs-source-audio-place.h. 13 cases: - the header's copies of AUDIO_OUTPUT_FRAMES, MAX_BUF_SIZE and OBS_MONITORING_TYPE_MONITOR_ONLY, and the enum's size; - the started and older rules over every pair of nine edge timestamps; - the packet's size from 0 to UINT32_MAX frames, in size_t; - the byte placement at 0, just under and at one frame, and one second, at 8000, 44100, 48000 and 384000 Hz, one block short of MAX_BUF_SIZE, a rate of 0, and the wrap of an older timestamp; - the fit just under, at and just over MAX_BUF_SIZE, and the pop off the back, with their size_t wraps; - each monitoring type, and every type from -64 to 64 and the ends of int; - the action frames at, just under and at one frame, at frames 1023 and 1024 and one second for each rate, the unclamped wrap, and the stop; - the fill's end and the mix rule over every 8-bit mask. source_output_audio_place(), source_output_audio_push_back(), the last step of source_output_audio_data() and apply_audio_actions() are also copied onto a stand-in source that counts each channel's bytes, to pin end to end: no audio_ts (reset, placed at 0), one frame later, less than a sample later (on top of the start, cut back), an older packet (reset at its own time) and one second later, at each rate; at 48 kHz a block just under, exactly at and one frame past MAX_BUF_SIZE (placed, placed, dropped); the push back just under, at and over it; every monitoring type with and without push_back and an audio_ts; and actions before, at and after audio_ts, at frames 1023 and 1024 (the second stays queued with everything after it), the fill up to an action, none, out of order, and the mixes. Characterized, not endorsed: - a packet less than one sample after audio_ts is placed at 0, on top of the samples already there, and an action that close applies at frame 0: the conversion rounds down; - a packet larger than MAX_BUF_SIZE on its own is dropped whole, even into an empty buffer; - a push back checks only the first channel's size; - an action before audio_ts applies at frame 0; once one is at frame 1024 or later, the loop stops and every later action waits, even one that is due; a later action at an earlier frame fills nothing; - a monitoring type outside the enum outputs; - the fit's sum and the pop wrap as size_t, and the placement and frame of a timestamp before audio_ts wrap (the callers reset or clamp first). It is in the native test graph, in name order, with the header as a watch input. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and no two enum types are compared. The real-libobs tests test_async_delay_audio, test_audio_sync_offset_change, test_audio_clock_drift, test_audio_buffering_subsample, test_media_sync_offset_restart, test_audio_restart_resampler_tail, test_source_volume_mix, test_source_audio_ranges and test_audio_controls cover the callers. Refs obs-rust#2461 * obs-source: Test the audio_place port RED for the port of libobs/obs-source-audio-place.c.h to a new audio_place module of rust/obs-source, next to audio_timing and volume_apply. The safe core is a stub (todo!()): started(), older(), size(), offset(), fits(), pop_back(), outputs(), action_frame(), action_stops(), fill_end() and mix_on(), with FRAMES, MAX_BUF_SIZE and MONITOR_ONLY. The plan sketched place() -> Reset + Drop | Place, route() -> Skip | PushBack | Place and action_frame() -> Stop | At(n). Those would read audio_ts once where the C reads it twice (the place's reset, the action clamp) and read it in the route when push_back is not set, so each step is its own function, asked at its own point, as obs-rust#2153 did. tests/source/audio_place.rs ports test_source_audio_place_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 cases and the stand-in source's copies of the callers included. Edge cases (edge_*) check the core against models of the original C: - every pair of 26 special timestamps (around 0, 2^32, 2^63, u64::MAX, one second, one sample and one block at 48 kHz) for the reset rules, the placement and the action frame at ten rates where every host's util_mul_div64() is exact (0, 1, 8000 to 384000 Hz and 1e9); - the size over special frame counts, and the fit, the fill's end and the stop over every pair, the pop over every triple, of 15 special sizes (around a block, MAX_BUF_SIZE, 2^32 and usize::MAX); - every monitoring type from -70,000 to 70,000 and the ends of int; - the mix rule for every low 16-bit mask under four high words at every bit, and indices past the width; - the first nanosecond of every frame from 0 to 1025 at eleven rates; - proptests (4,096 cases each): every decision over full-range values, and packet and action sequences through the stand-in against a copy of the callers with origin/master's expressions inline. soldr cargo test -p obs-data --test obs-tests-core -- source::audio_place passes 1 of 21 (the constants) and fails 20 with "not yet implemented". Refs obs-rust#2461 * obs-source: Port the source audio placement Ports libobs/obs-source-audio-place.c.h, the source audio placement and action timeline of obs-source.c, to the audio_place module of rust/obs-source. obs-source.c.h stays C around it: every read of the source (audio_ts at each of its points, monitoring_type, the channels' sizes and audio_mixers once per mix), audio_buf_mutex and audio_actions_mutex, audio_output_get_channels() and get_buf_placement() with its audio_output_get_sample_rate() call, reset_audio_data(), the deques, da_erase(), apply_audio_action(), every get_source_volume() call (before the loop and after each applied action), the volume array and multiply_vol_data(). The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/audio_place.rs), eleven functions: - started(): audio_ts != 0; older(): timestamp < audio_ts; - size(): frames times 4, wrapping usize; - offset() and action_frame(): util_mul_div64(timestamp - audio_ts, rate, 1e9) with the difference wrapping, cast to usize as the C casts to size_t; offset() times 4, wrapping; - fits(): the wrapping usize sum at most MAX_BUF_SIZE; pop_back(): the wrapping difference; - outputs(): not MONITOR_ONLY; action_stops(): frame >= FRAMES; fill_end(): the larger frame; - mix_on(): bit mix of the mask, none past the u32's width. The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. The conversion is transition_render's mul_div64() (now pub(crate), with to_size()): the host's util_mul_div64(), the wrapping uint64_t formula, or on MSVC x64 the exact 128-bit quotient, which in the C faults when it does not fit and there saturates. With a divisor of 1e9 both are the exact quotient for any rate up to 1e9 Hz. Shims (src/ffi/source_audio_place.rs): the eleven C signatures by value; the monitoring type as int. No pointer crosses and no struct is mirrored. Intentional differences, on inputs libobs never passes: mix_on() with a mix at or past 32 (the C's int shift is undefined from 31 on) says no mix; on MSVC x64 a frame count past 64 bits (a rate above 1e9 Hz), where the C faults, saturates. libobs asks mixes 0 to 5 and passes the output's sample rate. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-audio-place (LIBOBS_PORTED_SOURCES), whose PCH is only obs-source-audio-place.h and util/util_uint64.h; libobs.pch.h keeps the header for obs-source.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the eleven functions are local in all three, and the hybrid's come from the Rust archive. ci/test_ported_sources.py checks the group on every host. test_source_audio_place_steps still compiles the C file into itself, unchanged. The new test_source_audio_place_steps_rust builds the same test source against libobs_rust-static instead, as test_source_video_tick_steps_rust does, and links: the test includes the header and obs.h and calls only the eleven hidden functions. test_async_delay_audio, test_audio_sync_offset_change, test_audio_clock_drift, test_audio_buffering_subsample, test_media_sync_offset_restart, test_audio_restart_resampler_tail, test_source_volume_mix, test_source_audio_ranges, test_audio_controls, test_source_audio_timing_steps and test_source_volume_apply_steps see the swap through the real libobs, and pass on the C backend, the hybrid and libobs-c-reference. soldr cargo test -p obs-data --test obs-tests-core -- source::audio_place passes 21 of 21. No user-visible change, so no docs/features.md line. Refs obs-rust#2461 * obs-source: Check audio_place against the C Tier 3 for the audio_place port. oracle/source_audio_place.c compiles the unchanged libobs/obs-source-audio-place.c.h with its eleven functions renamed to oracle_*, plus the header's values and sizeof(size_t). tests/source/audio_place_parity.rs gives each input to the oracle, to the shim the hybrid links and to the core, and compares each bool as the byte the C returns (it must be 0 or 1) and each number exactly: - the header's values and sizeof(size_t); - the reset rules over every pair of 30 special timestamps, and the placement and the action frame over every pair at 16 rates (0, 1, 8000 to 384000 Hz, 1e9, 1e9 + 1 and UINT32_MAX), and size_t rates past 32 bits for the frame; - the first and last nanosecond of every frame from 0 to 2048 at eleven rates, and a stride of 70,000 differences at five; - the size over every frame count to 100,000 and every 65,521st uint32_t; the fit, the fill's end and the stop over every pair, and the pop over every triple, of 17 special sizes; - every monitoring type from -100,000 to 100,000, every 65,521st int and the ends; - the mix rule for every low 16-bit mask under eight high words at every mix from 0 to 30; - the callers (source_output_audio_place(), source_output_audio_push_back(), the last step of source_output_audio_data() and apply_audio_actions(), as the C test's stand-in source) on the oracle and on the shims: 36,864 packet pairs over rates, starts, channels, monitoring types, push backs, timestamps and sizes around MAX_BUF_SIZE, and 21,316 action lists; every trace, buffer, volume array and mix must match; - proptests (20,000 cases each) of every function over full-range values and of the callers over packet and action sequences from any state. Not compared: on MSVC x64 (cfg!(all(target_env = "msvc", target_arch = "x86_64"))) a placement or frame past 64 bits, where the C's _udiv128() faults, and the callers at a rate above 1e9 Hz, the only way to reach one; and the mix rule at 31 and up, where the C's int shift is undefined. Those are the two intentional differences. Otherwise no input is excluded. Mutation check (once, not committed): 28 mutants, 18 in the core and its conversion and 10 in the shims (failing tests per tier, Tier 1 of 21 and Tier 3 of 11): mutant Tier 1 Tier 3 core: started at > 1 2 1 core: older at <= 4 3 core: size of frames + 1 7 4 core: size in 2-byte samples 7 4 core: offset in frames 7 5 core: difference saturating 4 2 core: rate + 1 6 5 core: fits at < 5 3 core: fits saturating 2 1 core: pop saturating 3 2 core: pop one short 6 4 core: outputs above monitor only 5 4 core: action rate truncated to u32 0 2 core: stop at > 3 2 core: fill to the smaller frame 5 4 core: mix on the next bit 5 4 core: no mix 31 2 0 conversion: exact quotient on every host 0 3 shim: older arguments swapped 0 6 shim: offset timestamps swapped 0 5 shim: outputs inverted 0 4 shim: fits arguments swapped 0 0 shim: pop placement and size swapped 0 0 shim: action rate masked to 32 bits 0 2 shim: mix + 1 0 4 shim: fill_end arguments swapped 0 0 shim: size of frames + 1 0 4 shim: stop asks frame + 1 0 3 25 are killed. Tier 1 stays at rates up to 1e9 and below 2^32, so the rate truncation and the per-host conversion fall to Tier 3; Tier 3 leaves out mix 31 (undefined in the C), so that one falls to Tier 1. The three survivors are equivalent: the fit adds its arguments and the pop adds placement and size, either way round, and the fill's end is the larger of two frames. soldr cargo test -p obs-data --test obs-tests-core -- source::audio_place passes 32 of 32 (Tier 1 21, Tier 3 11). Refs obs-rust#2461 * docs: Record the source audio placement port rust/README.md gets the row for libobs/obs-source-audio-place.c.h (obs-source::audio_place), in sorted place: what moved, what stays C and why (every read at its point with the C's && and || around the calls, both mutexes, the deques and every get_source_volume() call), the characterized-not-endorsed behaviours, the two intentional differences, the tests that see the swap and what Tier 3 covers. The obs-source crate row, its Cargo description and the lib.rs crate docs name the new module. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. rust/obs-c-oracle/benches/port_comparison/source_audio_place.rs, in the sorted mod and modules![...] lists, runs 1024 packets around an audio timestamp at 48 kHz (no audio_ts yet, older, at it, a sample, a block and seconds later, near MAX_BUF_SIZE; every monitoring type; push back on and off) through the decisions of the last step of source_output_audio_data() and of source_output_audio_place() with two channels, then one action and its six mixes, on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median per 1024 packets: Rust 22.12 us, C 20.97 us (1.05x), about 1 ns a packet. The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2461
vpacher
pushed a commit
to vpacher/obs-studio
that referenced
this pull request
Oct 26, 2026
…-rust#2472) * libobs: Move the PulseAudio monitor steps Behaviour-neutral extraction before the Rust port. The decisions of do_stream_write(), on_audio_playback(), pulseaudio_sink_info(), audio_monitor_init(), on_sink_event(), audio_monitor_reset() and audio_monitor_destroy() in audio-monitoring/pulse/pulseaudio-output.c.h move to the new pulseaudio-monitor-steps.c.h, as twenty functions on plain values declared in pulseaudio-monitor-steps.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - do_stream_write(): _grow() (more than twice tlength queued, a uint32_t product) and _grown_tlength() (the queue as uint32_t), _uncork() (a corked stream starts once a whole tlength is queued), _write_more() (the write loop) and _write_short() (the server asks for more than is queued: cancel and wait); - on_audio_playback(): _playback_idle() (no activate refs), _playback_bytes() (bytes_per_frame * resample_frames, a product in uint_fast32_t) and _needs_volume() (not 1 within EPSILON); - pulseaudio_sink_info(): _sink_result() (error, end of list or a sink); - audio_monitor_init(): _has_device(), _self_monitor_check() (OBS_SOURCE_DO_NOT_SELF_MONITOR), _is_default(), _fallback() (no format and not "default": play on the default sink), _sink_named() (the default sink has a name), _format_invalid(), _tlength_usec() (25 ms) and _open_flags() (the fallback stream's flags are those of "default"); - on_sink_event(): _event_queued() (new and remove only); - audio_monitor_reset(): _context_good() (PA_CONTEXT_IS_GOOD); - audio_monitor_destroy(): _last(). The plan sketched one write_plan() returning grow, uncork and wait, and one open_route() and reset_route(). Those would read the queue and tlength before pa_stream_set_buffer_attr() and pa_stream_is_corked(), the settings before the output flags are checked, and the context state before the context is known not to be NULL, so each step is its own function, asked at its own point, as obs-rust#2153 did. The queue size is still read for each test and again for the new tlength, tlength again after the cork test, activate_refs once after the trylock, the format after each pulseaudio_get_sink_info(), and the monitor count under the monitoring mutex. C keeps pulseaudio_lock() and _unlock(), the playback mutex and its trylock, the monitoring mutex, every pa_* call (pa_stream_set_buffer_attr(), _is_corked(), _cork(), _begin_write(), _cancel_write(), _write(), _get_context(), pa_context_get_state(), pa_usec_to_bytes(), pa_sample_spec_valid(), pa_frame_size()), pulseaudio_get_server_info() and _get_sink_info(), get_default_id(), devices_match(), obs_source_get_settings(), the resampler, the deque, the buffer attributes it writes, the task queue, drop_backlog(), every allocation and every log. The NULL tests of pointers the C dereferences next (the device, the context, the stream) stay with them. The expressions move as they were: the uint32_t tlength * 2, the size_t comparisons, the (uint32_t) truncation of the new tlength, the uint_fast32_t product of the bytes (64 bits on glibc, 32 on FreeBSD), fabsf(vol - 1.0f) <= EPSILON through close_float(), and the masked event type. Checked in a scratch harness (not committed). It compiles origin/master's pulseaudio-output.c.h verbatim and this branch's with the moved file, each as its own C translation unit, over stubs that log every call with its arguments, in order: both locks, the trylock, every pa_* and wrapper call, the deque, the resampler, the settings, the source callbacks, the allocations, the task queue and every log line. The stubs answer from one seeded stream in call order. Another thread moves the queue size, tlength and the format around each lock, pa_* call and callback, moves activate_refs before each load, and adds a monitor to the list when it is unlocked; the sink info callback runs 1 to 3 times per call with eol 0, 1, -1, 2, -2, INT_MAX and INT_MIN. Each run is 1 to 8 operations on up to 8 monitors (create, write, playback, a direct sink info, sink events, running the queued events, reset, destroy), with queue sizes and tlengths at 0, 1, around 4800, around 2 * tlength, around 2^31 and 2^32 and SIZE_MAX; volumes of 1, 1 +- EPSILON and their neighbours, 0, -1, 2, NaN and +-infinity; activate refs of -1 to 2; any output flags; device ids NULL, "", "default", "defaults" and names; any format, rate and channel count from the server; every context state and values outside the enum. The monitors' state is compared after every run. - 2,600,000 runs (GCC and Clang -O2, 1,000,000 each; GCC -O0, 300,000; GCC -O0 with coverage, 100,000; ASan with UBSan under GCC -O0 and Clang -O2, 100,000 each) give equal events and equal state: 215,904,226 events. - Every branch of origin/master's do_stream_write(), on_audio_playback(), pulseaudio_sink_info(), audio_monitor_init(), handle_sink_event(), on_sink_event(), audio_monitor_reset() and audio_monitor_destroy() is reached both ways (gcov). - 32 deliberately broken moves were planted. 31 fail it: 24 changed decisions (each comparison moved by one, the uint32_t product done in size_t, the new tlength saturated, the bytes in uint32_t and one frame over, EPSILON at 1e-3, eol 1 taken as a sink, an error as the end, the flag bit moved, "default" as a prefix, the fallback also for "default", an empty default sink accepted, PA_SAMPLE_MAX taken as invalid, 20 ms, the fallback's flags from the chosen id, change events queued, the event type unmasked, a terminated context taken as good, the last monitor at one), and 7 moved reads or calls (tlength read before the cork test, the queue read before pa_stream_begin_write() for the short test, activate_refs loaded before the trylock, the settings read before the flag check, the format read before pulseaudio_get_sink_info(), pa_context_get_state() asked of a NULL context, and the monitor count read after the mutex is dropped). The 32nd, the queue size read once for the grow test and the new tlength, is equivalent: no call comes between the two reads, under both locks. git blame on the moved lines: upstream (b6042d9, bc9eee9, 9de1ffe, 5142a76, 73dea7c, e8a8ac5, 2963959 and formatting) and the fork's own fixes: the chosen device and its fallback (9295370), the reset that keeps a live monitor (82fdc46) and the stall catch-up (3ebc4fd). OBS_SOURCE_DO_NOT_SELF_MONITOR is copied into the header, so it needs no core header; pulseaudio-output.c.h checks it with _Static_assert. The new file joins libobs.pulse, before pulseaudio-output.c.h, with libobs-pulse.pch.h, which includes the new header and math-defs.h; os-linux.cmake and os-freebsd.cmake list the header. docs/rust-port/naming.md already maps libobs/audio-monitoring/ to rust/obs-audio-monitoring. The exported symbol sets are unchanged (1766 on the C build, hybrid and C reference); the twenty functions are local. The 17 PulseAudio tests pass on all three against a private pipewire-pulse (test_pulse_default_follow skips: it needs a PulseAudio daemon, and its PipeWire variant passes). Refs obs-rust#2470 * test: Characterize the PulseAudio monitor steps test_pulse_monitor_steps compiles libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h and pulseaudio-stream-flags.c.h (for pulseaudio_monitor_stream_flags()) with ASan and UBSan, and calls only their functions through pulseaudio-monitor-steps.h and pulseaudio-stream-flags.h. No server. 20 cases: - the copied OBS_SOURCE_DO_NOT_SELF_MONITOR and the sink results; - do_stream_write(): the grow rule at 2 * tlength - 1, at it and + 1 (strict >) over six tlengths, its uint32_t wrap at 2^31 and up, the new tlength's truncation, the cork rule at tlength - 1, at it and + 1, the write loop at 0, 1 and SIZE_MAX, and the short write when the server asks for more than, all of and less than the queue; - on_audio_playback(): activate refs of 0, 1, 2, -1, LONG_MIN and LONG_MAX; the bytes of a packet, with the uint_fast32_t product's width (64 bits on glibc, 32 on FreeBSD); the volume at 1, at the last floats within EPSILON of 1 on either side and the next ones, at 1 +- EPSILON (which round past it), 0, -0, 0.5, 2, -1, +-infinity and NaN; - pulseaudio_sink_info(): eol of 0, 1 to INT_MAX and -1 to INT_MIN; - audio_monitor_init(): no device (NULL), "default" against "", "Default", "default ", "defaults", "default.monitor" and a name; each of the 32 flag bits alone and cleared; the fallback for a gone sink with every kind of id; the default sink's name NULL, "" or set; the invalid format against every valid one and -2; the 25 ms buffer; the fallback stream's flags (those of "default", whatever the id) and the others' (their id's); - on_sink_event(): new, change, remove and the full type mask on six facilities, and high bits; - audio_monitor_reset(): every context state and two outside the enum; - audio_monitor_destroy(): the last monitor at 0, 1, 2 and SIZE_MAX. Stand-ins copy the order pulseaudio-output.c asks these in, with each call replaced by its answer, to pin end to end: the write loop at 25 ms of 48 kHz stereo float (corked one byte short: nothing; a whole tlength: uncorked and written; asked for more: cancelled, nothing popped; asked in pieces; a piece then more than is left; past twice tlength: grown, then uncorked; at exactly twice: not grown), 14 open routes (no device, the feedback loop prevented for "default" and a name, the flag or the match alone, "default", "default" with no format, the fallback and its three failures, and "" both ways), and the reset routes (replace, keep with no stream or a good context, ignore with no context or a context in any other state). Characterized, not endorsed: - tlength * 2 is a uint32_t product: a tlength of 2^31 or more wraps, so the buffer grows for a much smaller queue; - the new tlength is the queue truncated to uint32_t: past UINT32_MAX bytes the buffer shrinks (2^32 + 5 gives 5); - a NaN volume is not close to 1, so the volume step runs with it; - negative activate refs are not idle; - an empty monitoring device ("") is a name: it falls back to the default sink when it gives no format. It is in the native test graph, in name order, on Linux and FreeBSD with ENABLE_PULSEAUDIO, with both headers as watch inputs. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x. The real-libobs tests test_pulse_monitor_device, test_pulse_default_follow, test_pulse_monitor_reset, test_pulse_stream_restart, test_pulse_two_sources and test_pulse_monitor_samples cover the callers against a private sound server. Refs obs-rust#2470 * obs-audio-monitoring: Test the pulse monitor port RED for the port of libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h to a new pulse_monitor module of rust/obs-audio-monitoring, next to pulse_format and pulse_stream_flags. The safe core is a stub (todo!()): grow(), grown_tlength(), uncork(), write_more(), write_short(), playback_idle(), playback_bytes(), needs_volume(), sink_result(), has_device(), self_monitor_check(), is_default(), fallback(), sink_named(), format_invalid(), tlength_usec(), open_flags(), event_queued(), context_good() and last(), with DO_NOT_SELF_MONITOR, EPSILON, TLENGTH_USEC, the PA_CONTEXT_* states and the SinkResult enum. tests/audio_monitoring/pulse_monitor.rs ports test_pulse_monitor_steps 1:1: its 20 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases included, and the C test's stand-ins (the write loop, the open routes and the reset routes) written in Rust over the core. Edge cases (edge_*) check the core against models of the origin/master C, its expressions inline: the write rules over every pair of 21 or more special sizes and 12 special tlengths (around 4800, 9600, 2^31, 2^32, twice each tlength and SIZE_MAX); the bytes over 11 frame sizes, 12 frame counts and both uint_fast32_t widths; activate refs at the ends of i64; every float within 4096 ulps of 1 and of the two EPSILON boundaries, and the special floats; every eol edge and format with three ids; every low 16-bit event word and flag word under four high words; context states 0 to 64 and the top of u32; ids near "default". Two proptests (4,096 cases each): every decision over full-range values, and the write loop over queues and server asks against the origin/master loop. soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring::pulse_monitor passes 1 of 31 (the constants) and fails 30 with "not yet implemented". Refs obs-rust#2470 * obs-audio-monitoring: Port the pulse monitor steps Ports libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h, the PulseAudio monitor's open and write steps of pulseaudio-output.c, to the pulse_monitor module of rust/obs-audio-monitoring. pulseaudio-output.c.h stays C around it: both locks and the trylock, the monitoring mutex, every read of the monitor, the source and the settings, every pa_* call, the server and sink info calls, get_default_id(), devices_match(), the resampler, the deque, the buffer attributes, the task queue, every allocation and every log. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/pulse_monitor.rs): - grow(): queued > tlength.wrapping_mul(2), widened, as the C's uint32_t product; grown_tlength(): the low 32 bits of the queue; uncork(), write_more(), write_short(): the C's >=, > 0 and >; - playback_idle(): refs == 0; playback_bytes(): the product wrapping in 64 or 32 bits (uint_fast32_t's width, passed by the shim), then the low bits as a usize; needs_volume(): !((vol - 1.0).abs() <= EPSILON) in f32, so NaN needs the step; - sink_result(): eol < 0 Error, > 0 End, else Info; - has_device(), sink_named() (set and not empty), is_default() (the bytes equal "default"), fallback() (invalid and not "default"), format_invalid() (PA_SAMPLE_INVALID), self_monitor_check() (bit 9), tlength_usec() (25,000) and open_flags() (stream_flags() of "default" on the fallback, else of the id); - event_queued(): the masked type is new or remove; context_good(): connecting, authorizing, setting the name or ready; last(): 0. The module denies clippy's arithmetic, as, indexing, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state, takes no lock and does not divide. Shims (src/ffi/pulse_monitor.rs): the twenty functions keep the C signatures. pa_sample_format_t crosses as int, the other pa_* enums and the sink result (0 to 2) as unsigned int, long as c_long and uint_fast32_t as pulse_format's host alias. The id strings are read up to their NUL; no struct is mirrored. Intentional difference: a NULL id given to is_default(), or to fallback() with an invalid format, is not "default" and does not fall back; the C dereferences it. pulseaudio-output.c asks both only after has_device(). C side: the file leaves libobs.pulse for its own group, libobs.ported-pulse-monitor (LIBOBS_PULSE_PORTED_SOURCES), whose PCH is math-defs.h, pulseaudio-monitor-steps.h and pulseaudio-stream-flags.h; libobs-pulse.pch.h keeps the header for pulseaudio-output.c. The functions are not EXPORT, so the shims are hidden: rust-hidden.txt, the local: list of rust-exports.map and rust-unexports-macos.txt. libobs-rust already links the crate's ffi. ci/test_ported_sources.py checks the group on Linux and its absence without PulseAudio. test_pulse_monitor_steps still compiles the C file into itself, unchanged. test_pulse_monitor_steps_rust runs the same file against libobs_rust-static alone (the obs-audio-monitoring member needs nothing from libobs), on Linux and FreeBSD with ENABLE_PULSEAUDIO: 20 of 20. soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring::pulse_monitor passes 31 of 31. The exported symbol sets stay 1766 on the C build, the hybrid and the C reference; the 19 PulseAudio tests pass on the hybrid and the C reference and 18 on the C build, against a private pipewire-pulse (test_pulse_default_follow skips: it needs a PulseAudio daemon; its PipeWire variant passes). Refs obs-rust#2470 * obs-audio-monitoring: Compare pulse monitor to C Tier 3 for the pulse_monitor port. The oracle (rust/obs-c-oracle/oracle/pulse_monitor_steps.c) compiles the unchanged libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h with its twenty functions renamed to oracle_*, and its call of pulseaudio_monitor_stream_flags() renamed to the stream-flags oracle's, so C answers all the way down. It also gives its constants (the copied flag, the sink results, the PA_CONTEXT_* states, PA_SAMPLE_INVALID, sizeof(uint_fast32_t) and sizeof(long)) and a wrapper that converts the frame size to the host's uint_fast32_t as pulseaudio-output.c's field does; bound in src/pulse_monitor_steps.rs. Nothing in it divides. The oracle's stand-in <pulse/def.h> and <pulse/sample.h> (used where libpulse is not installed: MSVC, macOS) gain pa_context_state_t, PA_CONTEXT_IS_GOOD() and pa_usec_t, with libpulse's values; the oracle was also compiled against the stand-ins alone with GCC and Clang -Werror. tests/audio_monitoring/pulse_monitor_parity.rs compares the oracle, the shims and the core exactly, all three sides: - the fourteen constants and the 25 ms buffer; - the write rules over every pair of 151 sizes (around 0, 4800, 9600, 19200, 2^31, 2^32, each special tlength, twice it and its uint32_t wrap, and SIZE_MAX) with 14 special tlengths, and every pair of sizes for the short write; - the activate refs at the ends of long, the bytes over 14 frame sizes and 14 frame counts; - the volume at every float within 2^16 ulps of 1 and of both EPSILON boundaries, and every 4099th bit pattern of all 2^32 (NaNs, infinities, subnormals); - eol from -1000 to 1000 and a stride through all i32; every low 16-bit flag and event word, 256 under each of three high words and a stride through all u32; context states 0 to 4096 and the top of u32; - formats from -1000 to 1000 and the ends of int with 11 ids, the ids through every string function, and NULL where the C takes it; - the callers (the C test's stand-ins) on the oracle and on the shims: 980 write loops over tlengths, queues, cork states and server asks; 139,968 open routes over ids (NULL included), flags, the match, the formats, the default sink's name and the fallback's format, reaching every route; and the reset rule over every context state; - proptests (20,000 cases each) of every decision over full-range values and of the write loop. Only the intentional difference is excluded: is_default() and fallback() (with an invalid format) are not called on the oracle with a NULL id, which the C dereferences. Mutation check (once, not committed): 30 mutants, 23 in the core and 7 in the shims. mutant Tier 1 Tier 3 grow: >= 4 2 grow: product in usize 2 2 grown_tlength: saturating 4 4 uncork: > 4 3 write_more: > 1 2 2 write_short: >= 3 3 playback_idle: <= 0 3 2 playback_bytes: always 64-bit 2 0 playback_bytes: saturating 2 2 needs_volume: < 0 0 needs_volume: NaN taken as close 3 2 sink_result: eol 0 as the end 2 1 has_device: always 1 2 self_monitor_check: bit 8 4 3 is_default: as a prefix 3 2 fallback: also for "default" 3 2 sink_named: "" accepted 4 3 format_invalid: < 0 3 3 tlength_usec: 20 ms 2 1 open_flags: the id on the fallback 3 3 event_queued: change too 3 2 context_good: terminated too 3 2 last: <= 1 2 1 shim grow: arguments swapped 0 3 shim write_short: arguments swapped 0 4 shim playback_bytes: always 32-bit 0 2 shim sink_result: error as the end 0 2 shim open_flags: fallback dropped 0 3 shim has_device: NULL taken as set 0 2 shim context_good: state off by one 0 2 (failing tests per tier.) Tier 1 kills 22 of the 23 core mutants and Tier 3 28 of 30. needs_volume() with < survives both and is equivalent: no f32 differs from 1 by exactly 1e-4f (steps of 2^-23 above 1 and 2^-24 below never land on it). playback_bytes() always 64-bit survives Tier 3 only on a host where uint_fast32_t is 64-bit, as here (64-bit glibc); Tier 1 kills it, and Tier 3 does on FreeBSD and Windows. soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring::pulse_monitor passes 43 of 43 (31 Tier 1, 12 Tier 3). Refs obs-rust#2470 * docs: Record the pulse monitor steps port rust/README.md gets the row for libobs/audio-monitoring/pulse/pulseaudio-monitor-steps.c.h (obs-audio-monitoring::pulse_monitor): what moved, what stays C and why, the characterized-not-endorsed behaviours (the uint32_t tlength * 2 and the truncated new tlength among them), the byte count's host width, the one intentional difference and the tests that cover it; the obs-audio-monitoring crate row, its Cargo description and lib.rs name the new module. docs/rust-port/naming.md already maps libobs/audio-monitoring/ to rust/obs-audio-monitoring. rust/obs-c-oracle/benches/port_comparison/pulse_monitor.rs, in the sorted module list, runs 1024 packets through every decision on_audio_playback() and do_stream_write() ask (the activate refs, the bytes, the volume, the grow and cork rules and the write loop), on the shims and on the oracle, and checks both checksums match; obs-c-oracle gains obs-audio-monitoring as a dev-dependency (Cargo.lock). Release, x86_64 Linux, GCC, a loaded host, criterion medians of two runs: Rust 12.25 us, C 12.24 us (1.00x), and Rust 12.03 us, C 13.61 us. The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2470
vpacher
pushed a commit
to vpacher/obs-studio
that referenced
this pull request
Oct 26, 2026
…rust#2475) * libobs: Move the output encoder slot decisions Behaviour-neutral extraction before the Rust port. The decisions of the encoder slot setters and getters of obs-output.c move to libobs/obs-output-slots.c.h, as twelve functions on plain values declared in the new libobs/obs-output-slots.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - get_first_video_encoder_index() and get_first_audio_encoder_index(): _first_video() and _first_audio(), the lowest occupied slot of an occupancy mask the caller builds (bit i: slot i is set), as can_begin_data_capture() already does; obs_output_audio() now calls get_first_audio_encoder_index() instead of its own copy of the loop; - obs_output_set_mixer(): _mixer_in_range() and _mixer_mask(); - obs_output_set_video_encoder2() and obs_output_set_audio_encoder(): _video_type_ok() and _audio_type_ok() (the type gate, also the slot choice of obs_output_remove_encoder_internal()), _video_index_ok() and _audio_index_ok() (multitrack: below the slot count, else 0 only); for video, _default_index() and _scaled_axis_set() (the encoder at index 0 takes the scaled size when both axes are set); - obs_output_get_video_encoder2(), obs_output_get_audio_encoder() and obs_output_set_preferred_size2(): _video_slot() and _audio_slot(), the bounds, and _default_index() for the raw size write. The plan sketched one slot_gate() returning refuse, same or replace. That would load active() before the type gate logs and returns, and read the slot before the index rule, so each step is its own function, asked at its own point, as obs-rust#2153 did. The log_flag_* calls stay in their order with their short circuit, active() is loaded where it was (after the type gate, before the index rule; after the range check in set_mixer()), info.type is read twice in obs_output_remove_encoder_internal() as the if/else-if did, and scaled_height only when scaled_width is set. C keeps obs_output_valid(), the log_flag_* checks, flag_encoded(), active(), every read of the output and the encoder, every pointer comparison (the slot already holding the encoder, the slots that hold it), every obs_encoder_get_ref() and obs_encoder_release() in their order, obs_encoder_add_output() and _remove_output(), destroy_caption_track() and create_caption_track() (a NULL test of the encoder), obs_encoder_set_scaled_size(), obs_encoder_audio() and every log. obs_output_set_mixers(), obs_output_remove_encoder() and obs_output_set_service() are unchanged: they decide nothing beyond the flag, active and NULL checks that stay, and their short-circuit order (log_flag_service(), then active(), then service->active) cannot move into one call without loading or reading ahead. Checked in a scratch harness (not committed). It compiles origin/master's flag helpers, active(), the two index helpers, obs_output_video(), obs_output_audio(), the mixer setters and getter, both remove functions, the four encoder setters and three getters, obs_output_set_service() and both preferred-size setters verbatim, and this branch's with the moved file, as C++, over a stand-in output whose fields (the flags, the slots, the caption tracks, the scaled size, the mixer mask, the service, the encoders' types, the services' active and output) log every read and write with the value. It logs every obs_output_valid(), active load, reference, release, output hookup, caption track, scaled size, obs_encoder_audio() and _video() and log line, in order, and each call's result. The stubs answer from one seeded stream in call order; another thread may flip active after any load of it, and a reference may fail. Reads with no write or call between them are compared as a sorted run. - Inputs: one to four calls of the eighteen entry points on one output, with any flag word (the seven flags and random high bits), every slot empty or holding one of six encoders (two video, two audio, types 2 and 9), indexes 0, 1, max - 1, max, max + 1, 2^32, SIZE_MAX and random, NULL encoders and NULL outputs, sizes 0, 1, 1280 and random, three services (one active, one owned by another output). - One expected difference, normalized on both sides: building the mask reads every slot, where the loop stopped at the first set one (plain pointers, no call, lock or write between). A scan of slots 0, 1, 2, ... in order is cut after its first set slot; every other read must match. - 2,600,000 runs (GCC and Clang -O2, 1,000,000 each; GCC -O0, 300,000; GCC -O0 with coverage, 100,000; ASan with UBSan under GCC -O0 and Clang -O2, 100,000 each) give equal events and equal state after each run: 34,198,187 events. - Every line and branch of origin/master's functions, this branch's and the moved file's is reached both ways (gcov). - 22 deliberately broken moves were planted. 21 fail it: each decision changed (the bit test inverted, slot 0 skipped, the last audio slot missed, the mask shifted by one, the range check, mask, type, index, default-index, scaled-size and bound rules each off by one, inverted or on the wrong kind), active() loaded before the type gate, scaled_height read with scaled_width 0, info.type read once in remove_encoder_internal(), the audio index rule dropped (it crashes), the raw size written at any index, and obs_output_audio() taking slot 0. The 22nd, _first_audio() scanning ten slots, is equivalent here: the caller's mask has no bit from 6 up. The characterization test pins the function itself. git blame on the moved lines shows upstream commits (6ec0b2d, 84e1f47, 6da26a3, b8a3ae1, 2036de8 and earlier) and one fork change, the mixer range check of obs-rust#2142. The constants (OBS_OUTPUT_MULTI_TRACK_AUDIO and _VIDEO, the two slot counts, MAX_AUDIO_MIXES and the two encoder types) are copied into the header, so it needs no core header; obs-output.c.h checks them with _Static_assert. The new file joins libobs.core-output, just before obs-output.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) on the C build, hybrid and c-ref; the twelve functions are local. Refs obs-rust#2467 * test: Characterize the output encoder slot steps test_output_slots_steps compiles libobs/obs-output-slots.c.h with ASan and UBSan, and calls only its functions through obs-output-slots.h. 16 cases: - the copied constants; - the first occupied video slot over every 10-bit mask under four high words, the first audio slot over every 6-bit mask likewise, the last slot of each, and no write of the index when none is set; bits past the slot count are ignored (slots 6 to 9 are video only); - set_mixer()'s range check at 5, 6 and the edge indexes, and the mask over every shift below the width of size_t; - the two type gates over eight types (the two real ones, 2, 3, 9, the negative and INT_MAX); - the two index rules over every low 8-bit flag word, with and without high bits, at 15 edge indexes (0, 1, 2, 5, 6, 7, 9, 10, 11, 31, 32, 63, 64, SIZE_MAX - 1, SIZE_MAX): OBS_OUTPUT_MULTI_TRACK is the audio flag, OBS_OUTPUT_MULTI_TRACK_VIDEO the video one, and each says nothing about the other kind; - the default index, the scaled-size axis test and the two bounds. The callers are also copied onto a stand-in output that records every warning, active load, reference, release, hookup, caption track and scaled size in order: obs_output_set_video_encoder2(), obs_output_set_audio_encoder(), the getters, obs_output_get_video_encoder(), obs_output_audio(), obs_output_set_mixer(), obs_output_remove_encoder_internal() and obs_output_set_preferred_size2(). They pin, end to end, for raw, encoded, video-only, audio-only and multitrack outputs: the flag warnings before anything else, the type warning before the active load, the active refusal (even for NULL), the index rules at 0, 1, max - 1, max and SIZE_MAX, the same encoder twice (nothing after the active load), the release of the old encoder before the reference to the new one, NULL clearing a slot and destroying its caption track, the preferred size at index 0 only and only with both axes set, the getters' bounds whatever the flags, the first encoder of obs_output_get_video_encoder() and obs_output_audio(), set_mixer() at MAX_AUDIO_MIXES - 1 and at it (the range warning before the active refusal), remove_encoder_internal() clearing every slot of the encoder's kind, and set_preferred_size2()'s raw write at index 0 and encoder size at any slot. Characterized, not endorsed: - an encoder whose reference fails (it is being destroyed) leaves the slot empty but still gets a caption track: the C tests the encoder it was passed, not the reference it got; - clearing video slot 0 of an output with a scaled size still sets the size, on the NULL slot, so obs_encoder_set_scaled_size() logs a NULL parameter; - remove_encoder_internal() looks for a video encoder only in the video slots (the setters refuse to put it anywhere else). obs_output_set_service(), obs_output_set_mixers() and obs_output_remove_encoder() moved nothing, so they are not copied here. It is in the native test graph, in name order, with the header as a watch input, and links libm off MSVC. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and it compares no values of two different enum types. The real-libobs tests test_multitrack_encoder_override, test_output_input_checks, test_service_encoder_settings, test_output_interleave_e2e, test_output_caption_codec, test_raw_output_video_reset and test_output_null_id cover the callers; test_multitrack_ladder the frontend's track layout. Refs obs-rust#2467 * obs-output: Add Tier 1 tests for output slots RED for the port of libobs/obs-output-slots.c.h to a new output_slots module of rust/obs-output, next to video_checks. The safe core is a stub (todo!()): SlotKind (Video, Audio) and its count(), first_slot(), mixer_in_range(), mixer_mask(), type_ok(), index_ok(), default_index(), scaled_axis_set() and slot_exists(), with the multitrack flags, the slot counts, the two encoder types and MAX_AUDIO_MIXES (from video_checks). The two C functions per kind (_first_video and _first_audio, ...) take the kind here. tests/output/output_slots.rs ports test_output_slots_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 output written in Rust over the core. Edge cases (edge_*) check the core against models of the original C: the slot counts; the first slot over every 16-bit mask under four high words; the index rules over every low 16-bit flag word under four high words at indexes 0 to 11 and 15 edge values; the mixer mask past the width of usize (0, where the C's shift is undefined); the type gates over -1000 to 1000 and the i32 edges; a proptest of every decision over full-range values (4,096 cases); and a proptest of the stand-in over sequences of 1 to 11 calls (the setters, getters, obs_output_audio(), set_mixer(), remove_encoder_internal(), set_preferred_size2() and active flips) from any start, against the same stand-in with origin/master's expressions inline (4,096 cases). soldr cargo test -p obs-data --test obs-tests-core -- output::output_slots passes 1 of 23 (the constants) and fails 22 with "not yet implemented". Refs obs-rust#2467 * obs-output: Port the output encoder slot steps Ports libobs/obs-output-slots.c.h, the encoder slot rules and setter gates of obs-output.c, to the output_slots module of rust/obs-output. obs-output.c.h stays C around it: obs_output_valid(), the log_flag_* checks in their order, flag_encoded(), the active loads, every read of the output and the encoder, the occupancy masks, the pointer comparisons, every reference and release, the encoder hookups, the caption tracks, the scaled size and the logs. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/output_slots.rs): - SlotKind (Video, Audio): its count (10, 6), multitrack flag (OBS_OUTPUT_MULTI_TRACK_VIDEO, OBS_OUTPUT_MULTI_TRACK) and encoder type; - first_slot(): the lowest set bit of the mask below the count; - mixer_in_range(): below MAX_AUDIO_MIXES; mixer_mask(): bit idx; - type_ok(): the kind's encoder type; index_ok(): with the kind's multitrack flag below its count, else 0 only; slot_exists(): below the count, whatever the flags; - default_index(): 0; scaled_axis_set(): not 0. The module denies clippy's arithmetic, as, indexing, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state, takes no lock and does no arithmetic; its slot counts are asserted at compile time against the ones video_checks mirrors. Shims (src/ffi/output_slots.rs): the twelve functions keep the C signatures. The one pointer is the index the two first_* shims write, only when a slot is set, as the C did; no struct is mirrored. Intentional difference: mixer_mask() with an index at or past the width of size_t, where the C's shift is undefined, gives 0. The C asks only 0 to 5. C side: the file leaves libobs.core-output for its own group, libobs.ported-output-slots (LIBOBS_PORTED_SOURCES), whose PCH is only obs-output-slots.h; libobs.pch.h keeps the header for obs-output.c. The functions are not EXPORT, so the shims are hidden: rust-hidden.txt, the local: list of rust-exports.map and rust-unexports-macos.txt. libobs-rust already links the crate's ffi. ci/test_ported_sources.py checks the group on every host. test_output_slots_steps still compiles the C file into itself, unchanged. It has no _rust variant, as for test_output_raw_audio_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::output_slots passes 23 of 23. Refs obs-rust#2467 * obs-output: Check the output slots port against C Tier 3 for the output_slots port. The oracle (rust/obs-c-oracle/oracle/output_slots.c) compiles the unchanged libobs/obs-output-slots.c.h with its twelve functions renamed to oracle_*, plus its seven constants, bound in src/output_slots.rs. Nothing in it divides or calls out. tests/output/output_slots_parity.rs compares the oracle, the shims and the core exactly, all three sides: - the seven constants; - the first slot of each kind over every 16-bit mask under 16 high words and a stride through all u32, with whether the index was written (it starts as a sentinel); - the mixer range over 0 to 1023 and the edge indexes, the mask at every shift below the width of usize; - the type gates over -100,000 to 100,000 and the i32 edges; - the index rules over every low 16-bit flag word under four high words at indexes 0 to 11 and 15 edge values; - the default index and the bounds over 0 to 1023 and the edges, the scaled-size axis over 0 to 1023 and a stride through all u32; - the callers (both encoder setters, the getters, obs_output_get_video_encoder(), obs_output_audio(), set_mixer(), remove_encoder_internal() and set_preferred_size2(), as the C test's stand-in output) on the oracle and on the shims: every one- and two-call sequence of 14 calls from 64 starts (every combination of the video, audio, encoded and both multitrack flags, empty or with encoders, captions and a scaled size; 13,440 sequences), and each call from those starts made active, comparing every warning, active load, reference, hookup, caption track, scaled size and result; - proptests (20,000 cases each) of every decision over full-range values and of the callers over sequences of up to 16 calls from any start. The oracle is called for mixer_mask() only below the width of usize, where the C's shift is defined; that excludes exactly the intentional difference. Otherwise no input is excluded. Mutation check (once, not committed): 23 mutants, 16 in the core and 7 in the shims. mutant Tier 1 Tier 3 first_slot: bit test inverted 6 4 first_slot: slot 0 skipped 5 4 count: ten audio slots 10 6 bit_set: the next bit 6 4 mixer_in_range: <= 4 4 mixer_mask: the next bit 4 4 mixer_mask: all bits past the width 2 0 type_ok: inverted 10 4 encoder_type: kinds swapped 9 3 multi_track_flag: kinds swapped 8 4 index_ok: multitrack <= 6 4 index_ok: single track takes 1 6 3 index_ok: flag test inverted 8 4 default_index: <= 1 5 3 scaled_axis_set: > 1 1 1 slot_exists: <= 5 4 shim first_video: audio slots 0 4 shim first: index written when none 0 2 shim video_type_ok: audio 0 3 shim audio_index_ok: video 0 4 shim video_slot: audio 0 4 shim mixer_mask: the next index 0 4 shim scaled_axis_set: inverted 0 4 (failing tests per tier.) Tier 1 kills all 16 core mutants, Tier 3 22 of 23. Its survivor is the intentional difference: the mask past the width of usize, where the oracle is not called; Tier 1 pins it. soldr cargo test -p obs-data --test obs-tests-core -- output::output_slots passes 32 of 32 (23 Tier 1, 9 Tier 3). Refs obs-rust#2467 * docs: Record the output encoder slot port rust/README.md gets the row for libobs/obs-output-slots.c.h (obs-output::output_slots): what moved, what stays C and why, the one read that changed (the occupancy mask reads every slot, as can_begin_data_capture() already does), the characterized-not-endorsed behaviours (a caption track for a slot whose reference failed, the scaled size asked of a cleared slot), 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/output_slots.rs, in the sorted module list, runs 1024 rounds of every decision the setters, getters and obs_output_set_mixer() ask (both first-slot scans, the type, index, default-index, scaled-size, bound and mixer rules), on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median: Rust 14.81 us, C 15.29 us (0.97x). The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2467
vpacher
pushed a commit
to vpacher/obs-studio
that referenced
this pull request
Oct 26, 2026
…rust#2478) * libobs: Move the transition start decisions Behaviour-neutral extraction before the Rust port. The decisions of obs_transition_start(), set_source(), activate_transition(), obs_transition_get_active_source(), obs_transition_save(), obs_transition_set_manual_time(), obs_transition_set() and copy_source_state() in obs-source-transition.c.h move to libobs/obs-source-transition-start.c.h, as fourteen functions on plain values declared in the new libobs/obs-source-transition-start.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _refused(): the first refusal of obs_transition_start() (the destination is source A and nothing is running); - _walks(): whether the recursion walk runs (a destination that is not the transition itself); - _admit() -> GO | REFUSE | DONE: the second read's refusal and the manual same-target success; - _duration_ns(): (uint64_t)ms * 1000000; - _restart(): set_source()'s clock rule; - _adds(), _removes() and _calls_back(): the handover of an active slot (the new child added first, the old one removed only if the add worked) and the admission callback; - _unsized(): a transition size of 0; - _null_dest(): a start to no destination sets both flags itself; - _activates(): activate_transition() adds only to a slot not active yet; - _active_index(): B while transitioning, else A; - _manual_reset(): manual mode and t == 0.0f; - _child_active(): a child goes out (obs_transition_set()) or comes in (copy_source_state()) as an active child. Split per read, as obs-rust#2153 did. obs_transition_start() reads the sources in three lock sections on purpose (the plugin's transition_start callback can re-enter, and obs_transition_set() runs in between), so each function gets only what one section read and is asked where the C decided before. The rest stays C at its point: the locks, lock_textures(), the pointer comparisons, transition_active() and its ||, which reads the video flag only when the audio flag is clear (so the "finish the running transition first" step and the stop signal are still that read), the fixed duration read (only when it is enabled), the size reads (cy only when cx is not 0), copy_source_state()'s read of the old slot's flag (only with an old child), the swap gate (tr_dest == tr_source), every obs_source_get_ref() and obs_source_release(), the active child calls, the recursion walk and check_transition_recursion(), the plugin callback, the signals, recalculate_transition_size() and _matrices(), os_gettime_ns() and the logs. The mode crosses as int; the header copies OBS_TRANSITION_MODE_MANUAL and obs-source-transition.c.h checks it with _Static_assert (enum obs_transition_mode is already checked int-sized there). Checked in a scratch harness (not committed). It compiles origin/master's transition_active(), write_start_clock(), set_source(), obs_transition_get_active_source(), activate_transition(), check_transition_recursion(), obs_transition_start(), obs_transition_set_manual_time(), obs_transition_set(), obs_transition_save(), copy_source_state(), obs_transition_swap_begin(), obs_transition_swap_end() and obs_transition_clear() verbatim next to this branch's and the moved file, as C++, over stand-in sources whose fields log every read and write with its value. Every call is logged in order with its arguments: both mutexes of both transitions (lock and unlock), transition_valid(), obs_source_get_ref() (which may return NULL, as for a source being destroyed), obs_source_release(), the active child calls (the add may fail), obs_source_enum_full_tree() with each visit, obs_source_get_name(), blog(), the signals, os_gettime_ns(), the size and matrix recalculation and the obs_data writes. A concurrent writer, which takes the transition's mutex as libobs does, may move any source, slot flag, transitioning flag, the mode, the manual target and value, the size, the fixed duration and the start time at any unlock or call. The plugin's transition_start may do nothing, start the transition again (two levels deep), set it, set a manual time or write a field. Inputs: two transitions and four children; every slot empty or any source; every flag; modes 0, 1 and out of the enum; durations 0, 1, 300, 1000, UINT32_MAX - 1, UINT32_MAX and random; sizes 0, 1 and full HD; fixed duration on and off; manual times 0, -0, NaN, 1, 0.5, the smallest denormal, -1 and infinity; destinations empty, the transition itself, the other transition or a child; one to six operations each. 11,000,000 runs: 4,000,000 each with GCC and Clang at -O2, 1,000,000 each at -O0, 300,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2) and 400,000 with gcov. All 1,236,343,886 events match, as does the final state. Every branch of origin/master's functions is taken both ways, but set_source()'s callback == NULL edge: every caller passes activate_transition(). 29 deliberately broken moves were planted, and all 29 fail it: the second section read without its lock, the second section's reads merged into the first, the video flag read always (restart rule and active source), cy read always, the fixed duration read always, the old child removed before the add, obs_transition_save() reading the flags before its lock, the old slot's flag read without an old child, and twenty-one changed decisions (each operand of each rule dropped or inverted, the duration in us and in 32 bits, the size at 1, the reset at t <= 0 and not for -0.0, and the active index swapped). git blame on the moved lines shows upstream commits (6839ff7, a97039d, e6b52f2, a1fbf10) and the fork's recursion fix from obs-rust#737 (8094e1f: the clock flags, the walk's start value and the null destination); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol sets are unchanged; the fourteen functions are local. Refs obs-rust#2473 * test: Characterize the transition start checks test_transition_start_steps compiles libobs/obs-source-transition-start.c.h (ASan and UBSan) and calls only its functions through obs-source-transition-start.h. 17 cases: - the header's copy of OBS_TRANSITION_MODE_MANUAL, the enum's size and the admission values; - the first refusal and the recursion walk over all four inputs each; - the second admission over all 16 flag combinations at six modes (0, manual, 2, -1 and the ends of int); - the duration in ns at 0, 1, 300, around 2^32 ns and UINT32_MAX ms; - set_source()'s clock rule, the handover, the callback gate and the null destination over every combination, the size of 0, the slot activation, the active index and the active child rule; - the manual reset at 0, -0 (resets), NaN (does not), 1, the smallest denormal either side, -1 and infinity, and never outside manual mode. obs_transition_start(), set_source(), activate_transition(), obs_transition_set(), obs_transition_set_manual_time(), the active source and the swap are also copied onto a stand-in transition that counts each child's references and active references, to pin end to end: a start from idle (sized and unsized), to source A, to the transition itself and to a tree that holds it (refused before anything changes), while running (finished on B first, then to the new one), and to no destination with and without a source A; a re-entering transition_start callback that starts the same transition, to another destination and to the same one; a failed add (a cycle the walk did not see) that keeps the nested start's clock and child; the fixed duration on and off at 0, 1, 300 and UINT32_MAX against the same requested durations; the manual times at 0, -0, NaN and 1 in manual and auto mode; the swap with the same transition, a running one and inactive slots; and the set while running, idle and to none. Characterized, not endorsed: - the mode a re-entering start writes stays, even when the outer start then completes (the comment in obs_transition_start() says so); - since upstream's finish step (0df94d5) runs before the second read, a running manual transition started again to the same destination finishes on it, and the start is then refused as a start to source A: the transition jumps to the destination. The manual "already there" success needs another thread's start between the finish and the second read; - a start to no destination with a source B in a slot that is not active adds NULL, which fails, and is refused with the recursion warning (libobs never leaves a source B in an inactive slot); - obs_transition_set() marks slot A active even when the add of the new source fails, so the next set removes an active reference it never got. It is in the native test graph, in name order, with the header as a watch input. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and no two enum types are compared. The real-libobs tests test_transition_recursive_destination, test_transition_swap, test_studio_mode_swap, test_studio_mode_exit, test_saved_transition, test_tbar_position, test_fade_to_color_mix, test_visibility_transition and test_stinger_media_duration cover the callers. Refs obs-rust#2473 * obs-source: Test the transition_start port RED for the port of libobs/obs-source-transition-start.c.h to a new transition_start module of rust/obs-source, next to transition_clock and transition_render. The safe core is a stub (todo!()): refused(), walks(), admit() -> Admission (Go, Refuse, Done), duration_ns(), restart(), adds(), removes(), calls_back(), is_unsized() (unsized is a reserved word), null_dest(), activates(), active_index(), manual_reset() and child_active(), with MODE_MANUAL taken from transition_clock. The plan sketched first_gate(), second_gate(), clock(), handover(), after_add() and needs_resize() as wider steps. handover() and after_add() would decide the remove before the add's result is known, and needs_resize(cx, cy) would read cy when cx is 0, where the C reads it only when cx is not 0. So each step is its own function, asked at its own point, as obs-rust#2153 did; the fixed duration choice, the finish step and the swap gate stay C as the reads they are. tests/source/transition_start.rs ports test_transition_start_steps 1:1: its 17 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases and the stand-in transition's copies of the callers included. Edge cases (edge_*) check the core against models of the original C: - every decision over every combination of its flags; - the second admission over all 16 flag combinations and the manual reset at both zeros and NaN for every mode from -70,000 to 70,000 and the ends of i32; - the duration at every power of two and its neighbours, every 65,521st u32 and the ends, against the exact 128-bit product; - the manual reset over 18 special floats (both zeros, NaNs with either sign and payload, infinities, denormals, the extremes) at six modes, and every 4,099th f32 bit pattern; - proptests (4,096 cases each): every decision over full-range values and any f32 bit pattern, and sequences of up to eleven starts, sets, manual times, active source reads and swaps, with a re-entering plugin, failing adds, a fixed duration and unsized transitions, through the stand-in against a copy of the callers with origin/master's expressions inline. soldr cargo test -p obs-data --test obs-tests-core -- source::transition_start passes 1 of 23 (the constants) and fails 22 with "not yet implemented". Refs obs-rust#2473 * obs-source: Port the transition start checks Ports libobs/obs-source-transition-start.c.h, the start checks and child handover of obs-source-transition.c, to the transition_start module of rust/obs-source. obs-source-transition.c.h stays C around it: the three lock sections of obs_transition_start() with their reads, the pointer comparisons, transition_active(), the finish step, the fixed duration read, the size reads, lock_textures(), every obs_source_get_ref() and obs_source_release(), the active child calls in their order, the recursion walk, the plugin's transition_start callback (which can re-enter), the signals, the size and matrix recalculation, os_gettime_ns() and the logs. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/transition_start.rs), fourteen functions: - refused(): same_as_source && !active; walks(): has_dest && !recursive; - admit() -> Admission: Refuse as refused(), Done when active, manual, the same mode and the same destination, else Go; - duration_ns(): the u32 widened to u64 times 1e6 (cannot wrap); - restart(): !active || (!same_as_dest && !same_as_source); - adds(), removes(), calls_back() and child_active(): the C's &&; - is_unsized(): size == 0; null_dest(): !has_dest && same_as_dest && !same_as_source; activates(): !slot_active; - active_index(): 1 while active, else 0; - manual_reset(): MODE_MANUAL and t == 0.0, an IEEE compare (true for -0.0, false for NaN) as the C's t == 0.0f. MODE_MANUAL is transition_clock's. The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. Shims (src/ffi/source_transition_start.rs): the fourteen C signatures by value; the mode as int, the admission as the C's enum (u32, as source_transition_clock returns its step). No pointer crosses and no struct is mirrored. No intentional difference from the C. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-transition-start (LIBOBS_PORTED_SOURCES), whose PCH is only obs-source-transition-start.h; libobs.pch.h keeps the header for obs-source-transition.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the fourteen functions are local in all three, and the hybrid's come from the Rust archive (the group's object is built only for libobs-c-reference). ci/test_ported_sources.py checks the group on every host. test_transition_start_steps still compiles the C file into itself, unchanged. The new test_transition_start_steps_rust builds the same test source against libobs_rust-static instead, as test_source_audio_place_steps_rust does, and links: the test includes the header and obs.h and calls only the fourteen hidden functions. test_transition_recursive_destination, test_transition_swap, test_studio_mode_swap, test_studio_mode_exit, test_saved_transition, test_transition_scale_type, test_item_transition_empty_source, test_visibility_transition, test_stinger_media_duration, test_transition_removed_child_audio, test_group_hide_transition_audio, test_tbar_position, test_fade_to_color_mix, test_transition_audio_rescale, test_slideshow_manual_end, test_transition_clock_steps and test_transition_render_steps see the swap through the real libobs, and pass on the C backend, the hybrid and libobs-c-reference. soldr cargo test -p obs-data --test obs-tests-core -- source::transition_start passes 23 of 23. No user-visible change, so no docs/features.md line. Refs obs-rust#2473 * obs-source: Check transition_start against the C Tier 3 for the transition_start port. oracle/source_transition_start.c compiles the unchanged libobs/obs-source-transition-start.c.h with its fourteen functions renamed to oracle_*, plus the header's values and the sizes of the admission enum, bool and size_t. tests/source/transition_start_parity.rs gives each input to the oracle, to the shim the hybrid links and to the core, and compares each bool as the byte the C returns (it must be 0 or 1), the admission as the C's enum value and each number exactly: - the header's values and the three sizes; - every function of flags over every combination of them; - the second admission over all 16 flag combinations for every mode from -100,000 to 100,000, every 65,521st int and the ends; - the duration and the size rule over every value to 100,000, every 65,521st uint32_t, every power of two and its neighbours, and the ends; - the manual reset at every mode from -1,000 to 1,000 and the ends over 36 special floats, and in manual mode over every 257th f32 bit pattern, the 65,536 patterns either side of both zeros, of both infinities and of the start of both quiet NaN ranges; - proptests (20,000 cases each) of every function over any flags, any int mode, any uint32_t and any f32 bit pattern. Nothing is excluded: the C has no undefined or host-dependent result here, and the port has no intentional difference. The callers are not copied again: every function's whole flag domain is compared, and Tier 1's sequence proptest runs the copied callers on the core against origin/master's expressions inline. Mutation check (once, not committed): 43 mutants, 27 in the core and 16 in the shims (failing tests per tier, Tier 1 of 23 and Tier 3 of 6): mutant Tier 1 Tier 3 core: refused ignores active 7 3 core: refused ignores the source 17 3 core: walks ignores recursive 4 2 core: done without active 4 2 core: done in any mode 3 2 core: done without the same mode 3 2 core: done without the same dest 3 2 core: done asked before refuse 0 0 core: duration in us 11 2 core: duration in 32 bits 5 2 core: restart ignores active 4 2 core: restart ignores source A 2 2 core: restart || as && 5 2 core: adds ignores the slot 11 2 core: removes ignores the add 4 2 core: removes ignores the old child 2 2 core: calls back after a failed add 4 2 core: unsized at 1 1 1 core: null dest ignores source A 2 2 core: null dest ignores the dest 2 2 core: activates inverted 9 2 core: active index inverted 6 2 core: reset at t <= 0 4 2 core: reset not for -0.0 5 1 core: reset in any mode 5 1 core: child_active ignores the slot 3 2 core: MODE_MANUAL 2 5 4 shim: refuse and done swapped 0 2 shim: refused arguments swapped 0 2 shim: walks recursive inverted 0 2 shim: admit mode + 1 0 2 shim: duration + 1 0 2 shim: restart dest and source swapped 0 0 shim: removes old and add swapped 0 0 shim: adds arguments swapped 0 0 shim: unsized of size / 2 0 1 shim: null dest dest and source swapped 0 0 shim: active index inverted 0 2 shim: reset of -t 0 0 shim: reset mode + 1 0 1 shim: child_active arguments swapped 0 0 shim: calls_back add inverted 0 2 shim: activates inverted 0 2 36 are killed: Tier 1 kills every core mutant that changes a result, and Tier 3 kills every one that does, in the core and the shims. The seven survivors are equivalent: the core asking Done before Refuse (the two need active and !active, so they never meet); the shims swapping the arguments of adds(), removes(), child_active() (each an && of its arguments), restart() (symmetric in the destination and source A) and null_dest() (!has_dest && same_as_dest && !same_as_source is the same with has_dest and same_as_source swapped); and the reset of -t (negation keeps both zeros zero and NaN NaN). soldr cargo test -p obs-data --test obs-tests-core -- source::transition_start passes 29 of 29 (Tier 1 23, Tier 3 6). Refs obs-rust#2473 * docs: Record the transition start port rust/README.md gets the row for libobs/obs-source-transition-start.c.h (obs-source::transition_start), in sorted place: what moved, what stays C and why (every read in its lock section, since obs_transition_start() reads the sources in three sections on purpose and the plugin's transition_start callback can re-enter; the || around transition_active(), the fixed duration and size reads, the active child calls in their order, the walk, the callbacks and the signals), the characterized-not-endorsed behaviours, the tests that see the swap and what Tier 3 covers. The obs-source crate row, its Cargo description and the lib.rs crate docs name the new module. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. rust/obs-c-oracle/benches/port_comparison/source_transition_start.rs, in the sorted mod and modules![...] lists, runs 1024 starts over every combination of the flags the C reads, manual and auto modes, durations from 0 to UINT32_MAX ms and sizes of 0 and full HD, through every decision in the C's order, then a manual time and the set's two active child rules, on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median per 1024 starts: Rust 19.65 us, C 20.63 us (0.95x), about 19 ns a start. The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2473
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
Behaviour-neutral extraction before the Rust port. The flag rules and setter checks of obs-canvas.c.h move to libobs/obs-canvas-rules.c.h, as seventeen functions on plain values declared in the new libobs/obs-canvas-rules.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _main_flags() and _public_flags(): MAIN | PROGRAM for obs_create_main_canvas(), and the public mask of obs_canvas_create(), obs_canvas_create_private() and obs_load_canvas(), which still casts the saved int64 to uint32_t itself; - _main_view() and _mix_audio(): the view type and the mix's mix_audio, in obs_canvas_create_internal() and obs_canvas_reset_video_internal(); - _public(): a canvas that is not private is named, unnamed, renamed through the hash table and signalled on obs->signals (canvas_dosignal(), obs_canvas_create_internal(), obs_canvas_destroy(), obs_canvas_set_name()); - _holds_scenes(): SCENE_REF, in obs_canvas_destroy(), obs_canvas_insert_source() and obs_canvas_remove_source(); - _saves(): neither EPHEMERAL nor REMOVED; - _size_set() and _format_set(): obs_canvas_has_valid_video_info(); - _resets(), _global_signals(), _channel_ok(), _name_empty(), _renames(), _removable(), _mark_removed() and _removed(): the checks of obs_canvas_reset_video(), obs_canvas_rename_source(), obs_canvas_set_channel(), obs_canvas_set_name(), obs_canvas_remove() and obs_canvas_removed(). Split per read, as #2153 did. canvas->flags is read without a lock and obs_canvas_remove() writes it from any thread, so each check gets the value of its own read, at its point. Every check behind a || or && is still asked only where the C reached it: obs_source_is_scene() only on a SCENE_REF canvas, obs_video_active() only for a canvas that may reset, strcmp() only for a canvas that may be renamed, and each video info field only after the one before it was set. The rest stays C at its point: the allocations and frees, the context data calls, the signal handler setup, the mutexes, obs_view_init() and _free(), the mix and its list under mixes_mutex, HASH_CLEAR and the walk that takes next before each release (the #2038 and #2049 order), every reference and weak reference, the pointer checks (source, previous source, canvas, mix, the "already in a canvas" step), the group walk, the calldata, every signal, obs_source_activate() and _deactivate(), strcmp() and the logs. The flag values, REMOVED, the public mask, VIDEO_FORMAT_NONE and MAX_CHANNELS are copied into the header, so it needs only stdbool.h and stdint.h; obs-canvas.c.h checks them with _Static_assert. REMOVED and PUBLIC_CANVAS_FLAGS leave obs-canvas.c.h. Checked in a scratch harness (not committed). It compiles origin/master's obs-canvas.c.h verbatim, and this branch's with obs-canvas-rules.c.h, over a stand-in libobs.pch.h whose functions log every call in order with its arguments: the context data calls (init may fail), signal_handler_add_array() (may fail), the mutex init (may fail), every lock and unlock, obs_view_init() and _free(), the mix create (may fail) and free, the mix list, HASH_CLEAR, every signal with its calldata, the strong and weak references (a weak get may fail), obs_source_get_ref() (may return NULL), _release(), _is_scene(), _is_group(), _activate(), _deactivate(), obs_video_active(), the scene walks, the obs_data reads and writes, and blog(). A channel_change handler may replace the source in the calldata. A concurrent writer may flip any flag bit (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, REMOVED, an unknown bit), the private flag or a video info field of any live canvas at any call. Each run makes up to sixteen random calls of the whole canvas API (every constructor with random flags, names and video info; obs_load_canvas() with saved flags of 0, -1, INT64_MIN, INT64_MAX, above 32 bits and random; save, the video info check, both resets, insert, remove and rename of scene, group and plain sources, set_channel at 0 to 3, 63, 64, 65 and UINT32_MAX with the same, another or no source, set_name with NULL, "", "Main", the same and other names, remove, the getters, scene create, remove and move, refs taken and released, the mix clears and render), then releases everything and removes the sources left alive, as obs_free_data() does. The C++ build also logs every read and write of the flags, the private flag and the video info fields. 6,600,000 runs: 1,000,000 each with GCC and Clang at -O0 and -O2 as C (67,558,889 logged lines each side), 1,000,000 each with G++ at -O0 and -O2 as C++ with the logged reads (95,351,694 each side), and 200,000 each under ASan and UBSan with no recovery (GCC -O0 and Clang -O2 as C, G++ -O1 as C++). The two logs are identical in every configuration. gcov over 100,000 runs takes every branch of the moved decisions both ways, but the two no caller reaches: canvas_dosignal() with no core signal name, and obs_canvas_remove() failing to take a reference to a canvas its caller holds. 34 deliberately broken moves were planted, and the C++ build fails all 34: each rule changed (each operand dropped or swapped, a bound off by one, an inverted result, the REMOVED write dropped), the destroy walk reading the flags once before it, obs_video_active() asked before the flags and the flags read without video info, obs_source_is_scene() asked before the flags, a video info field read early, strcmp() before the MAIN check, the flags read before the canvas's own signal in set_channel(), remove_source() and rename_source(), the remove check after the reference, the private flag read once in set_name(), the create's mix_audio read from the canvas instead of its argument, and a second read of the flags in save. The C builds, which see reads only through the writer, fail 29 of them. git blame on the moved lines shows upstream commits (3d57b1f introducing canvases, 66f4792, 1ecea56, 0fd1261) and the fork's fe75932 (the public mask, #2151); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. The exported symbol sets are unchanged: 1766 on the C backend, the hybrid and libobs-c-reference, the same set on all three, with the seventeen functions local. Refs #2544.
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
RED for the port of libobs/obs-canvas-rules.c.h to a new canvas_rules module of rust/obs-core, next to canvas_draw. The safe core is a stub (todo!()): main_flags(), public_flags(), main_view(), mix_audio(), is_public() (public is the C name; is_public reads better in Rust), holds_scenes(), saves(), size_set(), format_set(), resets(), global_signals(), channel_ok(), name_empty(), renames(), removable(), mark_removed() and removed(), with the flag constants (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, PROGRAM, PREVIEW, DEVICE, REMOVED, PUBLIC), FORMAT_NONE and MAX_CHANNELS. name_empty() takes the name's first byte, None for NULL, so the core reads no pointer. The plan sketched wider steps (reset(has_ovi, flags, video_active), rename(empty, flags, same), scene_ref(flags, is_scene)). Each would take a value the C reads or calls only behind a || or &&, so each check is its own function, asked at its own point, as #2153 did; the pointer checks, obs_source_is_scene(), obs_video_active() and strcmp() stay C. tests/obs_core/canvas_rules.rs ports test_canvas_rules_steps 1:1: its 11 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases included. Three new proptests (edge_*, 4096 cases each) check every rule over any u32 flags, the load over any i64 (truncated as the C's cast, never keeping MAIN or REMOVED), and the size, format, channel, name byte and private rules over any value, against models written from the C's expressions. soldr cargo test -p obs-data --test obs-tests-core -- canvas_rules:: passes 1 of 14 (the constants) and fails 13 with "not yet implemented". Refs #2544.
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
Behaviour-neutral extraction before the Rust port. The flag rules and setter checks of obs-canvas.c.h move to libobs/obs-canvas-rules.c.h, as seventeen functions on plain values declared in the new libobs/obs-canvas-rules.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _main_flags() and _public_flags(): MAIN | PROGRAM for obs_create_main_canvas(), and the public mask of obs_canvas_create(), obs_canvas_create_private() and obs_load_canvas(), which still casts the saved int64 to uint32_t itself; - _main_view() and _mix_audio(): the view type and the mix's mix_audio, in obs_canvas_create_internal() and obs_canvas_reset_video_internal(); - _public(): a canvas that is not private is named, unnamed, renamed through the hash table and signalled on obs->signals (canvas_dosignal(), obs_canvas_create_internal(), obs_canvas_destroy(), obs_canvas_set_name()); - _holds_scenes(): SCENE_REF, in obs_canvas_destroy(), obs_canvas_insert_source() and obs_canvas_remove_source(); - _saves(): neither EPHEMERAL nor REMOVED; - _size_set() and _format_set(): obs_canvas_has_valid_video_info(); - _resets(), _global_signals(), _channel_ok(), _name_empty(), _renames(), _removable(), _mark_removed() and _removed(): the checks of obs_canvas_reset_video(), obs_canvas_rename_source(), obs_canvas_set_channel(), obs_canvas_set_name(), obs_canvas_remove() and obs_canvas_removed(). Split per read, as #2153 did. canvas->flags is read without a lock and obs_canvas_remove() writes it from any thread, so each check gets the value of its own read, at its point. Every check behind a || or && is still asked only where the C reached it: obs_source_is_scene() only on a SCENE_REF canvas, obs_video_active() only for a canvas that may reset, strcmp() only for a canvas that may be renamed, and each video info field only after the one before it was set. The rest stays C at its point: the allocations and frees, the context data calls, the signal handler setup, the mutexes, obs_view_init() and _free(), the mix and its list under mixes_mutex, HASH_CLEAR and the walk that takes next before each release (the #2038 and #2049 order), every reference and weak reference, the pointer checks (source, previous source, canvas, mix, the "already in a canvas" step), the group walk, the calldata, every signal, obs_source_activate() and _deactivate(), strcmp() and the logs. The flag values, REMOVED, the public mask, VIDEO_FORMAT_NONE and MAX_CHANNELS are copied into the header, so it needs only stdbool.h and stdint.h; obs-canvas.c.h checks them with _Static_assert. REMOVED and PUBLIC_CANVAS_FLAGS leave obs-canvas.c.h. Checked in a scratch harness (not committed). It compiles origin/master's obs-canvas.c.h verbatim, and this branch's with obs-canvas-rules.c.h, over a stand-in libobs.pch.h whose functions log every call in order with its arguments: the context data calls (init may fail), signal_handler_add_array() (may fail), the mutex init (may fail), every lock and unlock, obs_view_init() and _free(), the mix create (may fail) and free, the mix list, HASH_CLEAR, every signal with its calldata, the strong and weak references (a weak get may fail), obs_source_get_ref() (may return NULL), _release(), _is_scene(), _is_group(), _activate(), _deactivate(), obs_video_active(), the scene walks, the obs_data reads and writes, and blog(). A channel_change handler may replace the source in the calldata. A concurrent writer may flip any flag bit (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, REMOVED, an unknown bit), the private flag or a video info field of any live canvas at any call. Each run makes up to sixteen random calls of the whole canvas API (every constructor with random flags, names and video info; obs_load_canvas() with saved flags of 0, -1, INT64_MIN, INT64_MAX, above 32 bits and random; save, the video info check, both resets, insert, remove and rename of scene, group and plain sources, set_channel at 0 to 3, 63, 64, 65 and UINT32_MAX with the same, another or no source, set_name with NULL, "", "Main", the same and other names, remove, the getters, scene create, remove and move, refs taken and released, the mix clears and render), then releases everything and removes the sources left alive, as obs_free_data() does. The C++ build also logs every read and write of the flags, the private flag and the video info fields. 6,600,000 runs: 1,000,000 each with GCC and Clang at -O0 and -O2 as C (67,558,889 logged lines each side), 1,000,000 each with G++ at -O0 and -O2 as C++ with the logged reads (95,351,694 each side), and 200,000 each under ASan and UBSan with no recovery (GCC -O0 and Clang -O2 as C, G++ -O1 as C++). The two logs are identical in every configuration. gcov over 100,000 runs takes every branch of the moved decisions both ways, but the two no caller reaches: canvas_dosignal() with no core signal name, and obs_canvas_remove() failing to take a reference to a canvas its caller holds. 34 deliberately broken moves were planted, and the C++ build fails all 34: each rule changed (each operand dropped or swapped, a bound off by one, an inverted result, the REMOVED write dropped), the destroy walk reading the flags once before it, obs_video_active() asked before the flags and the flags read without video info, obs_source_is_scene() asked before the flags, a video info field read early, strcmp() before the MAIN check, the flags read before the canvas's own signal in set_channel(), remove_source() and rename_source(), the remove check after the reference, the private flag read once in set_name(), the create's mix_audio read from the canvas instead of its argument, and a second read of the flags in save. The C builds, which see reads only through the writer, fail 29 of them. git blame on the moved lines shows upstream commits (3d57b1f introducing canvases, 66f4792, 1ecea56, 0fd1261) and the fork's fe75932 (the public mask, #2151); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. The exported symbol sets are unchanged: 1766 on the C backend, the hybrid and libobs-c-reference, the same set on all three, with the seventeen functions local. Refs #2544.
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
RED for the port of libobs/obs-canvas-rules.c.h to a new canvas_rules module of rust/obs-core, next to canvas_draw. The safe core is a stub (todo!()): main_flags(), public_flags(), main_view(), mix_audio(), is_public() (public is the C name; is_public reads better in Rust), holds_scenes(), saves(), size_set(), format_set(), resets(), global_signals(), channel_ok(), name_empty(), renames(), removable(), mark_removed() and removed(), with the flag constants (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, PROGRAM, PREVIEW, DEVICE, REMOVED, PUBLIC), FORMAT_NONE and MAX_CHANNELS. name_empty() takes the name's first byte, None for NULL, so the core reads no pointer. The plan sketched wider steps (reset(has_ovi, flags, video_active), rename(empty, flags, same), scene_ref(flags, is_scene)). Each would take a value the C reads or calls only behind a || or &&, so each check is its own function, asked at its own point, as #2153 did; the pointer checks, obs_source_is_scene(), obs_video_active() and strcmp() stay C. tests/obs_core/canvas_rules.rs ports test_canvas_rules_steps 1:1: its 11 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases included. Three new proptests (edge_*, 4096 cases each) check every rule over any u32 flags, the load over any i64 (truncated as the C's cast, never keeping MAIN or REMOVED), and the size, format, channel, name byte and private rules over any value, against models written from the C's expressions. soldr cargo test -p obs-data --test obs-tests-core -- canvas_rules:: passes 1 of 14 (the constants) and fails 13 with "not yet implemented". Refs #2544.
6 of 7 tasks
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
Behaviour-neutral extraction before the Rust port. The decisions of transition_valid(), valid_scale_type(), obs_transition_load(), copy_source_state(), obs_transition_swap_begin() and obs_transition_swap_end() in obs-source-transition.c.h move to libobs/obs-source-transition-load.c.h, as six functions on plain values declared in the new libobs/obs-source-transition-load.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _is_transition(): the type check of transition_valid(), after obs_ptr_valid(); - _scale_type(): valid_scale_type(), used by obs_transition_set_scale_type() and obs_transition_load(): 0, 1 and 2 as they are, any other int64_t Max Only; - _looks_up(): obs_transition_load() looks its saved source up only with a name; - _source() -> KEEP | NOT_FOUND | REFUSE: what the load does with the looked-up source after the add (the add only for a found source); - _swaps(): the swap of a transition with itself does nothing, in both swap_begin() and swap_end(); - _copy_stores(): copy_source_state() stores the new child unless it was to be added as an active child and the add failed. obs_transition_load()'s release of the old source A (#2584) asks obs_source_transition_start_child_active(), the rule copy_source_state() and obs_transition_set() already ask. Split per step, as #2153 did, so every call and read stays where it was and under its condition: obs_ptr_valid(), the locks and their order, the pointer comparisons, the obs_data reads at the top, the lookup, the add only for a found source or an active new child (the C's own &&), every obs_source_get_ref() and obs_source_release(), the active child calls, the (uint32_t) truncations of the loaded alignment and size, the mode taken as is, the fields the swap hands over, the texrender swap, recalculate_transition_size() and _matrices(), and the logs. The getters' answers for an invalid transition (Max Only, 0, 0x0 and false) stay C as the literals they are. The source type and the scale type cross as int; the header copies OBS_SOURCE_TYPE_TRANSITION and the three scale types, and obs-source-transition.c.h checks them and that enum obs_source_type is int-sized with _Static_assert (the scale type enum is already checked there). Checked in a scratch harness (not committed). It compiles origin/master's transition_valid(), valid_scale_type(), obs_transition_set_scale_type(), obs_transition_get_scale_type(), obs_transition_get_alignment(), obs_transition_get_size(), obs_transition_fixed(), obs_transition_load(), copy_source_state(), obs_transition_swap_begin() and obs_transition_swap_end() verbatim next to this branch's and the moved file, as C++, over stand-in sources whose fields log every read and write with its value. Every call is logged in order with its arguments: both mutexes of both transitions (lock and unlock), obs_ptr_valid(), the obs_data reads, obs_get_source_by_name() (which may find nothing), obs_source_add_active_child() (which may fail), obs_source_remove_active_child(), obs_source_get_ref() (which may return NULL), obs_source_release(), obs_source_get_name(), blog(), obs_transition_clear() and the size and matrix recalculation. Another thread may write a source, a slot flag, the scale type, the fixed flag, the width or the video flag at any lock, unlock or call. Inputs: two transitions and four children of any source type (including values out of the enum), every slot empty or any child and active or not, no source, the transition swapped with itself or the other, names that are missing, unknown, a child or a transition, and loaded and set values at 0, 1, 2, 3, -1, 7, 255, 2^31, around 2^32, the ends of int64_t and random; one to four operations each. 5,800,000 runs: 2,000,000 each with GCC and Clang at -O2, 500,000 each at -O0, 300,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2) and 200,000 with gcov. All 149,390,395 logged events match, as does the final state (every field, reference and active reference). Every branch of origin/master's functions is taken both ways. 24 deliberately broken moves were planted, and all 24 fail it: each function's rule inverted, widened or made constant (the type at >= 2, STRETCH dropped, the default ASPECT, the value's low bit, the lookup always or never, NOT_FOUND and REFUSE swapped or made KEEP, the swap always or for the same transition, the store rule as add_ok, !adds && add_ok, adds || add_ok and !adds), and at the call sites the add for a source not found, the add for an inactive or missing new child, the old source A removed when inactive, the type check on a constant, the scale type taken mod 3 and the lookup without a name. git blame on the moved lines shows the upstream commits 6839ff7 and a1fbf10, and the fork's #2080 (the scale type rule), #2513 (the swap refusal) and #2584 (the release of the old source A); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol set is unchanged (1766 on the C backend); the six functions are local. Refs #2595.
6 of 7 tasks
rdoupe
added a commit
that referenced
this pull request
Oct 27, 2026
Behaviour-neutral extraction before the Rust port. The decisions of obs_source_set_flags(), obs_source_set_audio_mixers(), obs_source_get_audio_mixers(), obs_source_enable_push_to_mute(), obs_source_enable_push_to_talk(), obs_source_set_monitoring_enabled(), obs_source_set_monitoring_type(), obs_source_get_monitoring_type(), clamp_balance() and obs_source_set_audio_active() in obs-source.c.h move to libobs/obs-source-monitoring.c.h, as thirteen functions on plain values declared in the new libobs/obs-source-monitoring.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _changes(): a set does something only when the value changes (the flags, the mixers, monitoring on or off, and the push-to enables' signal); - _has_audio(): the mixers' gate for a source that does not own its info id (OBS_SOURCE_AUDIO in the output flags); - _mixers_store(): the low 32 bits of what an audio_mixers handler leaves; - _push_to_logs(): the push-to enables log a change on an audio source; - _on_type(): monitoring on and muted is Monitor Only, else Monitor and Output (#2447), for the compatibility signal and the getter; - _stored_type() and _monitor() -> KEEP | CREATE | DESTROY: the type obs_source_set_monitoring_enabled() stores and the monitor route; - _route() -> OFF | MONITOR_ONLY | MONITOR_AND_OUTPUT | ON: the steps of obs_source_set_monitoring_type() for a type (#2444, #2447); - _off_reads_mute() and _off_unmutes(): none looks at the mute only when Monitor Only set it, and undoes it if it is still on; - _only_mutes(): Monitor Only mutes first if not muted; - _balance(): clamp_balance(), NaN centred, else clamped to [0, 1] (#2051); - _audio_active() -> NONE | ACTIVATE | DEACTIVATE: the signal of a change. Split per step, as #2153 did, so every call and read stays where it was and under its condition: obs_source_valid(), audio_mutex, os_atomic_load_bool() of monitor_only_muted once before the steps and os_atomic_set_bool() of it and of audio_active, the reads of owns_info_id (and of the output flags only when it is false), obs_source_get_output_flags() before the changed test, user_muted read only when monitoring turns on, monitoring_enabled read again after the signals, obs_source_muted() only where the C's && reached it (after monitoring is off, for none), obs_source_set_muted() and obs_source_set_monitoring_enabled() in their order (the mute before monitoring turns on), every calldata_*(), signal and log, the (float) of the handler's balance, audio_monitor_create() and _destroy(), and the getters' answers for an invalid source (0, false and 0.5). clamp_balance() stays as an inline wrapper for its two calls. The monitoring type crosses as int; the header copies OBS_SOURCE_AUDIO and the three monitoring types, and obs-source.c.h checks them and that enum obs_monitoring_type is int-sized with _Static_assert. Checked in a scratch harness (not committed). It compiles origin/master's fifteen functions (the ten above with obs_source_get_flags(), obs_source_get_monitoring_enabled(), obs_source_get_balance_value(), obs_source_set_balance_value() and obs_source_audio_active()) verbatim next to this branch's and the moved file, as C++, over a stand-in source whose fields log every read and write with its value. Every call is logged in order with its arguments: obs_source_valid(), the lock and unlock, the calldata sets and gets, each signal, blog(), obs_source_get_output_flags(), the atomics, obs_source_muted(), obs_source_set_muted(), obs_source_dosignal(), the push-to signal and audio_monitor_create() and _destroy(). A signal handler may leave any mixers (above UINT32_MAX, negative, the ends of int64_t) or any balance, and another thread may write any field at any event. Inputs: an invalid source or any start state, flags and mixers at the edges and random, types 0 to 4, -1, the ends of int and random, balances at NaN (both signs), the signed zeros, the smallest subnormals, 1.0 and its neighbours, the ends of float, the infinities and random bit patterns; one to four operations each. 5,800,000 runs: 2,000,000 each with GCC and Clang at -O2, 500,000 each at -O0, 300,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2, without C++'s enum range check, which C does not have) and 200,000 with gcov. All 82,503,972 logged events match, as does the final state. Every branch of origin/master's functions is taken both ways. 30 deliberately broken moves were planted, and all 30 fail it: each function's rule inverted, widened or made constant (changes as == and >, the audio bit as bit 0 or any flag, the mixers shifted or saturated, the log rule without the flag or without the change, the on type constant or inverted, the stored type Monitor Only, the monitor never kept or created on the wrong edge, each route moved, the default OFF, the three mute steps constant, NaN as 0.0, the clamp at <= 0 and below 1.0, the active signal never NONE or on prev), and at the call sites the mute read before the mark, user_muted read without its log, the output flags read only after a change, the mixers' gate reading the output flags first, and the type taken mod 4. git blame on the moved lines shows the upstream commits d2934ec and 646836a, and the fork's #2058 (the balance clamp) and #2450 (the Monitor Only steps); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol set is unchanged (1766 on the C backend); the thirteen functions are local. Refs #2621.
MCPVOT
pushed a commit
to MCPVOT/obs-studio
that referenced
this pull request
Oct 30, 2026
* libobs: Move the canvas flag rules Behaviour-neutral extraction before the Rust port. The flag rules and setter checks of obs-canvas.c.h move to libobs/obs-canvas-rules.c.h, as seventeen functions on plain values declared in the new libobs/obs-canvas-rules.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _main_flags() and _public_flags(): MAIN | PROGRAM for obs_create_main_canvas(), and the public mask of obs_canvas_create(), obs_canvas_create_private() and obs_load_canvas(), which still casts the saved int64 to uint32_t itself; - _main_view() and _mix_audio(): the view type and the mix's mix_audio, in obs_canvas_create_internal() and obs_canvas_reset_video_internal(); - _public(): a canvas that is not private is named, unnamed, renamed through the hash table and signalled on obs->signals (canvas_dosignal(), obs_canvas_create_internal(), obs_canvas_destroy(), obs_canvas_set_name()); - _holds_scenes(): SCENE_REF, in obs_canvas_destroy(), obs_canvas_insert_source() and obs_canvas_remove_source(); - _saves(): neither EPHEMERAL nor REMOVED; - _size_set() and _format_set(): obs_canvas_has_valid_video_info(); - _resets(), _global_signals(), _channel_ok(), _name_empty(), _renames(), _removable(), _mark_removed() and _removed(): the checks of obs_canvas_reset_video(), obs_canvas_rename_source(), obs_canvas_set_channel(), obs_canvas_set_name(), obs_canvas_remove() and obs_canvas_removed(). Split per read, as obs-rust#2153 did. canvas->flags is read without a lock and obs_canvas_remove() writes it from any thread, so each check gets the value of its own read, at its point. Every check behind a || or && is still asked only where the C reached it: obs_source_is_scene() only on a SCENE_REF canvas, obs_video_active() only for a canvas that may reset, strcmp() only for a canvas that may be renamed, and each video info field only after the one before it was set. The rest stays C at its point: the allocations and frees, the context data calls, the signal handler setup, the mutexes, obs_view_init() and _free(), the mix and its list under mixes_mutex, HASH_CLEAR and the walk that takes next before each release (the obs-rust#2038 and obs-rust#2049 order), every reference and weak reference, the pointer checks (source, previous source, canvas, mix, the "already in a canvas" step), the group walk, the calldata, every signal, obs_source_activate() and _deactivate(), strcmp() and the logs. The flag values, REMOVED, the public mask, VIDEO_FORMAT_NONE and MAX_CHANNELS are copied into the header, so it needs only stdbool.h and stdint.h; obs-canvas.c.h checks them with _Static_assert. REMOVED and PUBLIC_CANVAS_FLAGS leave obs-canvas.c.h. Checked in a scratch harness (not committed). It compiles origin/master's obs-canvas.c.h verbatim, and this branch's with obs-canvas-rules.c.h, over a stand-in libobs.pch.h whose functions log every call in order with its arguments: the context data calls (init may fail), signal_handler_add_array() (may fail), the mutex init (may fail), every lock and unlock, obs_view_init() and _free(), the mix create (may fail) and free, the mix list, HASH_CLEAR, every signal with its calldata, the strong and weak references (a weak get may fail), obs_source_get_ref() (may return NULL), _release(), _is_scene(), _is_group(), _activate(), _deactivate(), obs_video_active(), the scene walks, the obs_data reads and writes, and blog(). A channel_change handler may replace the source in the calldata. A concurrent writer may flip any flag bit (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, REMOVED, an unknown bit), the private flag or a video info field of any live canvas at any call. Each run makes up to sixteen random calls of the whole canvas API (every constructor with random flags, names and video info; obs_load_canvas() with saved flags of 0, -1, INT64_MIN, INT64_MAX, above 32 bits and random; save, the video info check, both resets, insert, remove and rename of scene, group and plain sources, set_channel at 0 to 3, 63, 64, 65 and UINT32_MAX with the same, another or no source, set_name with NULL, "", "Main", the same and other names, remove, the getters, scene create, remove and move, refs taken and released, the mix clears and render), then releases everything and removes the sources left alive, as obs_free_data() does. The C++ build also logs every read and write of the flags, the private flag and the video info fields. 6,600,000 runs: 1,000,000 each with GCC and Clang at -O0 and -O2 as C (67,558,889 logged lines each side), 1,000,000 each with G++ at -O0 and -O2 as C++ with the logged reads (95,351,694 each side), and 200,000 each under ASan and UBSan with no recovery (GCC -O0 and Clang -O2 as C, G++ -O1 as C++). The two logs are identical in every configuration. gcov over 100,000 runs takes every branch of the moved decisions both ways, but the two no caller reaches: canvas_dosignal() with no core signal name, and obs_canvas_remove() failing to take a reference to a canvas its caller holds. 34 deliberately broken moves were planted, and the C++ build fails all 34: each rule changed (each operand dropped or swapped, a bound off by one, an inverted result, the REMOVED write dropped), the destroy walk reading the flags once before it, obs_video_active() asked before the flags and the flags read without video info, obs_source_is_scene() asked before the flags, a video info field read early, strcmp() before the MAIN check, the flags read before the canvas's own signal in set_channel(), remove_source() and rename_source(), the remove check after the reference, the private flag read once in set_name(), the create's mix_audio read from the canvas instead of its argument, and a second read of the flags in save. The C builds, which see reads only through the writer, fail 29 of them. git blame on the moved lines shows upstream commits (3d57b1f introducing canvases, 66f4792, 1ecea56, 0fd1261) and the fork's fe75932 (the public mask, obs-rust#2151); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. The exported symbol sets are unchanged: 1766 on the C backend, the hybrid and libobs-c-reference, the same set on all three, with the seventeen functions local. Refs obs-rust#2544. * test: Characterize the canvas flag rules test_canvas_rules_steps compiles libobs/obs-canvas-rules.c.h (ASan and UBSan) and calls only its functions through obs-canvas-rules.h. 11 cases: - the header's copies of the flags, REMOVED, the public mask, VIDEO_FORMAT_NONE and MAX_CHANNELS against obs.h; - the main canvas's flags (MAIN | PROGRAM), and the public mask over every single bit and every combination of the five public flags, MAIN, REMOVED and an unknown bit; - obs_load_canvas()'s cast of the saved int64 before the mask, at 0, the named flags, 0x80000000, 0xffffffff, above 32 bits, -1, -2, -32 and the ends of int64; - every flag rule (view type, mix_audio, scene references, save, reset, global signals, rename, remove, removed, the REMOVED write) over those 128 combinations and over every single bit; - the main, program, preview and device canvases, and a caller asking for MAIN; - the public canvas rule, the video info checks (sizes 0, 1, 1920 and UINT32_MAX; formats NONE, I420, NV12, P010 and outside the enum), the channel bound (0 to 1023, 63, 64, 65, 2^31 and UINT32_MAX), the empty name (NULL, "", " ", "a", "Main", "\0b", 0xff) and removing twice. Characterized, not endorsed: - the saved int64 is truncated before the mask, so bits above 31 are dropped silently and a negative value keeps the public flags of its low word (-1 loads as every public flag); - a video format outside the enum counts as set; - a removed canvas can still be reset and renamed. It is in the native test graph, in name order, with the header as a watch input. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and no two enum types are compared. Passes 11/11 on the C backend and the hybrid. test_canvas_flags, test_scene_private_canvas, test_canvas_destroy_scene_refs, test_shutdown_canvas_weak_ref, test_scene_canvas_characterization, test_context_names and test_view cover the callers through the real libobs, and pass on both. Refs obs-rust#2544. * obs-core: Test the canvas_rules port RED for the port of libobs/obs-canvas-rules.c.h to a new canvas_rules module of rust/obs-core, next to canvas_draw. The safe core is a stub (todo!()): main_flags(), public_flags(), main_view(), mix_audio(), is_public() (public is the C name; is_public reads better in Rust), holds_scenes(), saves(), size_set(), format_set(), resets(), global_signals(), channel_ok(), name_empty(), renames(), removable(), mark_removed() and removed(), with the flag constants (MAIN, ACTIVATE, MIX_AUDIO, SCENE_REF, EPHEMERAL, PROGRAM, PREVIEW, DEVICE, REMOVED, PUBLIC), FORMAT_NONE and MAX_CHANNELS. name_empty() takes the name's first byte, None for NULL, so the core reads no pointer. The plan sketched wider steps (reset(has_ovi, flags, video_active), rename(empty, flags, same), scene_ref(flags, is_scene)). Each would take a value the C reads or calls only behind a || or &&, so each check is its own function, asked at its own point, as obs-rust#2153 did; the pointer checks, obs_source_is_scene(), obs_video_active() and strcmp() stay C. tests/obs_core/canvas_rules.rs ports test_canvas_rules_steps 1:1: its 11 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases included. Three new proptests (edge_*, 4096 cases each) check every rule over any u32 flags, the load over any i64 (truncated as the C's cast, never keeping MAIN or REMOVED), and the size, format, channel, name byte and private rules over any value, against models written from the C's expressions. soldr cargo test -p obs-data --test obs-tests-core -- canvas_rules:: passes 1 of 14 (the constants) and fails 13 with "not yet implemented". Refs obs-rust#2544. * obs-core: Port the canvas flag rules Ports libobs/obs-canvas-rules.c.h, the canvas flag rules and setter checks of obs-canvas.c, to the canvas_rules module of rust/obs-core. obs-canvas.c.h stays C around it: every read of the canvas's flags, private flag and video info fields at its point, the allocations and frees, the context data calls, the signal handler setup, the mutexes, the view, the mix and its list, HASH_CLEAR and the destroy walk (the obs-rust#2038 and obs-rust#2049 order), every reference, the pointer checks, the group walk, obs_source_is_scene() and _is_group(), obs_video_active(), strcmp(), the calldata, every signal, the activation calls and the logs. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/canvas_rules.rs), seventeen functions: - main_flags(): MAIN | PROGRAM; public_flags(): flags & PUBLIC; - main_view(): ACTIVATE; mix_audio(): MIX_AUDIO; is_public(): !is_private; holds_scenes(): SCENE_REF; - saves(): neither EPHEMERAL nor REMOVED; size_set(): not 0; format_set(): not FORMAT_NONE (a format outside the enum is set); - resets() and renames(): not MAIN; global_signals(): MAIN; channel_ok(): below MAX_CHANNELS; - name_empty(): None or a first byte of 0; - removable(): neither REMOVED nor MAIN; mark_removed(): | REMOVED; removed(): REMOVED. The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. Shims (src/ffi/canvas_rules.rs): the seventeen C signatures by value; the flags as u32, the format as int. The one pointer is the name of obs_canvas_set_name(): the shim reads its first byte only when it is not NULL, as the C's !name || !*name. No struct is mirrored. No intentional difference from the C. C side: the file leaves libobs.core-source for its own group, libobs.ported-canvas-rules, registered in its own fragment, libobs/build/ported-source-sets/canvas-rules.json (LIBOBS_PORTED_SOURCES), so it edits no shared ported list. Its PCH is only obs-canvas-rules.h; libobs.pch.h keeps the header for obs-canvas.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference, the same set as origin/master; the seventeen functions are local in all three, and the hybrid's come from the Rust archive (the group's object is built only for libobs-c-reference). ci/test_ported_sources.py checks the group on every host. test_canvas_rules_steps still compiles the C file into itself, unchanged, and passes 11/11. It has no _rust variant: linking it against libobs_rust-static fails with 401 undefined references (108 symbols), because the shims' archive member (an obs_core codegen unit) also holds the other obs-core ports, as for test_canvas_draw_steps; its tests.d file says so. The Tier 3 parity tests compare the shims with the C instead. soldr cargo test -p obs-data --test obs-tests-core -- canvas_rules:: passes 14 of 14. No user-visible change, so no docs/features.md line. Refs obs-rust#2544. * obs-core: Check canvas_rules against the C rust/obs-c-oracle/oracle/canvas_rules.c compiles the unchanged libobs/obs-canvas-rules.c.h with its seventeen functions renamed oracle_*, after obs.h, plus the header's copies, enum obs_canvas_flags, VIDEO_FORMAT_NONE, MAX_CHANNELS and the type sizes. tests/obs_core/canvas_rules_parity.rs (7 tests) runs the shim, the C and the safe core on every input and compares the results exactly: the C's bool as the byte it returns, the flags as the uint32_t. - the 23 values and sizes against the C headers, and the main flags; - exhaustive: every flag rule for every low 16-bit flags word under 16 high words (bits 16, 17, 30 and 31), every single bit and every combination of the known flags, REMOVED and an unknown bit; the load for 786,432 saved int64 values (four high words, three top halves, every low half) and the ends; the size and channel for 0 to 70,000, every 65,521st u32 and the ends; the format for -70,000 to 70,000 and the ends; the name for NULL and every first byte, through a C string; - each caller's decisions in their order (the three constructors, the save, the reset, the channel bound and global signal, the name refusals and the public rename, the remove and REMOVED write, the video info chain), one copy on each side, for every combination of the known flags, REMOVED, an unknown bit, the private flag, six channels, four names, three video infos and five formats; - proptests (20,000 cases each): every decision over any value, and the callers over all of it at once. No input reaches a division or a 128-bit multiply on either side, so nothing is skipped on MSVC x64. No intentional differences. The parity module passed 3 runs in a row with fresh seeds. test_canvas_rules_steps passes 11/11 under ASan and UBSan. The committed regression files hold the seeds proptest saved while mutants failed; all pass on the port. Mutation check (the mutants are not committed): 36 mutants, 24 in the core and 12 in the shims, each run against Tier 1 (14 tests) and Tier 3 (7). 34 fail. The two that survive are equivalent: the resets shim calling renames() (both are "not MAIN"), and the name shim passing Some(0) for NULL (both are empty). Tier 1 does not reach the shims; Tier 3 kills every other shim mutant. Each mutant and the tests that fail on it: 1. core, main_flags: no SCENE_REF T1: steps_canvas_kinds, steps_constructor_flags T3: callers_every_input, proptest_callers, values_match_the_c_headers 2. core, public_flags: keeps MAIN T1: edge_flag_rules_any_flags, edge_load_any_int64, steps_canvas_kinds, steps_constructor_flags, steps_load_flags_from_int64 T3: callers_every_input, every_flags_word, every_load, proptest_callers, proptest_decisions 3. core, public_flags: keeps REMOVED T1: edge_flag_rules_any_flags, edge_load_any_int64, steps_constructor_flags, steps_load_flags_from_int64, steps_remove_twice T3: callers_every_input, every_flags_word, every_load, proptest_callers, proptest_decisions 4. core, public_flags: drops EPHEMERAL T1: edge_flag_rules_any_flags, edge_load_any_int64, steps_canvas_kinds, steps_constructor_flags, steps_load_flags_from_int64 T3: callers_every_input, every_flags_word, every_load, proptest_callers, proptest_decisions 5. core, main_view: MIX_AUDIO T1: edge_flag_rules_any_flags, steps_canvas_kinds, steps_flag_rules_every_bit, steps_flag_rules_every_combination T3: callers_every_input, every_flags_word, proptest_callers, proptest_decisions 6. core, mix_audio: ACTIVATE T1: as 5; T3: as 5 7. core, is_public: not negated T1: edge_values_any_input, steps_public_rule T3: callers_every_input, every_value, proptest_callers, proptest_decisions 8. core, holds_scenes: EPHEMERAL T1: edge_flag_rules_any_flags, steps_canvas_kinds, steps_flag_rules_every_bit, steps_flag_rules_every_combination, steps_remove_twice T3: every_flags_word, proptest_decisions 9. core, saves: ignores REMOVED T1: edge_flag_rules_any_flags, steps_flag_rules_every_bit, steps_flag_rules_every_combination, steps_remove_twice T3: callers_every_input, every_flags_word, proptest_callers, proptest_decisions 10. core, saves: ignores EPHEMERAL T1: as 5; T3: as 5 11. core, size_set: > 1 T1: steps_video_info_checks T3: every_value 12. core, format_set: > 0 T1: edge_values_any_input, steps_video_info_checks T3: callers_every_input, every_value, proptest_callers, proptest_decisions 13. core, resets: always T1: as 5; T3: as 5 14. core, global_signals: negated T1: edge_flag_rules_any_flags, edge_load_any_int64, steps_canvas_kinds, steps_flag_rules_every_bit, steps_flag_rules_every_combination T3: callers_every_input, every_flags_word, proptest_callers, proptest_decisions 15. core, channel_ok: <= T1: steps_channel_bound T3: callers_every_input, every_value, proptest_callers 16. core, name_empty: NULL only T1: edge_values_any_input, steps_name_checks T3: callers_every_input, every_value, proptest_callers, proptest_decisions 17. core, name_empty: NULL is a name T1: as 16; T3: as 16 18. core, renames: always T1: as 5; T3: as 5 19. core, removable: ignores REMOVED T1: as 9; T3: as 9 20. core, removable: ignores MAIN T1: as 5; T3: as 5 21. core, mark_removed: no write T1: as 9; T3: as 9 22. core, removed: bit 30 T1: as 9; T3: as 9 23. core, REMOVED: 1 << 30 T1: edge_flag_rules_any_flags, steps_constants, steps_flag_rules_every_bit T3: callers_every_input, every_flags_word, proptest_callers, proptest_decisions, values_match_the_c_headers 24. core, MAX_CHANNELS: 63 T1: steps_channel_bound, steps_constants T3: callers_every_input, every_value, proptest_callers, values_match_the_c_headers 25. shim, public_flags: main_flags T3: callers_every_input, every_flags_word, every_load, proptest_callers, proptest_decisions 26. shim, main_view: mix_audio T3: callers_every_input, every_flags_word, proptest_callers, proptest_decisions 27. shim, public: negated T3: callers_every_input, every_value, proptest_callers, proptest_decisions 28. shim, saves: removable T3: as 26 29. shim, resets: renames: SURVIVES (equivalent) 30. shim, global_signals: removed T3: as 26 31. shim, format_set: format & 0x7fffffff T3: every_value 32. shim, channel_ok: low byte only T3: every_value, proptest_callers, proptest_decisions 33. shim, name_empty: reads the byte, answers Some(1) T3: callers_every_input, every_value, proptest_callers, proptest_decisions 34. shim, name_empty: NULL as Some(0): SURVIVES (equivalent) 35. shim, mark_removed: public_flags T3: as 26 36. shim, removed: removable T3: as 26 Refs obs-rust#2544. * docs: Record the canvas_rules port - rust/README.md: the obs-core crate row names libobs/obs-canvas-rules.c.h, and a row for the file says what is swapped in the hybrid, what obs-canvas.c.h keeps and why each read asks its own function, the copied values, the characterized cases, why there is no _rust variant, and what Tier 3 covers; - rust/obs-core: the crate description and the lib.rs docs list the module; - docs/rust-port/naming.md: obs-canvas-rules.c.h, extracted from obs-canvas.c.h, maps to rust/obs-core; - rust/obs-c-oracle/benches/port_comparison/canvas_rules.rs: canvas_rules/create and canvas_rules/setters, the constructors' and the setters' decisions in their order over 1024 calls on each side, folded into a checksum both must match. It allocates nothing, so the per-module allocation check holds. The bench's build.rs finds it in the directory, so no shared list changes. port_comparison (x86_64 Linux, GCC, not pinned, load average about 3; criterion's median per 1024 calls): create 7.8 us Rust, 5.4 us C; setters 16.7 us Rust, 11.4 us C, about 2 to 5 ns more a decision through the exported shims. These run when a canvas is created, saved, reset, renamed or removed and when a scene or channel changes, never per frame. No docs/features.md line: the port changes no behaviour. Fixes obs-rust#2544. * test: Characterize the canvas rules' callers test_canvas_rules_steps pins the seventeen rules on their own, and the move was checked against the callers only in a scratch harness. This pins what the callers in obs-canvas.c do with the rules, through the real libobs and its public API, so it runs unchanged against the C backend, the hybrid and libobs-c-reference. 9 cases: - constructor_flags: the main canvas is MAIN | PROGRAM; create and create_private drop MAIN, REMOVED and unknown bits; obs_load_canvas() keeps the public flags of the saved value's low word; - save_rules: the saved flags and private flag, a private canvas reloaded, and no save for an ephemeral or a removed canvas; - reset_rules: no video info, the main canvas, and active video (a raw video callback on the main mix) are refused, with no video_reset signal; otherwise the canvas gets a mix and signals once; - set_name_rules: NULL, "", the same name and the main canvas are refused with no signal; a public canvas is renamed in the name table and signals canvas_rename globally; a private one signals only its own rename and stays out of the name table; - remove_rules: one remove signal each, none for a second remove or for the main canvas, and the REMOVED bit in the flags; - scene_refs: a scene on the main canvas (SCENE_REF) outlives its creator's reference until it is removed; a plain source on it gets no canvas reference; a scene on a canvas without SCENE_REF dies with its last reference; a SCENE_REF canvas releases its scenes when it is destroyed; - group_walk: removing a group removes its items from every scene of its canvas; a removed plain source leaves the canvas but its items stay in the scenes; - rename_source_signals: a scene rename on the main canvas signals source_rename globally, one on another canvas only on that canvas; - channel_replace: a channel_change handler that replaces the source. Characterized, not endorsed: the saved int64 is truncated before the mask; a removed canvas can still be renamed; the handler's replacement is stored and activated without a reference of its own, so clearing the channel releases one more reference on it than the canvas took, and the reference taken on the source passed in is never released. It needs a display and OpenGL (Linux, the graphics suite, under xvfb-run like test_main_mix_before_video), and is in the test graph in name order. No assert_in_range or fail_msg, and no two enum types are compared. Passes 9/9 three runs in a row on the C backend and the hybrid, and 9/9 against libobs-c-reference, each under a private Xvfb. Refs obs-rust#2544.
MCPVOT
pushed a commit
to MCPVOT/obs-studio
that referenced
this pull request
Oct 30, 2026
* libobs: Move the transition load decisions Behaviour-neutral extraction before the Rust port. The decisions of transition_valid(), valid_scale_type(), obs_transition_load(), copy_source_state(), obs_transition_swap_begin() and obs_transition_swap_end() in obs-source-transition.c.h move to libobs/obs-source-transition-load.c.h, as six functions on plain values declared in the new libobs/obs-source-transition-load.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _is_transition(): the type check of transition_valid(), after obs_ptr_valid(); - _scale_type(): valid_scale_type(), used by obs_transition_set_scale_type() and obs_transition_load(): 0, 1 and 2 as they are, any other int64_t Max Only; - _looks_up(): obs_transition_load() looks its saved source up only with a name; - _source() -> KEEP | NOT_FOUND | REFUSE: what the load does with the looked-up source after the add (the add only for a found source); - _swaps(): the swap of a transition with itself does nothing, in both swap_begin() and swap_end(); - _copy_stores(): copy_source_state() stores the new child unless it was to be added as an active child and the add failed. obs_transition_load()'s release of the old source A (obs-rust#2584) asks obs_source_transition_start_child_active(), the rule copy_source_state() and obs_transition_set() already ask. Split per step, as obs-rust#2153 did, so every call and read stays where it was and under its condition: obs_ptr_valid(), the locks and their order, the pointer comparisons, the obs_data reads at the top, the lookup, the add only for a found source or an active new child (the C's own &&), every obs_source_get_ref() and obs_source_release(), the active child calls, the (uint32_t) truncations of the loaded alignment and size, the mode taken as is, the fields the swap hands over, the texrender swap, recalculate_transition_size() and _matrices(), and the logs. The getters' answers for an invalid transition (Max Only, 0, 0x0 and false) stay C as the literals they are. The source type and the scale type cross as int; the header copies OBS_SOURCE_TYPE_TRANSITION and the three scale types, and obs-source-transition.c.h checks them and that enum obs_source_type is int-sized with _Static_assert (the scale type enum is already checked there). Checked in a scratch harness (not committed). It compiles origin/master's transition_valid(), valid_scale_type(), obs_transition_set_scale_type(), obs_transition_get_scale_type(), obs_transition_get_alignment(), obs_transition_get_size(), obs_transition_fixed(), obs_transition_load(), copy_source_state(), obs_transition_swap_begin() and obs_transition_swap_end() verbatim next to this branch's and the moved file, as C++, over stand-in sources whose fields log every read and write with its value. Every call is logged in order with its arguments: both mutexes of both transitions (lock and unlock), obs_ptr_valid(), the obs_data reads, obs_get_source_by_name() (which may find nothing), obs_source_add_active_child() (which may fail), obs_source_remove_active_child(), obs_source_get_ref() (which may return NULL), obs_source_release(), obs_source_get_name(), blog(), obs_transition_clear() and the size and matrix recalculation. Another thread may write a source, a slot flag, the scale type, the fixed flag, the width or the video flag at any lock, unlock or call. Inputs: two transitions and four children of any source type (including values out of the enum), every slot empty or any child and active or not, no source, the transition swapped with itself or the other, names that are missing, unknown, a child or a transition, and loaded and set values at 0, 1, 2, 3, -1, 7, 255, 2^31, around 2^32, the ends of int64_t and random; one to four operations each. 5,800,000 runs: 2,000,000 each with GCC and Clang at -O2, 500,000 each at -O0, 300,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2) and 200,000 with gcov. All 149,390,395 logged events match, as does the final state (every field, reference and active reference). Every branch of origin/master's functions is taken both ways. 24 deliberately broken moves were planted, and all 24 fail it: each function's rule inverted, widened or made constant (the type at >= 2, STRETCH dropped, the default ASPECT, the value's low bit, the lookup always or never, NOT_FOUND and REFUSE swapped or made KEEP, the swap always or for the same transition, the store rule as add_ok, !adds && add_ok, adds || add_ok and !adds), and at the call sites the add for a source not found, the add for an inactive or missing new child, the old source A removed when inactive, the type check on a constant, the scale type taken mod 3 and the lookup without a name. git blame on the moved lines shows the upstream commits 6839ff7 and a1fbf10, and the fork's obs-rust#2080 (the scale type rule), obs-rust#2513 (the swap refusal) and obs-rust#2584 (the release of the old source A); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol set is unchanged (1766 on the C backend); the six functions are local. Refs obs-rust#2595. * test: Characterize the transition load checks test_transition_load_steps compiles libobs/obs-source-transition-load.c.h and libobs/obs-source-transition-start.c.h (ASan and UBSan) and calls only their functions through the two headers. 10 cases: - the header's copies of OBS_SOURCE_TYPE_TRANSITION and the three scale types, the enums' sizes and the source outcome values; - the type check: only 2, over -1000..1000 and the ends of int; - the scale type: 0, 1 and 2 as they are, anything else Max Only (3, -1, the ends of int32_t and int64_t, -1000..1000), compared in 64 bits (2^32 + 1 and 2^32 + 2 are Max Only, not Aspect or Stretch); - the load's lookup and source outcome, the swap gate and copy_source_state()'s store rule over every combination. obs_transition_load(), copy_source_state() with the swap, the getters and obs_transition_set_scale_type() are also copied onto a stand-in transition whose children count their references and active references and refuse an add to a transition they contain, to pin end to end: the loaded fields; a missing name (no lookup, no warning), an unknown or empty name (none and a warning), a known source (kept, one reference and one active reference), a source that contains the transition (released, none and a warning, and the old source A still goes out); a load onto a slot A that holds a source (taken back), the same source again and an inactive slot A (released without a removal); the swap with itself (nothing); all 32 slot states of the swap (old child present and active or not, new child present, active and contained or not), each child left with the right references and the refusal storing none, inactive; and the getters and the setter on a source of every type and on none. Characterized, not endorsed: - the loaded alignment, width and height are truncated to their low 32 bits: 2^32 + 5 loads as 5, -1 as UINT32_MAX, INT64_MIN as 0; - the loaded mode is kept as is: 7 stays 7. It is in the native test graph, in name order, with both headers as watch inputs. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and no two enum types are compared. The real-libobs tests test_transition_load_release, test_transition_scale_type, test_transition_swap, test_transition_swap_active and test_transition_swap_cycle cover the callers. Refs obs-rust#2595. * obs-source: Test the transition_load port RED for the port of libobs/obs-source-transition-load.c.h to a new transition_load module of rust/obs-source, next to transition_clock, transition_render and transition_start. The safe core is a stub (todo!()): is_transition(), scale_type(), looks_up(), source() -> Source (Keep, NotFound, Refuse), swaps() and copy_stores(), with TYPE_TRANSITION and the scale types (taken from transition_clock). The plan sketched wider steps: load_fields() for the five loaded values, load_source(has_name, found, add_ok), release_old(), swap() and copy_slot(has_old, old_active, child_active, add_ok). The truncations and the mode stay C casts, so load_fields() comes down to scale_type(). load_source() and copy_slot() would take the add's result before the C knows whether it adds at all; so the lookup, the outcome after the add and the store rule are their own functions, and the C keeps its && before each add. release_old() is transition_start::child_active(), already ported, and the getters' defaults stay C literals. tests/source/transition_load.rs ports test_transition_load_steps 1:1: its 10 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases and the stand-in transition's copies of the callers included. Edge cases (edge_*) check the core against models of the original C: - every decision over every combination of its flags; - the type check over -100,000..100,000, the ends of i32 and 2 with any other bit set; - the scale type at every power of two with its neighbours and negations, a stride over i64 and the ends, against origin/master's valid_scale_type(); - proptests (4,096 cases each): every decision over full-range values, and sequences of up to eleven loads (any name, any int64_t values), swaps, swap_begin()s and swap_end()s alone, scale type sets and getter reads on three transitions of any source type with children that may contain them, through the stand-in against a copy of the callers with origin/master's expressions inline; both end in the same state, and every child's references match the slots that hold it. soldr cargo test -p obs-data --test obs-tests-core -- source::transition_load passes 1 of 15 (the constants) and fails 14 with "not yet implemented". Refs obs-rust#2595. * obs-source: Port the transition load checks Ports libobs/obs-source-transition-load.c.h, the load, scale type and swap checks of obs-source-transition.c, to the transition_load module of rust/obs-source. obs-source-transition.c.h stays C around it: obs_ptr_valid(), the locks and the texture locks in their order, the pointer comparisons, the obs_data reads, obs_get_source_by_name(), the add only for a found source or an active new child, every obs_source_get_ref() and obs_source_release(), the active child calls, the (uint32_t) truncations and the mode taken as is, the fields the swap hands over, the texrender swap, the size and matrix recalculation, the getters' literals and the logs. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/transition_load.rs), six functions: - is_transition(): type == TYPE_TRANSITION (2); - scale_type(): 1 and 2 as Aspect and Stretch, any other i64 Max Only, matched on the whole i64 (2^32 + 1 is not Aspect); - looks_up(): has_name; swaps(): !same; - source() -> Source: NotFound without a source, Refuse when the add failed, else Keep; - copy_stores(): !adds || add_ok. TYPE_TRANSITION is the header's; the scale types are transition_clock's. The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. Shims (src/ffi/source_transition_load.rs): the six C signatures by value; the source type and the scale type result as int, the loaded scale type as int64_t, the outcome as the C's enum (u32, as source_transition_start returns its admission). No pointer crosses and no struct is mirrored. No intentional difference from the C. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-transition-load (LIBOBS_PORTED_SOURCES), whose PCH is only obs-source-transition-load.h; libobs.pch.h keeps the header for obs-source-transition.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. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the six functions are local in all three, and the hybrid's come from the Rust archive (the group's object is built only for libobs-c-reference). ci/test_ported_sources.py checks the group on every host. test_transition_load_steps still compiles the C file into itself, unchanged. The new test_transition_load_steps_rust builds the same test source against libobs_rust-static instead, as test_transition_start_steps_rust does, and links: the test includes the two headers and obs.h and calls only hidden functions. The 28 transition tests (test_transition_*, test_studio_mode_swap, test_studio_mode_exit, test_saved_transition, test_tbar_position, test_fade_to_color_mix, test_visibility_transition, test_stinger_media_duration, test_item_transition_empty_source, test_group_hide_transition_audio and test_slideshow_manual_end, with the _rust variants) pass on the C backend, the hybrid and libobs-c-reference. soldr cargo test -p obs-data --test obs-tests-core -- source::transition_load:: passes 15 of 15. No user-visible change, so no docs/features.md line. Refs obs-rust#2595. * obs-source: Check transition_load against the C Tier 3 for the transition_load port. oracle/source_transition_load.c compiles the unmodified libobs/obs-source-transition-load.c.h with its six functions renamed to oracle_*, and exports the header's values and sizes by index. tests/source/transition_load_parity.rs gives each input to the oracle, the shim (the extern "C" function the hybrid links) and the core, and compares each bool as the C's byte (0 or 1, the same on both sides), the outcome as the C's enum value and each number exactly: - the header's values and the sizes of the outcome enum, bool and int; - every function of flags over every combination of them; - the type check over every int from -1,000,000 to 1,000,000, every 65,521st int, 2 with each other bit set and the ends; - the scale type over every value from -1,000,000 to 1,000,000, every power of two with its neighbours and negations, the 65,536 values either side of 2^32 and -2^32, the 65,536 at each end of int64_t and a stride over int64_t; - proptests (20,000 cases each) over any int type, any int64_t scale type and any flags. Nothing is excluded: the C has no undefined or host-dependent result here, and the port has no intentional difference. Mutation check: 23 mutants, all killed. 16 in the core (the type check at >= and !=, each scale type mapped wrong, the default Aspect, the value's low 32 bits matched, the lookup always or never, each source outcome inverted or swapped, the swap gate inverted or constant, and the store rule as add_ok, !adds && add_ok and adds || add_ok): Tier 1 and Tier 3 each kill all 16. 7 in the shims (a constant type, the scale type's low 32 bits, a constant lookup, the source and store arguments swapped, KEEP returned as REFUSE, the swap gate inverted): Tier 3 kills all 7 (Tier 1 calls only the core). Refs obs-rust#2595. * docs: Record the transition load port rust/README.md gets the row for libobs/obs-source-transition-load.c.h (obs-source::transition_load), in sorted place: what moved, what stays C and why (every read and call at its point and under its condition, the add only under the C's own &&, the truncating casts, the swap's handover and the getters' literals), the characterized-not-endorsed behaviours, the tests that see the swap and what Tier 3 covers. The obs-source crate row, its Cargo description and the lib.rs crate docs name the new module. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. rust/obs-c-oracle/benches/port_comparison/source_transition_load.rs runs 1024 loads over every combination of the flags the C reads, source types in and out of the enum and saved scale types at 0, 1, 2, 3, -1 and past 32 bits, each through the type check, the lookup, the source outcome and the scale type, then a swap's gate and the store rule of both slots, on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median per 1024 loads: Rust 16.99 us, C 16.72 us (1.02x), about 17 ns a load. The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2595.
MCPVOT
pushed a commit
to MCPVOT/obs-studio
that referenced
this pull request
Oct 30, 2026
* libobs: Move the source monitoring decisions Behaviour-neutral extraction before the Rust port. The decisions of obs_source_set_flags(), obs_source_set_audio_mixers(), obs_source_get_audio_mixers(), obs_source_enable_push_to_mute(), obs_source_enable_push_to_talk(), obs_source_set_monitoring_enabled(), obs_source_set_monitoring_type(), obs_source_get_monitoring_type(), clamp_balance() and obs_source_set_audio_active() in obs-source.c.h move to libobs/obs-source-monitoring.c.h, as thirteen functions on plain values declared in the new libobs/obs-source-monitoring.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - _changes(): a set does something only when the value changes (the flags, the mixers, monitoring on or off, and the push-to enables' signal); - _has_audio(): the mixers' gate for a source that does not own its info id (OBS_SOURCE_AUDIO in the output flags); - _mixers_store(): the low 32 bits of what an audio_mixers handler leaves; - _push_to_logs(): the push-to enables log a change on an audio source; - _on_type(): monitoring on and muted is Monitor Only, else Monitor and Output (obs-rust#2447), for the compatibility signal and the getter; - _stored_type() and _monitor() -> KEEP | CREATE | DESTROY: the type obs_source_set_monitoring_enabled() stores and the monitor route; - _route() -> OFF | MONITOR_ONLY | MONITOR_AND_OUTPUT | ON: the steps of obs_source_set_monitoring_type() for a type (obs-rust#2444, obs-rust#2447); - _off_reads_mute() and _off_unmutes(): none looks at the mute only when Monitor Only set it, and undoes it if it is still on; - _only_mutes(): Monitor Only mutes first if not muted; - _balance(): clamp_balance(), NaN centred, else clamped to [0, 1] (obs-rust#2051); - _audio_active() -> NONE | ACTIVATE | DEACTIVATE: the signal of a change. Split per step, as obs-rust#2153 did, so every call and read stays where it was and under its condition: obs_source_valid(), audio_mutex, os_atomic_load_bool() of monitor_only_muted once before the steps and os_atomic_set_bool() of it and of audio_active, the reads of owns_info_id (and of the output flags only when it is false), obs_source_get_output_flags() before the changed test, user_muted read only when monitoring turns on, monitoring_enabled read again after the signals, obs_source_muted() only where the C's && reached it (after monitoring is off, for none), obs_source_set_muted() and obs_source_set_monitoring_enabled() in their order (the mute before monitoring turns on), every calldata_*(), signal and log, the (float) of the handler's balance, audio_monitor_create() and _destroy(), and the getters' answers for an invalid source (0, false and 0.5). clamp_balance() stays as an inline wrapper for its two calls. The monitoring type crosses as int; the header copies OBS_SOURCE_AUDIO and the three monitoring types, and obs-source.c.h checks them and that enum obs_monitoring_type is int-sized with _Static_assert. Checked in a scratch harness (not committed). It compiles origin/master's fifteen functions (the ten above with obs_source_get_flags(), obs_source_get_monitoring_enabled(), obs_source_get_balance_value(), obs_source_set_balance_value() and obs_source_audio_active()) verbatim next to this branch's and the moved file, as C++, over a stand-in source whose fields log every read and write with its value. Every call is logged in order with its arguments: obs_source_valid(), the lock and unlock, the calldata sets and gets, each signal, blog(), obs_source_get_output_flags(), the atomics, obs_source_muted(), obs_source_set_muted(), obs_source_dosignal(), the push-to signal and audio_monitor_create() and _destroy(). A signal handler may leave any mixers (above UINT32_MAX, negative, the ends of int64_t) or any balance, and another thread may write any field at any event. Inputs: an invalid source or any start state, flags and mixers at the edges and random, types 0 to 4, -1, the ends of int and random, balances at NaN (both signs), the signed zeros, the smallest subnormals, 1.0 and its neighbours, the ends of float, the infinities and random bit patterns; one to four operations each. 5,800,000 runs: 2,000,000 each with GCC and Clang at -O2, 500,000 each at -O0, 300,000 each under ASan and UBSan with no recovery (GCC -O0, Clang -O2, without C++'s enum range check, which C does not have) and 200,000 with gcov. All 82,503,972 logged events match, as does the final state. Every branch of origin/master's functions is taken both ways. 30 deliberately broken moves were planted, and all 30 fail it: each function's rule inverted, widened or made constant (changes as == and >, the audio bit as bit 0 or any flag, the mixers shifted or saturated, the log rule without the flag or without the change, the on type constant or inverted, the stored type Monitor Only, the monitor never kept or created on the wrong edge, each route moved, the default OFF, the three mute steps constant, NaN as 0.0, the clamp at <= 0 and below 1.0, the active signal never NONE or on prev), and at the call sites the mute read before the mark, user_muted read without its log, the output flags read only after a change, the mixers' gate reading the output flags first, and the type taken mod 4. git blame on the moved lines shows the upstream commits d2934ec and 646836a, and the fork's obs-rust#2058 (the balance clamp) and obs-rust#2450 (the Monitor Only steps); they move as they are. The new file joins libobs.core-source with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol set is unchanged (1766 on the C backend); the thirteen functions are local. Refs obs-rust#2621. * test: Characterize the source monitoring rules test_source_monitoring_steps compiles libobs/obs-source-monitoring.c.h (ASan and UBSan) and calls only its functions through the header. 16 cases: - the header's copies of OBS_SOURCE_AUDIO and the three monitoring types, the enum's size and the monitor, route and active values; - the same-value rule over pairs of 32-bit edges and the four bools; - the audio gate over every bit and the mixers' stored value; - the push-to log rule over flags and changes; - the on and stored types and the monitor route, every combination; - the route over -1000..1000 and the ends of int, and the three mute steps; - the balance at NaN (quiet, negative and signalling), the signed zeros, the smallest subnormals, 1.0 and its neighbours, the ends of float and the infinities; - the audio active signal, every combination. obs_source_set_monitoring_type(), _set_monitoring_enabled(), _get_monitoring_type(), _set_balance_value(), _set_audio_mixers(), _get_audio_mixers(), _set_flags(), the push-to enables and _set_audio_active() are also copied onto a stand-in source that records its signals, logs, mute calls and monitor, to pin end to end: every type (none, Monitor Only, Monitor and Output, 3 and -1) from every start state (on or off, muted or not, Monitor Only's mark set or not), with the steps in order (the mute before monitoring turns on), the compatibility signal's type and the getter after each; Monitor Only then none (the mute goes) and with a mute set in between (it stays); the same value of monitoring on or off doing nothing; the balance sent and the one a handler leaves (NaN, 2.0, -1.0, 0.75, -0.0); the mixers of an audio source, a video-only source with and without its own info id and an invalid source, and a handler's value; the flags; the push-to enables with the same value (no signal, no log), a change (log, then signal) and on a video-only source (signal, no log); and audio active set twice (one signal). Characterized, not endorsed: - the mixers a handler leaves are truncated to their low 32 bits: 2^32 + 3 is 3, -1 is UINT32_MAX; - a balance of -0.0 stays -0.0; - Monitor and Output unmutes a mute the user set, while none keeps it. It is in the native test graph, in name order, with the header as a watch input and libm off MSVC. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x, and no two enum types are compared. The real-libobs tests test_source_monitoring_type, test_source_monitor_only_load and test_source_audio_balance_mono cover the callers. Refs obs-rust#2621. * obs-source: Test the monitoring port RED for the port of libobs/obs-source-monitoring.c.h to a new monitoring module of rust/obs-source, next to ptm_gate and volume_apply. The safe core is a stub (todo!()): changes(), has_audio(), mixers_store(), push_to_logs(), on_type(), stored_type(), monitor() -> Monitor (Keep, Create, Destroy), route() -> Route (Off, MonitorOnly, MonitorAndOutput, On), off_reads_mute(), off_unmutes(), only_mutes(), balance() and audio_active() -> Active (None, Activate, Deactivate), with AUDIO and the three monitoring types. The plan sketched wider steps: monitoring_enable(cur, enabled, muted) returning the compatibility type, the stored type and the monitor at once, monitoring_type_first(type, muted) and monitoring_type_after_disable(muted_for_monitor_only, muted_now), and type_of(valid, enabled, muted). Each would take a read the C makes only under a condition (user_muted only when monitoring turns on, monitoring_enabled again after the signals, obs_source_muted() only where its && reaches it) before the C knows it makes it; so the C keeps those conditions and asks one rule per read. The validity checks and the getters' literals stay C. tests/source/monitoring.rs ports test_source_monitoring_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 and the stand-in source's copies of the callers included. Edge cases (edge_*) check the core against models of origin/master's expressions: - every decision over every combination of its flags; - the route over -100,000..100,000, the ends of i32 and every power of two with its neighbours; - the mixers at every power of two of i64 with its neighbours and negations, and the audio gate at every bit; - the balance at every special value (both NaNs, signalling NaNs, the signed zeros, the subnormals, 1.0 and its neighbours, the ends and the infinities), every 1/4096 from -2.0 to 2.0 and a stride over every bit pattern; - proptests (4,096 cases each): every decision over full-range values, and sequences of up to eleven operations (flags, mixers, push-to, monitoring on or off, any type, the getters, any balance, audio active, a user mute, a handler that leaves any mixers or balance, the output flags and the info id) through the stand-in against a copy of the callers with origin/master's expressions inline; both end in the same state after every step. soldr cargo test -p obs-data --test obs-tests-core -- source::monitoring passes 1 of 22 (the constants) and fails 21 with "not yet implemented". Refs obs-rust#2621. * obs-source: Port the source monitoring rules Ports libobs/obs-source-monitoring.c.h, the monitoring, monitor-only mute, balance, mixer, flag, push-to and audio active rules of obs-source.c, to the monitoring module of rust/obs-source. obs-source.c.h stays C around it: obs_source_valid(), audio_mutex, the atomics on monitor_only_muted and audio_active, every read of the source's fields at its point (the output flags only when the source does not own its info id, user_muted only when monitoring turns on, monitoring_enabled again after the signals), obs_source_get_output_flags(), obs_source_muted() and obs_source_set_muted() under the C's own &&, every calldata_*(), signal and log, the (float) of the handler's balance, audio_monitor_create() and _destroy(), and the getters' literals. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/monitoring.rs), thirteen functions: - changes(): cur != value; - has_audio(): AUDIO (1 << 1) in the output flags; - mixers_store(): the low 32 bits of the i64, by its bytes; - push_to_logs(): has_audio() && changed; - on_type(), stored_type(): Monitor Only when muted, else Monitor and Output; Monitor and Output when on, else none; - monitor() -> Monitor: Create on false -> true, Destroy on true -> false, else Keep; - route() -> Route: 0, 1 and 2 to Off, MonitorOnly and MonitorAndOutput, any other i32 On; - off_reads_mute(), off_unmutes(), only_mutes(): the mark, the mute, and not muted; - balance(): NaN is 0.5, then the C's two compares in its order (not f32::clamp()), so -0.0 stays -0.0; - audio_active() -> Active: Activate on false -> true, Deactivate on true -> false, else None. The module denies clippy's arithmetic, indexing, as, float_cmp, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. Shims (src/ffi/source_monitoring.rs): the thirteen C signatures by value; the monitoring types as int, the handler's mixers as int64_t, the balance as float, the monitor, route and active outcomes as the C's enums (u32). No pointer crosses and no struct is mirrored. No intentional difference from the C. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-monitoring (LIBOBS_PORTED_SOURCES), whose PCH is only math.h and obs-source-monitoring.h; libobs.pch.h keeps the header for obs-source.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_source_monitoring_steps still compiles the C file into itself, unchanged. The new test_source_monitoring_steps_rust builds the same test source against libobs_rust-static instead, with libm off MSVC for nextafterf(), as test_transition_load_steps_rust does, and links: the test includes the header and obs.h and calls only hidden functions. It passes 16/16 on the C backend, the hybrid and libobs-c-reference, as does test_source_monitoring_steps; so do test_source_monitoring_type, test_source_monitor_only_load, test_source_audio_balance_mono and the other 80 source, audio, monitor, mute, push-to and volume tests (three failed once each under a parallel run and pass alone on both). The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the thirteen functions are local in all three, and the group's object is built only for libobs-c-reference. soldr cargo test -p obs-data --test obs-tests-core -- source::monitoring:: passes 22 of 22. No user-visible change, so no docs/features.md line. Refs obs-rust#2621. * obs-source: Check monitoring against the C Tier 3 for the monitoring port. oracle/source_monitoring.c compiles the unmodified libobs/obs-source-monitoring.c.h with its thirteen functions renamed to oracle_*, and exports the header's values and sizes by index (the renames also rename the monitor and route enum tags, which share their functions' names, so the enums are sized by what the functions return). tests/source/monitoring_parity.rs gives each input to the oracle, the shim (the extern "C" function the hybrid links) and the core, and compares each bool as the C's byte (0 or 1, the same on both sides), each outcome as the C's enum value, each integer exactly and the balance by its bits: - the header's values and the sizes of the three enums, bool, int and float; - every function of flags over every combination of them, and the push-to log rule with each flag bit; - the same-value rule and the audio gate over every pair of 32-bit edges and every bit; - the mixers at every power of two of int64_t with its neighbours and negations, the 65,536 values either side of 2^32 and -2^32 and at each end, and a stride over int64_t; - the route over every int from -1,000,000 to 1,000,000, every 65,521st int and the ends; - the balance over every bit pattern whose top byte is 0x00, 0x3f, 0x7f, 0x80, 0xbf or 0xff (the zeros, the subnormals, 0.5 to 2.0, the infinities and every NaN, of both signs: 100,663,296 patterns) and every 251st pattern of the rest; - proptests (20,000 cases) over full-range values. Nothing is excluded: the C has no undefined or host-dependent result here (isnan() and the compares are IEEE on every host, and the (uint32_t) of an int64_t is modular), and the port has no intentional difference. Every one of the 2^32 balance patterns was also checked once (131 s in a debug build, too slow to keep). Mutation check: 34 mutants, all killed. 22 in the core (changes as ==, the audio bit as bit 0, the mixers saturated or byte-swapped, the log rule without the flag or without the change, the on type inverted, the stored type Monitor Only, the monitor never created or created on the wrong edge, each route moved and the default Off, the three mute steps constant or inverted, NaN as 0.0, the clamp at <= 0.0 and above 0.999, the active signal on the wrong edge or never None): Tier 1 and Tier 3 each kill all 22. 12 in the shims (changes inverted, the mixers shifted, the log rule always changed, the on type inverted, the monitor's and the active signal's arguments swapped, the type taken mod 4, the balance's absolute value, Create as Destroy, On as Off, Activate as None, and off_unmutes() answered by the wrong rule): Tier 3 kills all 12 (Tier 1 calls only the core). Refs obs-rust#2621. * docs: Record the source monitoring port rust/README.md gets the row for libobs/obs-source-monitoring.c.h (obs-source::monitoring), in sorted place: what moved, what stays C and why (every read and call at its point and under its condition, the C's own && before each mute read, the atomics, the signals, the monitor and the getters' literals), the characterized-not-endorsed behaviours, the tests that see the swap and what Tier 3 covers. The obs-source crate row, its Cargo description and the lib.rs crate docs name the new module. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. rust/obs-c-oracle/benches/port_comparison/source_monitoring.rs runs 1024 updates over every combination of the flags the C reads, with monitoring types 0, 1, 2, 3 and -1, handler mixers of 0x3f, -1 and past 32 bits, and balances at NaN, -0.0, 0.25, 0.5, 1.0, 2.0 and -1.0, each through the same-value rule, the audio gate, the stored mixers, the push-to log rule, the monitoring types and monitor route, the type's route and its three mute steps, the balance twice and the active signal, on the shims and on the oracle, and checks both checksums match. Release, x86_64 Linux, GCC, a loaded host, median per 1024 updates: Rust 17.74 us, C 18.05 us (0.98x), about 17 ns an update. The port changes nothing a user can see, so docs/features.md has no line. Fixes obs-rust#2621.
rdoupe
added a commit
that referenced
this pull request
Oct 31, 2026
Review fix. The move made audio_resampler_comp_step() compute the delta before audio_resampler_resample() logged the engagement, and audio_resampler_destroy() read output_freq for the drift report before the report's gate. Master reads the correction (vc1) for the delta only after the engage log, and output_freq only when the report is due. Each decision is now split in two, so every read is back in its place (#2153): - audio_resampler_comp_step() gives only the action (IDLE, ENGAGE or SET); audio_resampler_comp_delta() gives the delta, and update_compensation() asks it after the engage log, right before swr_set_compensation(); - audio_resampler_comp_reports_drift() is the report's gate and audio_resampler_comp_input_rate() its rate, asked inside the blog() call only when the gate is open. The Rust core follows: step() returns Action (Idle, Engage, Set) with no delta, and delta(), reports_drift() and input_rate() are new; the shims, the oracle and the bench follow, and the hidden-symbol lists swap audio_resampler_comp_drift_report for the three new functions. test_audio_resampler_drift_steps asks the delta and the rate as the caller does (17 cases: delta_rounding is new, half-way corrections rounded away from zero). The Tier 1 tests do the same through a local helper, with every pinned value unchanged (27/27). Tier 3 compares the three new functions on all three sides and adds a proptest of the delta over every correction the clamp allows at any rate (12/12); five new mutants in the new functions and their shims are killed. The scratch move harness, rerun on this tree against origin/master: identical logs in all 8 builds (8,816,852 lines each side). The exported symbols are unchanged on the C, hybrid and C reference builds (1767 each), the nine functions local; test_audio_resampler_drift_steps, test_audio_clock_drift and test_audio_restart_resampler_tail pass on all three, none skipped. Refs #3139.
5 of 7 tasks
chriscoveries
pushed a commit
to chriscoveries/obsrust-fork
that referenced
this pull request
Oct 31, 2026
* libobs: Move the resampler drift decisions Behaviour-neutral extraction before the Rust port. The decisions of media-io/audio-resampler-ffmpeg.c.h move to the new media-io/audio-resampler-drift.c.h, as hidden functions on plain values and the compensation state, declared without EXPORT in audio-resampler-drift.h: - audio_resampler_sample_format(): convert_audio_format(), returning the libavutil value as an int; - audio_resampler_upmix_row(): the mono upmix row of audio_resampler_create() (false, writing nothing, for 0 or more than MAX_AUDIO_CHANNELS channels, where the C indexed past the table); - audio_resampler_comp_set_error(): the first-call reset and the dead band of audio_resampler_set_compensation_error(); - audio_resampler_comp_step(): clamp_drift() and the loop filter step of update_compensation(), returning IDLE, ENGAGE or SET with the delta; - audio_resampler_output_frames(): the padding while engaged; - audio_resampler_comp_count(): the sample counters while engaged; - audio_resampler_comp_drift_report(): the report's gate and its estimated input rate. struct compensation becomes struct audio_resampler_comp in the header, and the COMP_* constants become AUDIO_RESAMPLER_COMP_* there with the design comment (the caller still passes the distance to swr_set_compensation()), so their #undefs go. The header includes no FFmpeg header: the eight sample formats are AUDIO_RESAMPLER_FMT_* values, and audio-resampler-ffmpeg.c checks each against its AV_SAMPLE_FMT_* with a _Static_assert. audio-resampler-ffmpeg.c keeps every swr_* and av_* call, the output buffer, its size and the grow decision, the output pointer copies, convert_speaker_layout() and every log, in their places and under their conditions: the engage log still comes before swr_set_compensation(), and swr_set_matrix() is still asked only for a mono input to more than one channel. Checked in a scratch harness (not committed). It builds origin/master's audio-resampler-ffmpeg.c.h verbatim, and this branch's with the moved file, each over logging stand-ins for libswresample and libavutil (allocation, channel layouts, rescale, delay, matrix, compensation and convert, with injected failures) and for bmalloc, bfree and blog. Each run is one resampler: every audio format and one past the last, every speaker layout (mono inputs favoured), rates from 1 to 192000, up to 400 calls of 0 to 4096 frames, and compensation errors at the dead band's edges, at the ends of int64_t, ramping, or noisy around a drift, plus short runs that engage and end at once. 10,000 runs over 5 seeds in 8 builds (GCC and Clang, -O0 and -O2, with and without ASan and UBSan without recovery): the logs are identical, 8,816,852 lines each side in every build, with 959,178 compensation calls, 5,514 engagements, 5,443 drift reports and 4,452 upmix matrices. 24 broken moves were planted, and the harness fails 22: the dead band 1 ns narrower or moved the wrong way on the negative side, compensation never enabled, the C2 current reversed, vc2 unclamped, no lower clamp, never engaged, the idle check reordered, the delta's sign, truncation for lround(), a 10,000 ppm bound, padding by 1/256 or when not engaged, counting when not engaged, the report without output counted, the 7.1 row feeding the LFE, float planar as packed, and in the caller the engage log on every step, no delta on the engage step, the counts swapped, padding when only enabled and the step at the output rate. The two it passes cannot change what the caller does: the first error leaving vc2 as it was (it is still zero from bzalloc() then) and no row for one channel (asked only above one). The characterization test catches both. The new file has its own group, libobs.audio-resampler-drift, with a precompiled header of audio-resampler-drift.h (with audio-io.h), <math.h> and <stddef.h>, so the C oracle and a C test can compile it without FFmpeg; libobs-media.pch.h includes the header for audio-resampler-ffmpeg.c. The exported symbol set of the Linux C build is unchanged (1767); the seven functions are local (t). test_audio_clock_drift and test_audio_restart_resampler_tail pass on it (6 and 4 cases, none skipped). git blame on the moved lines shows Lain's resampler and pkv's mono upmix matrix, and the fork's own drift compensation. Refs obs-rust#3139. Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]> * test: Characterize the resampler drift loop test_audio_resampler_drift_steps compiles libobs/media-io/audio-resampler-drift.c.h (ASan and UBSan, -ffp-contract=off) and calls only its hidden functions through audio-resampler-drift.h, with no swr context and no FFmpeg header, so it runs on every platform (16 cases): - the constants: the 10 ms dead band, 1000 ppm, the 2^24 distance, the gain and both capacitors, the action values and MAX_AUDIO_CHANNELS; - every audio format to its libavutil value; - the mono upmix row for 1 to 8 channels (front pair and centre, no LFE), and no row, nothing written, for 0, 9, 64 and UINT32_MAX; - the first error enabling compensation and clearing both filter states, a later one keeping them; - the dead band at 0, +-1, +-(band - 1), +-band, +-(band + 1), +-50 ms and the ends of int64_t; - an error that stays in the band: 10,000 idle steps, no delta; - 10,000 steps of 480 frames at 48 kHz with a constant +50 ms and -50 ms error: engaged on the first step, each step's delta (an FNV-1a hash and their sum), both states bit for bit at eleven steps, and the 1000 ppm clamp (a delta of 16,777) reached at step 880; - steps of 1024 frames (the clamp at step 412), an error 1 ns past the band at 44.1 kHz (engaged, but never a delta), an error leaving the band after 100 idle steps (engaged then, once), an error back in the band (still engaged, the correction decays) and zero frames; - the output frame padding with and without engagement, at the multiples of 512; - the counters only while engaged, wrapping as uint64_t; - the drift report's gate (engaged, output counted) and its rate. Characterized, not endorsed: - an audio format past the last is S16; - the report divides first, so 48,048 input samples over 48,000 output at 48 kHz report a hair under 48,048 Hz; - a negative estimate (av_rescale_rnd() overflowing, cast) is padded toward 0. The doubles are compared bit for bit, so the test turns floating-point contraction off, as the shipped file will be when it is ported: GCC and Clang could otherwise fuse vc1 + ic1 / C1 * in_frames into an FMA where the hardware has one. MSVC does not contract under /fp:precise. It is in the native test graph, in name order, on every platform, with the header as a watch input and libm outside MSVC. No assert_in_range or fail_msg, so it builds with cmocka 1.x and 2.x and links on Windows. Passes on the C libobs build (16/16), and with GCC and Clang at -O0 and -O2 under ASan and UBSan. The real-libobs tests of the compensation are test_audio_clock_drift and test_audio_restart_resampler_tail. Refs obs-rust#3139. * obs-media-io: Test the resampler drift port RED for the port of libobs/media-io/audio-resampler-drift.c.h to a new audio_resampler_drift module of rust/obs-media-io, next to audio_io and format_conversion. The safe core is a stub (todo!()): sample_format(), upmix_row(), set_error() (the dead band), step() (one step of the loop filter, an Action: Idle, Engage or Set with the delta), output_frames(), count() and drift_report(), over Compensation, a #[repr(C)] mirror of struct audio_resampler_comp. The constants (DEAD_BAND_NS, MAX_PPM, DISTANCE, GAIN, C1, C2 and the eight sample formats in fmt) are real. tests/audio/audio_resampler_drift.rs ports test_audio_resampler_drift_steps 1:1: its 16 cases under the same names (steps_*), in the same order, with the same values and expectations (the pinned doubles as their bits), the characterized-not-endorsed cases included. Edge cases (edge_*) check the core against a model of the origin/master C, its expressions inline: the dead band over 21 errors (around the band, +-1 s, +-10 s and the ends of int64_t), enabled or not; eight steps from each of those errors at rates of 1 Hz to UINT32_MAX and 0 to UINT32_MAX frames, engaged or not, both states bit for bit; the delta rounding half away from zero, as lround() does; a zero input rate (NaN states and a delta of 0, as glibc's lround() cast to int); the padding at the ends of int (wrapping where the C overflows); the counters wrapping; and the report over counts around 0, 48,000, 2^53 and UINT64_MAX. Four proptests: the dead band over every int64_t, the loop over runs of up to 16 errors within +-10 s at 8 to 192 kHz with 1 to 4096 frames per step, the padding up to 2^20, and the counters. The tests are a module of the existing obs-media-io library harness, the media category's binary; no new test binary. soldr cargo test -p obs-media-io --lib -- audio::audio_resampler_drift:: passes 1 of 27 (the constants) and fails 26 with "not yet implemented". Refs obs-rust#3139. * obs-media-io: Port the resampler drift loop GREEN for obs-rust#3139. Ports libobs/media-io/audio-resampler-drift.c.h, the decisions of the libswresample resampler, to the audio_resampler_drift module of rust/obs-media-io. audio-resampler-ffmpeg.c stays C around it: every swr_* and av_* call (swr_set_matrix() and swr_set_compensation() among them), the output buffer, its size and the grow decision, the output pointer copies and every log. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/audio_resampler_drift.rs): - sample_format(): enum audio_format to the libavutil value, S16 for unknown and anything outside the enum; - upmix_row(): the mono upmix row for 1 to 8 channels, None otherwise; - set_error(): the first call enables and clears the filter, then the error less the 10 ms dead band; - step(): the lag-lead filter, operation for operation as the C (the charge pump, the C2 and C1 currents, both states advanced by the frame count and clamped to 1000 ppm of the input rate), then Idle, or Engage once and Set after, with the delta rounded half away from zero as lround() does; - output_frames(), count() and drift_report(). Compensation is a #[repr(C)] mirror of struct audio_resampler_comp, which stays in the resampler. The module denies clippy's arithmetic, as (allowed on the three casts the C makes), indexing, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state, takes no lock and allocates nothing. Rust never fuses a multiply and an add, and the C group is now built with -ffp-contract=off (GCC and Clang; MSVC does not contract), so the doubles agree bit for bit on every host. No intentional difference. The inputs the C never meets: a zero input rate (NaN states and a delta of 0, as glibc's lround() cast to int; swr_init() rejects the rate first) and an estimate whose padding overflows int (wrapped). Shims (src/ffi/audio_resampler_drift.rs): the seven functions keep the C signatures; enum audio_format crosses as int, the action (0 to 2) as unsigned int, the state as Compensation. A null pointer, which the C dereferences, is neither read nor written; audio-resampler-ffmpeg.c always passes the resampler's own state and its locals. C side: the file leaves libobs.audio-resampler-drift for its own ported group, libobs.ported-audio-resampler-drift, registered in libobs/build/ported-source-sets/audio-resampler-drift.json on every host, with the same precompiled header contents and -ffp-contract=off. 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 is ported on every host. test_audio_resampler_drift_steps still compiles the C file into itself, unchanged. There is no _rust variant against libobs_rust-static: the shims' archive member holds the rest of obs-media-io, which needs obs-util (bcrash, libuuid), 238 undefined references on its own; Tier 3 compares the shims with the C instead. soldr cargo test -p obs-media-io --lib -- audio::audio_resampler_drift:: passes 27 of 27. test_audio_resampler_drift_steps (16/16), test_audio_clock_drift (6/6) and test_audio_restart_resampler_tail (4/4) pass against the C, hybrid and C reference builds, none skipped, and the 40 audio and resampler tests against the hybrid. The exported symbols are identical on the Linux C, hybrid and C reference builds (1767 each, as on master), the seven shims local (t); only libobs-c-reference compiles the ported group. Refs obs-rust#3139. Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]> * obs-media-io: Compare resampler drift to C Tier 3 for the audio_resampler_drift port. The oracle (rust/obs-c-oracle/oracle/audio_resampler_drift.c) compiles the unchanged libobs/media-io/audio-resampler-drift.c.h with its seven functions renamed to oracle_*, and gives its constants (the dead band, the distance, the eight sample formats, MAX_AUDIO_CHANNELS, the action values, the four doubles) and the size, alignment and every field offset of struct audio_resampler_comp; bound in src/audio_resampler_drift.rs. It is built with -ffp-contract=off, as libobs now builds the file, and calls nothing but lround(). tests/audio/audio_resampler_drift_parity.rs compares the oracle, the shims and the core exactly, the doubles bit for bit, all three sides: - the constants and the layout; - every sample format from -2 to 20 and the ends of int; - the upmix row for 0 to 9, 64 and UINT32_MAX channels, written or not; - the dead band over 21 edge errors (enabled or not) and, by proptest, every int64_t; - eight steps from each edge error at rates of 1 Hz to UINT32_MAX and 0 to UINT32_MAX frames, engaged or not, both states and every delta; - half-way deltas, rounded away from zero on every side; - the padding over every estimate from 0 to 2^20 and the ends of int that do not overflow, engaged or not; - the counters and the drift report over counts around 0, 48,000, 2^53 and UINT64_MAX, at output rates of 0 to UINT32_MAX; - the resampler's own order by proptest (700 runs at the full level, about 100,000 steps): errors within +-10 s or near the band every few packets, input rates of 8,000 to 192,000 Hz, 1 to 4096 frames per step, the count of each conversion, the report at the end, and the engagement exactly once. No intentional difference. Left out, as the C never meets them: a zero input rate (NaN states; swr_init() rejects it, and Tier 1 pins the core's answer) and a padding that overflows int. Null pointers, which the C dereferences, are checked on the Rust side only. port_comparison gets benches/port_comparison/audio_resampler_drift.rs: 64 packets of 480 frames at 48 kHz, each a step, the padding and the count, with an error ramping out of the dead band and back every fourth packet, folded into a checksum both sides must match. Linux x86_64: Rust 833 ns, C 802 ns. It allocates nothing with bmalloc. Mutation check (done once, not committed); failing tests per mutant: | Mutant | Tier 1 | Tier 3 | |---|---|---| | sample_format: float as planar | 1 | 1 | | sample_format: outside the enum as U8 | 1 | 1 | | upmix: 7.1 feeds the LFE | 1 | 1 | | upmix: off by one | 1 | 2 | | set_error: vc2 kept | 3 | 2 | | set_error: band 1 ns narrower | 3 | 2 | | set_error: negative side away from 0 | 6 | 4 | | clamp: lower bound to +max | 3 | 3 | | step: C2 current reversed | 8 | 2 | | step: C1 term reassociated (last bit) | 4 | 2 | | step: C1 for C2 | 8 | 2 | | step: gain reassociated (last bit) | 7 | 2 | | step: never engaged | 9 | 3 | | step: idle while at rest | 2 | 1 | | step: delta sign | 8 | 3 | | round: ties to even | 1 | 1 | | step: engage and set swapped | 11 | 4 | | output_frames: 1 frame, not 2 | 3 | 1 | | output_frames: 1/256 | 3 | 1 | | count: when enabled | 3 | 2 | | drift_report: without output counted | 2 | 1 | | drift_report: multiplied first | 2 | 2 | | shim upmix: row not written | 0 | 1 | | shim set_error: error + 1 | 0 | 4 | | shim step: arguments swapped | 0 | 3 | | shim step: delta not written | 0 | 3 | | shim step: set reported as engage | 0 | 3 | | shim output_frames: always engaged | 0 | 1 | | shim count: swapped | 0 | 2 | | shim report: rate not written | 0 | 2 | | shim sample_format: off by one | 0 | 1 | All 31 are killed; the shim mutants by Tier 3, the tier that reaches the shims. The two "last bit" mutants reassociate a product, which changes only the last bit of a state: both tiers catch them. The proptest regression files keep seeds the mutants failed on. Tier 1 and Tier 3 pass (27/27 and 11/11). At the reduced parity level the longest new test takes 0.04 s (the loop proptest; 0.28 s for all 38 at the full level); peak RSS 6.6 MB over 25 runs; no threads of their own. Refs obs-rust#3139. * docs: Record the resampler drift loop port rust/README.md's port table has a row for libobs/media-io/audio-resampler-drift.c.h, after the media remux job: the seven functions (the sample format, the mono upmix row, the dead band, the loop filter step, the padding, the counters and the drift report), what stays C in audio-resampler-ffmpeg.c (every swr_* and av_* call, the buffer, its size and the grow decision, and every log), the _Static_asserts on the sample formats, the mirrored state, the -ffp-contract=off build, what is characterized, the inputs left out of Tier 3, the null pointers, and the tests that cover it. The crate table row already reads "Ports of libobs/media-io/*". The crate's description and its lib.rs module docs name the new module. naming.md's libobs/media-io/ row already maps the directory to the crate. No docs/features.md line: a port with no change in behaviour. Fixes obs-rust#3139. * libobs: Read the drift delta after its log Review fix. The move made audio_resampler_comp_step() compute the delta before audio_resampler_resample() logged the engagement, and audio_resampler_destroy() read output_freq for the drift report before the report's gate. Master reads the correction (vc1) for the delta only after the engage log, and output_freq only when the report is due. Each decision is now split in two, so every read is back in its place (obs-rust#2153): - audio_resampler_comp_step() gives only the action (IDLE, ENGAGE or SET); audio_resampler_comp_delta() gives the delta, and update_compensation() asks it after the engage log, right before swr_set_compensation(); - audio_resampler_comp_reports_drift() is the report's gate and audio_resampler_comp_input_rate() its rate, asked inside the blog() call only when the gate is open. The Rust core follows: step() returns Action (Idle, Engage, Set) with no delta, and delta(), reports_drift() and input_rate() are new; the shims, the oracle and the bench follow, and the hidden-symbol lists swap audio_resampler_comp_drift_report for the three new functions. test_audio_resampler_drift_steps asks the delta and the rate as the caller does (17 cases: delta_rounding is new, half-way corrections rounded away from zero). The Tier 1 tests do the same through a local helper, with every pinned value unchanged (27/27). Tier 3 compares the three new functions on all three sides and adds a proptest of the delta over every correction the clamp allows at any rate (12/12); five new mutants in the new functions and their shims are killed. The scratch move harness, rerun on this tree against origin/master: identical logs in all 8 builds (8,816,852 lines each side). The exported symbols are unchanged on the C, hybrid and C reference builds (1767 each), the nine functions local; test_audio_resampler_drift_steps, test_audio_clock_drift and test_audio_restart_resampler_tail pass on all three, none skipped. Refs obs-rust#3139. --------- Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]>
rdoupe
added a commit
that referenced
this pull request
Oct 31, 2026
Review fix. obs_effect_param_array_shape() read the row digit, the byte after it and the column digit at once, before ep_parse_param_assign_intfloat_array() added either error. The C reads the row digit for its test, adds the row error, reads it again for the count, then reads the byte after it, and the column digit for its test and, after the column error, again for the product. The shape becomes one function per read, each asked where the C read it (#2153): - obs_effect_param_rows_bad(type, is_float), before the row error; - obs_effect_param_rows(type, is_float), the count so far; - obs_effect_param_has_cols(type, is_float), the 'x'; - obs_effect_param_cols_bad(type, is_float), before the column error; - obs_effect_param_cols(type, is_float, count), the count times the column digit. Only a C string, bools and ints cross, so struct obs_effect_param_shape goes. The Rust core (rows_bad(), rows(), has_cols(), cols_bad() and cols() in place of array_shape() and Shape), its shims, the oracle (the route renamed by a function-like macro, which leaves the enum tag alone, with the sizes of bool, int and the route), the characterization (which asks them in the parser's order, and a new case for each alone), Tier 1, Tier 3 (each function compared on its own, the column ones with counts of 0, +-1 and +-1000 too), the bench, the three export lists and the rust/README.md row follow. The move harness reruns on this C against master's functions, plain and with a cf_adderror() stand-in that rewrites the dimension bytes of the type name: 0 differences in all 8 builds both ways, where the first move differs with the rewriting stand-in. 21 planted mutants, all caught. test_effect_param_types_steps (10 cases) catches all 20 mutants of the split C file. Tier 1 and Tier 3: 25/25; 25 mutants of the core and shims, all caught, the shim ones by Tier 3. Refs #3162.
5 of 7 tasks
chriscoveries
pushed a commit
to chriscoveries/obsrust-fork
that referenced
this pull request
Oct 31, 2026
* libobs: Move effect parameter types to own file Behaviour-neutral extraction before the Rust port. The parameter type decisions of effect-parser.c move to libobs/graphics/effect-param-types.c.h, as three functions on a type name declared in the new libobs/graphics/effect-param-types.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_effect_param_type(type): get_effect_param_type() whole, the shader parameter type that ep_compile_annotations() and ep_compile_param() give a type name; - obs_effect_param_route(type, is_texture): which default-value parser ep_parse_param_assignment_val() calls, in its order (texture flag, exact int and float, int and float prefixes, string prefix, exact bool, otherwise invalid); the caller switches on it; - obs_effect_param_array_shape(type, is_float): the value count of ep_parse_param_assign_intfloat_array() (the row digit, times the column digit after an 'x') and whether each digit is outside 1-4. effect-parser.c keeps every token call, every cf_adderror() (in the same order: the row error, then the column error), the value parsers, the brace and constructor handling, the loop over the values and the compile. The one reordering: the shape reads the column digit before the row error is added, where the C added it first; cf_adderror() only records the error and never touches the type name. Checked in a scratch harness (not committed): master's get_effect_param_type(), ep_parse_param_assign_intfloat_array() and ep_parse_param_assignment_val() against the moved code, over logging stand-ins for the token calls, cf_adderror() and the value parsers with scripted results, on 200,000 type names (40,000 under the sanitizers): the known names, cut by a byte or with one to three bytes of their letters, digits, 'x', '_' and a non-ASCII byte added, with and without the texture flag: gcc and clang, -O0 and -O2, with and without ASan/UBSan, 0 differences in 8 builds. 18 planted mutants (the texture flag, each route's compare and order, the row and column bounds, the count's product, the prefix length, the 'x', the texture prefix, two type names, the caller's errors, count and array flag) are all caught. Exported symbols are unchanged and identical on the C, hybrid and C reference libobs (1767); the three functions are local. Refs obs-rust#3162. * test: Characterize effect parameter types Characterization before the Rust port, against the C moved to libobs/graphics/effect-param-types.c: test_effect_param_types_steps (every platform, the moved file on its own, ASan and UBSan), 9 cases: - every exact type name, and any name starting with "texture" (characterized, not endorsed: "textures" too) is a texture; - case matters, and a suffix, a cut or an empty name is unknown; - every route, the texture flag first whatever the name, and a texture name without the flag invalid; - "strings" gets the string parser and "int1", "float3x3" and "integer" array values, with an unknown type (characterized, not endorsed); - the shapes of float2 to float4x4, int1 to int1x4, and only the byte after the row digit looked at for an 'x'; - a row digit outside 1-4 adds its error and still counts, 'x' - '0' for "floatx" (characterized, not endorsed); - a column digit outside 1-4 adds its error and still counts, the terminator as '\0' - '0' for "float4x" (characterized, not endorsed). Non-ASCII digit bytes are left out: their count follows the target's char signedness. The parity test covers them. Deliberate breaks of the moved C (19: the texture flag, each route's compare, the row and column bounds, the product, the prefix length, the 'x', the texture prefix, three type names, the float exact tests and the column flag): all 19 caught. Refs obs-rust#3162. * obs-graphics: Add Tier 1 tests for parameter types RED for obs-rust#3162. obs_graphics::effect_param_types has its API and docs, with todo!() bodies: param_type() (the shader parameter type of a type name), route() (the default-value parser a parameter gets) and array_shape() (the value count of an int or float array type, and its row and column errors). tests/shader/effect_param_types.rs: - steps_*: test_effect_param_types_steps.c 1:1 (9 cases, same names, values and expectations); - edge_*: non-ASCII digit bytes, counted as a C char on the target; a name that ends at the row digit or right after an 'x'; the route's order; and proptests of every decision against a model (param_type() against the ported shader_param_type()). All 15 fail on the stubs (obs-tests-graphics, shader::effect_param_types). Refs obs-rust#3162. * obs-graphics: Port the effect parameter types GREEN for obs-rust#3162. obs_graphics::effect_param_types implements the parameter type decisions of effect-parser.c: - param_type(): the shader parameter type of a type name, through the ported shader_param_names::shader_param_type(), the same map; - route(): the texture flag, exact int and float, the int and float prefixes, the string prefix, exact bool, otherwise invalid, in the C's order; - array_shape(): the row digit after the int or float prefix, times the column digit after an 'x', each a C char minus '0' (c_char, so signed or not as on the target), and whether each is outside 1-4. A byte past the end of the name reads as the terminator; the column digit is read only after an 'x'. No intentional difference. The module denies clippy::todo now too. C ABI (ffi::effect_param_types): three shims; the route crosses as int and struct obs_effect_param_shape is mirrored and crosses by value. A null name, which effect-parser.c never passes and the C would hand to strcmp(), reads as "". libobs: effect-param-types.c.h leaves libobs.graphics for its own group libobs.ported-effect-param-types, registered in libobs/build/ported-source-sets/effect-param-types.json, whose precompiled header includes the unit's header, <string.h> and util/dstr.h. The hybrid libobs leaves the group out and links the shims; the three symbols are listed in rust-exports.map, rust-hidden.txt and rust-unexports-macos.txt and stay hidden. ci/test_ported_sources.py lists the object. Exported symbols are unchanged and identical on the C, hybrid and C reference libobs (1767), the three functions local. test_effect_param_types_steps_rust builds the characterization against the shims in the production staticlib (libobs_rust-static, only with the hybrid backend), as test_graphics_immediate_steps_rust does, under ASan and UBSan; the test file is the same, as nothing differs. Tier 1: 15/15 (obs-tests-graphics, shader::effect_param_types). test_effect_param_types_steps: 9/9 on the C, hybrid and C reference builds; test_effect_param_types_steps_rust: 9/9. Refs obs-rust#3162. * obs-graphics: Check parameter types against C Tier 3 for obs-rust#3162. obs-c-oracle builds the original libobs/graphics/effect-param-types.c.h as oracle_obs_effect_param_* (oracle/effect_param_types.c, with the C dstr.c's astrcmp_n), with the GS_SHADER_PARAM_* and route values and the layout of struct obs_effect_param_shape. tests/shader/effect_param_types_parity.rs runs every call on the C, the shim and the core and compares the results exactly: the type, the route with and without the texture flag, and the shape after both prefixes for every name longer than the prefix. - the enums and the shape's size, alignment and field offsets; - every name of up to four bytes over the bytes that matter (the known names' letters, the digits, 'x', '_' and 0xc3, negative as a signed C char), and every known name followed by every tail of up to three of them; the decisions read a known prefix and at most three bytes after it, so these reach every path. Tails of three or more bytes are sampled by parity::keep() below the full level; - every known name with each one-byte suffix and prefix (1-255) and each one-byte cut; - every byte as the row digit, the column digit, or both, after both prefixes; - proptests of any bytes, alone and after a known name. No intentional difference. Left out, as the C never meets them: the shape of a name no longer than its prefix (the C reads past the terminator; the route never gives one) and a null name (the C calls strcmp(NULL); the shim reads it as "", checked on the Rust side). port_comparison gets benches/port_comparison/effect_param_types.rs: the 12 parameters of a typical effect through the route, the shape and the type as effect-parser.c asks them, folded into a checksum both sides match. Linux x86_64: Rust 189 ns, C 368 ns. It allocates nothing. Mutation check (done once, not committed); failing tests per mutant, Tier 1 / Tier 3: the texture flag ignored 2/7; exact int never matched 3/5; the int prefix shortened 1/3; float arrays as int 4/4; the string prefix exact 3/3; bool invalid 2/3; the int prefix length 4 6/6; 'X' for 'x' 5/5; the column read at the 'x' 6/5; the product a sum 6/5; the bounds 1-5 3/6 and 0-4 3/6; the digit unsigned 2/6; the column error as a row error 5/5; one name's type 2/2; and in the shims a null name as "int" 0/1, the flags swapped 0/7, the count capped 0/6 and the texture flag inverted 0/7. All 19 are killed, the shim mutants by Tier 3, the tier that reaches the shims. The proptest regression files keep seeds the mutants failed on. Tier 1 and Tier 3: 23/23, longest 0.02 s at reduced and 0.08 s at full, peak RSS 8 MB over 20 runs, no threads of their own. Refs obs-rust#3162. * docs: Record the effect parameter types port rust/README.md: the obs-graphics row names libobs/graphics/effect-param-types.c.h, and a row for the unit says what moved, what effect-parser.c keeps, the C behaviour kept, the null name and the tests. docs/rust-port/naming.md lists the file under rust/obs-graphics, and the crate's description and module docs name it. No docs/features.md line: a port with no change in behaviour. Fixes obs-rust#3162. * libobs: Split the effect array shape Review fix. obs_effect_param_array_shape() read the row digit, the byte after it and the column digit at once, before ep_parse_param_assign_intfloat_array() added either error. The C reads the row digit for its test, adds the row error, reads it again for the count, then reads the byte after it, and the column digit for its test and, after the column error, again for the product. The shape becomes one function per read, each asked where the C read it (obs-rust#2153): - obs_effect_param_rows_bad(type, is_float), before the row error; - obs_effect_param_rows(type, is_float), the count so far; - obs_effect_param_has_cols(type, is_float), the 'x'; - obs_effect_param_cols_bad(type, is_float), before the column error; - obs_effect_param_cols(type, is_float, count), the count times the column digit. Only a C string, bools and ints cross, so struct obs_effect_param_shape goes. The Rust core (rows_bad(), rows(), has_cols(), cols_bad() and cols() in place of array_shape() and Shape), its shims, the oracle (the route renamed by a function-like macro, which leaves the enum tag alone, with the sizes of bool, int and the route), the characterization (which asks them in the parser's order, and a new case for each alone), Tier 1, Tier 3 (each function compared on its own, the column ones with counts of 0, +-1 and +-1000 too), the bench, the three export lists and the rust/README.md row follow. The move harness reruns on this C against master's functions, plain and with a cf_adderror() stand-in that rewrites the dimension bytes of the type name: 0 differences in all 8 builds both ways, where the first move differs with the rewriting stand-in. 21 planted mutants, all caught. test_effect_param_types_steps (10 cases) catches all 20 mutants of the split C file. Tier 1 and Tier 3: 25/25; 25 mutants of the core and shims, all caught, the shim ones by Tier 3. Refs obs-rust#3162.
rdoupe
added a commit
that referenced
this pull request
Nov 1, 2026
Behaviour-neutral extraction before the Rust port. The output plan of audio_resampler_create() in media-io/audio-resampler-ffmpeg.c.h moves to the new media-io/audio-resampler-plan.c.h, as hidden functions on plain values declared without EXPORT in audio-resampler-drift.h. Each is asked at the line where audio_resampler_create() read its input, under the same condition (#2153): - audio_resampler_layout_mask(): convert_speaker_layout(), the channel mask of each speaker layout (0 for unknown and outside the enum), still asked only below libswresample 4.5.100; - audio_resampler_output_channels(): the output channels, where output_ch is set; - audio_resampler_planar_output(): whether the output format is planar; the caller still picks output_ch or 1 for the planes, reading output_ch only when it is; - audio_resampler_input_channels() and audio_resampler_is_4point1(): the input channels for the default input layout and the two 4.1 overrides, asked only on libswresample 4.5.100 and newer, src and dst each where they were read; - audio_resampler_upmixes_mono(): more than one output channel, the right side of the mono test's &&, so output_ch is read only for a mono input. The header still includes no FFmpeg header: the masks are AUDIO_RESAMPLER_CH_LAYOUT_* values, and audio-resampler-ffmpeg.c checks each against its AV_CH_LAYOUT_* with a _Static_assert, as it does for the sample formats. audio-resampler-ffmpeg.c keeps every swr_* and av_* call: the mono test is still the mask compare on the old libswresample and av_channel_layout_compare() on the newer one. The layout table is now built everywhere. The new file has its own live group, libobs.audio-resampler-plan, in the media lib-module, with a precompiled header of audio-resampler-drift.h only, so the C oracle and a C test can compile it alone. audio-resampler-drift.c.h is already ported, so the hybrid libobs would drop it; the plan joins it in the GREEN commit. No Rust: the hybrid libobs compiles the C too. The C, hybrid and C reference builds export the same 1767 symbols, the six new functions local (t) in each. Move harness (scratch, not committed): origin/master's audio-resampler-ffmpeg.c and this branch's with the moved file, each over logging stand-ins for libswresample and libavutil (layouts, allocation, matrix, init, convert, with injected failures) and for bmalloc, bfree and blog, on both libswresample paths. Every pair of speaker layouts (with -1, 8, 9, 100 and INT_MAX) and every output format (with -1, 9 and 100), then one resample and the planes handed out. 16 builds (GCC and Clang, -O0 and -O2, with and without ASan and UBSan without recovery, old and new libswresample): identical logs, 36,672 lines each side on the old path and 48,164 on the new. All 12 planted mutants differ: 5.1 as 5.1 (side), 2.1 as 4.0, unknown as mono, outside the enum as stereo (old path), one output channel too many, always planar or planar inverted, an unknown input as two channels, 4.1 for 4.0 or never, and the gate at one channel or never. test_audio_clock_drift (6), test_audio_restart_resampler_tail (4) and test_audio_resampler_drift_steps (17) pass on the C, hybrid and C reference builds, none skipped. git blame on the moved lines shows Lain's resampler and pkv's channel layout API and mono upmix. Refs #3332. Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]>
6 of 7 tasks
alerque
pushed a commit
to alerque/obs-studio
that referenced
this pull request
Nov 2, 2026
* libobs: Move the resampler output plan Behaviour-neutral extraction before the Rust port. The output plan of audio_resampler_create() in media-io/audio-resampler-ffmpeg.c.h moves to the new media-io/audio-resampler-plan.c.h, as hidden functions on plain values declared without EXPORT in audio-resampler-drift.h. Each is asked at the line where audio_resampler_create() read its input, under the same condition (obs-rust#2153): - audio_resampler_layout_mask(): convert_speaker_layout(), the channel mask of each speaker layout (0 for unknown and outside the enum), still asked only below libswresample 4.5.100; - audio_resampler_output_channels(): the output channels, where output_ch is set; - audio_resampler_planar_output(): whether the output format is planar; the caller still picks output_ch or 1 for the planes, reading output_ch only when it is; - audio_resampler_input_channels() and audio_resampler_is_4point1(): the input channels for the default input layout and the two 4.1 overrides, asked only on libswresample 4.5.100 and newer, src and dst each where they were read; - audio_resampler_upmixes_mono(): more than one output channel, the right side of the mono test's &&, so output_ch is read only for a mono input. The header still includes no FFmpeg header: the masks are AUDIO_RESAMPLER_CH_LAYOUT_* values, and audio-resampler-ffmpeg.c checks each against its AV_CH_LAYOUT_* with a _Static_assert, as it does for the sample formats. audio-resampler-ffmpeg.c keeps every swr_* and av_* call: the mono test is still the mask compare on the old libswresample and av_channel_layout_compare() on the newer one. The layout table is now built everywhere. The new file has its own live group, libobs.audio-resampler-plan, in the media lib-module, with a precompiled header of audio-resampler-drift.h only, so the C oracle and a C test can compile it alone. audio-resampler-drift.c.h is already ported, so the hybrid libobs would drop it; the plan joins it in the GREEN commit. No Rust: the hybrid libobs compiles the C too. The C, hybrid and C reference builds export the same 1767 symbols, the six new functions local (t) in each. Move harness (scratch, not committed): origin/master's audio-resampler-ffmpeg.c and this branch's with the moved file, each over logging stand-ins for libswresample and libavutil (layouts, allocation, matrix, init, convert, with injected failures) and for bmalloc, bfree and blog, on both libswresample paths. Every pair of speaker layouts (with -1, 8, 9, 100 and INT_MAX) and every output format (with -1, 9 and 100), then one resample and the planes handed out. 16 builds (GCC and Clang, -O0 and -O2, with and without ASan and UBSan without recovery, old and new libswresample): identical logs, 36,672 lines each side on the old path and 48,164 on the new. All 12 planted mutants differ: 5.1 as 5.1 (side), 2.1 as 4.0, unknown as mono, outside the enum as stereo (old path), one output channel too many, always planar or planar inverted, an unknown input as two channels, 4.1 for 4.0 or never, and the gate at one channel or never. test_audio_clock_drift (6), test_audio_restart_resampler_tail (4) and test_audio_resampler_drift_steps (17) pass on the C, hybrid and C reference builds, none skipped. git blame on the moved lines shows Lain's resampler and pkv's channel layout API and mono upmix. Refs obs-rust#3332. Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]> * test: Characterize the resampler output plan test_audio_resampler_plan_steps compiles the moved libobs/media-io/audio-resampler-plan.c.h into itself, with ASan and UBSan, and calls only its hidden functions through audio-resampler-drift.h, with no swr context and no FFmpeg header, so it runs on every platform (9 cases). A local helper asks them as audio_resampler_create() does: the planes from the output channels when the output is planar, the gate only for a mono input. - the seven channel masks; - the mask of every speaker layout, and 0 for SPEAKERS_UNKNOWN and for -1, 7 (the gap before 7.1), 9, 100, INT_MAX and INT_MIN; - the output channels of every layout, 0 outside the enum; - the planes of every format: the channels when planar, else 1, and 1 for a format outside the enum; - the input channels of every layout; - 4.1 on the input side, the output side, both, and nowhere else; - mono into each layout: one input channel, and the upmix only into two channels or more; - the upmix gate at 0, 1, 2, 3, 5, 8, 9, 64 and UINT32_MAX channels; - every pair of layouts from -2 to 10 and every format from -2 to 10 against the expressions audio_resampler_create() wrote. Characterized, not endorsed: - SPEAKERS_2POINT1 (FL, FR and LFE) has the surround mask (FL, FR and FC) on the old libswresample path; - an unknown input layout has 0 channels, which the newer libswresample path gives to av_channel_layout_default(); - a packed format with no output channels still has one plane. It is in the native test graph, in name order, on every platform, with the header as a watch input. No assert_in_range or fail_msg, and no comparison of two enum types, so it builds with cmocka 1.x and 2.x and with MSVC. test_audio_resampler_drift_steps is unchanged. Passes on the C and Rust build trees (9/9). Refs obs-rust#3332. * obs-media-io: Test the resampler output plan port RED for the port of libobs/media-io/audio-resampler-plan.c.h to the audio_resampler_drift module of rust/obs-media-io, beside the resampler's sample format, upmix row and drift loop. The safe core is a stub (todo!()): layout_mask(), output_channels(), planar_output(), input_channels(), is_4point1() and upmixes_mono(). The channel masks (ch_layout) are real. tests/audio/audio_resampler_plan.rs ports test_audio_resampler_plan_steps 1:1: its 9 cases under the same names (steps_*), in the same order, with the same values and expectations, the characterized-not-endorsed cases included, through the same kind of local helper that asks the core as audio_resampler_create() does. Edge cases (edge_*) check the core against a model of the origin/master C, its expressions inline: the mask of every layout from -1 to 10 and at the ends of int; the plan of every combination of those values as input layout, output layout and format; and the upmix gate at the ends of uint32_t, mono or not. Three proptests: the mask of any int, the plan of any three ints (half of them drawn from -2 to 10), and the gate of any channel count. The tests are a module of the existing obs-media-io library harness, the media category's binary; no new test binary. soldr cargo test -p obs-media-io --lib -- audio::audio_resampler_plan:: passes 1 of 15 (the constants) and fails 14 with "not yet implemented". Refs obs-rust#3332. * obs-media-io: Port the resampler output plan GREEN for obs-rust#3332. Ports libobs/media-io/audio-resampler-plan.c.h, the output plan of the libswresample resampler, to the audio_resampler_drift module of rust/obs-media-io. audio-resampler-ffmpeg.c stays C around it: every swr_* and av_* call (av_channel_layout_default() and av_channel_layout_compare() among them), the planes' choice, the 4.1 layout assignments, the output buffer and every log, each read in its place. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/audio_resampler_drift.rs): - layout_mask(): the channel mask of each enum speaker_layout value, through audio_io's speaker_layout_from_c(); 0 for unknown and any value outside the enum, 2.1 as surround as in the C; - output_channels() and input_channels(): audio_io's audio_channels() (0 outside the enum), the input count as an int; - planar_output(): audio_io's is_audio_planar(), false for a format outside the enum; - is_4point1(): the 4.1 layout and nothing else; - upmixes_mono(): more than one output channel. The module's lints (no arithmetic side effects, casts, indexing, unwrap or panics) cover the new functions; none keeps state, takes a lock or allocates. No intentional difference. Shims (src/ffi/audio_resampler_drift.rs): the six functions keep the C signatures; enum speaker_layout and enum audio_format cross as int. They take no pointers. C side: the file leaves its live group, libobs.audio-resampler-plan, for the existing ported group, libobs.ported-audio-resampler-drift, with the same precompiled header contents; the live group, its precompiled header and its source-set and lib-module entries go. The functions are not EXPORT, so the shims are hidden: the obs-media-io-audio_resampler_drift.txt fragment of rust-hidden.d. test_audio_resampler_plan_steps still compiles the C file into itself, unchanged; tests.d says why it has no _rust variant (the shims' archive member does not link on its own, as for the drift steps test). soldr cargo test -p obs-media-io --lib -- audio::audio_resampler_ passes 54 of 54 (15 new). test_audio_resampler_plan_steps (9/9), test_audio_resampler_drift_steps (17/17), test_audio_clock_drift (6/6) and test_audio_restart_resampler_tail (4/4) pass against the C, hybrid and C reference builds, none skipped. The exported symbols are identical on the Linux C, hybrid and C reference builds (1767 each, as on master), the six shims local (t); only libobs-c-reference compiles the ported group. Refs obs-rust#3332. Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]> * obs-media-io: Compare the resampler plan with C Tier 3 for the resampler output plan port. The oracle (rust/obs-c-oracle/oracle/audio_resampler_plan.c) compiles the unchanged libobs/media-io/audio-resampler-plan.c.h with its six functions renamed to oracle_*, and gives its seven channel masks; bound in src/audio_resampler_plan.rs. tests/audio/audio_resampler_plan_parity.rs compares the oracle, the shims and the core exactly, all three sides: - the masks; - the mask, the output channels, the input channels and the 4.1 test of every speaker layout from -300 to 300 and the ends of int, and by proptest of any int; - whether the output is planar for every format from -300 to 300 and the ends of int, and by proptest any int; - the upmix gate over 0 to 300 channels and the ends of uint32_t, and by proptest any count. No intentional difference, and no input left out: every int is a defined input to all six functions. port_comparison gets benches/port_comparison/audio_resampler_plan.rs: every pair of the eight speaker layouts in packed and planar float (128 plans), each asked as audio_resampler_create() asks it, folded into a checksum both sides must match. Linux x86_64: Rust 0.48 us, C 1.31 us; the plan is asked once per resampler. It allocates nothing with bmalloc. Mutation check (done once, not committed); failing tests per mutant: | Mutant | Tier 1 | Tier 3 | |---|---|---| | mask: 2.1 as stereo | 2 | 1 | | mask: 5.1 as 5.1 (side) | 2 | 1 | | mask: unknown as mono | 2 | 1 | | mask: outside the enum as stereo | 3 | 2 | | output channels: one too many | 7 | 2 | | channels: an unknown layout as two | 7 | 2 | | planar: inverted | 7 | 2 | | planar: a format outside the enum | 4 | 2 | | input channels: at least two | 5 | 2 | | 4.1: for 4.0 | 6 | 1 | | gate: at one channel | 3 | 1 | | gate: never | 4 | 2 | | shim mask: the next layout | 0 | 1 | | shim output channels: the next layout | 0 | 1 | | shim planar: inverted | 0 | 2 | | shim input channels: the next layout | 0 | 1 | | shim 4.1: inverted | 0 | 2 | | shim gate: inverted | 0 | 2 | All 18 are killed; the shim mutants by Tier 3, the tier that reaches the shims. The proptest regression files keep seeds the mutants failed on. Tier 1 and Tier 3 pass (15/15 and 7/7). At the reduced parity level the whole module, 22 tests, takes at most 53 ms over 25 runs; peak RSS 5.8 MB; no threads of their own. Refs obs-rust#3332. * docs: Record the resampler output plan port rust/README.md's port table has a row for libobs/media-io/audio-resampler-plan.c.h, after the drift loop's: the six functions (the channel mask, the output channels, whether the output is planar, the input channels, the 4.1 test and the mono upmix gate), each asked where the C read its input, what stays C in audio-resampler-ffmpeg.c (every swr_* and av_* call, the planes' choice, the 4.1 layout assignments and every log), the _Static_asserts on the masks, what is characterized, and the tests that cover it. The drift loop's row no longer lists convert_speaker_layout() among what C keeps. The crate's description and its lib.rs module docs name the output plan. naming.md's libobs/media-io/ row already maps the directory to the crate. No docs/features.md line: a port with no change in behaviour. Fixes obs-rust#3332. --------- Co-authored-by: Lain <[email protected]> Co-authored-by: pkv <[email protected]>
7 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #2130
What and why
Ports the deinterlace draw decisions of
libobs/obs-source-deinterlace.c.htorust/obs-source, as a new moduledeinterlace_draw, next todeinterlace_pacing(#1954). These are the decisions ofget_effect(),deinterlace_linear_required(),deinterlace_render()andobs_source_set_deinterlace_mode(): which effect a mode draws with, whether the draw is linear sRGB, the technique and multiplier for each pair of source and current colour spaces, whether the second field is due, and what a mode change does. A wrong technique gives washed-out or dark HDR/SDR deinterlaced video; a wrong frame2 compare brings back the one-field 2x output (#395, #1995). The step before this, the out-of-range mode fix (#2120), is already merged and its rule moves with the code.Six commits:
Move (behaviour-neutral) into
libobs/obs-source-deinterlace-draw.c.h, ten functions declared in the newobs-source-deinterlace-draw.hwithoutEXPORT(hidden):obs_source_deinterlace_draw_effect(): the effect of a mode, an enum C maps to the effect slot and file (none for DISABLE and modes outside the enum);obs_source_deinterlace_draw_linear_required();obs_source_deinterlace_draw_skip(): the early return;obs_source_deinterlace_draw_reads_linear_srgb()and_linear_srgb();obs_source_deinterlace_draw_technique()(an enum C maps to"Draw","DrawMultiply","DrawTonemap"or"DrawMultiplyTonemap"),_reads_white_level()and_multiplier();obs_source_deinterlace_draw_frame2();obs_source_deinterlace_draw_mode_change(): same, enable, disable or switch, a mode outside the enum being DISABLE (libobs: Disable an out-of-range deinterlace mode instead of drawing nothing #2120;deinterlace_mode_known()moves too).obs-source-deinterlace.c.hkeeps everygs_*call in its original order and under its original conditions,obs_load_effect()and theobs->videoeffect slots,convert_video_space(),obs_get_video_sdr_white_level(),enable_deinterlacing(),disable_deinterlacing()andobs_enter_graphics(). C passes their results in.convert_video_space()andgs_get_color_space(),gs_get_linear_srgb()was only read for aGS_CS_SRGBsource (the short circuit of the old expression), andobs_get_video_sdr_white_level()only for a pair that multiplies. One plan would have to call them all up front. So the C asks_reads_linear_srgb()and_reads_white_level()first and calls the graphics function only when they say so, exactly as before.floatdivision,white / 80.0for80.0f / white. The frame2 sum is the sameuint64_tarithmetic.TWOX_TOLERANCE, used only there, is now the pacing header'sOBS_SOURCE_DEINTERLACE_PACING_TWOX_TOLERANCE(1000000ULL, which the oldintconstant converted to).int, so values outside either enum take the paths they took.obs-source-deinterlace.c.hchecks that both enums areint-sized.get_effect(),deinterlace_mode_known(),deinterlace_linear_required(),deinterlace_render()andobs_source_set_deinterlace_mode()verbatim, and the moved versions, against stubs that log everygs_*andobs_*call with its arguments (floats as bits). The two traces are byte-identical under GCC -O2 and clang -O0: 100,601 effect lookups, 585,120 renders (every texture/size combination of the early return; 9 × 9 spaces in and out of the enum × the graphics flag × 16 modes × 20 white levels including NaNs, infinities, signed zeros and subnormals; 200,000 random white-level bit patterns; every combination of 16 edgeu64values and 8 half durations for frame2; 300,000 random and near-threshold frame2 inputs) and 100,512 mode changes. A planted change to the linear sRGB read or to the frame2 compare is caught. Master's copy of these functions is unchanged at the final base, and the harness was rerun after the rebase.The file stays in
libobs.core-sourcefor this commit. Exports are unchanged (1766).Characterization:
test_deinterlace_draw_plan_steps, 17 cases, compiling the moved file (ASan and UBSan). It pins:YADIF_2X) and the ends ofint, for the effect and the linear rule;UINT32_MAX;u64wrap pastUINT64_MAX, andhalf_duration < TWOX_TOLERANCE;It is in the test graph in name order, with libm except on MSVC, in the core suite (no suite size is pinned in
rust/obs-build/tests/native.rsany more, so there is nothing to bump).RED: Tier 1 in the crate, against
todo!().GREEN: the safe core and the
#[no_mangle]shims, in a newlibobs.ported-source-deinterlace-drawgroup with its own PCH (obs.h, the draw header and the pacing header). The export lists,source-sets.json, the unity lists andci/test_ported_sources.pyare updated, and a_rustvariant of the characterization is added.Tier 3: a C oracle and parity tests, with the mutation check.
Docs: the README rows, the crate's description and
lib.rs, and aport_comparisonbench file.Kept, characterized, not endorsed:
obs_get_video_sdr_white_level()is passed through unchecked. A level of 0 gives a multiplier of +inf from scRGB (80.0f / 0), -0 gives -inf, a negative level a negative multiplier, and a NaN a NaN. OBS sets levels from 80 to 480 nits.uint64_t. PastUINT64_MAXit lands near 0 and the second field is due at once; withhalf_duration < TWOX_TOLERANCEandframe_ts + offsetsmaller than the difference, it lands nearUINT64_MAXand the second field is never due. A source hasframe_tsandoffset0 only before its first frame, when nothing draws.obs_source_set_deinterlace_mode()no longer stores since libobs: Disable an out-of-range deinterlace mode instead of drawing nothing #2120, is not treated as DISABLE: a mode in the enum switches, and one outside it disables.The port keeps all three:
wrapping_*for every step of the sum, and onef32division.int; the effect comes back asint(-1 for none); the technique and the mode change as the C's enum values; bools and thefloatmultiplier as themselves. The three header enums share their function's name (enum obs_source_deinterlace_draw_technique obs_source_deinterlace_draw_technique(...)), which is legal C; the oracle's rename macros rename the tags too, and its size table names the renamed tags._rustvariant.test_deinterlace_draw_plan_steps_rustbuilds the unchanged test source againstlibobs_rust-static, with libm except on MSVC. The test includesobs.hfor the enum values, which pulls SIMDe andobsconfig.h, so the target takes$<TARGET_PROPERTY:libobs,INTERFACE_INCLUDE_DIRECTORIES>; it still links the archive alone. It passes 17/17 against the shims.libobs-c-reference, identical sets. The ten functions are local (t) in all three; in the hybrid they come from the Rust archive (the C group is compiled only into the C backend andlibobs-c-reference).render_frame25.2 and 25.8 µs Rust, 13.9 and 13.3 µs C per 1024 renders (1.8x to 1.9x), about 12 ns more per render, once a frame for each deinterlaced source.mode_change4.1 and 5.8 µs Rust, 6.0 and 4.2 µs C, within the noise.docs/features.mdline.Observed, not changed:
cargo bench -p obs-c-oracle --bench port_comparisonstops at thebmem/countfixture (left: 16, right: 0) after the deinterlace groups run. It does the same with this PR's bench removed, so it is not from this PR; to filter to one group, run-- source_deinterlace_draw, which completes its groups before the panic.RED → GREEN
2bbcf9bab.soldr cargo test -p obs-data --test obs-tests-core source::deinterlace_drawfails 27 of 27, each with "not yet implemented": the 17 portedsteps_*cases and the 10edge_*cases, four of them proptests. Recorded onc57815c05, the same commit before the rebases.0b68e58dc. Tier 1 passes 27/27. The table ran on the head,d14a4e2fb(based onaf31b65c9), under a privateXvfb -noresetwithdbus-run-session, a fresh HOME,ulimit -c 0and TMPDIR unset.libobs-c-referencewas built withninja libobs-c-referencebefore each run and is newer than the head commit; the c-ref lane putslibobs-c-reference/first onLD_LIBRARY_PATH, checked withldd.test_deinterlace_2x_field_order(5 rates)test_deinterlace_pacing_stepstest_deinterlace_pacing_steps_rusttest_deinterlace_mode_loadtest_media_restart_first_frametest_deinterlace_draw_plan_stepstest_deinterlace_draw_plan_steps_rust-j4, on4570bdc6f, the same commits based on56a900663)ctest skipped nothing, and no cmocka case in the table skipped (the 2x field order cases run, not skip, under the private Xvfb). The full ctest ran before the last rebase (onto #2133, #2138, #2139, #2140 and #2144, none touching these files); after it, the three libraries were rebuilt and the table, the gates and the list checks were rerun.
Reruns to report, all in
test_deinterlace_2x_field_order(#456, the load-induced hold), with the machine at a load average of 15 to 56 on 16 cores from other builds. Each was one field skipped or held one frame too long in one case; the rerun passed:2a08f87b0): hybridfirst_frame_linear_2x_unbuffered_50i_into_60(one field skipped), and onlibobs-c-reference, which runs the C,discard_2x_bottom_first_60i_into_60andlinear_2x_bottom_first_50i_into_50; load 56. All 73 passed on the reruns.9a9de62e6(the same commits based on6bae29730): hybriddiscard_2x_top_first_60i_into_50(a field held 3 frames, allowed 2 once) at load 17; of two reruns of the five rates, one passed and one failed once in60i_into_60at load 24. The full ctest on that head passed on both lanes (440/440 and 454/454), and the table passed at load 3 on hybrid and c-ref.4570bdc6f: hybridyadif_2x_top_first_60i_into_60(one field skipped) at load 23; the full hybrid ctest right after, with all five rates, passed (459/459).The draw decisions are proven equal to the C (harness and Tier 3), they are pure, and a wrong one would change every frame of a mode, not drop one field once; the C reference failed the same way at the same load.
Tier 3,
4d6bd60a1(source::deinterlace_draw_parity, 12 tests). Each run compares the bytes of the two results (bools as bytes, enums as values, the multiplier as itsf32bits):TWOX_TOLERANCEand the type sizes, against the C headers;i32over the whole range and the ends (205,551 modes) for the effect and the linear rule; every mode change between 41 modes;i32, 421,201 pairs) for the technique, the white level read and the multiplier; every pair of -3 to 6 at 26 special white levels;u64values and 10 half durations (58,320) and at the threshold -2 to +2;deinterlace_render()'s decisions in its order, one copy on each side (51,840 renders);u64times andu32half durations (half at the threshold), any space and any white level bit pattern (no float range), anyi32mode, and the render decisions over all of it.Tier 1 and the parity module passed 10 runs in a row with fresh seeds (39/39). No regression file came up; the ones the
todo!()stub and the mutants left were deleted.Mutation check (once, not committed): 40 mutants, Tier 1 (27 tests) and Tier 3 (12), failures per mutant.
>/ saturating sum / saturating- TWOX/ noTWOX/ half doubledvideo_timeandframe_tsswapped / modes swappedmode_known()without DISABLEframe_tsandoffsetswapped / shim width and height swapped35 are killed by Tier 3. The five that survive it are equivalent through the C ABI:
mode_known()only feedsmode_change(), which maps an unknown mode to DISABLE anyway (Tier 1 kills it); onef32division done inf64and rounded is the same correctly rounded result; the disable test can only come first when both modes are DISABLE, which is "same" before either; the sum and the size test are symmetric. Tier 1 does not reach the shims;test_deinterlace_draw_plan_steps_rustand Tier 3 do.Other runs, on the head
d14a4e2fb:uv run ci/local_gate.py --test-diff origin/master: ok. Workspace scope, 3401 of 3401 passed; the 4 skipped are tests ignored by default.--lane lint: ok.--lane cross: ok (on4570bdc6f; it builds libobs for Windows and macOS through the groups, the new PCH andlibobs.pch.hwith its one new include).ci/test_build_groups.py,ci/test_ported_sources.py,ci/test_oracle_standins.py,ci/test_sorted_shared_lists.py,ci/test_test_graph_sorted.py,ci/test_cmocka_rust_static_guard.py,ci/test_cmocka_includes.pyandci/test_cmocka_windows_diagnostics.py: OK.source-sets.json,test-graph.json, the three export lists and the other shared lists were diffed by hand against origin/master: each is master's list plus this PR's lines. One conflict, in therust/README.mdcrate table (obs-scene: Port the scene item names and coordinate keys #2129 changed theobs-scene/row next to ours): master's row kept, ours updated.cargo fmt -pdoes not reach the test modules through obs-data's path), and clippy'smanual_is_multiple_ofin the bench.Checklist
master(or the description starts with a Stacked: note)docs/features.mdis added or updated (not applicable: no user-visible change)-W..., ratchets): built with scripting ON (PR CI builds no OBS app: rungh workflow run ci.yml --ref <branch>for the full builds) and cross-checked with clang and MSVC (not applicable: no warning or flag change)