diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index cbe5bf3256..29bb8fdb18 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -50,6 +50,7 @@ #include "libobs/obs-sceneitem-addref-fields.c.h" #include "libobs/obs-sceneitem-defer-update-fields.c.h" #include "libobs/obs-shader-param-introspection-fields.c.h" +#include "libobs/obs-source-activate-fields.c.h" #include "libobs/obs-source-active-child-fields.c.h" #include "libobs/obs-source-async-compensation-fields.c.h" #include "libobs/obs-source-async-decoupled-fields.c.h" diff --git a/libobs/build/libobs.ported-source-activate+.h.c b/libobs/build/libobs.ported-source-activate+.h.c new file mode 100644 index 0000000000..ca58f8682b --- /dev/null +++ b/libobs/build/libobs.ported-source-activate+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original source activate and deactivate for C reference. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-activate.c.h" diff --git a/libobs/build/ported-source-sets/source-activate.json b/libobs/build/ported-source-sets/source-activate.json new file mode 100644 index 0000000000..21d53baf56 --- /dev/null +++ b/libobs/build/ported-source-sets/source-activate.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-activate+.h.c" + ] +} diff --git a/libobs/cmake/rust-hidden.d/obs-source-source_activate.txt b/libobs/cmake/rust-hidden.d/obs-source-source_activate.txt new file mode 100644 index 0000000000..a519576977 --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-source-source_activate.txt @@ -0,0 +1,5 @@ +# obs-source-activate.c.h (#5811): views, canvases, active children and the +# four public show and active counters call them inside libobs. Declared in +# obs-internal.h without EXPORT, so the shims stay hidden. +obs_source_activate +obs_source_deactivate diff --git a/libobs/obs-source-activate-fields.c.h b/libobs/obs-source-activate-fields.c.h new file mode 100644 index 0000000000..e65d279948 --- /dev/null +++ b/libobs/obs-source-activate-fields.c.h @@ -0,0 +1,42 @@ +#include "libobs/build/libobs.pch.h" + +/* What obs_source_activate() and obs_source_deactivate() and their tree + * callbacks change (the obs-source shim): a live source's show_refs and + * activate_refs, each step one atomic increment, decrement or load, as the + * original did it. The caller rejects a NULL source; the tree walk + * (obs_source_enum_active_tree()) passes the children. */ +void obs_source_activate_inc_show_refs(obs_source_t *source); +void obs_source_activate_inc_show_refs(obs_source_t *source) +{ + os_atomic_inc_long(&source->show_refs); +} + +void obs_source_activate_dec_show_refs(obs_source_t *source); +void obs_source_activate_dec_show_refs(obs_source_t *source) +{ + os_atomic_dec_long(&source->show_refs); +} + +long obs_source_activate_load_show_refs(const obs_source_t *source); +long obs_source_activate_load_show_refs(const obs_source_t *source) +{ + return os_atomic_load_long(&source->show_refs); +} + +void obs_source_activate_inc_activate_refs(obs_source_t *source); +void obs_source_activate_inc_activate_refs(obs_source_t *source) +{ + os_atomic_inc_long(&source->activate_refs); +} + +void obs_source_activate_dec_activate_refs(obs_source_t *source); +void obs_source_activate_dec_activate_refs(obs_source_t *source) +{ + os_atomic_dec_long(&source->activate_refs); +} + +long obs_source_activate_load_activate_refs(const obs_source_t *source); +long obs_source_activate_load_activate_refs(const obs_source_t *source) +{ + return os_atomic_load_long(&source->activate_refs); +} diff --git a/libobs/obs-source-activate.c.h b/libobs/obs-source-activate.c.h new file mode 100644 index 0000000000..687c75b420 --- /dev/null +++ b/libobs/obs-source-activate.c.h @@ -0,0 +1,65 @@ +#include "libobs/build/libobs.pch.h" + +static void activate_tree(obs_source_t *parent, obs_source_t *child, void *param) +{ + os_atomic_inc_long(&child->activate_refs); + + UNUSED_PARAMETER(parent); + UNUSED_PARAMETER(param); +} + +static void deactivate_tree(obs_source_t *parent, obs_source_t *child, void *param) +{ + os_atomic_dec_long(&child->activate_refs); + + UNUSED_PARAMETER(parent); + UNUSED_PARAMETER(param); +} + +static void show_tree(obs_source_t *parent, obs_source_t *child, void *param) +{ + os_atomic_inc_long(&child->show_refs); + + UNUSED_PARAMETER(parent); + UNUSED_PARAMETER(param); +} + +static void hide_tree(obs_source_t *parent, obs_source_t *child, void *param) +{ + os_atomic_dec_long(&child->show_refs); + + UNUSED_PARAMETER(parent); + UNUSED_PARAMETER(param); +} + +void obs_source_activate(obs_source_t *source, enum view_type type) +{ + if (!obs_source_valid(source, "obs_source_activate")) + return; + + os_atomic_inc_long(&source->show_refs); + obs_source_enum_active_tree(source, show_tree, NULL); + + if (type == MAIN_VIEW) { + os_atomic_inc_long(&source->activate_refs); + obs_source_enum_active_tree(source, activate_tree, NULL); + } +} + +void obs_source_deactivate(obs_source_t *source, enum view_type type) +{ + if (!obs_source_valid(source, "obs_source_deactivate")) + return; + + if (os_atomic_load_long(&source->show_refs) > 0) { + os_atomic_dec_long(&source->show_refs); + obs_source_enum_active_tree(source, hide_tree, NULL); + } + + if (type == MAIN_VIEW) { + if (os_atomic_load_long(&source->activate_refs) > 0) { + os_atomic_dec_long(&source->activate_refs); + obs_source_enum_active_tree(source, deactivate_tree, NULL); + } + } +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index c7ecb4c214..5668f78ea9 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -634,70 +634,6 @@ static void hide_source(obs_source_t *source) obs_source_dosignal(source, "source_hide", "hide"); } -static void activate_tree(obs_source_t *parent, obs_source_t *child, void *param) -{ - os_atomic_inc_long(&child->activate_refs); - - UNUSED_PARAMETER(parent); - UNUSED_PARAMETER(param); -} - -static void deactivate_tree(obs_source_t *parent, obs_source_t *child, void *param) -{ - os_atomic_dec_long(&child->activate_refs); - - UNUSED_PARAMETER(parent); - UNUSED_PARAMETER(param); -} - -static void show_tree(obs_source_t *parent, obs_source_t *child, void *param) -{ - os_atomic_inc_long(&child->show_refs); - - UNUSED_PARAMETER(parent); - UNUSED_PARAMETER(param); -} - -static void hide_tree(obs_source_t *parent, obs_source_t *child, void *param) -{ - os_atomic_dec_long(&child->show_refs); - - UNUSED_PARAMETER(parent); - UNUSED_PARAMETER(param); -} - -void obs_source_activate(obs_source_t *source, enum view_type type) -{ - if (!obs_source_valid(source, "obs_source_activate")) - return; - - os_atomic_inc_long(&source->show_refs); - obs_source_enum_active_tree(source, show_tree, NULL); - - if (type == MAIN_VIEW) { - os_atomic_inc_long(&source->activate_refs); - obs_source_enum_active_tree(source, activate_tree, NULL); - } -} - -void obs_source_deactivate(obs_source_t *source, enum view_type type) -{ - if (!obs_source_valid(source, "obs_source_deactivate")) - return; - - if (os_atomic_load_long(&source->show_refs) > 0) { - os_atomic_dec_long(&source->show_refs); - obs_source_enum_active_tree(source, hide_tree, NULL); - } - - if (type == MAIN_VIEW) { - if (os_atomic_load_long(&source->activate_refs) > 0) { - os_atomic_dec_long(&source->activate_refs); - obs_source_enum_active_tree(source, deactivate_tree, NULL); - } - } -} - static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, uint64_t sys_time); static void filter_frame(obs_source_t *source, struct obs_source_frame **ref_frame) diff --git a/rust/README.md b/rust/README.md index ed2dd5b219..374957589d 100644 --- a/rust/README.md +++ b/rust/README.md @@ -423,6 +423,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-scene-transform-update.c.h` | `obs-scene::transform_update` | Swapped in hybrid `libobs` (group `libobs.ported-scene-transform-update`). The transform update decisions of `scene_video_render()` and `update_transforms_and_prune_sources()`, two hidden functions on plain values: `obs_scene_transform_update_scene_size` (`scene_size_changed()`: whether the scene has a new size since its last render; the stored size changes only on a change) and `obs_scene_transform_update_item` (whether an item's transform is computed again on this walk: its `update_transform` flag, a source size that is not the one of its last transform, each dimension compared, or a new scene size). `obs-scene.c.h` keeps the video locks, the item list walk, the recursion into a group's scene, the removed-source check and the removal, the group rebuild flag, `update_item_transform()` (the defer check, the size read, the lock, the signal), `resize_group()` and every size read; it reads the source size only when the flag is clear, as the original `||` stopped at the flag, so a source's `get_width`/`get_height` run as often as before. The scene's stored size crosses as two `uint32_t` pointers (written only on a change), the rest by value; no struct is mirrored. Kept, characterized, not endorsed: a flag set while an item is deferred survives `obs_sceneitem_defer_update_end()`, which computes the transform without clearing it, so the next walk computes it once more. `test_scene_transform_update_steps` compiles the C into itself and `test_scene_transform_update_steps_rust` runs the same test source against `libobs_rust-static`; `test_scene_transform_update_walk` runs the walk through the real libobs with `obs_scene_prune_sources()` (the `item_transform` signals in order and the `get_width`/`get_height` calls: a new item, idle, flagged, resized, deferred and removed items, and a group's child update, resize flag, removed child, deferred child and removed group), and `test_scene_group_transform`, `test_group_child_drift`, `test_group_extent`, `test_group_recursion` and `test_group_teardown_uaf` see the swap through the hybrid. Tier 3 compares the results and the stored size exhaustively over the flags and every pair of edge sizes, with proptests over the `u32` ranges, and runs a walk model of `update_transforms_and_prune_sources()` with the shims against the oracle over random scenes and renders. No intentional differences. | | `libobs/obs-sceneitem-addref.c.h` | `obs-scene::item_addref` | Swapped in hybrid `libobs` (group `libobs.ported-sceneitem-addref`). Safe Rust makes NULL a silent no-op and otherwise calls the private adapter `obs-sceneitem-addref-fields.c.h` once, which does the original `os_atomic_inc_long(&item->ref)`, so C keeps the counter's layout, its platform `long` width (32-bit on Windows) and the atomic ordering; no item layout is mirrored. `obs_sceneitem_release` is unchanged. Kept, characterized, not endorsed: zero and negative counts also increment, and the native limit wraps. Tier 1 mirrors both cases of the unchanged `test_sceneitem_addref`; Tier 2 runs it against both libobs builds; Tier 3 compares the original C on a real-header item with the shim on a byte copy over fill patterns, native long edges and a proptest, and checks the counter's width in the real header, a silent NULL, and concurrent calls adding exactly one each. No intentional differences; no network protocol (Tier 4 inapplicable). | | `libobs/obs-sceneitem-private-settings.c.h` | `obs-scene::item_private_settings` | Swapped in hybrid `libobs` (group `libobs.ported-scene-item-private-settings`). Returns the item's stored `private_settings` unchanged, stored NULL included, after exactly one `obs_data_addref` per call; a NULL item logs the original `obs_ptr_valid` LOG_DEBUG diagnostic and returns NULL. The shim reads only that field, unlocked as in C, through a real-header-verified item prefix; no new private adapter. Unchanged actual-library C characterization (`test_sceneitem_private_settings`) covers Tier 2; Tier 3 compares identity, reference counts, every item byte and the NULL log with the unchanged extracted C. No intentional differences; Tier 4 does not apply. | +| `libobs/obs-source-activate.c.h` | `obs-source::activate`, shims in `obs-source::ffi::source_activate` | #5811: swapped in hybrid `libobs` (group `libobs.ported-source-activate`). `obs_source_activate()` and `obs_source_deactivate()` (declared in `obs-internal.h` without `EXPORT`, so the shims are hidden through `rust-hidden.d`), which views, canvases, active children and the four public show and active counters call: a NULL source logs one `LOG_DEBUG` line naming the entry and nothing else happens. Activate: `show_refs` +1, then one `obs_source_enum_active_tree()` walk adding 1 to each child's `show_refs`; only for `MAIN_VIEW`, then `activate_refs` +1 and a second walk for the children's `activate_refs`. Deactivate: only when `show_refs` is above zero, -1 and a walk subtracting 1 from each child's (a child is not floor-checked); then for `MAIN_VIEW`, only when `activate_refs` is above zero, the same for `activate_refs`. The four tree callbacks (`show_tree`, `hide_tree`, `activate_tree`, `deactivate_tree`) are Rust. Safe core over a `Counters` trait; the atomic increments, decrements and loads stay C in `obs-source-activate-fields.c.h` (live group `libobs.core-source`, no `EXPORT`), and the walk is the C `obs_source_enum_active_tree()`. The new `test_source_activate` runs against hybrid and reference libraries through the four public counters on a nested active tree (the entries' own NULL check can't be reached from outside libobs, so Tier 1 and Tier 3 cover it). Tier 3 runs the original C and the Rust exports on noise-filled real-header sources with a scripted walk over every call, source (NULL too), view type, root counter edge and edge set plus a proptest, comparing each walk's root and every counter when it began, the counters after, the log lines and every other byte, and rejects eleven mutants. The tracing doubles of these two symbols in `obs-c-oracle/oracle/view.c` are gone: the view, show-counter and active-child tests reach the Rust exports, whose adapter stand-ins report the same trace for their test sources. | None. | | `libobs/obs-source-active-child.c.h` | `obs-source::active_child`, shims in `obs-source::ffi::source_active_child` | #5622: swapped in hybrid `libobs` (group `libobs.ported-source-active-child`). `obs_source_add_active_child()` and `obs_source_remove_active_child()`, which scenes, groups and transitions call when a child gains or loses a showing parent. A NULL parent or child logs one `LOG_DEBUG` line naming the function and the parameter (parent first); add returns false. Add refuses `parent == child` with its `LOG_WARNING` line, then walks the child's full tree once with the parent as the walk's stop source and refuses, silently, when the parent is an edge's child or parent anywhere in it (`check_descendant()`). It then loads the parent's `show_refs` and `activate_refs` once each, in that order (#2081), and activates the child `show_refs` times, `MAIN_VIEW` for the first `activate_refs` and `AUX_VIEW` for the rest (none for a count at or below zero). Remove mirrors the loop with deactivations and has no self or cycle check. Safe core over a `Libobs` trait; the shims reach the C walk through `obs_source_active_child_enum_full_tree()` (the hidden wrapper `obs-source.c.h` gained in the extraction), the counter loads through `obs-source-active-child-fields.c.h` (live group `libobs.core-source`, no `EXPORT`), and call `obs_source_activate()` / `obs_source_deactivate()` directly. The unchanged `test_source_active_child` runs against hybrid and reference libraries through the real libobs. Tier 3 runs the original C and the Rust exports on noise-filled real-header sources over a scripted walk (every walk, activation and deactivation in order, the result, the log lines, every other byte; with and without counters changing under the loop), a grid, a proptest, and rejects ten mutants. The test-only `oracle/source_active_child_links.c` stand-ins are gone: the Rust exports define both names in the test binaries now. | None. | | `libobs/obs-source-async-compensation-setter.c.h`, `libobs/obs-source-async-compensation-getter.c.h` | `obs-source::async_compensation` | Public compensation request setter and getter (#5595), swapped in hybrid libobs (group `libobs.ported-source-async-compensation`). Preserves atomic stores and loads, NULL debug diagnostics (the getter answers false) and all timing/frame state without taking a mutex; NULL is rejected before the field adapter. Real-header atomic layout, original C differential sequences (each stored request read back by both getters, nothing written), unchanged audio-input resampler coverage and the unchanged `test_source_async_flag_pair` on both builds. No intentional differences. | | `libobs/obs-source-async-decoupled.c.h` | `obs-source::async_decoupled`, `obs-source-seam` | Unconditional flag store and enable-only locked timing invalidation plus the existing audio reset seam, including repeated enable. Unchanged actual-library characterization, safe Tier 1 mirrors and real-source Tier 3 state/order parity. No intentional differences; Tier 4 does not apply. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index c2702827e0..f68836073d 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -35,6 +35,8 @@ mod canonical_scene_item_get_group_swap_is_registered; mod canonical_scene_item_order_position_swap_is_registered; #[path = "native/registration/canonical_scene_item_set_order_swap_is_registered.rs"] mod canonical_scene_item_set_order_swap_is_registered; +#[path = "native/registration/canonical_source_activate_swap_is_registered.rs"] +mod canonical_source_activate_swap_is_registered; #[path = "native/registration/canonical_source_active_child_swap_is_registered.rs"] mod canonical_source_active_child_swap_is_registered; #[path = "native/registration/canonical_source_async_flag_pair_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_activate_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_activate_swap_is_registered.rs new file mode 100644 index 0000000000..8418bf7ee8 --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_activate_swap_is_registered.rs @@ -0,0 +1,49 @@ +use super::*; + +#[test] +fn canonical_source_activate_swap_is_registered() { + use obs_build::validation::graph::{Graph, Source}; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut graph = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); + let name = "test_source_activate"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + let selected = graph.select(&[(os.into(), true)].into()).unwrap(); + // The test compiles no copy of the C: it reaches the two hidden + // entries through the exported counters of the real libobs (Rust in + // hybrid, the original C in the reference). + assert!( + matches!(selected.targets[name].sources.as_slice(), [Source::Path(path)] + if path == "test/cmocka/test_source_activate.c") + ); + assert!(selected.targets[name].definitions.is_empty()); + assert_eq!(selected.tests[name].target, name); + } + let ported = + fs::read_to_string(root.join("libobs/build/ported-source-sets/source-activate.json")) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-activate+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-activate+.h.c")).unwrap(); + assert!(group.contains("#include \"libobs/obs-source-activate.c.h\"")); + let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core-source+.h.c")).unwrap(); + assert!(!hybrid.contains("#include \"libobs/obs-source-activate.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source-activate-fields.c.h\"")); + // Declared in obs-internal.h without EXPORT: hidden, never exported. + let hidden = + fs::read_to_string(root.join("libobs/cmake/rust-hidden.d/obs-source-source_activate.txt")) + .unwrap(); + assert_eq!( + hidden + .lines() + .filter(|line| !line.starts_with('#')) + .collect::>(), + ["obs_source_activate", "obs_source_deactivate"] + ); + assert!( + !root + .join("libobs/cmake/rust-exports.d/obs-source-source_activate.txt") + .exists() + ); +} diff --git a/rust/obs-c-oracle/oracle.d/source-activate.list b/rust/obs-c-oracle/oracle.d/source-activate.list new file mode 100644 index 0000000000..f10fcdf108 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-activate.list @@ -0,0 +1 @@ +source-activate.inc|libobs/obs-source-activate.c.h|auto diff --git a/rust/obs-c-oracle/oracle/audio_callback_links.c b/rust/obs-c-oracle/oracle/audio_callback_links.c index 0ff3a0323b..91d6271db4 100644 --- a/rust/obs-c-oracle/oracle/audio_callback_links.c +++ b/rust/obs-c-oracle/oracle/audio_callback_links.c @@ -1,15 +1,15 @@ -/* Test-only link stand-ins: obs_source_audio_render() and - * obs_source_enum_active_tree() under libobs's own names, for the test - * binaries that link the obs-core shims without libobs. +/* Test-only link stand-in: obs_source_audio_render() under libobs's own + * name, for the test binaries that link the obs-core shims without libobs. * * The audio tick's shim (rust/obs-core/src/ffi/audio_callback.rs) exports - * audio_callback(), whose libobs calls name them. The MSVC, MinGW and macOS + * audio_callback(), whose libobs calls name it. The MSVC, MinGW and macOS * linkers want every symbol an object names resolved, used or not, so * obs-tests-core needs a definition; libobs has the real ones. * obs_source_active() is the real Rust export of obs-source (#5401), whose * counter adapters oracle/source_showing_active.c compiles, and * obs_source_removed() is its export too (#5587), whose flag adapter * oracle/source_removed.c compiles. + * obs_source_enum_active_tree() is oracle/source_activate.c's (#5811). * obs_source_get_ref() and obs_source_release() (oracle/view.c), * obs_source_get_name() (the obs-missing-files tests), * audio_output_get_sample_rate() and audio_output_get_channels() @@ -29,10 +29,3 @@ void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t chann UNUSED_PARAMETER(sample_rate); UNUSED_PARAMETER(size); } - -void obs_source_enum_active_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param) -{ - UNUSED_PARAMETER(source); - UNUSED_PARAMETER(enum_callback); - UNUSED_PARAMETER(param); -} diff --git a/rust/obs-c-oracle/oracle/source_activate.c b/rust/obs-c-oracle/oracle/source_activate.c new file mode 100644 index 0000000000..1353f0c274 --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_activate.c @@ -0,0 +1,272 @@ +/* Tier 3: the unchanged extracted obs_source_activate() and + * obs_source_deactivate() with their four tree callbacks + * (libobs/obs-source-activate.c.h), renamed oracle_*, and the production + * counter adapters the Rust shims call (obs-source-activate-fields.c.h, + * compiled here under saf_real_* names), over the real private layout. + * + * This file holds the one definition, for the test binaries, of each + * counter adapter and of obs_source_enum_active_tree(). With a fixture of + * this file installed on the calling thread, the adapters are the real + * ones, and the walk is a scripted one that both sides reach: it records + * the root and every node's counters, then reports the case's edges in + * order to the callback it was given (the original's static callbacks, or + * the Rust ones). Without one, the adapters report to oracle/view.c's + * activation trace for the view, canvas, show-counter and active-child + * tests' sources (they never touch those), and the walk does nothing. The + * real walk and counters are covered by test_source_activate. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include +#define obs_source_activate oracle_obs_source_activate +#define obs_source_deactivate oracle_obs_source_deactivate +#include "libobs/build/libobs.pch.h" +#include "source-activate.inc" +#undef obs_source_deactivate +#undef obs_source_activate + +#define obs_source_activate_inc_show_refs saf_real_inc_show_refs +#define obs_source_activate_dec_show_refs saf_real_dec_show_refs +#define obs_source_activate_load_show_refs saf_real_load_show_refs +#define obs_source_activate_inc_activate_refs saf_real_inc_activate_refs +#define obs_source_activate_dec_activate_refs saf_real_dec_activate_refs +#define obs_source_activate_load_activate_refs saf_real_load_activate_refs +#include "source_activate_fields.inc" +#undef obs_source_activate_load_activate_refs +#undef obs_source_activate_dec_activate_refs +#undef obs_source_activate_inc_activate_refs +#undef obs_source_activate_load_show_refs +#undef obs_source_activate_dec_show_refs +#undef obs_source_activate_inc_show_refs + +#define SAF_NODES 4 +#define SAF_EDGES 8 +#define SAF_EVENTS 8 +/* An index for NULL, and for a pointer that is no node. */ +#define SAF_NULL 0xfe +#define SAF_OTHER 0xff + +/* One call: activate (which 0) or deactivate (1) of node `source` (-1 for + * NULL) for `view_type`, from the given counters, on nodes whose every + * other byte is `noise`. Each walk reports `edges` edges, each between two + * nodes (a parent of -1 is NULL; children are always nodes). */ +struct saf_case { + uint8_t which; + int8_t source; + uint8_t noise; + uint32_t view_type; + long show[SAF_NODES]; + long active[SAF_NODES]; + uint8_t edges; + int8_t edge_parent[SAF_EDGES]; + int8_t edge_child[SAF_EDGES]; +}; + +/* What one side did: each walk in order (its root, and every node's + * show_refs and activate_refs when it began), the counters afterwards, its + * log lines (count, level of the last, the last), and whether every other + * byte of the nodes is as before. */ +struct saf_result { + uint32_t events; + int64_t trace[SAF_EVENTS][1 + 2 * SAF_NODES]; + long show[SAF_NODES]; + long active[SAF_NODES]; + uint32_t log_count; + int32_t log_level; + char log[128]; + bool untouched; +}; + +struct saf_fixture { + struct obs_source nodes[SAF_NODES]; + const struct saf_case *c; + struct saf_result *out; +}; + +/* Per thread: the Rust test harness runs cases on several threads. */ +static _Thread_local struct saf_fixture *saf_current; + +static int64_t saf_index(const void *source) +{ + struct saf_fixture *f = saf_current; + if (!source) + return SAF_NULL; + for (size_t i = 0; i < SAF_NODES; i++) { + if (source == &f->nodes[i]) + return (int64_t)i; + } + return SAF_OTHER; +} + +static obs_source_t *saf_node(int8_t index) +{ + return index < 0 || index >= SAF_NODES ? NULL : &saf_current->nodes[index]; +} + +/* ------------------------------------------------------------------------- */ +/* the one definition of each adapter and of the walk */ + +void oracle_view_activation_step(const obs_source_t *source, bool deactivate, bool active); + +void obs_source_activate_inc_show_refs(obs_source_t *source); +void obs_source_activate_inc_show_refs(obs_source_t *source) +{ + if (saf_current) + saf_real_inc_show_refs(source); + else + oracle_view_activation_step(source, false, false); +} + +void obs_source_activate_dec_show_refs(obs_source_t *source); +void obs_source_activate_dec_show_refs(obs_source_t *source) +{ + /* Never reached without a fixture: the loads below answer 0. */ + if (saf_current) + saf_real_dec_show_refs(source); +} + +long obs_source_activate_load_show_refs(const obs_source_t *source); +long obs_source_activate_load_show_refs(const obs_source_t *source) +{ + if (saf_current) + return saf_real_load_show_refs(source); + oracle_view_activation_step(source, true, false); + return 0; +} + +void obs_source_activate_inc_activate_refs(obs_source_t *source); +void obs_source_activate_inc_activate_refs(obs_source_t *source) +{ + if (saf_current) + saf_real_inc_activate_refs(source); + else + oracle_view_activation_step(source, false, true); +} + +void obs_source_activate_dec_activate_refs(obs_source_t *source); +void obs_source_activate_dec_activate_refs(obs_source_t *source) +{ + if (saf_current) + saf_real_dec_activate_refs(source); +} + +long obs_source_activate_load_activate_refs(const obs_source_t *source); +long obs_source_activate_load_activate_refs(const obs_source_t *source) +{ + if (saf_current) + return saf_real_load_activate_refs(source); + oracle_view_activation_step(source, true, true); + return 0; +} + +/* Also linked by the test binaries that run the audio tick's shim (which + * names it, #5401) and never reach it. */ +void obs_source_enum_active_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param) +{ + struct saf_fixture *f = saf_current; + if (!f) + return; + struct saf_result *out = f->out; + if (out->events < SAF_EVENTS) { + int64_t *e = out->trace[out->events]; + e[0] = saf_index(source); + for (size_t i = 0; i < SAF_NODES; i++) { + e[1 + i] = f->nodes[i].show_refs; + e[1 + SAF_NODES + i] = f->nodes[i].activate_refs; + } + } + out->events++; + for (uint8_t i = 0; i < f->c->edges && i < SAF_EDGES; i++) + enum_callback(saf_node(f->c->edge_parent[i]), saf_node(f->c->edge_child[i]), param); +} + +/* ------------------------------------------------------------------------- */ +/* the parity run */ + +#if defined(__GNUC__) || defined(__clang__) +static void saf_capture(int level, const char *format, va_list args, void *param) __attribute__((format(printf, 2, 0))); +#endif +static void saf_capture(int level, const char *format, va_list args, void *param) +{ + struct saf_result *out = param; + out->log_count++; + out->log_level = level; + vsnprintf(out->log, sizeof(out->log), format, args); +} + +typedef void (*saf_call)(obs_source_t *, uint32_t); +typedef void (*saf_get_log)(log_handler_t *, void **); +typedef void (*saf_set_log)(log_handler_t, void *); + +static void saf_original_activate(obs_source_t *source, uint32_t view_type) +{ + oracle_obs_source_activate(source, (enum view_type)view_type); +} + +static void saf_original_deactivate(obs_source_t *source, uint32_t view_type) +{ + oracle_obs_source_deactivate(source, (enum view_type)view_type); +} + +/* The original calls, for the parity test's other side. */ +void oracle_source_activate_originals(saf_call *activate, saf_call *deactivate); +void oracle_source_activate_originals(saf_call *activate, saf_call *deactivate) +{ + *activate = saf_original_activate; + *deactivate = saf_original_deactivate; +} + +/* Runs one case through `activate` or `deactivate` on fresh noise-filled + * nodes. False when the fixture could not be built or an adapter does not + * reach its field. */ +bool oracle_source_activate_run(saf_call activate, saf_call deactivate, saf_get_log get, saf_set_log set, + const struct saf_case *c, struct saf_result *out); +bool oracle_source_activate_run(saf_call activate, saf_call deactivate, saf_get_log get, saf_set_log set, + const struct saf_case *c, struct saf_result *out) +{ + struct saf_fixture *f = malloc(sizeof(*f)); + struct obs_source *before = malloc(sizeof(f->nodes)); + if (!f || !before) { + free(f); + free(before); + return false; + } + memset(f, c->noise, sizeof(*f)); + memset(out, 0, sizeof(*out)); + out->log_level = -1; + f->c = c; + f->out = out; + bool valid = true; + for (size_t i = 0; i < SAF_NODES; i++) { + f->nodes[i].show_refs = c->show[i]; + f->nodes[i].activate_refs = c->active[i]; + /* The real adapters reach the fields they name. */ + valid = valid && saf_real_load_show_refs(&f->nodes[i]) == c->show[i] && + saf_real_load_activate_refs(&f->nodes[i]) == c->active[i]; + } + memcpy(before, f->nodes, sizeof(f->nodes)); + + log_handler_t old_handler; + void *old_param; + get(&old_handler, &old_param); + saf_current = f; + set(saf_capture, out); + obs_source_t *source = saf_node(c->source); + if (c->which == 0) + activate(source, c->view_type); + else + deactivate(source, c->view_type); + set(old_handler, old_param); + saf_current = NULL; + + for (size_t i = 0; i < SAF_NODES; i++) { + out->show[i] = f->nodes[i].show_refs; + out->active[i] = f->nodes[i].activate_refs; + before[i].show_refs = f->nodes[i].show_refs; + before[i].activate_refs = f->nodes[i].activate_refs; + } + out->untouched = memcmp(before, f->nodes, sizeof(f->nodes)) == 0; + free(before); + free(f); + return valid; +} diff --git a/rust/obs-c-oracle/oracle/source_active_child.c b/rust/obs-c-oracle/oracle/source_active_child.c index f4c8949008..67e3ebf3d5 100644 --- a/rust/obs-c-oracle/oracle/source_active_child.c +++ b/rust/obs-c-oracle/oracle/source_active_child.c @@ -7,10 +7,12 @@ * Both sides reach the same stand-ins: the full-tree walk * (obs_source_active_child_enum_full_tree(), the hidden wrapper in * obs-source.c.h, defined here as a scripted walk that reports a case's - * edges in order) and the tracing obs_source_activate() / - * obs_source_deactivate() doubles of oracle/view.c, which read a source's - * name at offset 0, where struct obs_source keeps context.name. The real - * walk and activation are covered by test_source_active_child. */ + * edges in order) and obs_source_activate() / obs_source_deactivate(), + * obs-source's Rust exports (#5811), whose counter adapters report to + * oracle/view.c's activation trace for these nodes (they leave the + * counters alone), which reads a source's name at offset 0, where struct + * obs_source keeps context.name. The real walk and activation are covered + * by test_source_active_child and test_source_activate. */ #define _NO_CRT_STDIO_INLINE #include #include @@ -118,6 +120,7 @@ void obs_source_active_child_enum_full_tree(obs_source_t *source, obs_source_enu typedef void (*oracle_view_trace_fn)(const char *event, const char *name, long long value); void oracle_view_set_trace(oracle_view_trace_fn hook); +void oracle_view_flush(void); static void active_child_trace(const char *event, const char *name, long long value) { @@ -215,6 +218,7 @@ bool oracle_source_active_child_run(active_child_add_fn add, active_child_remove out->returned = add(parent, child); else remove(parent, child); + oracle_view_flush(); set(old_handler, old_param); oracle_view_set_trace(NULL); active_child_current = NULL; diff --git a/rust/obs-c-oracle/oracle/source_show_active_counters.c b/rust/obs-c-oracle/oracle/source_show_active_counters.c index d6099b2107..3465198879 100644 --- a/rust/obs-c-oracle/oracle/source_show_active_counters.c +++ b/rust/obs-c-oracle/oracle/source_show_active_counters.c @@ -1,8 +1,9 @@ /* Original obs_source_inc_showing(), obs_source_inc_active(), * obs_source_dec_showing() and obs_source_dec_active(), renamed oracle_*. * The obs_source_activate() / obs_source_deactivate() both sides call are - * the tracing test doubles of oracle/view.c, so a C call and a Rust call - * give comparable traces (call, source name, view type). */ + * obs-source's Rust exports (#5811), whose counter adapters report to + * oracle/view.c for these test sources, so a C call and a Rust call give + * comparable traces (call, source name, view type). */ #define _NO_CRT_STDIO_INLINE #include #include @@ -20,6 +21,7 @@ typedef void (*oracle_view_trace_fn)(const char *event, const char *name, long long value); void oracle_view_set_trace(oracle_view_trace_fn hook); +void oracle_view_flush(void); struct source_show_active_counters_record { unsigned log_count; @@ -91,6 +93,7 @@ bool oracle_source_show_active_counters_check(source_show_active_counters_call c recording = &records[side]; set_log(source_show_active_counters_capture, &records[side]); calls[side](source); + oracle_view_flush(); set_log(previous, param); recording = NULL; } diff --git a/rust/obs-c-oracle/oracle/view.c b/rust/obs-c-oracle/oracle/view.c index 7f9d769939..d27db3fc26 100644 --- a/rust/obs-c-oracle/oracle/view.c +++ b/rust/obs-c-oracle/oracle/view.c @@ -6,7 +6,18 @@ * traces. Views are real struct obs_view (the doubles read and write its * fields as obs-view.c does; the lock only traces). Sources are * struct oracle_view_source, passed as obs_source_t pointers: a name for - * the trace, a removed flag, and whether obs_source_get_ref() refuses it. */ + * the trace, a removed flag, and whether obs_source_get_ref() refuses it. + * + * obs_source_activate() and obs_source_deactivate() are obs-source's Rust + * exports (#5811), which both sides reach. For a source no + * oracle/source_activate.c fixture holds, their counter adapters are the + * stand-ins there, which report each step here instead of touching the + * source: the first step of a call (show_refs raised, or loaded) starts an + * "activate" or "deactivate" event for AUX_VIEW, and a step on + * activate_refs makes it MAIN_VIEW. The event is traced (call, source + * name, view type) before the next traced step, when the hook changes, or + * at oracle_view_flush(), so a trace reads as it did when these were + * tracing doubles. */ #ifndef _WIN32 #define _GNU_SOURCE #endif @@ -65,12 +76,54 @@ static struct { } mixes[ORACLE_VIEW_MIXES]; static size_t mix_num; -static void trace(const char *event, const char *name, long long value) +/* The activation event still open on this thread (see the top). */ +static _Thread_local struct { + bool open; + bool deactivate; + const obs_source_t *source; + long long type; +} pending; + +static void emit(const char *event, const char *name, long long value) { if (trace_hook) trace_hook(event, name, value); } +static const char *src_name(const obs_source_t *source); + +void oracle_view_flush(void); +void oracle_view_flush(void) +{ + if (!pending.open) + return; + pending.open = false; + emit(pending.deactivate ? "deactivate" : "activate", src_name(pending.source), pending.type); +} + +static void trace(const char *event, const char *name, long long value) +{ + oracle_view_flush(); + emit(event, name, value); +} + +/* One counter step of obs_source_activate() (deactivate false) or + * obs_source_deactivate() (true) on a source: on activate_refs (active + * true) or on show_refs. */ +void oracle_view_activation_step(const obs_source_t *source, bool deactivate, bool active); +void oracle_view_activation_step(const obs_source_t *source, bool deactivate, bool active) +{ + if (active && pending.open && pending.deactivate == deactivate && pending.source == source) { + pending.type = MAIN_VIEW; + return; + } + oracle_view_flush(); + pending.open = true; + pending.deactivate = deactivate; + pending.source = source; + pending.type = active ? MAIN_VIEW : AUX_VIEW; +} + static const char *src_name(const obs_source_t *source) { return source ? ((const struct oracle_view_source *)(const void *)source)->name : NULL; @@ -87,6 +140,7 @@ int oracle_view_type_of(struct obs_view *view); void oracle_view_set_trace(oracle_view_trace_fn hook) { + oracle_view_flush(); trace_hook = hook; } @@ -245,16 +299,6 @@ void obs_source_release(obs_source_t *source) trace("release", src_name(source), 0); } -void obs_source_activate(obs_source_t *source, enum view_type type) -{ - trace("activate", src_name(source), (long long)type); -} - -void obs_source_deactivate(obs_source_t *source, enum view_type type) -{ - trace("deactivate", src_name(source), (long long)type); -} - void obs_source_video_render(obs_source_t *source) { trace("render", src_name(source), 0); diff --git a/rust/obs-c-oracle/src/view.rs b/rust/obs-c-oracle/src/view.rs index 4fda0b73d6..60c118c492 100644 --- a/rust/obs-c-oracle/src/view.rs +++ b/rust/obs-c-oracle/src/view.rs @@ -41,6 +41,10 @@ unsafe extern "C" { ); pub fn oracle_view_set_trace(hook: OracleViewTrace); + /// Traces the activation event still open on this thread, if any + /// (`obs_source_activate()` / `obs_source_deactivate()` on a view test + /// source; see oracle/view.c). + pub fn oracle_view_flush(); /// Clears the mixes; `fail_mutex` makes `obs_view_mutex_init` fail; /// `main_mix_info` is what `obs_view_main_mix_info` returns. pub fn oracle_view_reset(fail_mutex: bool, main_mix_info: *mut c_void); diff --git a/rust/obs-core/tests/obs_core/view_parity.rs b/rust/obs-core/tests/obs_core/view_parity.rs index 57b6092ad7..e53ff1d695 100644 --- a/rust/obs-core/tests/obs_core/view_parity.rs +++ b/rust/obs-core/tests/obs_core/view_parity.rs @@ -25,8 +25,9 @@ use obs_c_oracle::view::{ OracleViewSource, oracle_obs_view_add, oracle_obs_view_add2, oracle_obs_view_create, oracle_obs_view_destroy, oracle_obs_view_enum_video_info, oracle_obs_view_free, oracle_obs_view_get_source, oracle_obs_view_init, oracle_obs_view_remove, - oracle_obs_view_render, oracle_obs_view_set_source, oracle_view_channel_at, oracle_view_mix_at, - oracle_view_mix_num, oracle_view_reset, oracle_view_set_trace, oracle_view_type_of, + oracle_obs_view_render, oracle_obs_view_set_source, oracle_view_channel_at, oracle_view_flush, + oracle_view_mix_at, oracle_view_mix_num, oracle_view_reset, oracle_view_set_trace, + oracle_view_type_of, }; use obs_core::ffi::view as shim; use obs_core::view::MAX_CHANNELS; @@ -54,6 +55,8 @@ unsafe extern "C" fn record(event: *const c_char, name: *const c_char, value: c_ } fn take_trace() -> Vec { + // SAFETY: no arguments; it traces through the hook the test installed. + unsafe { oracle_view_flush() }; std::mem::take(&mut *TRACE.lock().unwrap_or_else(|e| e.into_inner())) } diff --git a/rust/obs-source/Cargo.toml b/rust/obs-source/Cargo.toml index 8a97dbaced..f661655787 100644 --- a/rust/obs-source/Cargo.toml +++ b/rust/obs-source/Cargo.toml @@ -2,7 +2,7 @@ autotests = false name = "obs-source" version = "0.1.0" -description = "Rust ports of libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-copy-filters.c.h (obs_source_copy_filters and obs_source_copy_single_filter), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-duplicate-entry.c.h (obs_source_duplicate), libobs/obs-source-filter-add.c.h (obs_source_filter_add), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-filter-remove.c.h (obs_source_filter_remove and its refless step), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-frame-copy-data.c.h (obs_source_frame_copy, running the copy plan), libobs/obs-source-frame-wrappers.c.h (the six async-frame entry points), libobs/obs-source-get-release-frame.c.h (obs_source_get_frame and obs_source_release_frame), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-output-cea708.c.h (obs_source_output_cea708), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-remove.c.h (obs_source_remove), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-set-name.c.h (the source rename), libobs/obs-source-show-preloaded-video.c.h (obs_source_show_preloaded_video), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-access.c.h (the transition getters and manual controls; C shims in obs-source-seam), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-load.c.h (the transition load, scale type and swap checks), libobs/obs-source-transition-restore.c.h (the transition load; C shim in obs-source-seam), libobs/obs-source-transition-render.c.h (the transition render and audio steps), libobs/obs-source-transition-sample-time.c.h (the transition's per-sample audio time), libobs/obs-source-transition-settings.c.h (the transition settings; C shims in obs-source-seam), libobs/obs-source-transition-size.c.h (the transition size, child matrices and tick; C shims in obs-source-seam), libobs/obs-source-transition-slots.c.h (the transition child slots and swap; C shims in obs-source-seam), libobs/obs-source-transition-start.c.h (the transition start checks and child handover), libobs/obs-source-transition-stop.c.h (the transition clock read and stop; C shims in obs-source-seam), libobs/obs-source-transition-switch.c.h (the transition start and set; C shims in obs-source-seam), libobs/obs-source-transition-video.c.h (the transition video render; C shims in obs-source-seam), the rest of libobs/obs-source-transition.c.h (the transition audio render, init and free; C shims in obs-source-seam), libobs/obs-source-video-tick.c.h (the per-frame video tick decisions) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions), libobs/obs-source-volume-mul.c.h (the source volume multiply kernels)" +description = "Rust ports of libobs/obs-source-activate.c.h (obs_source_activate and obs_source_deactivate), libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-copy-filters.c.h (obs_source_copy_filters and obs_source_copy_single_filter), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-duplicate-entry.c.h (obs_source_duplicate), libobs/obs-source-filter-add.c.h (obs_source_filter_add), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-filter-remove.c.h (obs_source_filter_remove and its refless step), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-frame-copy-data.c.h (obs_source_frame_copy, running the copy plan), libobs/obs-source-frame-wrappers.c.h (the six async-frame entry points), libobs/obs-source-get-release-frame.c.h (obs_source_get_frame and obs_source_release_frame), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-output-cea708.c.h (obs_source_output_cea708), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-remove.c.h (obs_source_remove), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-set-name.c.h (the source rename), libobs/obs-source-show-preloaded-video.c.h (obs_source_show_preloaded_video), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-access.c.h (the transition getters and manual controls; C shims in obs-source-seam), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-load.c.h (the transition load, scale type and swap checks), libobs/obs-source-transition-restore.c.h (the transition load; C shim in obs-source-seam), libobs/obs-source-transition-render.c.h (the transition render and audio steps), libobs/obs-source-transition-sample-time.c.h (the transition's per-sample audio time), libobs/obs-source-transition-settings.c.h (the transition settings; C shims in obs-source-seam), libobs/obs-source-transition-size.c.h (the transition size, child matrices and tick; C shims in obs-source-seam), libobs/obs-source-transition-slots.c.h (the transition child slots and swap; C shims in obs-source-seam), libobs/obs-source-transition-start.c.h (the transition start checks and child handover), libobs/obs-source-transition-stop.c.h (the transition clock read and stop; C shims in obs-source-seam), libobs/obs-source-transition-switch.c.h (the transition start and set; C shims in obs-source-seam), libobs/obs-source-transition-video.c.h (the transition video render; C shims in obs-source-seam), the rest of libobs/obs-source-transition.c.h (the transition audio render, init and free; C shims in obs-source-seam), libobs/obs-source-video-tick.c.h (the per-frame video tick decisions) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions), libobs/obs-source-volume-mul.c.h (the source volume multiply kernels)" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/rust/obs-source/src/activate.rs b/rust/obs-source/src/activate.rs new file mode 100644 index 0000000000..0fe8183ab5 --- /dev/null +++ b/rust/obs-source/src/activate.rs @@ -0,0 +1,137 @@ +//! `obs_source_activate()` and `obs_source_deactivate()` (`obs-internal.h`, +//! no `EXPORT`): the show and active counters of a source and of its active +//! tree, which views, canvases, active children and the four public +//! counters (`obs_source_inc_showing()` and the rest, [`crate::show_active_counters`]) +//! move. +//! +//! The counters stay in the C `struct obs_source`, changed atomically +//! (`os_atomic_*_long()`), and so does the tree walk +//! (`obs_source_enum_active_tree()`); both are reached through +//! [`Counters`]. [`visit`] is the four tree callbacks of the C (`show_tree`, +//! `hide_tree`, `activate_tree`, `deactivate_tree`). +#![deny( + clippy::arithmetic_side_effects, + clippy::indexing_slicing, + clippy::as_conversions, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unimplemented, + clippy::unreachable +)] + +use core::ffi::{CStr, c_long}; + +pub use crate::show_active_counters::{AUX_VIEW, MAIN_VIEW}; + +/// The function named in [`activate`]'s NULL diagnostic. +pub const ACTIVATE_FUNCTION: &CStr = c"obs_source_activate"; +/// The function named in [`deactivate`]'s NULL diagnostic. +pub const DEACTIVATE_FUNCTION: &CStr = c"obs_source_deactivate"; + +/// One of a source's two counters. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Counter { + /// `show_refs`. + Show, + /// `activate_refs`. + Activate, +} + +/// Which of the four C tree callbacks a walk runs on each child. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Tree { + /// `show_tree`: the child's `show_refs` +1. + Show, + /// `activate_tree`: the child's `activate_refs` +1. + Activate, + /// `hide_tree`: the child's `show_refs` -1. + Hide, + /// `deactivate_tree`: the child's `activate_refs` -1. + Deactivate, +} + +impl Tree { + /// All four, in the C's order. + pub const ALL: [Self; 4] = [Self::Activate, Self::Deactivate, Self::Show, Self::Hide]; + + /// The counter the callback changes. + pub fn counter(self) -> Counter { + match self { + Self::Show | Self::Hide => Counter::Show, + Self::Activate | Self::Deactivate => Counter::Activate, + } + } + + /// True when the callback adds one, false when it subtracts one. + pub fn raises(self) -> bool { + matches!(self, Self::Show | Self::Activate) + } +} + +/// What activation reads and changes, each one C step. +pub trait Counters { + /// A live source, as the C passes it. + type Source: Copy; + /// `os_atomic_inc_long(&source->)`. + fn inc(&mut self, source: Self::Source, counter: Counter); + /// `os_atomic_dec_long(&source->)`. + fn dec(&mut self, source: Self::Source, counter: Counter); + /// `os_atomic_load_long(&source->)`. + fn load(&mut self, source: Self::Source, counter: Counter) -> c_long; + /// `obs_source_enum_active_tree(source, , NULL)`: each + /// child it reports goes to [`visit`] with `tree`. + fn walk(&mut self, source: Self::Source, tree: Tree); + /// `obs_source_valid()`'s NULL line: `": Null 'source' + /// parameter"` at `LOG_DEBUG`. + fn log_null(&mut self, function: &'static CStr); +} + +/// `obs_source_activate(source, type)`: `None` is a NULL source, logged +/// under [`ACTIVATE_FUNCTION`], and nothing else happens. Otherwise +/// `show_refs` +1 and a [`Tree::Show`] walk; then, only for [`MAIN_VIEW`], +/// `activate_refs` +1 and a [`Tree::Activate`] walk. Any other view type +/// touches only the show counters. +pub fn activate(counters: &mut C, source: Option, view_type: u32) { + let Some(source) = source else { + counters.log_null(ACTIVATE_FUNCTION); + return; + }; + counters.inc(source, Counter::Show); + counters.walk(source, Tree::Show); + if view_type == MAIN_VIEW { + counters.inc(source, Counter::Activate); + counters.walk(source, Tree::Activate); + } +} + +/// `obs_source_deactivate(source, type)`: `None` is a NULL source, logged +/// under [`DEACTIVATE_FUNCTION`], and nothing else happens. Otherwise, only +/// when `show_refs` is above zero, `show_refs` -1 and a [`Tree::Hide`] +/// walk; then, only for [`MAIN_VIEW`] and only when `activate_refs` is +/// above zero, `activate_refs` -1 and a [`Tree::Deactivate`] walk. Each +/// counter is loaded once, just before its own step. +pub fn deactivate(counters: &mut C, source: Option, view_type: u32) { + let Some(source) = source else { + counters.log_null(DEACTIVATE_FUNCTION); + return; + }; + if counters.load(source, Counter::Show) > 0 { + counters.dec(source, Counter::Show); + counters.walk(source, Tree::Hide); + } + if view_type == MAIN_VIEW && counters.load(source, Counter::Activate) > 0 { + counters.dec(source, Counter::Activate); + counters.walk(source, Tree::Deactivate); + } +} + +/// One tree callback on one child: its counter +1 or -1, with no check of +/// the value (a child can go below zero). +pub fn visit(counters: &mut C, child: C::Source, tree: Tree) { + if tree.raises() { + counters.inc(child, tree.counter()); + } else { + counters.dec(child, tree.counter()); + } +} diff --git a/rust/obs-source/src/active_child.rs b/rust/obs-source/src/active_child.rs index 5035e51b58..9ab8e20834 100644 --- a/rust/obs-source/src/active_child.rs +++ b/rust/obs-source/src/active_child.rs @@ -5,8 +5,9 @@ //! once for each of the parent's show references, `MAIN_VIEW` for the first //! `activate_refs` of them and `AUX_VIEW` for the rest. Remove mirrors the //! activations with deactivations, without the self or cycle checks. The -//! full-tree walk, the two counter loads and `obs_source_activate()` / -//! `obs_source_deactivate()` stay C; the core reaches them through +//! full-tree walk and the two counter loads stay C, and +//! `obs_source_activate()` / `obs_source_deactivate()` are called through +//! the C ABI ([`crate::activate`], #5811); the core reaches them through //! [`Libobs`]. #![deny( diff --git a/rust/obs-source/src/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index 1b93621da5..2f7796e48f 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -2,6 +2,7 @@ mod callback_list; +pub mod source_activate; pub mod source_active_child; pub mod source_async_compensation; pub mod source_async_flag_getters; diff --git a/rust/obs-source/src/ffi/source_activate.rs b/rust/obs-source/src/ffi/source_activate.rs new file mode 100644 index 0000000000..5284a7fd06 --- /dev/null +++ b/rust/obs-source/src/ffi/source_activate.rs @@ -0,0 +1,150 @@ +//! C ABI of `obs_source_activate()` and `obs_source_deactivate()`, declared +//! in `obs-internal.h` without `EXPORT`, so both stay hidden +//! (`libobs/cmake/rust-hidden.d`). The counters stay behind the atomic +//! adapters of `obs-source-activate-fields.c.h`; the walk is the C +//! `obs_source_enum_active_tree()`, given the four tree callbacks here. +use crate::activate::{Counter, Counters, Tree, activate, deactivate, visit}; +use core::ffi::{CStr, c_char, c_int, c_long, c_void}; +use core::ptr::{NonNull, null_mut}; + +/// `obs_source_enum_proc_t`. +pub type EnumProc = Option; + +unsafe extern "C" { + fn obs_source_activate_inc_show_refs(source: *mut c_void); + fn obs_source_activate_dec_show_refs(source: *mut c_void); + fn obs_source_activate_load_show_refs(source: *const c_void) -> c_long; + fn obs_source_activate_inc_activate_refs(source: *mut c_void); + fn obs_source_activate_dec_activate_refs(source: *mut c_void); + fn obs_source_activate_load_activate_refs(source: *const c_void) -> c_long; + fn obs_source_enum_active_tree(source: *mut c_void, callback: EnumProc, param: *mut c_void); + fn blog(level: c_int, format: *const c_char, ...); +} + +/// `LOG_DEBUG`, the level of `obs_source_valid()`'s NULL line. +const LOG_DEBUG: c_int = 400; + +/// libobs: each method is the one C step the original made. +#[derive(Clone, Copy, Debug, Default)] +pub struct Libobs; + +impl Counters for Libobs { + type Source = NonNull; + fn inc(&mut self, source: NonNull, counter: Counter) { + // SAFETY: a live source (the caller's, checked not NULL, or a child + // the walk reports), whose counter the adapter changes atomically. + unsafe { + match counter { + Counter::Show => obs_source_activate_inc_show_refs(source.as_ptr()), + Counter::Activate => obs_source_activate_inc_activate_refs(source.as_ptr()), + } + } + } + fn dec(&mut self, source: NonNull, counter: Counter) { + // SAFETY: as in `inc`. + unsafe { + match counter { + Counter::Show => obs_source_activate_dec_show_refs(source.as_ptr()), + Counter::Activate => obs_source_activate_dec_activate_refs(source.as_ptr()), + } + } + } + fn load(&mut self, source: NonNull, counter: Counter) -> c_long { + // SAFETY: as in `inc`; the adapter only loads. + unsafe { + match counter { + Counter::Show => obs_source_activate_load_show_refs(source.as_ptr()), + Counter::Activate => obs_source_activate_load_activate_refs(source.as_ptr()), + } + } + } + fn walk(&mut self, source: NonNull, tree: Tree) { + let callback: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) = match tree { + Tree::Show => show_tree, + Tree::Activate => activate_tree, + Tree::Hide => hide_tree, + Tree::Deactivate => deactivate_tree, + }; + // SAFETY: a live source; the callback reads no parameter. + unsafe { obs_source_enum_active_tree(source.as_ptr(), Some(callback), null_mut()) } + } + fn log_null(&mut self, function: &'static CStr) { + // SAFETY: static strings match the two %s arguments of the format. + unsafe { + blog( + LOG_DEBUG, + c"%s: Null '%s' parameter".as_ptr(), + function.as_ptr(), + c"source".as_ptr(), + ); + } + } +} + +/// One child of the walk. The walk never reports a NULL child +/// (`obs_source_enum_active_tree()` reads each child's type before it calls +/// the callback), so a NULL one, which the original would dereference, does +/// nothing here. +fn callback(child: *mut c_void, tree: Tree) { + if let Some(child) = NonNull::new(child) { + visit(&mut Libobs, child, tree); + } +} + +/// `show_tree`. +/// +/// # Safety +/// `child` is a live source, as `obs_source_enum_active_tree()` passes it. +pub unsafe extern "C" fn show_tree(_parent: *mut c_void, child: *mut c_void, _param: *mut c_void) { + callback(child, Tree::Show); +} + +/// `activate_tree`. +/// +/// # Safety +/// As [`show_tree`]. +pub unsafe extern "C" fn activate_tree( + _parent: *mut c_void, + child: *mut c_void, + _param: *mut c_void, +) { + callback(child, Tree::Activate); +} + +/// `hide_tree`. +/// +/// # Safety +/// As [`show_tree`]. +pub unsafe extern "C" fn hide_tree(_parent: *mut c_void, child: *mut c_void, _param: *mut c_void) { + callback(child, Tree::Hide); +} + +/// `deactivate_tree`. +/// +/// # Safety +/// As [`show_tree`]. +pub unsafe extern "C" fn deactivate_tree( + _parent: *mut c_void, + child: *mut c_void, + _param: *mut c_void, +) { + callback(child, Tree::Deactivate); +} + +/// `obs_source_activate()` (hidden). +/// +/// # Safety +/// A non-null source must be live under the original libobs ownership contract. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_activate(source: *mut c_void, view_type: u32) { + activate(&mut Libobs, NonNull::new(source), view_type); +} + +/// `obs_source_deactivate()` (hidden). +/// +/// # Safety +/// A non-null source must be live under the original libobs ownership contract. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_deactivate(source: *mut c_void, view_type: u32) { + deactivate(&mut Libobs, NonNull::new(source), view_type); +} diff --git a/rust/obs-source/src/ffi/source_active_child.rs b/rust/obs-source/src/ffi/source_active_child.rs index 6cb6404e47..a4c286b406 100644 --- a/rust/obs-source/src/ffi/source_active_child.rs +++ b/rust/obs-source/src/ffi/source_active_child.rs @@ -1,9 +1,10 @@ //! C ABI of `obs_source_add_active_child()` and //! `obs_source_remove_active_child()`. The full-tree walk (with its stop -//! source), the counter loads and `obs_source_activate()` / -//! `obs_source_deactivate()` stay C: the walk through obs-source.c.h's hidden -//! `obs_source_active_child_enum_full_tree()`, the loads through +//! source) and the counter loads stay C: the walk through obs-source.c.h's +//! hidden `obs_source_active_child_enum_full_tree()`, the loads through //! `obs-source-active-child-fields.c.h` (both without `EXPORT`). +//! `obs_source_activate()` / `obs_source_deactivate()` are reached through +//! the C ABI (Rust since #5811, [`crate::ffi::source_activate`]). use crate::active_child; use core::ffi::{CStr, c_char, c_int, c_long, c_void}; use core::ptr::NonNull; diff --git a/rust/obs-source/src/ffi/source_show_active_counters.rs b/rust/obs-source/src/ffi/source_show_active_counters.rs index 0cf96f0c1a..41e9b570ac 100644 --- a/rust/obs-source/src/ffi/source_show_active_counters.rs +++ b/rust/obs-source/src/ffi/source_show_active_counters.rs @@ -1,7 +1,8 @@ //! C ABI of `obs_source_inc_showing()`, `obs_source_inc_active()`, //! `obs_source_dec_showing()` and `obs_source_dec_active()`. The counters -//! themselves, and the walk of the source's active tree, stay in the C -//! `obs_source_activate()` / `obs_source_deactivate()` (`obs-internal.h`). +//! themselves, and the walk of the source's active tree, are +//! `obs_source_activate()` / `obs_source_deactivate()` (`obs-internal.h`; +//! [`crate::ffi::source_activate`]), called through the C ABI. use crate::show_active_counters::{Change, Direction, apply}; use core::ffi::{CStr, c_char, c_int, c_void}; use core::ptr::NonNull; diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 482d5f23f4..8dd506f667 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -2,6 +2,10 @@ //! `libobs/obs-source-deinterlace.c` and `libobs/obs-source-transition.c` //! (one of them with decisions of `libobs/obs-scene.c`), //! one module per file: so far +//! `libobs/obs-source-activate.c.h`, `obs_source_activate()` and +//! `obs_source_deactivate()` with their tree callbacks (the counters' atomic +//! steps stay in a C fields adapter, the walk in +//! `obs_source_enum_active_tree()`); //! `libobs/obs-source-async-decoupled.c.h`, the async decoupled setter //! `obs_source_set_async_decoupled()` (generic over the source; its C shim //! is in `obs-source-seam`); @@ -197,6 +201,7 @@ #![deny(unsafe_code)] +pub mod activate; pub mod active_child; pub mod async_compensation; pub mod async_decoupled; diff --git a/rust/obs-source/src/show_active_counters.rs b/rust/obs-source/src/show_active_counters.rs index 79ad5b79e3..7cab242cae 100644 --- a/rust/obs-source/src/show_active_counters.rs +++ b/rust/obs-source/src/show_active_counters.rs @@ -1,7 +1,8 @@ //! `obs_source_inc_showing()`, `obs_source_inc_active()`, //! `obs_source_dec_showing()` and `obs_source_dec_active()`: each checks its //! source, then hands it to `obs_source_activate()` or -//! `obs_source_deactivate()` (both stay C) with an auxiliary or main view. +//! `obs_source_deactivate()` ([`crate::activate`], reached through the C +//! ABI) with an auxiliary or main view. use core::ffi::CStr; /// `MAIN_VIEW` of the private `enum view_type` (`obs-internal.h`). diff --git a/rust/obs-source/tests/source/activate.rs b/rust/obs-source/tests/source/activate.rs new file mode 100644 index 0000000000..189dd62280 --- /dev/null +++ b/rust/obs-source/tests/source/activate.rs @@ -0,0 +1,309 @@ +//! Tier 1 mirrors of test_source_activate.c, plus the NULL source the C test +//! can't reach (every public caller checks first). The model is the C test's +//! tree (a lists b and d, b lists c) with the counters of each node; its walk +//! reports the children post-order, as `obs_source_enum_active_tree()` +//! does, and records every step with all eight counters at that moment. +use core::ffi::{CStr, c_long}; +use obs_source::activate::{ + ACTIVATE_FUNCTION, AUX_VIEW, Counter, Counters, DEACTIVATE_FUNCTION, MAIN_VIEW, Tree, activate, + deactivate, visit, +}; + +const A: usize = 0; +const B: usize = 1; +const C: usize = 2; +const D: usize = 3; +const NODES: usize = 4; + +/// The children each node lists, as the C test's fixture. +fn children(node: usize) -> &'static [usize] { + match node { + A => &[B, D], + B => &[C], + _ => &[], + } +} + +/// `[show_refs; 4]`, `[activate_refs; 4]`. +type Refs = ([c_long; NODES], [c_long; NODES]); + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Step { + Inc(usize, Counter), + Dec(usize, Counter), + Load(usize, Counter), + /// A walk from the root with its callback, and the counters it began on. + Walk(usize, Tree, Refs), + Log(&'static str), +} + +#[derive(Default)] +struct Model { + refs: Refs, + steps: Vec, +} + +impl Model { + fn new(refs: Refs) -> Self { + Self { + refs, + steps: Vec::new(), + } + } + + fn counter(&mut self, node: usize, counter: Counter) -> &mut c_long { + match counter { + Counter::Show => &mut self.refs.0[node], + Counter::Activate => &mut self.refs.1[node], + } + } + + fn report(&mut self, node: usize, tree: Tree) { + for &child in children(node) { + self.report(child, tree); + visit(self, child, tree); + } + } +} + +impl Counters for Model { + type Source = usize; + fn inc(&mut self, source: usize, counter: Counter) { + self.steps.push(Step::Inc(source, counter)); + *self.counter(source, counter) += 1; + } + fn dec(&mut self, source: usize, counter: Counter) { + self.steps.push(Step::Dec(source, counter)); + *self.counter(source, counter) -= 1; + } + fn load(&mut self, source: usize, counter: Counter) -> c_long { + self.steps.push(Step::Load(source, counter)); + *self.counter(source, counter) + } + fn walk(&mut self, source: usize, tree: Tree) { + self.steps.push(Step::Walk(source, tree, self.refs)); + self.report(source, tree); + } + fn log_null(&mut self, function: &'static CStr) { + self.steps.push(Step::Log(function.to_str().unwrap())); + } +} + +/// The steps a walk of `tree` from A makes on the children: each child's +/// counter, post-order. +fn walk_steps(tree: Tree) -> Vec { + let counter = tree.counter(); + let each = |n| { + if tree.raises() { + Step::Inc(n, counter) + } else { + Step::Dec(n, counter) + } + }; + vec![each(C), each(B), each(D)] +} + +fn run(call: fn(&mut Model, Option, u32), view_type: u32, refs: Refs) -> Model { + let mut model = Model::new(refs); + call(&mut model, Some(A), view_type); + model +} + +/// The NULL source the public callers never pass: one line naming the +/// entry, nothing else. +#[test] +fn null_source_logs_once_and_changes_nothing() { + for view_type in [MAIN_VIEW, AUX_VIEW, 0, 7] { + let mut model = Model::new(([3; NODES], [2; NODES])); + activate(&mut model, None, view_type); + deactivate(&mut model, None, view_type); + assert_eq!( + model.steps, + [ + Step::Log("obs_source_activate"), + Step::Log("obs_source_deactivate") + ] + ); + assert_eq!(model.refs, ([3; NODES], [2; NODES])); + } + assert_eq!(ACTIVATE_FUNCTION, c"obs_source_activate"); + assert_eq!(DEACTIVATE_FUNCTION, c"obs_source_deactivate"); +} + +/// aux_activate_raises_show_refs_in_one_walk. +#[test] +fn aux_activate_raises_show_refs_in_one_walk() { + let model = run(activate, AUX_VIEW, Refs::default()); + let mut want = vec![ + Step::Inc(A, Counter::Show), + Step::Walk(A, Tree::Show, ([1, 0, 0, 0], [0; NODES])), + ]; + want.extend(walk_steps(Tree::Show)); + assert_eq!(model.steps, want); + assert_eq!(model.refs, ([1; NODES], [0; NODES])); +} + +/// main_activate_walks_show_then_active. +#[test] +fn main_activate_walks_show_then_active() { + let model = run(activate, MAIN_VIEW, Refs::default()); + let mut want = vec![ + Step::Inc(A, Counter::Show), + Step::Walk(A, Tree::Show, ([1, 0, 0, 0], [0; NODES])), + ]; + want.extend(walk_steps(Tree::Show)); + want.push(Step::Inc(A, Counter::Activate)); + want.push(Step::Walk(A, Tree::Activate, ([1; NODES], [1, 0, 0, 0]))); + want.extend(walk_steps(Tree::Activate)); + assert_eq!(model.steps, want); + assert_eq!(model.refs, ([1; NODES], [1; NODES])); +} + +/// Any view type but MAIN_VIEW only shows. +#[test] +fn other_view_types_only_show() { + for view_type in [0, AUX_VIEW, 3, u32::MAX] { + let shown = run(activate, view_type, Refs::default()); + assert_eq!(shown.refs, ([1; NODES], [0; NODES])); + let hidden = run(deactivate, view_type, ([1; NODES], [1; NODES])); + assert_eq!(hidden.refs, ([0; NODES], [1; NODES])); + } +} + +/// activate_adds_one_to_any_count: activation never loads a counter. +#[test] +fn activate_adds_one_to_any_count() { + let model = run(activate, MAIN_VIEW, ([-3, 0, 7, 2], [5, -1, 0, 9])); + assert_eq!(model.refs, ([-2, 1, 8, 3], [6, 0, 1, 10])); + assert!(!model.steps.iter().any(|s| matches!(s, Step::Load(..)))); + assert_eq!( + model + .steps + .iter() + .filter(|s| matches!(s, Step::Walk(..))) + .count(), + 2 + ); +} + +/// aux_deactivate_lowers_show_refs_in_one_walk. +#[test] +fn aux_deactivate_lowers_show_refs_in_one_walk() { + let model = run(deactivate, AUX_VIEW, ([2; NODES], [1; NODES])); + let mut want = vec![ + Step::Load(A, Counter::Show), + Step::Dec(A, Counter::Show), + Step::Walk(A, Tree::Hide, ([1, 2, 2, 2], [1; NODES])), + ]; + want.extend(walk_steps(Tree::Hide)); + assert_eq!(model.steps, want); + assert_eq!(model.refs, ([1; NODES], [1; NODES])); +} + +/// main_deactivate_walks_show_then_active. +#[test] +fn main_deactivate_walks_show_then_active() { + let model = run(deactivate, MAIN_VIEW, ([1; NODES], [1; NODES])); + let mut want = vec![ + Step::Load(A, Counter::Show), + Step::Dec(A, Counter::Show), + Step::Walk(A, Tree::Hide, ([0, 1, 1, 1], [1; NODES])), + ]; + want.extend(walk_steps(Tree::Hide)); + want.extend([ + Step::Load(A, Counter::Activate), + Step::Dec(A, Counter::Activate), + Step::Walk(A, Tree::Deactivate, ([0; NODES], [0, 1, 1, 1])), + ]); + want.extend(walk_steps(Tree::Deactivate)); + assert_eq!(model.steps, want); + assert_eq!(model.refs, ([0; NODES], [0; NODES])); +} + +/// descendants_are_not_floor_checked. +#[test] +fn descendants_are_not_floor_checked() { + let model = run(deactivate, MAIN_VIEW, ([1, 0, -4, 0], [1, 0, 0, 3])); + assert_eq!(model.refs, ([0, -1, -5, -1], [0, -1, -1, 2])); +} + +/// deactivate_at_zero_does_nothing: the counters are loaded, nothing else. +#[test] +fn deactivate_at_zero_does_nothing() { + for refs in [([0, 3, 3, 3], [0, 3, 3, 3]), ([-2, 3, 3, 3], [-1, 3, 3, 3])] { + let model = run(deactivate, MAIN_VIEW, refs); + assert_eq!( + model.steps, + [ + Step::Load(A, Counter::Show), + Step::Load(A, Counter::Activate) + ] + ); + assert_eq!(model.refs, refs); + let model = run(deactivate, AUX_VIEW, refs); + assert_eq!(model.steps, [Step::Load(A, Counter::Show)]); + assert_eq!(model.refs, refs); + } +} + +/// hidden_but_active_root_walks_once. +#[test] +fn hidden_but_active_root_walks_once() { + let model = run(deactivate, MAIN_VIEW, ([0, 2, 2, 2], [1, 2, 2, 2])); + let mut want = vec![ + Step::Load(A, Counter::Show), + Step::Load(A, Counter::Activate), + Step::Dec(A, Counter::Activate), + Step::Walk(A, Tree::Deactivate, ([0, 2, 2, 2], [0, 2, 2, 2])), + ]; + want.extend(walk_steps(Tree::Deactivate)); + assert_eq!(model.steps, want); + assert_eq!(model.refs, ([0, 2, 2, 2], [0, 1, 1, 1])); +} + +/// aux_deactivate_ignores_activate_refs. +#[test] +fn aux_deactivate_ignores_activate_refs() { + let model = run(deactivate, AUX_VIEW, ([0, 2, 2, 2], [4, 2, 2, 2])); + assert_eq!(model.steps, [Step::Load(A, Counter::Show)]); + assert_eq!(model.refs, ([0, 2, 2, 2], [4, 2, 2, 2])); +} + +/// balanced_sequence_ends_at_zero. +#[test] +fn balanced_sequence_ends_at_zero() { + let mut model = Model::default(); + activate(&mut model, Some(A), MAIN_VIEW); + activate(&mut model, Some(A), AUX_VIEW); + activate(&mut model, Some(A), MAIN_VIEW); + assert_eq!(model.refs, ([3; NODES], [2; NODES])); + deactivate(&mut model, Some(A), AUX_VIEW); + deactivate(&mut model, Some(A), MAIN_VIEW); + deactivate(&mut model, Some(A), MAIN_VIEW); + assert_eq!(model.refs, ([0; NODES], [0; NODES])); + model.steps.clear(); + deactivate(&mut model, Some(A), MAIN_VIEW); + assert!(!model.steps.iter().any(|s| matches!(s, Step::Walk(..)))); + assert_eq!(model.refs, ([0; NODES], [0; NODES])); +} + +/// The four callbacks: one counter of the child, +1 or -1, never loaded. +#[test] +fn each_callback_moves_one_counter_of_the_child() { + for tree in Tree::ALL { + for start in [c_long::MIN + 1, -1, 0, 1, 5] { + let mut model = Model::new(([start; NODES], [start; NODES])); + visit(&mut model, C, tree); + let step = if tree.raises() { + Step::Inc(C, tree.counter()) + } else { + Step::Dec(C, tree.counter()) + }; + assert_eq!(model.steps, [step]); + } + } + assert_eq!(Tree::Show.counter(), Counter::Show); + assert_eq!(Tree::Hide.counter(), Counter::Show); + assert_eq!(Tree::Activate.counter(), Counter::Activate); + assert_eq!(Tree::Deactivate.counter(), Counter::Activate); +} diff --git a/rust/obs-source/tests/source/activate_parity.rs b/rust/obs-source/tests/source/activate_parity.rs new file mode 100644 index 0000000000..9b0e34ec6d --- /dev/null +++ b/rust/obs-source/tests/source/activate_parity.rs @@ -0,0 +1,465 @@ +//! Tier 3: the original C `obs_source_activate()` and +//! `obs_source_deactivate()` (with their four static tree callbacks) and the +//! Rust exports, on noise-filled real-header sources (oracle/ +//! source_activate.c). Both reach the same scripted +//! `obs_source_enum_active_tree()`, which records its root and every +//! node's counters when it begins and reports a case's edges to the +//! callback it was given; the Rust side reaches the production counter +//! adapters. Compares every walk in order, the counters afterwards, the log +//! lines and every other byte of the sources, over every call, source +//! (NULL included), view type (MAIN, AUX and others), root counter edge and +//! edge set, plus a proptest; and rejects mutants. No intentional +//! differences. Excluded: a NULL child, which the real walk can't report +//! (it reads each child's type first); the original would dereference it. +use core::ffi::{CStr, c_char, c_long, c_void}; +use core::ptr::NonNull; +use obs_source::activate::{AUX_VIEW, Counter, Counters, MAIN_VIEW, Tree}; +use obs_source::ffi::source_activate::{Libobs, obs_source_activate, obs_source_deactivate}; +use obs_util::ffi::base::{base_get_log_handler, base_set_log_handler}; +use proptest::prelude::*; + +const NODES: usize = 4; +const EDGES: usize = 8; +const EVENTS: usize = 8; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct Case { + which: u8, + source: i8, + noise: u8, + view_type: u32, + show: [c_long; NODES], + active: [c_long; NODES], + edges: u8, + edge_parent: [i8; EDGES], + edge_child: [i8; EDGES], +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Outcome { + events: u32, + trace: [[i64; 1 + 2 * NODES]; EVENTS], + show: [c_long; NODES], + active: [c_long; NODES], + log_count: u32, + log_level: i32, + log: [c_char; 128], + untouched: bool, +} + +impl Default for Outcome { + fn default() -> Self { + Self { + events: 0, + trace: [[0; 1 + 2 * NODES]; EVENTS], + show: [0; NODES], + active: [0; NODES], + log_count: 0, + log_level: 0, + log: [0; 128], + untouched: false, + } + } +} + +impl Outcome { + fn log(&self) -> &str { + // SAFETY: the oracle wrote a NUL-terminated string (or left zeros). + unsafe { CStr::from_ptr(self.log.as_ptr()) } + .to_str() + .unwrap() + } + + /// The walks' roots, in order. + fn roots(&self) -> Vec { + self.trace + .iter() + .take(usize::try_from(self.events).unwrap()) + .map(|e| e[0]) + .collect() + } +} + +type Call = unsafe extern "C" fn(*mut c_void, u32); +type GetLog = unsafe extern "C" fn(*mut *mut c_void, *mut *mut c_void); +type SetLog = unsafe extern "C" fn(*mut c_void, *mut c_void); + +unsafe extern "C" { + fn oracle_source_activate_originals(activate: *mut Option, deactivate: *mut Option); + fn oracle_source_activate_run( + activate: Call, + deactivate: Call, + get: GetLog, + set: SetLog, + case: *const Case, + out: *mut Outcome, + ) -> bool; +} + +fn originals() -> (Call, Call) { + let mut activate = None; + let mut deactivate = None; + // SAFETY: two writable slots for function pointers. + unsafe { oracle_source_activate_originals(&raw mut activate, &raw mut deactivate) }; + (activate.unwrap(), deactivate.unwrap()) +} + +/// Runs one side; panics when the oracle could not build the fixture or an +/// adapter does not reach its field. +fn run(activate: Call, deactivate: Call, case: &Case) -> Outcome { + let mut out = Outcome::default(); + // SAFETY: the isolated child owns the log handler; the case and the + // outcome are valid for the call. + let valid = unsafe { + oracle_source_activate_run( + activate, + deactivate, + base_get_log_handler, + base_set_log_handler, + case, + &mut out, + ) + }; + assert!(valid, "the oracle fixture or an adapter failed: {case:?}"); + out +} + +/// The original's outcome, when the given calls agree with it. +fn check_with(activate: Call, deactivate: Call, case: &Case) -> Option { + let (original_activate, original_deactivate) = originals(); + let original = run(original_activate, original_deactivate, case); + let ported = run(activate, deactivate, case); + (ported == original).then_some(original) +} + +fn check(case: &Case) -> Outcome { + check_with(obs_source_activate, obs_source_deactivate, case) + .unwrap_or_else(|| panic!("the Rust exports disagree with the original C: {case:?}")) +} + +fn case(which: u8, source: i8, view_type: u32, root: [c_long; 2], edges: &[(i8, i8)]) -> Case { + let mut case = Case { + which, + source, + noise: 0xa5, + view_type, + // Every node's counters differ, so a step on the wrong one shows. + show: [11, 111, 211, 311], + active: [13, 113, 213, 313], + edges: u8::try_from(edges.len()).unwrap(), + ..Case::default() + }; + if let Ok(i) = usize::try_from(source) { + case.show[i] = root[0]; + case.active[i] = root[1]; + } + for (i, (p, c)) in edges.iter().enumerate() { + case.edge_parent[i] = *p; + case.edge_child[i] = *c; + } + case +} + +/// Edge sets the walk reports from node 0: none, the C test's tree +/// (post-order: c under b, b and d under a), the root itself, a repeated +/// child, and a NULL parent. +const EDGE_SETS: [&[(i8, i8)]; 5] = [ + &[], + &[(1, 2), (0, 1), (0, 3)], + &[(0, 0)], + &[(0, 1), (0, 1), (2, 3)], + &[(-1, 2)], +]; + +// --- mutants --------------------------------------------------------------- + +/// A hand-written port with one change, on the real adapters and walk. +#[derive(Clone, Copy)] +enum Change { + /// NULL logs nothing. + SilentNull, + /// NULL is logged under the other entry's name. + SwapNullNames, + /// MAIN_VIEW and AUX_VIEW swapped. + SwapViews, + /// The active step comes before the show step. + ActiveFirst, + /// Each walk runs the opposite callback (show for hide, and back). + OppositeWalk, + /// The show walk runs the active callback. + WrongCounterWalk, + /// Deactivation steps without checking the root's counter. + NoFloorCheck, + /// Deactivation checks `>= 0` instead of `> 0`. + FloorAtZero, + /// MAIN deactivation skips the active step when the show step ran. + ActiveOnlyWhenHidden, + /// The walk runs before the root's own step. + WalkFirst, + /// The walk is skipped. + NoWalk, +} + +fn opposite(tree: Tree) -> Tree { + match tree { + Tree::Show => Tree::Hide, + Tree::Hide => Tree::Show, + Tree::Activate => Tree::Deactivate, + Tree::Deactivate => Tree::Activate, + } +} + +fn step(change: Change, source: NonNull, counter: Counter, tree: Tree, raise: bool) { + let tree = match change { + Change::OppositeWalk => opposite(tree), + Change::WrongCounterWalk if tree == Tree::Show => Tree::Activate, + _ => tree, + }; + let mut libobs = Libobs; + let own = |libobs: &mut Libobs| { + if raise { + libobs.inc(source, counter); + } else { + libobs.dec(source, counter); + } + }; + match change { + Change::WalkFirst => { + libobs.walk(source, tree); + own(&mut libobs); + } + Change::NoWalk => own(&mut libobs), + _ => { + own(&mut libobs); + libobs.walk(source, tree); + } + } +} + +fn is_main(change: Change, view_type: u32) -> bool { + match change { + Change::SwapViews => view_type != MAIN_VIEW, + _ => view_type == MAIN_VIEW, + } +} + +fn null(change: Change, function: &'static CStr, other: &'static CStr) { + match change { + Change::SilentNull => {} + Change::SwapNullNames => Libobs.log_null(other), + _ => Libobs.log_null(function), + } +} + +fn mutant_activate(change: Change, source: *mut c_void, view_type: u32) { + let Some(source) = NonNull::new(source) else { + null(change, c"obs_source_activate", c"obs_source_deactivate"); + return; + }; + let main = is_main(change, view_type); + if main && matches!(change, Change::ActiveFirst) { + step(change, source, Counter::Activate, Tree::Activate, true); + } + step(change, source, Counter::Show, Tree::Show, true); + if main && !matches!(change, Change::ActiveFirst) { + step(change, source, Counter::Activate, Tree::Activate, true); + } +} + +fn mutant_deactivate(change: Change, source: *mut c_void, view_type: u32) { + let Some(source) = NonNull::new(source) else { + null(change, c"obs_source_deactivate", c"obs_source_activate"); + return; + }; + let mut libobs = Libobs; + let above = |libobs: &mut Libobs, counter| match change { + Change::NoFloorCheck => true, + Change::FloorAtZero => libobs.load(source, counter) >= 0, + _ => libobs.load(source, counter) > 0, + }; + let main = is_main(change, view_type); + if main && matches!(change, Change::ActiveFirst) && above(&mut libobs, Counter::Activate) { + step(change, source, Counter::Activate, Tree::Deactivate, false); + } + let mut hid = false; + if above(&mut libobs, Counter::Show) { + step(change, source, Counter::Show, Tree::Hide, false); + hid = true; + } + if main + && !matches!(change, Change::ActiveFirst) + && !(hid && matches!(change, Change::ActiveOnlyWhenHidden)) + && above(&mut libobs, Counter::Activate) + { + step(change, source, Counter::Activate, Tree::Deactivate, false); + } +} + +macro_rules! mutant { + ($activate:ident, $deactivate:ident, $change:expr) => { + unsafe extern "C" fn $activate(source: *mut c_void, view_type: u32) { + mutant_activate($change, source, view_type); + } + unsafe extern "C" fn $deactivate(source: *mut c_void, view_type: u32) { + mutant_deactivate($change, source, view_type); + } + }; +} + +mutant!(a_silent, d_silent, Change::SilentNull); +mutant!(a_swap_null, d_swap_null, Change::SwapNullNames); +mutant!(a_swap_views, d_swap_views, Change::SwapViews); +mutant!(a_active_first, d_active_first, Change::ActiveFirst); +mutant!(a_opposite, d_opposite, Change::OppositeWalk); +mutant!(a_wrong_counter, d_wrong_counter, Change::WrongCounterWalk); +mutant!(a_no_floor, d_no_floor, Change::NoFloorCheck); +mutant!(a_floor_zero, d_floor_zero, Change::FloorAtZero); +mutant!(a_only_hidden, d_only_hidden, Change::ActiveOnlyWhenHidden); +mutant!(a_walk_first, d_walk_first, Change::WalkFirst); +mutant!(a_no_walk, d_no_walk, Change::NoWalk); + +// --- the checks ------------------------------------------------------------ + +fn pinned() { + // NULL: one LOG_DEBUG line naming the entry, no walk, nothing written. + for (which, function) in [(0, "obs_source_activate"), (1, "obs_source_deactivate")] { + for view_type in [MAIN_VIEW, AUX_VIEW] { + let out = check(&case(which, -1, view_type, [1, 1], EDGE_SETS[1])); + assert_eq!((out.log_count, out.log_level), (1, 400)); + assert_eq!(out.log(), format!("{function}: Null 'source' parameter")); + assert_eq!(out.events, 0); + assert!(out.untouched); + assert_eq!(out.show, [11, 111, 211, 311]); + } + } + + // MAIN activate on the C test's tree: two walks, every counter +1. + let out = check(&case(0, 0, MAIN_VIEW, [0, 0], EDGE_SETS[1])); + assert_eq!(out.roots(), [0, 0]); + assert_eq!(out.trace[0][1..5], [1, 111, 211, 311]); + assert_eq!(out.trace[1][1..5], [1, 112, 212, 312]); + assert_eq!(out.trace[1][5..9], [1, 113, 213, 313]); + assert_eq!(out.show, [1, 112, 212, 312]); + assert_eq!(out.active, [1, 114, 214, 314]); + assert_eq!(out.log_count, 0); + assert!(out.untouched); + + // AUX activate: one walk, activate_refs untouched. + let out = check(&case(0, 0, AUX_VIEW, [0, 0], EDGE_SETS[1])); + assert_eq!(out.roots(), [0]); + assert_eq!(out.active, [0, 113, 213, 313]); + + // Deactivate at zero: no walk, nothing moves. + let out = check(&case(1, 0, MAIN_VIEW, [0, 0], EDGE_SETS[1])); + assert_eq!(out.events, 0); + assert_eq!(out.show, [0, 111, 211, 311]); + assert_eq!(out.active, [0, 113, 213, 313]); + + // Hidden but active: only the active walk. + let out = check(&case(1, 0, MAIN_VIEW, [0, 1], EDGE_SETS[1])); + assert_eq!(out.roots(), [0]); + assert_eq!(out.active, [0, 112, 212, 312]); + + // A repeated child moves twice; the root as its own child once more. + let out = check(&case(0, 0, AUX_VIEW, [0, 0], EDGE_SETS[3])); + assert_eq!(out.show, [1, 113, 211, 312]); + let out = check(&case(0, 0, AUX_VIEW, [0, 0], EDGE_SETS[2])); + assert_eq!(out.show[0], 2); +} + +fn grid() -> impl Iterator { + let mut cases = Vec::new(); + for which in 0..2u8 { + for source in [-1i8, 0, 2] { + for view_type in [0, MAIN_VIEW, AUX_VIEW, 3, u32::MAX] { + for show in [-2, -1, 0, 1, 2] { + for active in [-1, 0, 1, 3] { + for edges in EDGE_SETS { + cases.push(case(which, source, view_type, [show, active], edges)); + } + } + } + } + } + } + cases.into_iter() +} + +fn grid_and_mutants() { + let mut count = 0usize; + for c in grid() { + let out = check(&c); + assert!(out.untouched); + count += 1; + } + assert_eq!(count, 2 * 3 * 5 * 5 * 4 * EDGE_SETS.len()); + + let mutants: [(&str, Call, Call); 11] = [ + ("silent NULL", a_silent, d_silent), + ("NULL names swapped", a_swap_null, d_swap_null), + ("views swapped", a_swap_views, d_swap_views), + ("active step first", a_active_first, d_active_first), + ("opposite walk", a_opposite, d_opposite), + ( + "show walk runs the active callback", + a_wrong_counter, + d_wrong_counter, + ), + ("no floor check", a_no_floor, d_no_floor), + ("floor at zero", a_floor_zero, d_floor_zero), + ("active step only when hidden", a_only_hidden, d_only_hidden), + ("walk before the root's step", a_walk_first, d_walk_first), + ("no walk", a_no_walk, d_no_walk), + ]; + for (name, activate, deactivate) in mutants { + assert!( + grid().any(|c| check_with(activate, deactivate, &c).is_none()), + "the mutant '{name}' agreed with the original C" + ); + } +} + +fn random_cases() { + let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig { + cases: obs_c_oracle::parity::cases(512), + failure_persistence: None, + ..ProptestConfig::default() + }); + // Children are always nodes: the real walk never reports NULL. + let edge = (-1i8..4, 0i8..4); + runner + .run( + &( + (0u8..2, -1i8..4, any::()), + prop_oneof![Just(MAIN_VIEW), Just(AUX_VIEW), any::()], + ( + proptest::array::uniform4(-3 as c_long..4), + proptest::array::uniform4(-3 as c_long..4), + ), + proptest::collection::vec(edge, 0..=EDGES), + ), + |((which, source, noise), view_type, (show, active), edges)| { + let mut c = case(which, source, view_type, [0, 0], &edges); + c.noise = noise; + c.show = show; + c.active = active; + let out = check(&c); + prop_assert!(out.untouched); + prop_assert!(out.events <= 2); + Ok(()) + }, + ) + .unwrap(); +} + +#[test] +fn activate_matches_c() { + if !crate::output::isolated(concat!(module_path!(), "::activate_matches_c")) { + return; + } + pinned(); + grid_and_mutants(); + random_cases(); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 21a44a9227..d662597f59 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -1,5 +1,7 @@ //! obs-source integration tests, one module per extracted C file. +mod activate; +mod activate_parity; mod active_child; mod active_child_parity; mod async_compensation; diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index eab3a7ae79..3fecbd463b 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -17086,6 +17086,21 @@ "SIMDe::SIMDe" ] }, + "test_source_activate": { + "sources": [ + "test/cmocka/test_source_activate.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ] + }, "test_source_active_child": { "sources": [ "test/cmocka/test_source_active_child.c" @@ -29817,6 +29832,19 @@ "test_slideshow_size": { "target": "test_slideshow_size" }, + "test_source_activate": { + "target": "test_source_activate", + "command": [ + "${target}" + ], + "suite": "core", + "optional_prefixes": [ + [ + "xvfb-run", + "-a" + ] + ] + }, "test_source_active_child": { "target": "test_source_active_child", "command": [ diff --git a/test/cmocka/test_source_activate.c b/test/cmocka/test_source_activate.c new file mode 100644 index 0000000000..859b943b66 --- /dev/null +++ b/test/cmocka/test_source_activate.c @@ -0,0 +1,414 @@ +/* Characterization of obs_source_activate() and obs_source_deactivate() + * (#5811), the internal calls behind obs_source_inc_showing(), + * obs_source_inc_active(), obs_source_dec_showing() and + * obs_source_dec_active(), views, canvases and active children. + * + * Both are declared in obs-internal.h without EXPORT, so the test reaches + * them through the four public counters: inc_showing activates for + * AUX_VIEW, inc_active for MAIN_VIEW, and the dec pair deactivates the + * same way. (Their own NULL check can't be reached from outside libobs: + * every caller checks first. Tier 1 and Tier 3 cover it.) + * + * What it pins, on private sources of a started core whose + * enum_active_sources lists children (a lists b and d, b lists c), with + * every visit of the walk recording all eight counters at that moment: + * + * - AUX activate: the root's show_refs +1, then one walk of the active + * tree (children before their parent's own step, post-order) that adds + * 1 to each descendant's show_refs. activate_refs never moves. + * - MAIN activate: the same, then the root's activate_refs +1 and a second + * walk that adds 1 to each descendant's activate_refs. + * - AUX deactivate: only when the root's show_refs is above zero, -1 and a + * walk subtracting 1 from each descendant's show_refs. A descendant's + * count is not floor-checked: it goes below zero. + * - MAIN deactivate: that, then, only when the root's activate_refs is + * above zero, the same for activate_refs. Each counter is checked on + * its own: a hidden root that is still active walks once. + * - A root at zero is left alone and is never walked. + * - Nothing is logged. + * + * obs_startup() needs a display on Linux, so the test runs under xvfb-run + * when it is installed. No video is reset, so no tick reacts to the + * counters. */ +#include +#include +#include +#include +#include +#include +#include +#include "obs-internal.h" + +#define NODE_ID "test_source_activate_node" +#define NODES 4 +#define MAX_CHILDREN 2 +#define MAX_VISITS 32 + +/* ------------------------------------------------------------------------- */ +/* log capture */ + +static unsigned log_count; +#if defined(__GNUC__) || defined(__clang__) +static void capture_log(int level, const char *format, va_list args, void *param) __attribute__((format(printf, 2, 0))); +#endif +static void capture_log(int level, const char *format, va_list args, void *param) +{ + (void)level; + (void)format; + (void)args; + (void)param; + log_count++; +} + +static log_handler_t saved_handler; +static void *saved_param; + +static void capture_start(void) +{ + base_get_log_handler(&saved_handler, &saved_param); + base_set_log_handler(capture_log, NULL); + log_count = 0; +} + +static void capture_stop(void) +{ + base_set_log_handler(saved_handler, saved_param); +} + +/* ------------------------------------------------------------------------- */ +/* the node source type */ + +/* One visit of the walk: which node's enum_active_sources ran, and every + * node's show_refs and activate_refs at that moment. */ +struct visit { + size_t node; + long show[NODES]; + long active[NODES]; +}; + +struct node { + size_t index; + obs_source_t *children[MAX_CHILDREN]; + size_t child_count; +}; + +static obs_source_t *sources[NODES]; +static struct visit visits[MAX_VISITS]; +static size_t visit_count; + +static const char *node_name(void *type_data) +{ + (void)type_data; + return "activate node"; +} + +static void *node_create(obs_data_t *settings, obs_source_t *source) +{ + (void)settings; + (void)source; + return bzalloc(sizeof(struct node)); +} + +static void node_destroy(void *data) +{ + bfree(data); +} + +static uint32_t node_size(void *data) +{ + (void)data; + return 16; +} + +static void node_enum_active(void *data, obs_source_enum_proc_t enum_callback, void *param) +{ + struct node *node = data; + if (visit_count < MAX_VISITS) { + struct visit *v = &visits[visit_count]; + v->node = node->index; + for (size_t i = 0; i < NODES; i++) { + v->show[i] = os_atomic_load_long(&sources[i]->show_refs); + v->active[i] = os_atomic_load_long(&sources[i]->activate_refs); + } + } + visit_count++; + for (size_t i = 0; i < node->child_count; i++) + enum_callback(sources[node->index], node->children[i], param); +} + +static void register_node(void) +{ + struct obs_source_info info = { + .id = NODE_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_VIDEO, + .get_name = node_name, + .create = node_create, + .destroy = node_destroy, + .get_width = node_size, + .get_height = node_size, + .enum_active_sources = node_enum_active, + }; + obs_register_source(&info); +} + +/* ------------------------------------------------------------------------- */ +/* fixture: a lists b and d, b lists c */ + +enum { A, B, C, D }; + +static int fixture_setup(void **state) +{ + (void)state; + static const char *names[NODES] = {"a", "b", "c", "d"}; + struct node *nodes[NODES]; + for (size_t i = 0; i < NODES; i++) { + sources[i] = obs_source_create_private(NODE_ID, names[i], NULL); + assert_non_null(sources[i]); + nodes[i] = obs_obj_get_data(sources[i]); + assert_non_null(nodes[i]); + nodes[i]->index = i; + } + nodes[A]->children[0] = sources[B]; + nodes[A]->children[1] = sources[D]; + nodes[A]->child_count = 2; + nodes[B]->children[0] = sources[C]; + nodes[B]->child_count = 1; + visit_count = 0; + memset(visits, 0, sizeof(visits)); + return 0; +} + +static int fixture_teardown(void **state) +{ + (void)state; + for (size_t i = 0; i < NODES; i++) { + os_atomic_set_long(&sources[i]->show_refs, 0); + os_atomic_set_long(&sources[i]->activate_refs, 0); + obs_source_release(sources[i]); + sources[i] = NULL; + } + /* Sources are destroyed on the destruction thread, which logs. Let it + * finish here, so those lines never land in the next test's capture. */ + obs_wait_for_destroy_queue(); + return 0; +} + +/* ------------------------------------------------------------------------- */ +/* helpers */ + +/* Counters as {a, b, c, d}. */ +struct counters { + long show[NODES]; + long active[NODES]; +}; + +static void set_counters(const struct counters *c) +{ + for (size_t i = 0; i < NODES; i++) { + os_atomic_set_long(&sources[i]->show_refs, c->show[i]); + os_atomic_set_long(&sources[i]->activate_refs, c->active[i]); + } +} + +static void assert_counters(const struct counters *c) +{ + for (size_t i = 0; i < NODES; i++) { + assert_int_equal(os_atomic_load_long(&sources[i]->show_refs), c->show[i]); + assert_int_equal(os_atomic_load_long(&sources[i]->activate_refs), c->active[i]); + } +} + +static void assert_visit(size_t index, size_t node, const struct counters *c) +{ + assert_true(index < visit_count); + assert_int_equal(visits[index].node, node); + for (size_t i = 0; i < NODES; i++) { + assert_int_equal(visits[index].show[i], c->show[i]); + assert_int_equal(visits[index].active[i], c->active[i]); + } +} + +static void run(void (*call)(obs_source_t *)) +{ + visit_count = 0; + capture_start(); + call(sources[A]); + capture_stop(); + assert_int_equal(log_count, 0); +} + +/* ------------------------------------------------------------------------- */ +/* activate */ + +/* One walk, the order of its visits: a's own enum first, then b (whose child + * c is raised before b), then d. Each descendant is raised after its own + * enum ran, so a visit sees its node at the old value. */ +static void aux_activate_raises_show_refs_in_one_walk(void **state) +{ + (void)state; + run(obs_source_inc_showing); + assert_int_equal(visit_count, 4); + /* a's show_refs rose before the walk started. */ + assert_visit(0, A, &(struct counters){{1, 0, 0, 0}, {0, 0, 0, 0}}); + assert_visit(1, B, &(struct counters){{1, 0, 0, 0}, {0, 0, 0, 0}}); + assert_visit(2, C, &(struct counters){{1, 0, 0, 0}, {0, 0, 0, 0}}); + /* c, then b, were raised before d was visited. */ + assert_visit(3, D, &(struct counters){{1, 1, 1, 0}, {0, 0, 0, 0}}); + assert_counters(&(struct counters){{1, 1, 1, 1}, {0, 0, 0, 0}}); +} + +/* The show walk, then a's activate_refs and a second walk. */ +static void main_activate_walks_show_then_active(void **state) +{ + (void)state; + run(obs_source_inc_active); + assert_int_equal(visit_count, 8); + assert_visit(0, A, &(struct counters){{1, 0, 0, 0}, {0, 0, 0, 0}}); + assert_visit(3, D, &(struct counters){{1, 1, 1, 0}, {0, 0, 0, 0}}); + /* The second walk starts after every show_refs rose and a's + * activate_refs with them. */ + assert_visit(4, A, &(struct counters){{1, 1, 1, 1}, {1, 0, 0, 0}}); + assert_visit(5, B, &(struct counters){{1, 1, 1, 1}, {1, 0, 0, 0}}); + assert_visit(6, C, &(struct counters){{1, 1, 1, 1}, {1, 0, 0, 0}}); + assert_visit(7, D, &(struct counters){{1, 1, 1, 1}, {1, 1, 1, 0}}); + assert_counters(&(struct counters){{1, 1, 1, 1}, {1, 1, 1, 1}}); +} + +/* Activation never looks at the current values: from any count, +1. */ +static void activate_adds_one_to_any_count(void **state) +{ + (void)state; + set_counters(&(struct counters){{-3, 0, 7, 2}, {5, -1, 0, 9}}); + run(obs_source_inc_active); + assert_int_equal(visit_count, 8); + assert_counters(&(struct counters){{-2, 1, 8, 3}, {6, 0, 1, 10}}); +} + +/* ------------------------------------------------------------------------- */ +/* deactivate */ + +static void aux_deactivate_lowers_show_refs_in_one_walk(void **state) +{ + (void)state; + set_counters(&(struct counters){{2, 2, 2, 2}, {1, 1, 1, 1}}); + run(obs_source_dec_showing); + assert_int_equal(visit_count, 4); + assert_visit(0, A, &(struct counters){{1, 2, 2, 2}, {1, 1, 1, 1}}); + assert_visit(3, D, &(struct counters){{1, 1, 1, 2}, {1, 1, 1, 1}}); + assert_counters(&(struct counters){{1, 1, 1, 1}, {1, 1, 1, 1}}); +} + +static void main_deactivate_walks_show_then_active(void **state) +{ + (void)state; + set_counters(&(struct counters){{1, 1, 1, 1}, {1, 1, 1, 1}}); + run(obs_source_dec_active); + assert_int_equal(visit_count, 8); + assert_visit(0, A, &(struct counters){{0, 1, 1, 1}, {1, 1, 1, 1}}); + assert_visit(3, D, &(struct counters){{0, 0, 0, 1}, {1, 1, 1, 1}}); + assert_visit(4, A, &(struct counters){{0, 0, 0, 0}, {0, 1, 1, 1}}); + assert_visit(7, D, &(struct counters){{0, 0, 0, 0}, {0, 0, 0, 1}}); + assert_counters(&(struct counters){{0, 0, 0, 0}, {0, 0, 0, 0}}); +} + +/* Only the root is checked: descendants go below zero. */ +static void descendants_are_not_floor_checked(void **state) +{ + (void)state; + set_counters(&(struct counters){{1, 0, -4, 0}, {1, 0, 0, 3}}); + run(obs_source_dec_active); + assert_int_equal(visit_count, 8); + assert_counters(&(struct counters){{0, -1, -5, -1}, {0, -1, -1, 2}}); +} + +/* A root at zero is left alone and never walked. */ +static void deactivate_at_zero_does_nothing(void **state) +{ + (void)state; + set_counters(&(struct counters){{0, 3, 3, 3}, {0, 3, 3, 3}}); + run(obs_source_dec_showing); + assert_int_equal(visit_count, 0); + run(obs_source_dec_active); + assert_int_equal(visit_count, 0); + set_counters(&(struct counters){{-2, 3, 3, 3}, {-1, 3, 3, 3}}); + run(obs_source_dec_active); + assert_int_equal(visit_count, 0); + assert_counters(&(struct counters){{-2, 3, 3, 3}, {-1, 3, 3, 3}}); +} + +/* Each counter is checked on its own: a hidden root that is still active + * skips the show walk and takes the active one. */ +static void hidden_but_active_root_walks_once(void **state) +{ + (void)state; + set_counters(&(struct counters){{0, 2, 2, 2}, {1, 2, 2, 2}}); + run(obs_source_dec_active); + assert_int_equal(visit_count, 4); + assert_visit(0, A, &(struct counters){{0, 2, 2, 2}, {0, 2, 2, 2}}); + assert_counters(&(struct counters){{0, 2, 2, 2}, {0, 1, 1, 1}}); +} + +/* dec_showing leaves activate_refs alone even when only it is set. */ +static void aux_deactivate_ignores_activate_refs(void **state) +{ + (void)state; + set_counters(&(struct counters){{0, 2, 2, 2}, {4, 2, 2, 2}}); + run(obs_source_dec_showing); + assert_int_equal(visit_count, 0); + assert_counters(&(struct counters){{0, 2, 2, 2}, {4, 2, 2, 2}}); +} + +/* A balanced sequence ends where it started, on every node. */ +static void balanced_sequence_ends_at_zero(void **state) +{ + (void)state; + run(obs_source_inc_active); + run(obs_source_inc_showing); + run(obs_source_inc_active); + assert_counters(&(struct counters){{3, 3, 3, 3}, {2, 2, 2, 2}}); + run(obs_source_dec_showing); + run(obs_source_dec_active); + run(obs_source_dec_active); + assert_counters(&(struct counters){{0, 0, 0, 0}, {0, 0, 0, 0}}); + run(obs_source_dec_active); + assert_int_equal(visit_count, 0); + assert_counters(&(struct counters){{0, 0, 0, 0}, {0, 0, 0, 0}}); +} + +/* ------------------------------------------------------------------------- */ + +static int group_setup(void **state) +{ + (void)state; + if (!obs_startup("en-US", NULL, NULL)) + return -1; + register_node(); + return 0; +} + +static int group_teardown(void **state) +{ + (void)state; + obs_shutdown(); + return 0; +} + +#define CASE(f) cmocka_unit_test_setup_teardown(f, fixture_setup, fixture_teardown) + +int main(void) +{ + const struct CMUnitTest tests[] = { + CASE(aux_activate_raises_show_refs_in_one_walk), + CASE(main_activate_walks_show_then_active), + CASE(activate_adds_one_to_any_count), + CASE(aux_deactivate_lowers_show_refs_in_one_walk), + CASE(main_deactivate_walks_show_then_active), + CASE(descendants_are_not_floor_checked), + CASE(deactivate_at_zero_does_nothing), + CASE(hidden_but_active_root_walks_once), + CASE(aux_deactivate_ignores_activate_refs), + CASE(balanced_sequence_ends_at_zero), + }; + return cmocka_run_group_tests(tests, group_setup, group_teardown); +} diff --git a/test/cmocka/tests.d/test_source_activate.cmake b/test/cmocka/tests.d/test_source_activate.cmake new file mode 100644 index 0000000000..dff7c2ccc1 --- /dev/null +++ b/test/cmocka/tests.d/test_source_activate.cmake @@ -0,0 +1,8 @@ +# obs_source_activate and obs_source_deactivate (#5811), through the four +# public counters: activate raises the source's show_refs and walks its active +# tree once adding 1 to each descendant's, then for MAIN_VIEW the same for +# activate_refs; deactivate lowers each counter (show first, activate only for +# MAIN_VIEW) only when the source's is above zero, with a walk subtracting 1 +# from each descendant (not floor-checked). A source at zero is not walked. +# Nothing logs. Real core under xvfb-run. Registered once in +# build/test-graph.json, consumed by CMake and Cargo.