diff --git a/ci/test_bench_libobs_stand_ins.py b/ci/test_bench_libobs_stand_ins.py index bc676865bd..6800c32a53 100644 --- a/ci/test_bench_libobs_stand_ins.py +++ b/ci/test_bench_libobs_stand_ins.py @@ -37,9 +37,10 @@ # The key-name store is absent: #5321 exports it from obs-hotkey (hidden in # libobs, defined by the workspace). The output name getter is absent as # well: #5302 exports it from obs-output, and the interleaver names its -# output through a private seam too. +# output through a private seam too. The encoder group started count is +# absent: #5319 exports it from obs-output, and the oracle defines its +# private adapters (oracle/encoder_group_num_started.c). SYMBOLS = ( - "obs_encoder_group_num_started", "obs_encoder_interleave_info", "obs_hotkey_binding_fields", "obs_hotkey_identity_fields", diff --git a/libobs/build/libobs.core-output+.h.c b/libobs/build/libobs.core-output+.h.c index 93984fe919..adc2058477 100644 --- a/libobs/build/libobs.core-output+.h.c +++ b/libobs/build/libobs.core-output+.h.c @@ -17,7 +17,7 @@ #include "libobs/obs-encoder-get-name-fields.c.h" #include "libobs/obs-encoder-gpu-scaling-getters-fields.c.h" #include "libobs/obs-encoder-group-lifecycle-fields.c.h" -#include "libobs/obs-encoder-group-num-started.c.h" +#include "libobs/obs-encoder-group-num-started-fields.c.h" #include "libobs/obs-encoder-init-fields.c.h" #include "libobs/obs-encoder-last-error-fields.c.h" #include "libobs/obs-encoder-media-getters-fields.c.h" diff --git a/libobs/build/libobs.ported-encoder-group-num-started+.h.c b/libobs/build/libobs.ported-encoder-group-num-started+.h.c new file mode 100644 index 0000000000..7b7ea8cfce --- /dev/null +++ b/libobs/build/libobs.ported-encoder-group-num-started+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original encoder group started-count query, C reference only. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-encoder-group-num-started.c.h" diff --git a/libobs/build/ported-source-sets/encoder-group-num-started.json b/libobs/build/ported-source-sets/encoder-group-num-started.json new file mode 100644 index 0000000000..1fe1584f04 --- /dev/null +++ b/libobs/build/ported-source-sets/encoder-group-num-started.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-encoder-group-num-started+.h.c" + ] +} diff --git a/libobs/cmake/rust-hidden.d/obs-output-encoder_group_num_started.txt b/libobs/cmake/rust-hidden.d/obs-output-encoder_group_num_started.txt new file mode 100644 index 0000000000..17e9d32ffa --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-output-encoder_group_num_started.txt @@ -0,0 +1,4 @@ +# obs-encoder-group-num-started.c: output interleaving and obs_encoder_set_group +# read a group's started-encoder count inside libobs. Declared in +# obs-internal.h without EXPORT, so the shim stays hidden the same way. +obs_encoder_group_num_started diff --git a/libobs/obs-encoder-group-num-started-fields.c.h b/libobs/obs-encoder-group-num-started-fields.c.h new file mode 100644 index 0000000000..a8cc2f2769 --- /dev/null +++ b/libobs/obs-encoder-group-num-started-fields.c.h @@ -0,0 +1,24 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters for the Rust obs_encoder_group_num_started(). The group's + * mutex and its num_encoders_started stay in C; Rust decides when each is + * used: the count is read once, between one lock and one unlock, as every + * writer (encoder start and stop, set-group) changes it under the same + * mutex. The group is never NULL here, as in the original. */ +void obs_encoder_group_num_started_lock(struct obs_encoder_group *group); +void obs_encoder_group_num_started_lock(struct obs_encoder_group *group) +{ + pthread_mutex_lock(&group->mutex); +} + +uint32_t obs_encoder_group_num_started_read(const struct obs_encoder_group *group); +uint32_t obs_encoder_group_num_started_read(const struct obs_encoder_group *group) +{ + return group->num_encoders_started; +} + +void obs_encoder_group_num_started_unlock(struct obs_encoder_group *group); +void obs_encoder_group_num_started_unlock(struct obs_encoder_group *group) +{ + pthread_mutex_unlock(&group->mutex); +} diff --git a/rust/README.md b/rust/README.md index c03f652959..70a732fbe9 100644 --- a/rust/README.md +++ b/rust/README.md @@ -292,6 +292,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-encoder-metadata-getters.c.h` (extracted from `obs-encoder.c.h`) | `obs-output::encoder_metadata` | Five public instance metadata getters: codec/type from current info, ID/type data/caps from original info. No intended differences: NULL defaults and exact diagnostics, borrowed pointer identity, full-width caps, no locks, reference changes or plugin callbacks. Private field-pointer seam avoids mirroring the encoder layout; real-header view/enum layout checks, exact differential parity and unchanged actual-library `test_encoder_metadata_getters` cover both libraries. | | `libobs/obs-encoder-dimensions.c.h` | `obs-output::encoder_dimensions` | Public `obs_encoder_get_width` and `obs_encoder_get_height` swapped in hybrid libobs (group `libobs.ported-encoder-dimensions`). Reuses `encoder_size::video_size_route`; preserves NULL debug logs, wrong-type warnings including the encoder name, media absence before stored axes, independent full-width scaled axes and lazy video fallback. A borrowed field-address adapter keeps the private encoder layout in C. `test_encoder_dimensions` characterizes actual libraries and remains unchanged after its C-only commit. Tier 1 mirrors its assertions; real-header checks cover every view field and encoder type layout. Tier 3 compares both getters, full diagnostics and whole-encoder immutability for edges and randomized fields, using callbacks for media reads and the oracle C size helper. No intentional behavior differences. Tier 4 is inapplicable. | | `libobs/obs-encoder-group-lifecycle.c.h` | `obs-output::encoder_group_lifecycle` | Encoder-group allocation, deferred destruction and ordered locked teardown swapped in hybrid libobs. Native allocation, private fields and mutex primitives stay behind C adapters; the safe core clears each encoder back-pointer before releasing its reference, frees the list, unlocks and destroys the mutex, then frees the group. Tier 1 mirrors the source characterization; real-header view layout and bounded randomized C/Rust operation traces include init failure and the locked stop-path handoff. Actual-library Tier 2 checks zero initialization, deferred requests, back-pointers and strong-reference ownership. No intentional differences; Tier 4 is inapplicable. | +| `libobs/obs-encoder-group-num-started.c.h` | `obs-output::encoder_group_num_started` | Swapped in hybrid `libobs` (group `libobs.ported-encoder-group-num-started` keeps the original for the C reference). The hidden `obs_encoder_group_num_started` (`obs-internal.h`, listed in `rust-hidden.d`), which output interleaving and `obs_encoder_set_group` call. Rust owns the decision: the group's mutex is taken once, `num_encoders_started` read once while it is held, and the mutex released once, so the value seen under the lock is returned over the full `uint32_t` range; the group is never NULL (the C precondition). The mutex and the count stay in C behind private adapters (`obs-encoder-group-num-started-fields.c.h`); Rust never sees the group layout or its pthread mutex. Only the unchanged characterization compiled the original, and the one other C definition of the name (`output_interleave_fields_stub.c`) never links the Rust archive, so no shared Rust-static support member is added. The unchanged `test_encoder_group_num_started` keeps testing the C source; its twin `test_encoder_group_num_started_rust` compiles the same fixture with the same recorder definitions and runs its assertions on the Rust shim through the real adapters. The interleave parity fixture now reaches its groups through the real shim (the oracle's adapters forward them), and the bench's stand-in is gone. Tier 1 mirrors every assertion plus the lock/read/unlock order; Tier 3 runs the original and the shim on two recording fixture groups (result, each lock and unlock, both groups byte for byte, count rewritten in the lock and/or unlock), with real-header layout checks and mutants. No intentional differences; no network protocol (Tier 4 inapplicable). | | `libobs/obs-encoder-init.c.h` | `obs-output::encoder_init` | Encoder context/mutex initialization swapped through a private C operation table. Rust preserves sentinel setup, immediate failure returns, partial state, recursive lock selection and live defaults callback order. Original C body retained unchanged for the reference and differential oracle; real-header table layout and unchanged public creation characterization cover the boundary. No intentional differences; Tier 4 does not apply. | | `libobs/obs-encoder-last-error.c.h` | `obs-output::encoder_last_error` | Swapped in hybrid `libobs` (group `libobs.ported-encoder-last-error`). `obs_encoder_get_last_error` preserves the NULL default and exact diagnostic, borrowed NULL/empty/arbitrary-byte message pointer identity, independent encoders and unchanged state. C supplies only the private field address, without a Rust mirror of `struct obs_encoder`. Real-header view layout checks, Tier 3 randomized parity with persistence disabled and a mutation check, and unchanged `test_encoder_last_error_getter` against both actual libraries cover the swap. No intentional differences; no ownership or locking changes. | | `libobs/obs-encoder-reroute.c.h` (extracted from `obs-encoder.c.h`) | `obs-output::encoder_reroute` | `obs_encoder_create_rerouted` swapped in hybrid `libobs` (group `libobs.ported-encoder-reroute`, Refs #4413). Keeps the NULL debug diagnostics, the create-only permission (the thread-local stays in `obs-encoder.c.h`), the registry lookup through `find_encoder`, matching against the original info's type and case-insensitive codec, installing the whole replacement table before calling its `create` with the current settings, and passing its result back with no rollback on NULL. A borrowed field adapter keeps the private encoder layout in C. Tier 1 mirrors the unchanged `test_encoder_reroute`; Tier 3 compares exact traces against the original C over the characterized cases and random inputs, plus the real-header view layout and the log lines. 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 fd1877c275..272527db89 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -317,6 +317,8 @@ mod canonical_encoder_frame_rate_divisor_is_registered; mod canonical_encoder_gpu_scaling_getters_is_registered; #[path = "native/registration/canonical_encoder_group_null_is_registered.rs"] mod canonical_encoder_group_null_is_registered; +#[path = "native/registration/canonical_encoder_group_num_started_swap_is_registered.rs"] +mod canonical_encoder_group_num_started_swap_is_registered; #[path = "native/registration/canonical_encoder_outputs_swap_is_registered.rs"] mod canonical_encoder_outputs_swap_is_registered; #[path = "native/registration/canonical_encoder_preferred_color_setters_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_encoder_group_num_started_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_encoder_group_num_started_swap_is_registered.rs new file mode 100644 index 0000000000..1815e77894 --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_encoder_group_num_started_swap_is_registered.rs @@ -0,0 +1,180 @@ +use super::*; + +const ORIGINAL: &str = "libobs/obs-encoder-group-num-started.c.h"; +const FIELDS: &str = "libobs/obs-encoder-group-num-started-fields.c.h"; +const SHIM: &str = "obs_encoder_group_num_started"; +const ADAPTERS: [&str; 3] = [ + "obs_encoder_group_num_started_lock", + "obs_encoder_group_num_started_read", + "obs_encoder_group_num_started_unlock", +]; +const DEFINITIONS: [&str; 2] = [ + "pthread_mutex_lock=encoder_group_count_record_lock", + "pthread_mutex_unlock=encoder_group_count_record_unlock", +]; + +fn graph_json(root: &Path) -> serde_json::Value { + serde_json::from_str( + &fs::read_to_string(root.join("test/cmocka/build/test-graph.json")).unwrap(), + ) + .unwrap() +} + +/// No other target compiles the original, and the only cmocka source that +/// defines the shim's name (output_interleave_fields_stub.c, for the +/// interleaver's C fixture) is linked without the Rust archive, so neither +/// collides with the swap and no standalone Rust-static consumer needs a +/// shared copy of the adapters. +#[test] +fn canonical_encoder_group_num_started_original_has_one_consumer() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let graph = graph_json(&root); + let targets = graph["targets"].as_object().unwrap(); + let compiles = |target: &serde_json::Value, source: &str| { + let source = serde_json::json!(source); + target["sources"].as_array().unwrap().contains(&source) + || target["unity_groups"].as_object().is_some_and(|groups| { + groups + .values() + .any(|g| g.as_array().unwrap().contains(&source)) + }) + }; + let consumers: Vec<_> = targets + .iter() + .filter(|(_, target)| compiles(target, ORIGINAL)) + .map(|(name, _)| name.as_str()) + .collect(); + assert_eq!(consumers, ["test_encoder_group_num_started"]); + let stub = "test/cmocka/output_interleave_fields_stub.c"; + let stub_text = fs::read_to_string(root.join(stub)).unwrap(); + assert!(stub_text.contains(&format!("uint32_t {SHIM}(struct obs_encoder_group *group)"))); + for (name, target) in targets { + if compiles(target, stub) { + let libraries = target["libraries"].to_string(); + assert!( + !libraries.contains("libobs_rust-static"), + "{name} defines {SHIM} and links the Rust archive" + ); + } + } +} + +/// The unchanged characterization keeps testing the original; its twin +/// compiles the same fixture with the same recorder definitions, without the +/// original, so the Rust shim locks and reads through the real adapters and +/// the test's recorders. +#[test] +fn canonical_encoder_group_num_started_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 c_test = "test_encoder_group_num_started"; + let rust_test = "test_encoder_group_num_started_rust"; + graph + .targets + .retain(|key, _| key == c_test || key == rust_test); + graph + .tests + .retain(|key, _| key == c_test || key == rust_test); + let test_source = "test/cmocka/test_encoder_group_num_started.c"; + let record = "test/cmocka/encoder-group-num-started-record-support.c"; + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + for available in [false, true] { + let facts = [ + (os.into(), true), + ("HAVE_LIBOBS_RUST_STATIC".into(), available), + ] + .into(); + let selected = graph.select(&facts).unwrap(); + assert!(matches!(selected.targets[c_test].sources.as_slice(), + [Source::Path(a), Source::Path(b)] if a == test_source && b == ORIGINAL)); + assert_eq!(selected.targets[c_test].definitions, DEFINITIONS); + assert_eq!(selected.tests[c_test].target, c_test); + assert_eq!(selected.targets.contains_key(rust_test), available); + if !available { + continue; + } + let target = &selected.targets[rust_test]; + assert!(matches!(target.sources.as_slice(), + [Source::Path(a), Source::Path(b)] if a == test_source && b == record)); + assert_eq!(target.definitions, DEFINITIONS); + assert_eq!(selected.tests[rust_test].target, rust_test); + } + } + files_are_wired(&root, record); +} + +/// Darwin binds an executable's calls by two-level namespace: a name +/// libobs.dylib exports would bind there, past the twin's own definitions +/// (#5226). The shim is hidden in both libraries and the adapters are never +/// exported, so the twin can only take the shim from the Rust archive and +/// the adapters (with the test's recorders) from its own objects. +#[test] +fn canonical_encoder_group_num_started_names_stay_private() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let names = |dir: &str| -> Vec { + let mut names = Vec::new(); + for entry in fs::read_dir(root.join(dir)).unwrap() { + let text = fs::read_to_string(entry.unwrap().path()).unwrap(); + names.extend( + text.lines() + .map(str::trim) + .filter(|line| !line.starts_with('#') && !line.is_empty()) + .map(str::to_owned), + ); + } + names + }; + let exports = names("libobs/cmake/rust-exports.d"); + let hidden = names("libobs/cmake/rust-hidden.d"); + assert!(hidden.iter().any(|name| name == SHIM)); + for name in std::iter::once(SHIM).chain(ADAPTERS) { + assert!( + !exports.iter().any(|export| export == name), + "{name} exported" + ); + } + let internal = fs::read_to_string(root.join("libobs/obs-internal.h")).unwrap(); + assert!(internal.contains(&format!( + "extern uint32_t {SHIM}(struct obs_encoder_group *group);" + ))); + let fields = fs::read_to_string(root.join(FIELDS)).unwrap(); + assert!(!fields.contains("EXPORT")); + for name in ADAPTERS { + assert!(fields.contains(name), "{name} missing from {FIELDS}"); + assert!( + !internal.contains(name), + "{name} declared in obs-internal.h" + ); + } +} + +/// The record support, the ported group, the hybrid group and the hidden list. +fn files_are_wired(root: &Path, record: &str) { + let fields = format!("#include \"{FIELDS}\""); + let record_text = fs::read_to_string(root.join(record)).unwrap(); + assert!(record_text.contains(&fields)); + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/encoder-group-num-started.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-encoder-group-num-started+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-encoder-group-num-started+.h.c")) + .unwrap(); + let original = format!("#include \"{ORIGINAL}\""); + assert!(group.contains(&original)); + let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core-output+.h.c")).unwrap(); + assert!(!hybrid.contains(&original)); + // The C-owned mutex and count stay in the core group. + assert!(hybrid.contains(&fields)); + let hidden = fs::read_to_string( + root.join("libobs/cmake/rust-hidden.d/obs-output-encoder_group_num_started.txt"), + ) + .unwrap(); + let names: Vec<_> = hidden + .lines() + .filter(|line| !line.starts_with('#') && !line.trim().is_empty()) + .collect(); + assert_eq!(names, [SHIM]); +} diff --git a/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_encoder_group_num_started_rust.json b/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_encoder_group_num_started_rust.json new file mode 100644 index 0000000000..c3e9f9ce25 --- /dev/null +++ b/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_encoder_group_num_started_rust.json @@ -0,0 +1,36 @@ +{ + "schema": 1, + "targets": { + "test_encoder_group_num_started_rust": { + "sources": [ + "test/cmocka/test_encoder_group_num_started.c", + "test/cmocka/encoder-group-num-started-record-support.c" + ], + "definitions": [ + "pthread_mutex_lock=encoder_group_count_record_lock", + "pthread_mutex_unlock=encoder_group_count_record_unlock" + ], + "libraries": [ + "libobs_rust-static", + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + } + }, + "tests": { + "test_encoder_group_num_started_rust": { + "target": "test_encoder_group_num_started_rust", + "command": [ + "${target}" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + } + } +} diff --git a/rust/obs-c-oracle/benches/port_comparison.rs b/rust/obs-c-oracle/benches/port_comparison.rs index 804064df99..6d4bfc1e0f 100644 --- a/rust/obs-c-oracle/benches/port_comparison.rs +++ b/rust/obs-c-oracle/benches/port_comparison.rs @@ -93,11 +93,6 @@ mod libobs_stand_ins { called("obs_output_interleave_encoder_name") } - #[unsafe(no_mangle)] - pub extern "C" fn obs_encoder_group_num_started() -> ! { - called("obs_encoder_group_num_started") - } - #[unsafe(no_mangle)] pub extern "C" fn obs_encoder_interleave_info() -> ! { called("obs_encoder_interleave_info") diff --git a/rust/obs-c-oracle/oracle/encoder_group_num_started.c b/rust/obs-c-oracle/oracle/encoder_group_num_started.c new file mode 100644 index 0000000000..87d5862921 --- /dev/null +++ b/rust/obs-c-oracle/oracle/encoder_group_num_started.c @@ -0,0 +1,273 @@ +/* Original obs_encoder_group_num_started() and the real-header adapters of + * obs-encoder-group-num-started-fields.c.h on two recording fixture groups. + * Under cargo test these adapters are the only definitions of their real + * names, so the Rust shim reaches this fixture. Every lock and unlock of the + * group mutex is recorded; either can rewrite the count, as the unchanged + * test_encoder_group_num_started.c does, so a read outside the pair, a + * second read or a value taken after the unlock shows. The probe runs the + * original and a candidate on the same case and reports any difference in + * the result, the trace or the groups left behind, instead of aborting, so + * mutants are observable. + * + * The interleave parity fixture (rust/obs-output/tests/output/ + * interleave_parity.rs) has groups of its own that the same shim reaches: + * it installs per-thread handlers, and the adapters forward every group that + * is not one of these two to them. One definition of each name serves both + * (the scene_enum_items.c shape). */ +/* The MSVC UCRT headers define snprintf and friends inline in every object + * that includes them, which lets a COFF link pull this member into an + * unrelated test; keep them declarations only. */ +#define _NO_CRT_STDIO_INLINE +#include "libobs/build/libobs.pch.h" +#include +#include + +#define EGNS_TRACE 64 + +/* Case flags: rewrite the count in the lock, in the unlock, and query the + * second group instead of the first. */ +#define EGNS_CHANGE_ON_LOCK 0x01 +#define EGNS_CHANGE_ON_UNLOCK 0x02 +#define EGNS_SECOND 0x04 + +typedef uint32_t (*egns_query_fn)(struct obs_encoder_group *group); +typedef void (*egns_foreign_fn)(void *group); +typedef uint32_t (*egns_foreign_read_fn)(const void *group); + +static _Thread_local struct obs_encoder_group egns_groups[2]; +static _Thread_local struct obs_encoder_group *egns_selected; +static _Thread_local bool egns_locked, egns_change_on_lock, egns_change_on_unlock; +static _Thread_local uint32_t egns_locked_value, egns_unlocked_value; +static _Thread_local char egns_trace[EGNS_TRACE]; +static _Thread_local size_t egns_trace_len; +static _Thread_local egns_foreign_fn egns_foreign_lock, egns_foreign_unlock; +static _Thread_local egns_foreign_read_fn egns_foreign_read; + +static void egns_event(char value) +{ + if (egns_trace_len + 1 < sizeof(egns_trace)) { + egns_trace[egns_trace_len++] = value; + egns_trace[egns_trace_len] = '\0'; + } +} + +static bool egns_selected_mutex(const pthread_mutex_t *mutex) +{ + return egns_selected && mutex == &egns_selected->mutex; +} + +/* 'L' and 'U'; '?' for another mutex, 'R' for a lock already held, 'X' for + * an unlock not held. */ +static int egns_lock(pthread_mutex_t *mutex) +{ + egns_event('L'); + if (!egns_selected_mutex(mutex)) + egns_event('?'); + if (egns_locked) + egns_event('R'); + egns_locked = true; + if (egns_change_on_lock && egns_selected) + egns_selected->num_encoders_started = egns_locked_value; + return 0; +} + +static int egns_unlock(pthread_mutex_t *mutex) +{ + egns_event('U'); + if (!egns_selected_mutex(mutex)) + egns_event('?'); + if (!egns_locked) + egns_event('X'); + if (egns_change_on_unlock && egns_selected) + egns_selected->num_encoders_started = egns_unlocked_value; + egns_locked = false; + return 0; +} + +uint32_t oracle_obs_encoder_group_num_started(struct obs_encoder_group *group); + +/* winpthreads defines the lock functions as macros: rename them to the + * recorders only for the original and the adapters. The adapters keep + * private names here; the real names below dispatch to them. */ +#pragma push_macro("pthread_mutex_lock") +#pragma push_macro("pthread_mutex_unlock") +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#define pthread_mutex_lock egns_lock +#define pthread_mutex_unlock egns_unlock +#define obs_encoder_group_num_started oracle_obs_encoder_group_num_started +#include "libobs/obs-encoder-group-num-started.c.h" +#undef obs_encoder_group_num_started +#define obs_encoder_group_num_started_lock egns_adapter_lock +#define obs_encoder_group_num_started_read egns_adapter_read +#define obs_encoder_group_num_started_unlock egns_adapter_unlock +#include "encoder_group_num_started_fields.inc" +#undef obs_encoder_group_num_started_unlock +#undef obs_encoder_group_num_started_read +#undef obs_encoder_group_num_started_lock +#pragma pop_macro("pthread_mutex_unlock") +#pragma pop_macro("pthread_mutex_lock") + +static bool egns_own(const struct obs_encoder_group *group) +{ + return group == &egns_groups[0] || group == &egns_groups[1]; +} + +/* Another fixture's groups on this thread go to its handlers; NULL clears + * them. */ +void oracle_encoder_group_num_started_foreign(egns_foreign_fn lock, egns_foreign_read_fn read, egns_foreign_fn unlock); +void oracle_encoder_group_num_started_foreign(egns_foreign_fn lock, egns_foreign_read_fn read, egns_foreign_fn unlock) +{ + egns_foreign_lock = lock; + egns_foreign_read = read; + egns_foreign_unlock = unlock; +} + +void obs_encoder_group_num_started_lock(struct obs_encoder_group *group); +void obs_encoder_group_num_started_lock(struct obs_encoder_group *group) +{ + if (!egns_own(group) && egns_foreign_lock) + egns_foreign_lock(group); + else + egns_adapter_lock(group); +} + +uint32_t obs_encoder_group_num_started_read(const struct obs_encoder_group *group); +uint32_t obs_encoder_group_num_started_read(const struct obs_encoder_group *group) +{ + if (!egns_own(group) && egns_foreign_read) + return egns_foreign_read(group); + return egns_adapter_read(group); +} + +void obs_encoder_group_num_started_unlock(struct obs_encoder_group *group); +void obs_encoder_group_num_started_unlock(struct obs_encoder_group *group) +{ + if (!egns_own(group) && egns_foreign_unlock) + egns_foreign_unlock(group); + else + egns_adapter_unlock(group); +} + +struct egns_case { + uint32_t first; + uint32_t second; + uint32_t on_lock; + uint32_t on_unlock; + uint8_t flags; +}; + +struct egns_result { + uint32_t value; + char trace[EGNS_TRACE]; + struct obs_encoder_group groups[2]; +}; + +/* The test's groups: both counts, and unrelated lifecycle state that must + * neither clamp nor gate the count. */ +static void egns_reset(const struct egns_case *c) +{ + memset(egns_groups, 0, sizeof(egns_groups)); + egns_groups[0].num_encoders_started = c->first; + egns_groups[1].num_encoders_started = c->second; + egns_groups[0].destroy_on_stop = true; + egns_groups[1].frame_rate_divisors_lcm = UINT32_MAX; + egns_selected = &egns_groups[(c->flags & EGNS_SECOND) ? 1 : 0]; + egns_change_on_lock = (c->flags & EGNS_CHANGE_ON_LOCK) != 0; + egns_change_on_unlock = (c->flags & EGNS_CHANGE_ON_UNLOCK) != 0; + egns_locked_value = c->on_lock; + egns_unlocked_value = c->on_unlock; + egns_locked = false; + egns_trace_len = 0; + egns_trace[0] = '\0'; +} + +/* The trace ends with 'K' if the call left the mutex held. */ +static void egns_run(egns_query_fn query, const struct egns_case *c, struct egns_result *out) +{ + egns_reset(c); + out->value = query(egns_selected); + if (egns_locked) + egns_event('K'); + memcpy(out->trace, egns_trace, sizeof(out->trace)); + memcpy(out->groups, egns_groups, sizeof(out->groups)); + egns_selected = NULL; + egns_locked = false; +} + +/* 0: match. 1: the results differ, 2: the traces differ, 4: the groups left + * differ, 0x100: bad arguments. */ +unsigned oracle_encoder_group_num_started_probe(egns_query_fn query, uint32_t first, uint32_t second, uint32_t on_lock, + uint32_t on_unlock, uint8_t flags); +unsigned oracle_encoder_group_num_started_probe(egns_query_fn query, uint32_t first, uint32_t second, uint32_t on_lock, + uint32_t on_unlock, uint8_t flags) +{ + static _Thread_local struct egns_result original, actual; + if (!query) + return 0x100; + const struct egns_case c = {first, second, on_lock, on_unlock, flags}; + egns_run(oracle_obs_encoder_group_num_started, &c, &original); + egns_run(query, &c, &actual); + unsigned diff = 0; + if (original.value != actual.value) + diff |= 1; + if (strcmp(original.trace, actual.trace) != 0) + diff |= 2; + if (memcmp(original.groups, actual.groups, sizeof(original.groups)) != 0) + diff |= 4; + return diff; +} + +/* The original's result, its trace and the queried group's count after the + * call, for the characterization checks. */ +uint32_t oracle_encoder_group_num_started_original(uint32_t first, uint32_t second, uint32_t on_lock, + uint32_t on_unlock, uint8_t flags, char *trace, size_t trace_size, + uint32_t *after); +uint32_t oracle_encoder_group_num_started_original(uint32_t first, uint32_t second, uint32_t on_lock, + uint32_t on_unlock, uint8_t flags, char *trace, size_t trace_size, + uint32_t *after) +{ + static _Thread_local struct egns_result result; + const struct egns_case c = {first, second, on_lock, on_unlock, flags}; + egns_run(oracle_obs_encoder_group_num_started, &c, &result); + if (trace_size) { + size_t n = strlen(result.trace); + if (n >= trace_size) + n = trace_size - 1; + memcpy(trace, result.trace, n); + trace[n] = '\0'; + } + if (after) + *after = result.groups[(flags & EGNS_SECOND) ? 1 : 0].num_encoders_started; + return result.value; +} + +/* Where the real header puts the fields the adapters touch. */ +void oracle_encoder_group_num_started_layout(size_t *mutex, size_t *count, size_t *count_size); +void oracle_encoder_group_num_started_layout(size_t *mutex, size_t *count, size_t *count_size) +{ + *mutex = offsetof(struct obs_encoder_group, mutex); + *count = offsetof(struct obs_encoder_group, num_encoders_started); + *count_size = sizeof(((struct obs_encoder_group *)0)->num_encoders_started); +} + +/* The adapters against the real fields: the lock and unlock on the group's + * own mutex, and a read of exactly num_encoders_started, which changes + * nothing. */ +bool oracle_encoder_group_num_started_adapters(void); +bool oracle_encoder_group_num_started_adapters(void) +{ + const struct egns_case c = {0x12345678u, 0x9abcdef0u, 0, 0, EGNS_SECOND}; + egns_reset(&c); + unsigned char before[sizeof(egns_groups)]; + memcpy(before, egns_groups, sizeof(egns_groups)); + struct obs_encoder_group *group = &egns_groups[1]; + obs_encoder_group_num_started_lock(group); + bool ok = egns_locked && obs_encoder_group_num_started_read(group) == 0x9abcdef0u && + obs_encoder_group_num_started_read(&egns_groups[0]) == 0x12345678u; + obs_encoder_group_num_started_unlock(group); + ok = ok && !egns_locked && strcmp(egns_trace, "LU") == 0; + ok = ok && memcmp(before, egns_groups, sizeof(egns_groups)) == 0; + egns_selected = NULL; + return ok; +} diff --git a/rust/obs-output/src/encoder_group_num_started.rs b/rust/obs-output/src/encoder_group_num_started.rs new file mode 100644 index 0000000000..997db5098a --- /dev/null +++ b/rust/obs-output/src/encoder_group_num_started.rs @@ -0,0 +1,41 @@ +//! Safe core of `libobs/obs-encoder-group-num-started.c.h`: +//! `obs_encoder_group_num_started()`, the number of a group's encoders that +//! have started. +//! +//! The group's mutex is taken once, the count read once while it is held, +//! and the mutex released once; the value read under the lock is returned, +//! whatever the count becomes after the unlock. The full `uint32_t` range +//! passes through unchanged: no other group state clamps or gates it. The +//! group itself, its mutex and its count stay with the caller; the group is +//! never NULL (the C precondition), so there is no NULL case to decide. + +#![deny( + clippy::arithmetic_side_effects, + clippy::as_conversions, + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + +/// An encoder group as the count query sees it: `group->mutex` and +/// `group->num_encoders_started`. +pub trait StartedCount { + /// Take the group's mutex. + fn lock(&mut self); + /// One read of `num_encoders_started`. + fn read(&mut self) -> u32; + /// Release the group's mutex. + fn unlock(&mut self); +} + +/// The group's started-encoder count, read under its mutex. +pub fn num_started(group: &mut G) -> u32 { + group.lock(); + let num_started = group.read(); + group.unlock(); + num_started +} diff --git a/rust/obs-output/src/ffi/encoder_group_num_started.rs b/rust/obs-output/src/ffi/encoder_group_num_started.rs new file mode 100644 index 0000000000..d9a9ed5afe --- /dev/null +++ b/rust/obs-output/src/ffi/encoder_group_num_started.rs @@ -0,0 +1,47 @@ +//! `obs_encoder_group_num_started()` over C-owned state: the group's +//! `mutex` and `num_encoders_started`, behind the private adapters of +//! `libobs/obs-encoder-group-num-started-fields.c.h`. +//! +//! Declared in `obs-internal.h` without `EXPORT`, so the shim stays hidden +//! (`rust-hidden.d/obs-output-encoder_group_num_started.txt`). The lock, the +//! one read and the unlock are the safe core's +//! ([`crate::encoder_group_num_started`]); Rust never sees the group's layout +//! or its pthread mutex. +use core::ffi::c_void; + +unsafe extern "C" { + fn obs_encoder_group_num_started_lock(group: *mut c_void); + fn obs_encoder_group_num_started_read(group: *const c_void) -> u32; + fn obs_encoder_group_num_started_unlock(group: *mut c_void); +} + +/// A live group, never NULL (the C precondition, which this keeps: the +/// pointer goes to the adapters unchecked, as the original dereferences it). +struct Group(*mut c_void); + +impl crate::encoder_group_num_started::StartedCount for Group { + fn lock(&mut self) { + // SAFETY: the caller's live group, its mutex initialized and not held + // by this thread; the core locks once and unlocks once. + unsafe { obs_encoder_group_num_started_lock(self.0) } + } + fn read(&mut self) -> u32 { + // SAFETY: read under the group's mutex, which `lock` holds. + unsafe { obs_encoder_group_num_started_read(self.0) } + } + fn unlock(&mut self) { + // SAFETY: called once, after `lock`. + unsafe { obs_encoder_group_num_started_unlock(self.0) } + } +} + +/// The number of the group's encoders that have started, read under the +/// group's mutex. +/// +/// # Safety +/// As for the C function: `group` is a live encoder group, not NULL, with +/// its mutex initialized and not held by this thread. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_encoder_group_num_started(group: *mut c_void) -> u32 { + crate::encoder_group_num_started::num_started(&mut Group(group)) +} diff --git a/rust/obs-output/src/ffi/mod.rs b/rust/obs-output/src/ffi/mod.rs index 3894bd4ab6..5a2897f3eb 100644 --- a/rust/obs-output/src/ffi/mod.rs +++ b/rust/obs-output/src/ffi/mod.rs @@ -16,6 +16,7 @@ pub mod encoder_gpu_gates; pub mod encoder_gpu_rescale; pub mod encoder_gpu_scaling_getters; pub mod encoder_group_lifecycle; +pub mod encoder_group_num_started; pub mod encoder_group_reconfig; pub mod encoder_init; pub mod encoder_last_error; diff --git a/rust/obs-output/src/lib.rs b/rust/obs-output/src/lib.rs index 78cfe7b888..9358e7ab43 100644 --- a/rust/obs-output/src/lib.rs +++ b/rust/obs-output/src/lib.rs @@ -162,6 +162,7 @@ pub mod encoder_gpu_gates; pub mod encoder_gpu_rescale; pub mod encoder_gpu_scaling_getters; pub mod encoder_group_lifecycle; +pub mod encoder_group_num_started; pub mod encoder_group_reconfig; pub mod encoder_init; pub mod encoder_last_error; diff --git a/rust/obs-output/tests/output/encoder_group_num_started.rs b/rust/obs-output/tests/output/encoder_group_num_started.rs new file mode 100644 index 0000000000..45a62497a9 --- /dev/null +++ b/rust/obs-output/tests/output/encoder_group_num_started.rs @@ -0,0 +1,182 @@ +//! Tier 1: `obs_output::encoder_group_num_started`, the safe core of +//! `obs_encoder_group_num_started()`. +//! +//! The `characterization_*` cases port every assertion of the unchanged +//! `test/cmocka/test_encoder_group_num_started.c` onto two recording groups, +//! its two cases one for one: each query locks the selected group's mutex +//! exactly once and unlocks it exactly once, never nested and never the other +//! group's; the exact count comes back over the full `u32` range (0, 1, 2, +//! 32, `u32::MAX - 1`, `u32::MAX`) for the queried group and its complement +//! for the other, with unrelated lifecycle state set and nothing in either +//! group changed; and a count rewritten by the lock and again by the unlock +//! returns the value seen under the lock and leaves the unlock's value. +//! +//! The `edge_*` cases are new: the one read happens between the one lock +//! and the one unlock, in that order, and a proptest over any count and any +//! rewrite in the lock or the unlock against the C's snapshot rule. + +use obs_output::encoder_group_num_started::{StartedCount, num_started}; +use proptest::prelude::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Event { + Lock(usize), + Read(usize), + Unlock(usize), +} + +/// `struct obs_encoder_group` as the C test sets it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Group { + num_encoders_started: u32, + destroy_on_stop: bool, + frame_rate_divisors_lcm: u32, +} + +/// The C test's statics: both groups, the selected one, the call counts, +/// the lock state and the rewrites the lock and unlock make. +#[derive(Debug, Default)] +struct Fixture { + groups: [Group; 2], + selected: Option, + lock_calls: u32, + unlock_calls: u32, + locked: bool, + change_on_lock: bool, + change_on_unlock: bool, + locked_value: u32, + unlocked_value: u32, + events: Vec, +} + +/// The `struct obs_encoder_group *` the query was given. +struct Query<'a> { + fixture: &'a mut Fixture, + group: usize, +} + +impl StartedCount for Query<'_> { + /// The test's `pthread_mutex_lock()`. + fn lock(&mut self) { + let f = &mut *self.fixture; + assert_eq!(Some(self.group), f.selected, "the selected group's mutex"); + assert!(!f.locked); + assert_eq!(f.lock_calls, 0); + assert_eq!(f.unlock_calls, 0); + f.lock_calls += 1; + f.locked = true; + if f.change_on_lock { + f.groups[self.group].num_encoders_started = f.locked_value; + } + f.events.push(Event::Lock(self.group)); + } + fn read(&mut self) -> u32 { + let f = &mut *self.fixture; + f.events.push(Event::Read(self.group)); + f.groups[self.group].num_encoders_started + } + /// The test's `pthread_mutex_unlock()`. + fn unlock(&mut self) { + let f = &mut *self.fixture; + assert_eq!(Some(self.group), f.selected, "the selected group's mutex"); + assert!(f.locked); + assert_eq!(f.lock_calls, 1); + assert_eq!(f.unlock_calls, 0); + f.unlock_calls += 1; + if f.change_on_unlock { + f.groups[self.group].num_encoders_started = f.unlocked_value; + } + f.locked = false; + f.events.push(Event::Unlock(self.group)); + } +} + +/// `query()`. +fn query(fixture: &mut Fixture, group: usize) -> u32 { + fixture.selected = Some(group); + fixture.lock_calls = 0; + fixture.unlock_calls = 0; + let result = num_started(&mut Query { fixture, group }); + assert_eq!(fixture.lock_calls, 1); + assert_eq!(fixture.unlock_calls, 1); + assert!(!fixture.locked); + result +} + +/// `setup()`. +fn setup() -> Fixture { + Fixture::default() +} + +#[test] +fn characterization_exact_count_and_group() { + let mut f = setup(); + for value in [0, 1, 2, 32, u32::MAX - 1, u32::MAX] { + f.groups[0].num_encoders_started = value; + f.groups[1].num_encoders_started = !value; + // Unrelated lifecycle state must not clamp or gate the count. + f.groups[0].destroy_on_stop = true; + f.groups[1].frame_rate_divisors_lcm = u32::MAX; + let before = f.groups; + assert_eq!(query(&mut f, 0), value); + assert_eq!(query(&mut f, 1), !value); + assert_eq!(f.groups, before); + } +} + +#[test] +fn characterization_snapshot_inside_mutex_calls() { + let mut f = setup(); + f.change_on_lock = true; + f.change_on_unlock = true; + for value in [0, 1, u32::MAX] { + f.locked_value = value; + f.unlocked_value = !value; + f.groups[0].num_encoders_started = f.unlocked_value; + assert_eq!(query(&mut f, 0), value); + assert_eq!(f.groups[0].num_encoders_started, f.unlocked_value); + } +} + +#[test] +fn edge_one_read_between_the_lock_and_the_unlock() { + for group in [0, 1] { + let mut f = setup(); + f.groups[group].num_encoders_started = 7; + assert_eq!(query(&mut f, group), 7); + assert_eq!( + f.events, + [Event::Lock(group), Event::Read(group), Event::Unlock(group)] + ); + } +} + +proptest! { + #[test] + fn edge_any_count_returns_the_value_under_the_lock( + start in any::(), + other in any::(), + on_lock in prop::option::of(any::()), + on_unlock in prop::option::of(any::()), + group in 0..2usize, + ) { + let mut f = setup(); + f.groups[group].num_encoders_started = start; + f.groups[1 - group].num_encoders_started = other; + f.change_on_lock = on_lock.is_some(); + f.locked_value = on_lock.unwrap_or(0); + f.change_on_unlock = on_unlock.is_some(); + f.unlocked_value = on_unlock.unwrap_or(0); + let result = query(&mut f, group); + prop_assert_eq!(result, on_lock.unwrap_or(start)); + prop_assert_eq!( + f.groups[group].num_encoders_started, + on_unlock.or(on_lock).unwrap_or(start) + ); + prop_assert_eq!(f.groups[1 - group].num_encoders_started, other); + prop_assert_eq!( + &f.events, + &[Event::Lock(group), Event::Read(group), Event::Unlock(group)] + ); + } +} diff --git a/rust/obs-output/tests/output/encoder_group_num_started_parity.rs b/rust/obs-output/tests/output/encoder_group_num_started_parity.rs new file mode 100644 index 0000000000..0d9f5accc4 --- /dev/null +++ b/rust/obs-output/tests/output/encoder_group_num_started_parity.rs @@ -0,0 +1,260 @@ +//! Tier 3: the original extracted `obs_encoder_group_num_started()` versus +//! the shim on two recording fixture groups +//! (oracle/encoder_group_num_started.c), through the real-named adapters. +//! Compared: the value returned, every lock and unlock of the group mutex +//! (the queried group's own, never nested, none left held), and both groups +//! byte for byte afterwards, over any counts, with the count rewritten by +//! the lock, the unlock, both or neither, so a read outside the pair or a +//! second read shows. +//! +//! The real-header layout check pins the two fields the adapters touch, and +//! the adapters are checked against the real struct. +//! +//! No intentional differences. Mutants show the probe catches a read before +//! the lock, a read after the unlock, a missing lock, a missing unlock, and +//! a count clamped to `i32::MAX` or to 16 bits. +#![allow(unsafe_code)] +use core::ffi::{CStr, c_char, c_void}; +use obs_output::ffi::encoder_group_num_started::obs_encoder_group_num_started; +use proptest::prelude::*; + +type Query = unsafe extern "C" fn(*mut c_void) -> u32; +unsafe extern "C" { + fn oracle_encoder_group_num_started_probe( + query: Query, + first: u32, + second: u32, + on_lock: u32, + on_unlock: u32, + flags: u8, + ) -> u32; + fn oracle_encoder_group_num_started_original( + first: u32, + second: u32, + on_lock: u32, + on_unlock: u32, + flags: u8, + trace: *mut c_char, + trace_size: usize, + after: *mut u32, + ) -> u32; + fn oracle_encoder_group_num_started_layout( + mutex: *mut usize, + count: *mut usize, + count_size: *mut usize, + ); + fn oracle_encoder_group_num_started_adapters() -> bool; + fn obs_encoder_group_num_started_lock(group: *mut c_void); + fn obs_encoder_group_num_started_read(group: *const c_void) -> u32; + fn obs_encoder_group_num_started_unlock(group: *mut c_void); +} + +/// Case flags, as the oracle reads them. +const ON_LOCK: u8 = 0x01; +const ON_UNLOCK: u8 = 0x02; +const SECOND: u8 = 0x04; + +/// The test's counts. +const VALUES: [u32; 6] = [0, 1, 2, 32, u32::MAX - 1, u32::MAX]; + +fn probe(query: Query, first: u32, second: u32, on_lock: u32, on_unlock: u32, flags: u8) -> u32 { + // SAFETY: the oracle owns the fixture groups every candidate reaches. + unsafe { + oracle_encoder_group_num_started_probe(query, first, second, on_lock, on_unlock, flags) + } +} + +/// The original's result, trace (`L` lock, `U` unlock, `K` left held) and +/// the queried group's count afterwards. +fn original( + first: u32, + second: u32, + on_lock: u32, + on_unlock: u32, + flags: u8, +) -> (u32, String, u32) { + let mut trace = [0 as c_char; 64]; + let mut after = 0; + // SAFETY: the buffer and `after` are writable; the oracle writes + // NUL-terminated text. + let value = unsafe { + oracle_encoder_group_num_started_original( + first, + second, + on_lock, + on_unlock, + flags, + trace.as_mut_ptr(), + trace.len(), + &raw mut after, + ) + }; + // SAFETY: NUL-terminated by the oracle. + let trace = unsafe { CStr::from_ptr(trace.as_ptr()) } + .to_str() + .unwrap() + .to_owned(); + (value, trace, after) +} + +#[test] +fn real_header_layout_and_adapters() { + let (mut mutex, mut count, mut count_size) = (usize::MAX, 0, 0); + // SAFETY: three writable sizes. + unsafe { + oracle_encoder_group_num_started_layout(&raw mut mutex, &raw mut count, &raw mut count_size) + }; + // The mutex leads the struct; the count is a full uint32_t after it. + assert_eq!(mutex, 0); + assert!(count > mutex); + assert_eq!(count_size, size_of::()); + // SAFETY: the oracle checks the adapters on its own fixture. + assert!(unsafe { oracle_encoder_group_num_started_adapters() }); +} + +#[test] +fn original_matches_the_characterization() { + // exact_count_and_group + for value in VALUES { + assert_eq!( + original(value, !value, 0, 0, 0), + (value, "LU".into(), value) + ); + assert_eq!( + original(value, !value, 0, 0, SECOND), + (!value, "LU".into(), !value) + ); + } + // snapshot_inside_mutex_calls + for value in [0, 1, u32::MAX] { + assert_eq!( + original(!value, 0, value, !value, ON_LOCK | ON_UNLOCK), + (value, "LU".into(), !value) + ); + } +} + +#[test] +fn characterized_edges() { + for first in VALUES { + for second in [0, u32::MAX] { + for flags in 0..8u8 { + for (on_lock, on_unlock) in [(1, 2), (u32::MAX, 0), (0, u32::MAX)] { + assert_eq!( + probe( + obs_encoder_group_num_started, + first, + second, + on_lock, + on_unlock, + flags + ), + 0, + "{first} {second} {on_lock} {on_unlock} {flags:#x}" + ); + } + } + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(512), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn any_case_matches_c( + first in any::(), + second in any::(), + on_lock in any::(), + on_unlock in any::(), + flags in 0..8u8, + ) { + prop_assert_eq!(probe(obs_encoder_group_num_started, first, second, on_lock, on_unlock, flags), 0); + } +} + +// --------------------------------------------------------------------------- +// mutants, over the same adapters + +/// The unbroken steps, written directly over the adapters. +unsafe extern "C" fn unbroken(group: *mut c_void) -> u32 { + // SAFETY: mutants run only inside the probe, on its fixture groups. + unsafe { + obs_encoder_group_num_started_lock(group); + let value = obs_encoder_group_num_started_read(group); + obs_encoder_group_num_started_unlock(group); + value + } +} + +unsafe extern "C" fn read_before_lock(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`. + unsafe { + let value = obs_encoder_group_num_started_read(group); + obs_encoder_group_num_started_lock(group); + obs_encoder_group_num_started_unlock(group); + value + } +} + +unsafe extern "C" fn read_after_unlock(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`. + unsafe { + obs_encoder_group_num_started_lock(group); + obs_encoder_group_num_started_unlock(group); + obs_encoder_group_num_started_read(group) + } +} + +unsafe extern "C" fn without_lock(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`. + unsafe { + let value = obs_encoder_group_num_started_read(group); + obs_encoder_group_num_started_unlock(group); + value + } +} + +unsafe extern "C" fn without_unlock(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`; the probe records the mutex left held. + unsafe { + obs_encoder_group_num_started_lock(group); + obs_encoder_group_num_started_read(group) + } +} + +unsafe extern "C" fn clamped_to_i32(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`. + let value = unsafe { unbroken(group) }; + value.min(i32::MAX.unsigned_abs()) +} + +unsafe extern "C" fn clamped_to_u16(group: *mut c_void) -> u32 { + // SAFETY: as in `unbroken`. + let value = unsafe { unbroken(group) }; + value.min(u32::from(u16::MAX)) +} + +#[test] +fn mutants_are_caught() { + let sweep = |query: Query| { + let mut diff = 0; + for first in VALUES { + for flags in 0..8u8 { + diff |= probe(query, first, !first, first ^ 1, first ^ 2, flags); + } + } + diff + }; + // The unbroken model of the steps passes the same sweep. + assert_eq!(sweep(unbroken), 0); + for (name, mutant) in [ + ("read_before_lock", read_before_lock as Query), + ("read_after_unlock", read_after_unlock), + ("without_lock", without_lock), + ("without_unlock", without_unlock), + ("clamped_to_i32", clamped_to_i32), + ("clamped_to_u16", clamped_to_u16), + ] { + assert_ne!(sweep(mutant), 0, "{name} survived"); + } +} diff --git a/rust/obs-output/tests/output/interleave_parity.rs b/rust/obs-output/tests/output/interleave_parity.rs index 38f68656b6..c26c42f7e3 100644 --- a/rust/obs-output/tests/output/interleave_parity.rs +++ b/rust/obs-output/tests/output/interleave_parity.rs @@ -6,12 +6,17 @@ //! //! Both sides run on a test output ([`Fixture`]) through the same stand-ins //! defined here: the accessors `obs_output_interleave_fields`, -//! `obs_output_caption_track_fields`, `obs_encoder_interleave_info` and -//! `obs_encoder_group_num_started`, the `obs-output.c` wrappers (`active`, -//! the two first-encoder-index helpers, `add_caption`), the output's -//! `encoded_packet`, its packet callbacks and the two name getters. The -//! packet copy and release are the real ones obs-encoder exports, counted -//! as the delay parity counts them. Each stand-in records its call, +//! `obs_output_caption_track_fields` and `obs_encoder_interleave_info`, the +//! `obs-output.c` wrappers (`active`, the two first-encoder-index helpers, +//! `add_caption`), the output's `encoded_packet`, its packet callbacks and +//! the two name getters. The packet copy and release are the real ones +//! obs-encoder exports, counted as the delay parity counts them, and the +//! group's started count is the real `obs_encoder_group_num_started` that +//! obs-output exports: its adapters forward this fixture's groups to the +//! group handlers here (installed per thread through +//! `oracle_encoder_group_num_started_foreign`, which shares the one +//! definition of each adapter with the count's own parity test). Each +//! stand-in records its call, //! with whether `interleaved_mutex`, `pkt_callbacks_mutex` and the caption //! mutex were held, into the output it was given. `add_caption` and the //! packet callbacks change the packet (and the callbacks the packet time), @@ -274,10 +279,11 @@ struct Encoder { name: CString, } -/// An encoder group: its started count. +/// An encoder group: its started count, and whether its mutex is held. struct Group { owner: *mut Fixture, num_started: u32, + locked: bool, } /// The encoders of a run. @@ -425,6 +431,7 @@ impl Fixture { group: Box::new(Group { owner: ptr::null_mut(), num_started: 2, + locked: false, }), active: true, add_caption_result: true, @@ -434,6 +441,7 @@ impl Fixture { let me: *mut Fixture = &raw mut *f; f.data = me.cast(); f.group.owner = me; + install_group_handlers(); for i in 0..setup.videos { f.video_encoders[i] = (&raw mut f.encoders[i]).cast(); } @@ -644,6 +652,18 @@ impl Drop for Fixture { unsafe extern "C" { fn os_gettime_ns() -> u64; + fn oracle_encoder_group_num_started_foreign( + lock: unsafe extern "C" fn(*mut c_void), + read: unsafe extern "C" fn(*const c_void) -> u32, + unlock: unsafe extern "C" fn(*mut c_void), + ); +} + +/// Send this thread's fixture groups, reached through the real +/// `obs_encoder_group_num_started`, to the handlers below. +fn install_group_handlers() { + // SAFETY: plain function pointers, kept per thread by the oracle. + unsafe { oracle_encoder_group_num_started_foreign(group_lock, group_read, group_unlock) }; } #[derive(Debug, Clone, PartialEq, Eq)] @@ -889,16 +909,29 @@ pub unsafe extern "C" fn obs_encoder_interleave_info( unsafe { (*encoder.cast::()).info } } -/// `obs_encoder_group_num_started`, recorded. +/// The group adapter `obs_encoder_group_num_started_lock`, over a fixture's +/// group. /// /// # Safety /// /// `group` is a live fixture's group. -#[unsafe(no_mangle)] -pub unsafe extern "C" fn obs_encoder_group_num_started(group: *mut c_void) -> u32 { +unsafe extern "C" fn group_lock(group: *mut c_void) { + // SAFETY: caller contract. + let g = unsafe { &mut *group.cast::() }; + assert!(!g.locked, "the group mutex is not nested"); + g.locked = true; +} + +/// The group adapter `obs_encoder_group_num_started_read`, recorded. +/// +/// # Safety +/// +/// `group` is a live fixture's group. +unsafe extern "C" fn group_read(group: *const c_void) -> u32 { // SAFETY: caller contract; the owner is the fixture the step runs on. unsafe { let g = &*group.cast::(); + assert!(g.locked, "the count is read under the group mutex"); let o = &mut *g.owner; let locked = held(o.mutex); o.events.push(Event::NumStarted { group: 0, locked }); @@ -906,6 +939,18 @@ pub unsafe extern "C" fn obs_encoder_group_num_started(group: *mut c_void) -> u3 } } +/// The group adapter `obs_encoder_group_num_started_unlock`. +/// +/// # Safety +/// +/// `group` is a live fixture's group. +unsafe extern "C" fn group_unlock(group: *mut c_void) { + // SAFETY: caller contract. + let g = unsafe { &mut *group.cast::() }; + assert!(g.locked, "the group mutex is held"); + g.locked = false; +} + /// `obs_output_interleave_output_name`. /// /// # Safety diff --git a/rust/obs-output/tests/output/main.rs b/rust/obs-output/tests/output/main.rs index f3dc38d335..1ed5f15cbd 100644 --- a/rust/obs-output/tests/output/main.rs +++ b/rust/obs-output/tests/output/main.rs @@ -37,6 +37,8 @@ mod encoder_gpu_scaling_getters; mod encoder_gpu_scaling_getters_parity; mod encoder_group_lifecycle; mod encoder_group_lifecycle_parity; +mod encoder_group_num_started; +mod encoder_group_num_started_parity; mod encoder_group_reconfig; mod encoder_group_reconfig_parity; mod encoder_init; diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index cb880da0ee..a7eb798f21 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -3865,6 +3865,28 @@ } ] }, + "test_encoder_group_num_started_rust": { + "sources": [ + "test/cmocka/test_encoder_group_num_started.c", + "test/cmocka/encoder-group-num-started-record-support.c" + ], + "definitions": [ + "pthread_mutex_lock=encoder_group_count_record_lock", + "pthread_mutex_unlock=encoder_group_count_record_unlock" + ], + "libraries": [ + "libobs_rust-static", + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + }, "test_encoder_group_reconfig_steps": { "sources": [ "test/cmocka/test_encoder_group_reconfig_steps.c", @@ -24152,6 +24174,13 @@ "${target}" ] }, + "test_encoder_group_num_started_rust": { + "target": "test_encoder_group_num_started_rust", + "command": [ + "${target}" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC" + }, "test_encoder_group_reconfig_steps": { "target": "test_encoder_group_reconfig_steps", "command": [ diff --git a/test/cmocka/encoder-group-num-started-record-support.c b/test/cmocka/encoder-group-num-started-record-support.c new file mode 100644 index 0000000000..c58288e0ce --- /dev/null +++ b/test/cmocka/encoder-group-num-started-record-support.c @@ -0,0 +1,6 @@ +/* test_encoder_group_num_started_rust: the real private group-count + * adapters, compiled with the unchanged characterization's own definitions + * (pthread_mutex_lock=encoder_group_count_record_lock and the unlock), so + * they lock and unlock through the test's recorders exactly as the C target + * binds the original. */ +#include "libobs/obs-encoder-group-num-started-fields.c.h"