diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index e48e40891f..d39e2b30ef 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -80,6 +80,7 @@ #include "libobs/obs-source-filter-relationship-fields.c.h" #include "libobs/obs-source-flags-mixers-fields.c.h" #include "libobs/obs-source-frame-wrappers-fields.c.h" +#include "libobs/obs-source-get-release-frame-fields.c.h" #include "libobs/obs-source-get-weak-fields.c.h" #include "libobs/obs-source-handler-getters-fields.c.h" #include "libobs/obs-source-hidden-setter-fields.c.h" diff --git a/libobs/build/libobs.ported-source-get-release-frame+.h.c b/libobs/build/libobs.ported-source-get-release-frame+.h.c new file mode 100644 index 0000000000..1586b44c66 --- /dev/null +++ b/libobs/build/libobs.ported-source-get-release-frame+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original obs_source_get_frame and obs_source_release_frame for C reference. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-get-release-frame.c.h" diff --git a/libobs/build/ported-source-sets/source-get-release-frame.json b/libobs/build/ported-source-sets/source-get-release-frame.json new file mode 100644 index 0000000000..19824c8aba --- /dev/null +++ b/libobs/build/ported-source-sets/source-get-release-frame.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-get-release-frame+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-source-source_get_release_frame.txt b/libobs/cmake/rust-exports.d/obs-source-source_get_release_frame.txt new file mode 100644 index 0000000000..af8664cbd4 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-source-source_get_release_frame.txt @@ -0,0 +1,2 @@ +obs_source_get_frame +obs_source_release_frame diff --git a/libobs/obs-internal.h b/libobs/obs-internal.h index f8224aefde..14e59f21ee 100644 --- a/libobs/obs-internal.h +++ b/libobs/obs-internal.h @@ -1899,6 +1899,16 @@ extern bool obs_source_frame_wrappers_destroying(obs_source_t *source); extern void obs_source_frame_wrappers_output(obs_source_t *source, const struct obs_source_frame *frame); extern void obs_source_frame_wrappers_preload(obs_source_t *source, const struct obs_source_frame *frame); extern void obs_source_frame_wrappers_set(obs_source_t *source, const struct obs_source_frame *frame); +/* Async frame adapters for the Rust obs_source_get_frame() and + * obs_source_release_frame() (obs-source-get-release-frame-fields.c.h). + * Non-NULL only. */ +extern void obs_source_async_frame_lock(obs_source_t *source); +extern void obs_source_async_frame_unlock(obs_source_t *source); +extern struct obs_source_frame *obs_source_async_frame_take_current(obs_source_t *source); +extern void obs_source_async_frame_addref(struct obs_source_frame *frame); +extern bool obs_source_async_frame_release_ref(struct obs_source_frame *frame); +extern void obs_source_async_frame_destroy(struct obs_source_frame *frame); +extern void obs_source_async_frame_return(obs_source_t *source, struct obs_source_frame *frame); extern void set_deinterlace_texture_size(obs_source_t *source); extern void deinterlace_process_last_frame(obs_source_t *source, uint64_t sys_time); diff --git a/libobs/obs-source-get-release-frame-fields.c.h b/libobs/obs-source-get-release-frame-fields.c.h new file mode 100644 index 0000000000..34c7d5b328 --- /dev/null +++ b/libobs/obs-source-get-release-frame-fields.c.h @@ -0,0 +1,59 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters of the Rust obs_source_get_frame() and + * obs_source_release_frame() (obs-internal.h), each the line of + * obs-source-get-release-frame.c.h it stands for. NULL is rejected first. */ + +void obs_source_async_frame_lock(obs_source_t *source) +{ + pthread_mutex_lock(&source->async_mutex); +} + +void obs_source_async_frame_unlock(obs_source_t *source) +{ + pthread_mutex_unlock(&source->async_mutex); +} + +struct obs_source_frame *obs_source_async_frame_take_current(obs_source_t *source) +{ + struct obs_source_frame *frame = source->cur_async_frame; + source->cur_async_frame = NULL; + return frame; +} + +void obs_source_async_frame_addref(struct obs_source_frame *frame) +{ + os_atomic_inc_long(&frame->refs); +} + +bool obs_source_async_frame_release_ref(struct obs_source_frame *frame) +{ + return os_atomic_dec_long(&frame->refs) == 0; +} + +void obs_source_async_frame_destroy(struct obs_source_frame *frame) +{ + obs_source_frame_destroy(frame); +} + +void obs_source_async_frame_return(obs_source_t *source, struct obs_source_frame *frame) +{ + remove_async_frame(source, frame); +} + +/* Moved unchanged from obs-source.c.h, so the adapters' closure is one + * file for Rust-static consumers. */ +void remove_async_frame(obs_source_t *source, struct obs_source_frame *frame) +{ + if (frame) + frame->prev_frame = false; + + for (size_t i = 0; i < source->async_cache.num; i++) { + struct async_frame *f = &source->async_cache.array[i]; + + if (f->frame == frame) { + f->used = false; + break; + } + } +} diff --git a/libobs/obs-source-get-release-frame.c.h b/libobs/obs-source-get-release-frame.c.h new file mode 100644 index 0000000000..a7468e3622 --- /dev/null +++ b/libobs/obs-source-get-release-frame.c.h @@ -0,0 +1,47 @@ +#include "libobs/build/libobs.pch.h" + +/* + * Ensures that cached frames are displayed on time. If multiple frames + * were cached between renders, then releases the unnecessary frames and uses + * the frame with the closest timing to ensure sync. Also ensures that timing + * with audio is synchronized. + */ +struct obs_source_frame *obs_source_get_frame(obs_source_t *source) +{ + struct obs_source_frame *frame = NULL; + + if (!obs_source_valid(source, "obs_source_get_frame")) + return NULL; + + pthread_mutex_lock(&source->async_mutex); + + frame = source->cur_async_frame; + source->cur_async_frame = NULL; + + if (frame) { + os_atomic_inc_long(&frame->refs); + } + + pthread_mutex_unlock(&source->async_mutex); + + return frame; +} + +void obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame) +{ + if (!frame) + return; + + if (!source) { + obs_source_frame_destroy(frame); + } else { + pthread_mutex_lock(&source->async_mutex); + + if (os_atomic_dec_long(&frame->refs) == 0) + obs_source_frame_destroy(frame); + else + remove_async_frame(source, frame); + + pthread_mutex_unlock(&source->async_mutex); + } +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index a8cb9fab92..847f43c155 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -2461,21 +2461,6 @@ _Static_assert(OBS_SOURCE_AUDIO_INPUT_LINEAR == OBS_BALANCE_TYPE_LINEAR, "OBS_BA _Static_assert(sizeof(enum audio_format) == sizeof(int), "enum audio_format is passed as int"); _Static_assert(sizeof(enum speaker_layout) == sizeof(int), "enum speaker_layout is passed as int"); -void remove_async_frame(obs_source_t *source, struct obs_source_frame *frame) -{ - if (frame) - frame->prev_frame = false; - - for (size_t i = 0; i < source->async_cache.num; i++) { - struct async_frame *f = &source->async_cache.array[i]; - - if (f->frame == frame) { - f->used = false; - break; - } - } -} - /* obs-source-async-pacing.c decides with the same threshold */ _Static_assert(OBS_SOURCE_ASYNC_PACING_MAX_TS_VAR == MAX_TS_VAR, "MAX_TS_VAR"); @@ -2525,52 +2510,6 @@ static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, u return frame; } -/* - * Ensures that cached frames are displayed on time. If multiple frames - * were cached between renders, then releases the unnecessary frames and uses - * the frame with the closest timing to ensure sync. Also ensures that timing - * with audio is synchronized. - */ -struct obs_source_frame *obs_source_get_frame(obs_source_t *source) -{ - struct obs_source_frame *frame = NULL; - - if (!obs_source_valid(source, "obs_source_get_frame")) - return NULL; - - pthread_mutex_lock(&source->async_mutex); - - frame = source->cur_async_frame; - source->cur_async_frame = NULL; - - if (frame) { - os_atomic_inc_long(&frame->refs); - } - - pthread_mutex_unlock(&source->async_mutex); - - return frame; -} - -void obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame) -{ - if (!frame) - return; - - if (!source) { - obs_source_frame_destroy(frame); - } else { - pthread_mutex_lock(&source->async_mutex); - - if (os_atomic_dec_long(&frame->refs) == 0) - obs_source_frame_destroy(frame); - else - remove_async_frame(source, frame); - - pthread_mutex_unlock(&source->async_mutex); - } -} - static inline void render_filter_bypass(obs_source_t *target, gs_effect_t *effect, const char *tech_name) { gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); diff --git a/rust/README.md b/rust/README.md index 4a4897cd30..36331f384a 100644 --- a/rust/README.md +++ b/rust/README.md @@ -471,6 +471,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-source-frame-copy.c.h` | `obs-source::frame_copy` | Swapped in hybrid `libobs` (group `libobs.ported-source-frame-copy`). The async frame copy plan and cache decisions of `obs-source.c`, as six functions on plain values: `obs_source_frame_copy_plan()` (`copy_frame_data()`, `copy_frame_data_plane()` and `copy_frame_data_line()`: the colour range only when the frame is not full range, 065379b; then per format each plane's rows, `(height + 1) / 2` for 4:2:0 chroma, 8440a53; one copy of line size x rows in `size_t` when the two line sizes are equal, else rows of the smaller line size; no plane for P216, P416 and values outside the enum), `obs_source_frame_copy_cache_step()` (`cache_video()`'s queue limit at `MAX_ASYNC_FRAMES`, 7f7901b, which clears the cache and refuses the frame, then `async_texture_changed()`'s reset on a new size or convert type), `obs_source_frame_copy_cache_clean()` (one entry of `clean_cache()`: an unused entry counts one more call and is dropped at `MAX_UNUSED_FRAME_DURATION`, 3a90be3, 0815d5c), `obs_source_frame_copy_full_range()` and `_full_range2()` (a frame given to `obs_source_output_video()`, `obs_source_preload_video()` or `obs_source_set_video_frame()` that is not YUV is full range, 8d125dc; their `*2()` variants are full range when `resolve_video_range()` gives `VIDEO_RANGE_FULL`) and `obs_source_frame_copy_preload_changed()` (`preload_frame_changed()`). They are declared in `obs-source-frame-copy.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `memcpy()` (it runs the plan, each row at `y * line size` in `uint32_t`), the metadata copy, `obs_source_frame_create()` and `_destroy()`, the `async_cache` and `async_frames` darrays and the walk that picks the first unused entry (with #2048's `prev_frame` reset, #2009), `async_mutex`, the refcount atomics, and `get_convert_type()` (it passes the two convert types). Everything crosses by value, as `#[repr(C)]` mirrors of the header's structs: no pointer crosses. The formats and ranges cross as `int`, so values outside the enums take the C's paths. The arithmetic is the C's, wrap for wrap: `(height + 1) / 2` in `u32` and the one copy's size as a `usize` product. Kept, characterized, not endorsed: P216 and P416 copy no plane ("Unimplemented"); `UINT32_MAX` rows have 0 chroma rows; an unused count past 5 is never dropped (unreachable); the `*2()` rule keeps an explicit `VIDEO_RANGE_PARTIAL` on an RGB frame, which the first rule would make full range. Intentional difference, unreachable: `clean_cache()`'s `++unused_count` overflows a `long` at `LONG_MAX`, which is undefined in C; the port wraps. No entry gets past 5. `test_source_frame_copy_steps` compiles the C into itself, and `test_source_frame_copy_steps_rust` runs the same test source against `libobs_rust-static`; `test_video_frame`, the media restart tests, the v4l2 and PipeWire camera tests, `test_async_rotation_normalize` and the deinterlace tests see the swap through the real libobs. Tier 3 compares every field of every result over every C format value against every pattern of the four planes' line sizes (equal, smaller, larger, 0, or a destination of 0) at the `u32` height edges (2,280,000 plans), real frame line sizes, the queue limit over every length up to 64 with each key field changed alone, every count from -1000 to 1000 and the `c_long` ends but `LONG_MAX`, the range rules over formats -300 to 300 and every range from -10 to 10 with the `i32` ends, every preload combination around the edges, and proptests over each. | | `libobs/obs-source-frame-wrappers.c.h` | `obs-source::frame_wrappers`, shim in `obs-source::ffi::source_frame_wrappers` | #5760: the six async-frame entry points `obs_source_output_video()`, `obs_source_preload_video()`, `obs_source_set_video_frame()` and their `*2()` variants, swapped in hybrid `libobs` (group `libobs.ported-source-frame-wrappers`). A source being destroyed returns at once, before the NULL check; a NULL frame goes to the worker as NULL, and the two `set_video_frame` entries hand it to the preload worker (upstream quirk, characterized, not endorsed). An `obs_source_frame` is copied whole with only `full_range` replaced by `frame_copy::full_range`; an `obs_source_frame2` gives a zeroed frame of its planes, size, timestamp, format, flip, flags, transfer and colour matrix and range, with `full_range` from `frame_copy::full_range2` and `max_luminance` 0. The worker gets the local copy; the caller's frame is only read. `destroying()` and the three workers (`obs_source_output_video_internal()`, `_preload_video_internal()`, `_set_video_frame_internal()`, no longer `static`, declared in `obs-internal.h`) stay C behind `obs-source-frame-wrappers-fields.c.h`. The new `test_source_frame_wrappers` runs against hybrid and reference libraries; Tier 3 runs the original C and the Rust exports on a real private source with `destroying()` and the workers recorded, comparing which worker runs, the source, the frame pointer (NULL, the caller's or a copy) and every field of the frame it gets as bits, with the layouts of both frame structs checked, four export mutants and a proptest over random frames. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-get-name.c.h` | `obs-source::source_name` | Borrowed source context name getter (#4505): unchanged NULL debug diagnostic, private nameless NULL, pointer identity and original lifetime. Lazy safe core, opaque C field adapter and real standalone link support; Tier 1 getter assertions, original-C differential and mutation checks, unchanged context-name Tier 2. No intentional differences; Tier 4 does not apply. | +| `libobs/obs-source-get-release-frame.c.h` | `obs-source::get_release_frame`, shim in `obs-source::ffi::source_get_release_frame` | #5757: `obs_source_get_frame()` and `obs_source_release_frame()` swapped in hybrid `libobs` (group `libobs.ported-source-get-release-frame`). A NULL source logs the `obs_source_valid()` line and returns NULL from get; otherwise `cur_async_frame` is taken under `async_mutex` (the slot left NULL) with one added reference. Release ignores a NULL frame, destroys the frame of a NULL source without locking, and otherwise, under `async_mutex`, drops one reference and destroys at zero, else returns the frame to the async cache through `remove_async_frame()`. The mutex, slot, atomics, destroy and `remove_async_frame()` (moved unchanged from `obs-source.c.h`) stay C in `obs-source-get-release-frame-fields.c.h`, which also reaches Rust-static consumers through `source-get-release-frame-link-support.c`; the do-nothing release and cache stand-ins of `oracle/source_deinterlace_links.c` are gone. The new `test_source_get_release_frame` runs against hybrid and reference libraries; Tier 3 runs the original C and the Rust exports over real sources and frames on the same adapters, comparing results, recorded lock, unlock and destroy calls, the diagnostic and the state left, with four export mutants and a proptest over call sequences. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-get-weak.c.h` | `obs-source::get_weak` | #5228: `obs_source_get_weak_source()` swapped in hybrid `libobs` (group `libobs.ported-source-get-weak`). A NULL source returns NULL without reading anything or logging; otherwise the source's own `context.control`, read through the narrow private adapter `obs-source-get-weak-fields.c.h`, goes once through the C-owned `obs_weak_source_addref()` (also for a NULL control, a no-op there) and is returned. The strong count, the control and the source bytes stay untouched; release and the atomics stay in C. The unchanged `test_source_get_weak` runs against hybrid and reference libraries; Tier 3 runs the original C and the Rust export over present/absent sources and controls, noise-filled layouts and repeated calls, comparing returns, addref calls and arguments, weak and strong counts and source bytes. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-handler-getters.c.h`, `libobs/obs-source-signal-handler.c.h` | `obs-source::handler_getters` | Borrowed procedure handler getter (#4073) and signal handler getter (#5591), preserving pointer identity, absent handlers, NULL diagnostics and unchanged state. Both originals are in the reference-only group `libobs.ported-source-handler-getters`. Live discovered field adapter (signal and procedure addresses) for standalone consumers, real-header layout, Tier 1, differential mutation coverage and unchanged actual-library Tier 2 (`test_source_handler_getters`, `test_source_signal_handler_getter`). The audio-controls oracle's NULL-answering signal handler stand-in is renamed to `oracle_audio_controls_get_signal_handler` so it no longer collides with the Rust export in `obs-tests-core`. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-hidden-setter.c.h` | `obs-source::hidden_setter` | Hidden-state assignment through a borrowed boolean and thin ABI shim; real private field adapter, full-object C oracle parity, repeated assignments and unchanged `test_source_boolean_queries` coverage. NULL is checked before any field accessor; excluded from C differential inputs. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 646b87c353..e91c32d53a 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -57,6 +57,8 @@ mod canonical_source_flags_mixers_swap_is_registered; mod canonical_source_frame_copy_data_swap_is_registered; #[path = "native/registration/canonical_source_frame_wrappers_swap_is_registered.rs"] mod canonical_source_frame_wrappers_swap_is_registered; +#[path = "native/registration/canonical_source_get_release_frame_swap_is_registered.rs"] +mod canonical_source_get_release_frame_swap_is_registered; #[path = "native/registration/canonical_source_get_weak_swap_is_registered.rs"] mod canonical_source_get_weak_swap_is_registered; #[path = "native/registration/canonical_source_last_async_ts_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_get_release_frame_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_get_release_frame_swap_is_registered.rs new file mode 100644 index 0000000000..2e090721eb --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_get_release_frame_swap_is_registered.rs @@ -0,0 +1,45 @@ +use super::*; + +#[test] +fn canonical_source_get_release_frame_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_get_release_frame"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + let selected = graph + .select(&[("OS_LINUX".into(), true), ("OS_WINDOWS".into(), false)].into()) + .unwrap(); + // The unchanged test compiles no copy of the C: it calls the exported + // obs_source_get_frame() and obs_source_release_frame() 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_get_release_frame.c") + ); + assert_eq!(selected.tests[name].target, name); + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/source-get-release-frame.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-get-release-frame+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-get-release-frame+.h.c")) + .unwrap(); + assert!(group.contains("#include \"libobs/obs-source-get-release-frame.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-get-release-frame.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source-get-release-frame-fields.c.h\"")); + let support = + fs::read_to_string(root.join("test/cmocka/build/rust-static-support.json")).unwrap(); + assert!(support.contains("test/cmocka/source-get-release-frame-link-support.c")); + let exports = fs::read_to_string( + root.join("libobs/cmake/rust-exports.d/obs-source-source_get_release_frame.txt"), + ) + .unwrap(); + assert_eq!( + exports.lines().collect::>(), + ["obs_source_get_frame", "obs_source_release_frame"] + ); +} diff --git a/rust/obs-c-oracle/oracle.d/source-get-release-frame.list b/rust/obs-c-oracle/oracle.d/source-get-release-frame.list new file mode 100644 index 0000000000..a0054ac37d --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-get-release-frame.list @@ -0,0 +1 @@ +source-get-release-frame.inc|libobs/obs-source-get-release-frame.c.h|auto diff --git a/rust/obs-c-oracle/oracle/source_deinterlace_links.c b/rust/obs-c-oracle/oracle/source_deinterlace_links.c index f1c5ee0fca..9e10149448 100644 --- a/rust/obs-c-oracle/oracle/source_deinterlace_links.c +++ b/rust/obs-c-oracle/oracle/source_deinterlace_links.c @@ -5,8 +5,12 @@ * are oracle/source_deinterlace_getters.c's), and do-nothing definitions * of the libobs calls the deinterlace shims * (rust/obs-source-seam/src/ffi/source_deinterlace.rs) name under libobs's - * own names: the frame cache, the async texture upload, the effect load - * and the framebuffer sRGB calls. The SDR white level is obs-core's own + * own names: the async texture upload, the effect load and the + * framebuffer sRGB calls. The frame release (obs_source_release_frame()) is + * obs-source's own Rust export (rust/obs-source/src/ffi/ + * source_get_release_frame.rs), over the production adapters and + * remove_async_frame() that oracle/source_get_release_frame.c compiles + * (#5757). The SDR white level is obs-core's own * Rust export (rust/obs-core/src/ffi/video_level_queries.rs), which reads * oracle/video_level_queries.c's core: NULL outside its parity test, so * the default 300. The deinterlace texture size is obs-source's own Rust @@ -34,12 +38,6 @@ struct obs_core *oracle_deinterlace_obs; -void remove_async_frame(obs_source_t *source, struct obs_source_frame *frame) -{ - UNUSED_PARAMETER(source); - UNUSED_PARAMETER(frame); -} - bool set_async_texture_size(struct obs_source *source, const struct obs_source_frame *frame) { UNUSED_PARAMETER(source); @@ -57,12 +55,6 @@ bool update_async_textures(struct obs_source *source, const struct obs_source_fr return false; } -void obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame) -{ - UNUSED_PARAMETER(source); - UNUSED_PARAMETER(frame); -} - gs_effect_t *obs_load_effect(gs_effect_t **effect, const char *file) { UNUSED_PARAMETER(file); diff --git a/rust/obs-c-oracle/oracle/source_get_release_frame.c b/rust/obs-c-oracle/oracle/source_get_release_frame.c new file mode 100644 index 0000000000..c1b28c0ec8 --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_get_release_frame.c @@ -0,0 +1,230 @@ +/* Tier 3: the unchanged extracted obs_source_get_frame() and + * obs_source_release_frame() (libobs/obs-source-get-release-frame.c.h) + * against the Rust exports, over real private source and frame layouts. + * + * The production adapters the Rust exports call + * (libobs/obs-source-get-release-frame-fields.c.h, remove_async_frame() + * included) are compiled here, once for every test binary, and both sides + * share them: the original calls remove_async_frame() directly. Both are + * built with the async_mutex lock and unlock and obs_source_frame_destroy() + * routed through recorders that do the real work and log each call, so the + * parity test compares the call sequence as well as the state left. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include +#include "libobs/build/libobs.pch.h" + +enum { + GRF_LOCK = 1, + GRF_UNLOCK = 2, + GRF_DESTROY = 3, +}; + +#define GRF_MAX_EVENTS 256 + +struct grf_event { + int kind; + const void *arg; +}; + +static struct grf_event grf_events[GRF_MAX_EVENTS]; +static size_t grf_event_count; + +static void grf_record(int kind, const void *arg) +{ + if (grf_event_count < GRF_MAX_EVENTS) + grf_events[grf_event_count] = (struct grf_event){kind, arg}; + grf_event_count++; +} + +static int grf_mutex_lock(pthread_mutex_t *mutex) +{ + grf_record(GRF_LOCK, mutex); + return pthread_mutex_lock(mutex); +} + +static int grf_mutex_unlock(pthread_mutex_t *mutex) +{ + grf_record(GRF_UNLOCK, mutex); + return pthread_mutex_unlock(mutex); +} + +static void grf_frame_destroy(struct obs_source_frame *frame) +{ + grf_record(GRF_DESTROY, frame); + obs_source_frame_destroy(frame); +} + +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#define pthread_mutex_lock grf_mutex_lock +#define pthread_mutex_unlock grf_mutex_unlock +#define obs_source_frame_destroy grf_frame_destroy + +#define obs_source_get_frame oracle_obs_source_get_frame +#define obs_source_release_frame oracle_obs_source_release_frame +struct obs_source_frame *oracle_obs_source_get_frame(obs_source_t *source); +void oracle_obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame); +#include "source-get-release-frame.inc" +#undef obs_source_get_frame +#undef obs_source_release_frame + +#include "source-get-release-frame-fields.inc" + +#undef obs_source_frame_destroy +#undef pthread_mutex_lock +#undef pthread_mutex_unlock + +/* The calls recorded since the last read, oldest first; returns the count + * (more than max when some were dropped) and clears the log. */ +size_t oracle_grf_events(int *kinds, const void **args, size_t max); +size_t oracle_grf_events(int *kinds, const void **args, size_t max) +{ + size_t count = grf_event_count; + for (size_t i = 0; i < count && i < max && i < GRF_MAX_EVENTS; i++) { + kinds[i] = grf_events[i].kind; + args[i] = grf_events[i].arg; + } + grf_event_count = 0; + return count; +} + +void *oracle_grf_source_new(void); +void *oracle_grf_source_new(void) +{ + struct obs_source *source = bzalloc(sizeof(*source)); + /* As obs_source_init(). */ + if (pthread_mutex_init_recursive(&source->async_mutex) != 0) { + bfree(source); + return NULL; + } + return source; +} + +void oracle_grf_source_free(struct obs_source *source); +void oracle_grf_source_free(struct obs_source *source) +{ + da_free(source->async_cache); + pthread_mutex_destroy(&source->async_mutex); + bfree(source); +} + +const void *oracle_grf_mutex(const struct obs_source *source); +const void *oracle_grf_mutex(const struct obs_source *source) +{ + return &source->async_mutex; +} + +void oracle_grf_set_current(struct obs_source *source, struct obs_source_frame *frame); +void oracle_grf_set_current(struct obs_source *source, struct obs_source_frame *frame) +{ + source->cur_async_frame = frame; +} + +struct obs_source_frame *oracle_grf_current(const struct obs_source *source); +struct obs_source_frame *oracle_grf_current(const struct obs_source *source) +{ + return source->cur_async_frame; +} + +void oracle_grf_cache_push(struct obs_source *source, struct obs_source_frame *frame, bool used, long unused_count); +void oracle_grf_cache_push(struct obs_source *source, struct obs_source_frame *frame, bool used, long unused_count) +{ + struct async_frame entry = {frame, unused_count, used}; + da_push_back(source->async_cache, &entry); +} + +/* Slot index's frame, used flag and unused count; false past the end. */ +bool oracle_grf_cache_slot(const struct obs_source *source, size_t index, const void **frame, bool *used, + long *unused_count); +bool oracle_grf_cache_slot(const struct obs_source *source, size_t index, const void **frame, bool *used, + long *unused_count) +{ + if (index >= source->async_cache.num) + return false; + *frame = source->async_cache.array[index].frame; + *used = source->async_cache.array[index].used; + *unused_count = source->async_cache.array[index].unused_count; + return true; +} + +/* Two allocations, as obs_source_frame_create(): the frame and its data. */ +struct obs_source_frame *oracle_grf_frame_new(long refs, bool prev_frame); +struct obs_source_frame *oracle_grf_frame_new(long refs, bool prev_frame) +{ + struct obs_source_frame *frame = bzalloc(sizeof(*frame)); + frame->data[0] = bmalloc(16); + frame->refs = refs; + frame->prev_frame = prev_frame; + return frame; +} + +void oracle_grf_frame_free(struct obs_source_frame *frame); +void oracle_grf_frame_free(struct obs_source_frame *frame) +{ + bfree(frame->data[0]); + bfree(frame); +} + +long oracle_grf_frame_refs(const struct obs_source_frame *frame); +long oracle_grf_frame_refs(const struct obs_source_frame *frame) +{ + return frame->refs; +} + +bool oracle_grf_frame_prev(const struct obs_source_frame *frame); +bool oracle_grf_frame_prev(const struct obs_source_frame *frame) +{ + return frame->prev_frame; +} + +/* The diagnostics logged between begin and end. */ +struct grf_log { + unsigned count; + int level; + char message[256]; +}; + +static struct grf_log grf_log; +static log_handler_t grf_previous; +static void *grf_previous_param; + +#if defined(__GNUC__) || defined(__clang__) +static void grf_capture(int level, const char *format, va_list args, void *param) __attribute__((format(printf, 2, 0))); +#endif +static void grf_capture(int level, const char *format, va_list args, void *param) +{ + struct grf_log *log = param; + log->count++; + log->level = level; + vsnprintf(log->message, sizeof(log->message), format, args); +} + +typedef void (*grf_get_log)(log_handler_t *, void **); +typedef void (*grf_set_log)(log_handler_t, void *); + +void oracle_grf_log_begin(grf_get_log get_log, grf_set_log set_log); +void oracle_grf_log_begin(grf_get_log get_log, grf_set_log set_log) +{ + memset(&grf_log, 0, sizeof(grf_log)); + get_log(&grf_previous, &grf_previous_param); + set_log(grf_capture, &grf_log); +} + +/* Restores logging; returns the count, with the last level and message. */ +unsigned oracle_grf_log_end(grf_set_log set_log, int *level, char *message, size_t size); +unsigned oracle_grf_log_end(grf_set_log set_log, int *level, char *message, size_t size) +{ + set_log(grf_previous, grf_previous_param); + *level = grf_log.level; + snprintf(message, size, "%s", grf_log.message); + return grf_log.count; +} + +/* For a mutant: drops one reference behind the export. */ +void oracle_grf_frame_drop_ref(struct obs_source_frame *frame); +void oracle_grf_frame_drop_ref(struct obs_source_frame *frame) +{ + frame->refs--; +} diff --git a/rust/obs-source/Cargo.toml b/rust/obs-source/Cargo.toml index 822b09c5ce..bfa0889e18 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), 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-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), 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-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-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-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), 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-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), 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-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/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index 6d626a7d93..cd368b33d9 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -49,6 +49,7 @@ pub mod source_frame_copy; pub mod source_frame_copy_data; pub mod source_frame_init; pub mod source_frame_wrappers; +pub mod source_get_release_frame; pub mod source_get_weak; pub mod source_handler_getters; pub mod source_hidden_setter; diff --git a/rust/obs-source/src/ffi/source_get_release_frame.rs b/rust/obs-source/src/ffi/source_get_release_frame.rs new file mode 100644 index 0000000000..f89444219d --- /dev/null +++ b/rust/obs-source/src/ffi/source_get_release_frame.rs @@ -0,0 +1,103 @@ +//! C ABI for `libobs/obs-source-get-release-frame.c.h`: +//! `obs_source_get_frame()` and `obs_source_release_frame()` (`EXPORT` in +//! `obs.h`, `rust-exports.d`). +//! +//! Runs the safe core ([`crate::get_release_frame`]) over the C-owned +//! source and frame: `async_mutex`, `cur_async_frame`, the frame's `refs`, +//! `obs_source_frame_destroy()` and `remove_async_frame()` are reached +//! through the adapters in `obs-source-get-release-frame-fields.c.h`, each +//! the line of the C it stands for, so the atomics and the mutex stay the +//! C's own. A NULL source logs the `obs_source_valid()` line. +//! +//! No intentional differences from C. + +use core::ffi::{CStr, c_char, c_int, c_void}; + +use crate::get_release_frame::{self, Host}; + +unsafe extern "C" { + fn obs_source_async_frame_lock(source: *mut c_void); + fn obs_source_async_frame_unlock(source: *mut c_void); + fn obs_source_async_frame_take_current(source: *mut c_void) -> *mut c_void; + fn obs_source_async_frame_addref(frame: *mut c_void); + fn obs_source_async_frame_release_ref(frame: *mut c_void) -> bool; + fn obs_source_async_frame_destroy(frame: *mut c_void); + fn obs_source_async_frame_return(source: *mut c_void, frame: *mut c_void); + fn blog(level: c_int, format: *const c_char, ...); +} + +/// `LOG_DEBUG` (`util/base.h`). +const LOG_DEBUG: c_int = 400; + +/// The live libobs objects the caller hands over. +struct Libobs; + +impl Host for Libobs { + type Source = *mut c_void; + type Frame = *mut c_void; + fn null_source(&self, func: &'static CStr) { + // SAFETY: static strings match the two %s arguments of the format. + unsafe { + blog( + LOG_DEBUG, + c"%s: Null '%s' parameter".as_ptr(), + func.as_ptr(), + c"source".as_ptr(), + ); + } + } + fn lock(&self, source: *mut c_void) { + // SAFETY: a live, non-null source. + unsafe { obs_source_async_frame_lock(source) } + } + fn unlock(&self, source: *mut c_void) { + // SAFETY: a live source whose async_mutex this call locked. + unsafe { obs_source_async_frame_unlock(source) } + } + fn take_current(&self, source: *mut c_void) -> Option<*mut c_void> { + // SAFETY: a live source with its async_mutex held. + let frame = unsafe { obs_source_async_frame_take_current(source) }; + (!frame.is_null()).then_some(frame) + } + fn addref(&self, frame: *mut c_void) { + // SAFETY: the non-null frame the source held, under its mutex. + unsafe { obs_source_async_frame_addref(frame) } + } + fn release_ref(&self, frame: *mut c_void) -> bool { + // SAFETY: the caller's live, non-null frame. + unsafe { obs_source_async_frame_release_ref(frame) } + } + fn destroy(&self, frame: *mut c_void) { + // SAFETY: the caller's live, non-null frame, given up here. + unsafe { obs_source_async_frame_destroy(frame) } + } + fn return_to_cache(&self, source: *mut c_void, frame: *mut c_void) { + // SAFETY: a live source with its async_mutex held and the caller's + // live frame. + unsafe { obs_source_async_frame_return(source, frame) } + } +} + +/// `obs_source_get_frame(source)`. +/// +/// # Safety +/// `source` is NULL or a live source. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_get_frame(source: *mut c_void) -> *mut c_void { + get_release_frame::get_frame(&Libobs, (!source.is_null()).then_some(source)) + .unwrap_or(core::ptr::null_mut()) +} + +/// `obs_source_release_frame(source, frame)`. +/// +/// # Safety +/// `source` is NULL or a live source; `frame` is NULL or a live frame the +/// caller holds a reference to (or owns, with a NULL source). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_release_frame(source: *mut c_void, frame: *mut c_void) { + get_release_frame::release_frame( + &Libobs, + (!source.is_null()).then_some(source), + (!frame.is_null()).then_some(frame), + ); +} diff --git a/rust/obs-source/src/get_release_frame.rs b/rust/obs-source/src/get_release_frame.rs new file mode 100644 index 0000000000..0107ae8e9d --- /dev/null +++ b/rust/obs-source/src/get_release_frame.rs @@ -0,0 +1,83 @@ +//! Safe core of `libobs/obs-source-get-release-frame.c.h`: the exported +//! async-frame consumer pair `obs_source_get_frame()` and +//! `obs_source_release_frame()`. +//! +//! `get_frame` rejects a missing source with its `obs_source_valid()` +//! diagnostic; otherwise, under `async_mutex`, it takes `cur_async_frame` +//! (leaving the slot empty) and adds one reference to it. `release_frame` +//! ignores a missing frame and destroys the frame of a missing source +//! without locking anything; otherwise, under `async_mutex`, it drops one +//! reference and destroys the frame at zero, or else gives it back to the +//! async cache (`remove_async_frame()`). +//! +//! No intentional differences from C. + +#![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; + +/// The source and frame operations the pair performs, in the C's terms. +pub trait Host { + /// A live, non-null source. + type Source: Copy; + /// A live, non-null frame. + type Frame: Copy; + /// `obs_source_valid(NULL, func)`: the `LOG_DEBUG` line. + fn null_source(&self, func: &'static CStr); + /// `pthread_mutex_lock(&source->async_mutex)`. + fn lock(&self, source: Self::Source); + /// `pthread_mutex_unlock(&source->async_mutex)`. + fn unlock(&self, source: Self::Source); + /// Takes `cur_async_frame`, leaving NULL behind. + fn take_current(&self, source: Self::Source) -> Option; + /// `os_atomic_inc_long(&frame->refs)`. + fn addref(&self, frame: Self::Frame); + /// `os_atomic_dec_long(&frame->refs) == 0`. + fn release_ref(&self, frame: Self::Frame) -> bool; + /// `obs_source_frame_destroy(frame)`. + fn destroy(&self, frame: Self::Frame); + /// `remove_async_frame(source, frame)`. + fn return_to_cache(&self, source: Self::Source, frame: Self::Frame); +} + +/// `obs_source_get_frame(source)`. +pub fn get_frame(host: &H, source: Option) -> Option { + let Some(source) = source else { + host.null_source(c"obs_source_get_frame"); + return None; + }; + host.lock(source); + let frame = host.take_current(source); + if let Some(frame) = frame { + host.addref(frame); + } + host.unlock(source); + frame +} + +/// `obs_source_release_frame(source, frame)`. +pub fn release_frame(host: &H, source: Option, frame: Option) { + let Some(frame) = frame else { + return; + }; + let Some(source) = source else { + host.destroy(frame); + return; + }; + host.lock(source); + if host.release_ref(frame) { + host.destroy(frame); + } else { + host.return_to_cache(source, frame); + } + host.unlock(source); +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 82b48615c6..7866a12d15 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -236,6 +236,7 @@ pub mod frame_copy; pub mod frame_copy_data; pub mod frame_init; pub mod frame_wrappers; +pub mod get_release_frame; pub mod get_weak; pub mod handler_getters; pub mod hidden_setter; diff --git a/rust/obs-source/tests/source/get_release_frame.rs b/rust/obs-source/tests/source/get_release_frame.rs new file mode 100644 index 0000000000..b5a5540cf1 --- /dev/null +++ b/rust/obs-source/tests/source/get_release_frame.rs @@ -0,0 +1,245 @@ +//! Tier 1: `obs_source::get_release_frame` over a recording model of the +//! source and its frames, mirroring every `test_source_get_release_frame` +//! case plus the order of every step and the lock's scope. +use obs_source::get_release_frame::{Host, get_frame, release_frame}; +use std::cell::RefCell; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Event { + NullSource(&'static core::ffi::CStr), + Lock, + Unlock, + Take, + Addref(usize), + ReleaseRef(usize), + Destroy(usize), + Return(usize), +} + +#[derive(Default)] +struct Frame { + refs: i64, + prev_frame: bool, + destroyed: bool, +} + +#[derive(Default)] +struct State { + locked: bool, + current: Option, + frames: Vec, + /// (frame, used), in cache order. + cache: Vec<(usize, bool)>, + events: Vec, +} + +struct Model(RefCell); + +impl Model { + fn new(frames: &[(i64, bool)]) -> Self { + Model(RefCell::new(State { + frames: frames + .iter() + .map(|&(refs, prev_frame)| Frame { + refs, + prev_frame, + destroyed: false, + }) + .collect(), + ..State::default() + })) + } + fn events(&self) -> Vec { + std::mem::take(&mut self.0.borrow_mut().events) + } +} + +impl Host for Model { + type Source = (); + type Frame = usize; + fn null_source(&self, func: &'static core::ffi::CStr) { + self.0.borrow_mut().events.push(Event::NullSource(func)); + } + fn lock(&self, (): ()) { + let mut s = self.0.borrow_mut(); + assert!(!s.locked, "locks once"); + s.locked = true; + s.events.push(Event::Lock); + } + fn unlock(&self, (): ()) { + let mut s = self.0.borrow_mut(); + assert!(s.locked); + s.locked = false; + s.events.push(Event::Unlock); + } + fn take_current(&self, (): ()) -> Option { + let mut s = self.0.borrow_mut(); + assert!(s.locked, "cur_async_frame is read under async_mutex"); + s.events.push(Event::Take); + s.current.take() + } + fn addref(&self, frame: usize) { + let mut s = self.0.borrow_mut(); + assert!(s.locked); + s.events.push(Event::Addref(frame)); + s.frames[frame].refs += 1; + } + fn release_ref(&self, frame: usize) -> bool { + let mut s = self.0.borrow_mut(); + assert!(s.locked); + s.events.push(Event::ReleaseRef(frame)); + s.frames[frame].refs -= 1; + s.frames[frame].refs == 0 + } + fn destroy(&self, frame: usize) { + let mut s = self.0.borrow_mut(); + s.events.push(Event::Destroy(frame)); + assert!(!s.frames[frame].destroyed); + s.frames[frame].destroyed = true; + } + fn return_to_cache(&self, (): (), frame: usize) { + let mut s = self.0.borrow_mut(); + assert!(s.locked); + s.events.push(Event::Return(frame)); + s.frames[frame].prev_frame = false; + if let Some(slot) = s.cache.iter_mut().find(|(f, _)| *f == frame) { + slot.1 = false; + } + } +} + +use Event::*; + +#[test] +fn get_null_source() { + let m = Model::new(&[(1, true)]); + m.0.borrow_mut().current = Some(0); + assert_eq!(get_frame(&m, None), None); + assert_eq!(m.events(), [NullSource(c"obs_source_get_frame")]); + assert_eq!(m.0.borrow().current, Some(0)); +} + +#[test] +fn get_without_frame() { + let m = Model::new(&[]); + assert_eq!(get_frame(&m, Some(())), None); + assert_eq!(m.events(), [Lock, Take, Unlock]); + assert!(!m.0.borrow().locked); +} + +#[test] +fn get_takes_current_with_a_reference() { + let m = Model::new(&[(1, true), (1, false)]); + m.0.borrow_mut().current = Some(0); + m.0.borrow_mut().cache = vec![(0, true)]; + assert_eq!(get_frame(&m, Some(())), Some(0)); + assert_eq!(m.events(), [Lock, Take, Addref(0), Unlock]); + let s = m.0.borrow(); + assert_eq!(s.current, None); + assert_eq!(s.frames[0].refs, 2); + assert!(s.frames[0].prev_frame); + assert_eq!(s.cache, [(0, true)]); + drop(s); + // Taken once: the slot is empty now. + assert_eq!(get_frame(&m, Some(())), None); + assert_eq!(m.events(), [Lock, Take, Unlock]); + assert_eq!(m.0.borrow().frames[0].refs, 2); +} + +#[test] +fn release_null_frame() { + let m = Model::new(&[(2, true)]); + release_frame(&m, Some(()), None); + release_frame(&m, None, None); + assert_eq!(m.events(), []); + assert_eq!(m.0.borrow().frames[0].refs, 2); +} + +#[test] +fn release_null_source_destroys() { + let m = Model::new(&[(5, true)]); + release_frame(&m, None, Some(0)); + // Whatever its references, and without the lock. + assert_eq!(m.events(), [Destroy(0)]); + assert_eq!(m.0.borrow().frames[0].refs, 5); +} + +#[test] +fn release_last_reference_destroys() { + let m = Model::new(&[(1, true)]); + m.0.borrow_mut().cache = vec![(0, true)]; + release_frame(&m, Some(()), Some(0)); + assert_eq!(m.events(), [Lock, ReleaseRef(0), Destroy(0), Unlock]); + // The cache is left alone (characterized, not endorsed). + assert_eq!(m.0.borrow().cache, [(0, true)]); +} + +#[test] +fn release_returns_to_cache() { + let m = Model::new(&[(1, true), (3, true)]); + m.0.borrow_mut().cache = vec![(0, true), (1, true), (1, true)]; + release_frame(&m, Some(()), Some(1)); + assert_eq!(m.events(), [Lock, ReleaseRef(1), Return(1), Unlock]); + { + let s = m.0.borrow(); + assert_eq!(s.frames[1].refs, 2); + assert!(!s.frames[1].prev_frame); + assert!(s.frames[0].prev_frame); + assert_eq!(s.cache, [(0, true), (1, false), (1, true)]); + } + release_frame(&m, Some(()), Some(1)); + assert_eq!(m.events(), [Lock, ReleaseRef(1), Return(1), Unlock]); + assert_eq!(m.0.borrow().frames[1].refs, 1); +} + +#[test] +fn release_uncached() { + let m = Model::new(&[(1, true), (2, true)]); + m.0.borrow_mut().cache = vec![(0, true)]; + release_frame(&m, Some(()), Some(1)); + assert_eq!(m.events(), [Lock, ReleaseRef(1), Return(1), Unlock]); + let s = m.0.borrow(); + assert_eq!(s.frames[1].refs, 1); + assert!(!s.frames[1].prev_frame); + assert_eq!(s.cache, [(0, true)]); +} + +#[test] +fn release_unreferenced() { + // Zero goes below zero and is not destroyed (characterized, not + // endorsed). + let m = Model::new(&[(0, true)]); + m.0.borrow_mut().cache = vec![(0, true)]; + release_frame(&m, Some(()), Some(0)); + assert_eq!(m.events(), [Lock, ReleaseRef(0), Return(0), Unlock]); + let s = m.0.borrow(); + assert_eq!(s.frames[0].refs, -1); + assert!(!s.frames[0].destroyed); + assert_eq!(s.cache, [(0, false)]); +} + +#[test] +fn get_then_release() { + let m = Model::new(&[(1, false)]); + m.0.borrow_mut().current = Some(0); + m.0.borrow_mut().cache = vec![(0, true)]; + let got = get_frame(&m, Some(())); + release_frame(&m, Some(()), got); + assert_eq!( + m.events(), + [ + Lock, + Take, + Addref(0), + Unlock, + Lock, + ReleaseRef(0), + Return(0), + Unlock + ] + ); + let s = m.0.borrow(); + assert_eq!(s.frames[0].refs, 1); + assert_eq!(s.cache, [(0, false)]); + assert_eq!(s.current, None); +} diff --git a/rust/obs-source/tests/source/get_release_frame_parity.rs b/rust/obs-source/tests/source/get_release_frame_parity.rs new file mode 100644 index 0000000000..01577489d0 --- /dev/null +++ b/rust/obs-source/tests/source/get_release_frame_parity.rs @@ -0,0 +1,519 @@ +//! Tier 3: the original C `obs_source_get_frame()` and +//! `obs_source_release_frame()` against the Rust exports, each on its own +//! real private source and frames (`source_get_release_frame.c`). Both run +//! over the same production adapters, with the async mutex and the frame +//! destroy recorded, and the same call sequences; every call's result, the +//! recorded lock, unlock and destroy calls, the diagnostic, and the state +//! left (the current frame, each live frame's references and `prev_frame`, +//! every cache slot) must match. No intentional differences or exclusions. +use core::ffi::{c_char, c_int, c_long, c_void}; +use obs_source::ffi::source_get_release_frame::{ + obs_source_get_frame as rust_get, obs_source_release_frame as rust_release, +}; +use obs_util::ffi::base::{base_get_log_handler, base_set_log_handler}; +use proptest::prelude::*; + +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); +type Get = unsafe extern "C" fn(*mut c_void) -> *mut c_void; +type Release = unsafe extern "C" fn(*mut c_void, *mut c_void); + +unsafe extern "C" { + fn oracle_obs_source_get_frame(source: *mut c_void) -> *mut c_void; + fn oracle_obs_source_release_frame(source: *mut c_void, frame: *mut c_void); + fn oracle_grf_events(kinds: *mut c_int, args: *mut *const c_void, max: usize) -> usize; + fn oracle_grf_source_new() -> *mut c_void; + fn oracle_grf_source_free(source: *mut c_void); + fn oracle_grf_mutex(source: *const c_void) -> *const c_void; + fn oracle_grf_set_current(source: *mut c_void, frame: *mut c_void); + fn oracle_grf_current(source: *const c_void) -> *mut c_void; + fn oracle_grf_cache_push(source: *mut c_void, frame: *mut c_void, used: bool, unused: c_long); + fn oracle_grf_cache_slot( + source: *const c_void, + index: usize, + frame: *mut *const c_void, + used: *mut bool, + unused: *mut c_long, + ) -> bool; + fn oracle_grf_frame_new(refs: c_long, prev_frame: bool) -> *mut c_void; + fn oracle_grf_frame_free(frame: *mut c_void); + fn oracle_grf_frame_refs(frame: *const c_void) -> c_long; + fn oracle_grf_frame_prev(frame: *const c_void) -> bool; + fn oracle_grf_log_begin(get: GetLog, set: SetLog); + fn oracle_grf_log_end(set: SetLog, level: *mut c_int, message: *mut c_char, size: usize) + -> u32; +} + +#[derive(Debug, Clone, Copy)] +enum Op { + Get { + null_source: bool, + }, + Release { + null_source: bool, + frame: Option, + }, +} + +#[derive(Debug, Clone)] +struct Scenario { + /// (refs, prev_frame) of each frame. + frames: Vec<(c_long, bool)>, + current: Option, + /// (frame, used, unused_count), in cache order. + cache: Vec<(usize, bool, c_long)>, + ops: Vec, +} + +/// A pointer the run knows: NULL, the mutex, a frame by index, or other. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Ptr { + Null, + Mutex, + Frame(usize), + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Step { + op: usize, + result: Ptr, + events: Vec<(c_int, Ptr)>, + log: (u32, c_int, Vec), + current: Ptr, + /// (refs, prev_frame) of each frame, None once destroyed. + frames: Vec>, + cache: Vec<(Ptr, bool, c_long)>, +} + +const DESTROY: c_int = 3; + +/// One run's real source and frames, owned by the oracle. +struct World { + source: *mut c_void, + mutex: *const c_void, + frames: Vec<*mut c_void>, + live: Vec, +} + +impl World { + fn new(scenario: &Scenario) -> Self { + // SAFETY: the oracle allocates a real source and frames and links + // them as the scenario says; every index is below the frame count. + unsafe { + let source = oracle_grf_source_new(); + assert!(!source.is_null()); + let frames: Vec<*mut c_void> = scenario + .frames + .iter() + .map(|&(refs, prev)| oracle_grf_frame_new(refs, prev)) + .collect(); + if let Some(current) = scenario.current { + oracle_grf_set_current(source, frames[current]); + } + for &(frame, used, unused) in &scenario.cache { + oracle_grf_cache_push(source, frames[frame], used, unused); + } + oracle_grf_events(core::ptr::null_mut(), core::ptr::null_mut(), 0); + World { + source, + mutex: oracle_grf_mutex(source), + live: vec![true; frames.len()], + frames, + } + } + } + + fn name(&self, ptr: *const c_void) -> Ptr { + if ptr.is_null() { + Ptr::Null + } else if ptr == self.mutex { + Ptr::Mutex + } else { + self.frames + .iter() + .position(|&f| f.cast_const() == ptr) + .map_or(Ptr::Unknown, Ptr::Frame) + } + } + + fn current(&self) -> *mut c_void { + // SAFETY: the live source. + unsafe { oracle_grf_current(self.source) } + } + + /// A frame is released only while live and no longer the source's + /// current frame, as callers do after a get. + fn skips(&self, op: Op) -> bool { + matches!(op, Op::Release { frame: Some(frame), .. } + if !self.live[frame] || self.current() == self.frames[frame]) + } + + fn call(&self, op: Op, get: Get, release: Release) -> *mut c_void { + let source = |null: bool| { + if null { + core::ptr::null_mut() + } else { + self.source + } + }; + // SAFETY: NULL or the live source, NULL or a live frame (skips()). + unsafe { + match op { + Op::Get { null_source } => get(source(null_source)), + Op::Release { null_source, frame } => { + release( + source(null_source), + frame.map_or(core::ptr::null_mut(), |f| self.frames[f]), + ); + core::ptr::null_mut() + } + } + } + } + + /// The recorded calls since the last read; marks destroyed frames. + fn events(&mut self) -> Vec<(c_int, Ptr)> { + let mut kinds = [0; 16]; + let mut args = [core::ptr::null(); 16]; + // SAFETY: both buffers hold the max passed. + let n = unsafe { oracle_grf_events(kinds.as_mut_ptr(), args.as_mut_ptr(), kinds.len()) }; + assert!(n <= kinds.len()); + let events: Vec<(c_int, Ptr)> = (0..n).map(|i| (kinds[i], self.name(args[i]))).collect(); + for &(kind, ptr) in &events { + if let (DESTROY, Ptr::Frame(f)) = (kind, ptr) { + self.live[f] = false; + } + } + events + } + + fn cache(&self) -> Vec<(Ptr, bool, c_long)> { + let mut cache = Vec::new(); + loop { + let (mut frame, mut used, mut unused) = (core::ptr::null(), false, 0); + // SAFETY: the live source; the outputs are plain locals. + let present = unsafe { + oracle_grf_cache_slot( + self.source, + cache.len(), + &raw mut frame, + &raw mut used, + &raw mut unused, + ) + }; + if !present { + return cache; + } + cache.push((self.name(frame), used, unused)); + } + } + + fn frames(&self) -> Vec> { + self.frames + .iter() + .zip(&self.live) + .map(|(&f, &alive)| { + // SAFETY: a live frame. + alive.then(|| unsafe { (oracle_grf_frame_refs(f), oracle_grf_frame_prev(f)) }) + }) + .collect() + } +} + +impl Drop for World { + fn drop(&mut self) { + // SAFETY: each live frame and the source are freed once; destroyed + // frames were freed by the recorded destroy. + unsafe { + for (&frame, &alive) in self.frames.iter().zip(&self.live) { + if alive { + oracle_grf_frame_free(frame); + } + } + oracle_grf_source_free(self.source); + } + } +} + +/// Runs the call and returns its diagnostics: count, level, message. +fn logged(call: impl FnOnce() -> *mut c_void) -> (*mut c_void, (u32, c_int, Vec)) { + let mut level = 0; + let mut message = [0 as c_char; 256]; + // SAFETY: the isolated child owns the log handler; the capture is + // restored before returning, and the message buffer holds its size. + unsafe { + oracle_grf_log_begin(base_get_log_handler, base_set_log_handler); + let result = call(); + let count = oracle_grf_log_end( + base_set_log_handler, + &raw mut level, + message.as_mut_ptr(), + message.len(), + ); + let message = core::ffi::CStr::from_ptr(message.as_ptr()) + .to_bytes() + .to_vec(); + (result, (count, level, message)) + } +} + +fn run(scenario: &Scenario, get: Get, release: Release) -> Vec { + let mut world = World::new(scenario); + let mut steps = Vec::new(); + for (index, &op) in scenario.ops.iter().enumerate() { + if world.skips(op) { + continue; + } + let (result, log) = logged(|| world.call(op, get, release)); + let events = world.events(); + steps.push(Step { + op: index, + result: world.name(result), + events, + log, + current: world.name(world.current()), + frames: world.frames(), + cache: world.cache(), + }); + } + steps +} + +fn agree(scenario: &Scenario, get: Get, release: Release) -> bool { + run( + scenario, + oracle_obs_source_get_frame, + oracle_obs_source_release_frame, + ) == run(scenario, get, release) +} + +fn check(scenario: &Scenario) -> Vec { + let c = run( + scenario, + oracle_obs_source_get_frame, + oracle_obs_source_release_frame, + ); + let rust = run(scenario, rust_get, rust_release); + assert_eq!(c, rust, "{scenario:?}"); + c +} + +/// Every `test_source_get_release_frame` case as one sequence, with the +/// shared answer pinned so a change on both sides still fails. +fn characterized() -> Scenario { + Scenario { + frames: vec![(1, true), (3, true), (5, true), (1, true), (0, true)], + current: Some(0), + cache: vec![ + (2, true, 1), + (1, true, 2), + (1, true, 5), + (3, true, 4), + (4, true, 0), + ], + ops: vec![ + Op::Get { null_source: true }, + Op::Get { null_source: false }, + Op::Get { null_source: false }, + Op::Release { + null_source: false, + frame: None, + }, + Op::Release { + null_source: true, + frame: None, + }, + Op::Release { + null_source: false, + frame: Some(0), + }, + Op::Release { + null_source: false, + frame: Some(1), + }, + Op::Release { + null_source: false, + frame: Some(1), + }, + Op::Release { + null_source: true, + frame: Some(2), + }, + Op::Release { + null_source: false, + frame: Some(3), + }, + Op::Release { + null_source: false, + frame: Some(4), + }, + ], + } +} + +#[test] +fn get_release_frame_matches_c() { + if !crate::output::isolated(concat!(module_path!(), "::get_release_frame_matches_c")) { + return; + } + let steps = check(&characterized()); + pin_gets(&steps); + pin_releases(&steps); +} + +/// The shared answer of the characterized gets, pinned. +fn pin_gets(steps: &[Step]) { + let lock = (1, Ptr::Mutex); + let unlock = (2, Ptr::Mutex); + // NULL source: the obs_source_valid() line and nothing else. + assert_eq!(steps[0].result, Ptr::Null); + assert!(steps[0].events.is_empty()); + assert_eq!( + steps[0].log, + ( + 1, + 400, + b"obs_source_get_frame: Null 'source' parameter".to_vec() + ) + ); + // The current frame is taken with one more reference, then the slot is + // empty. + assert_eq!(steps[1].result, Ptr::Frame(0)); + assert_eq!(steps[1].events, [lock, unlock]); + assert_eq!(steps[1].current, Ptr::Null); + assert_eq!(steps[1].frames[0], Some((2, true))); + assert_eq!(steps[2].result, Ptr::Null); +} + +/// The shared answer of the characterized releases, pinned. +fn pin_releases(steps: &[Step]) { + let lock = (1, Ptr::Mutex); + let unlock = (2, Ptr::Mutex); + let destroy = |f| (DESTROY, Ptr::Frame(f)); + // NULL frames: nothing. + assert!(steps[3].events.is_empty() && steps[4].events.is_empty()); + assert_eq!(steps[4].log.0, 0); + // Back from 2 to 1: returned to the cache (not in it here). + assert_eq!(steps[5].events, [lock, unlock]); + assert_eq!(steps[5].frames[0], Some((1, false))); + // 3 to 2: the first slot holding it is marked unused; then 2 to 1. + assert_eq!(steps[6].frames[1], Some((2, false))); + assert_eq!(steps[6].cache[1], (Ptr::Frame(1), false, 2)); + assert_eq!(steps[6].cache[2], (Ptr::Frame(1), true, 5)); + assert_eq!(steps[7].frames[1], Some((1, false))); + assert_eq!(steps[7].cache[2], (Ptr::Frame(1), true, 5)); + // A NULL source destroys whatever the references, without the lock. + assert_eq!(steps[8].events, [destroy(2)]); + assert_eq!(steps[8].frames[2], None); + assert!(steps[8].cache[0].1); + // The last reference destroys under the lock; the cache keeps its slot. + assert_eq!(steps[9].events, [lock, destroy(3), unlock]); + assert_eq!(steps[9].cache[3], (Ptr::Frame(3), true, 4)); + // Zero goes below zero and is returned, not destroyed. + assert_eq!(steps[10].events, [lock, unlock]); + assert_eq!(steps[10].frames[4], Some((-1, false))); + assert_eq!(steps[10].cache[4], (Ptr::Frame(4), false, 0)); +} + +/// Mutants of the exports: each must disagree with the original. +unsafe extern "C" fn get_silent_null(source: *mut c_void) -> *mut c_void { + if source.is_null() { + return core::ptr::null_mut(); + } + // SAFETY: a live oracle source. + unsafe { rust_get(source) } +} +unsafe extern "C" fn get_without_reference(source: *mut c_void) -> *mut c_void { + // SAFETY: NULL or a live oracle source. + let frame = unsafe { rust_get(source) }; + if !frame.is_null() { + // SAFETY: the live frame the export returned; drop the reference it + // added. + unsafe { oracle_grf_frame_drop_ref(frame) }; + } + frame +} +unsafe extern "C" fn release_unlocked(source: *mut c_void, frame: *mut c_void) { + let _ = source; + // SAFETY: NULL or the caller's live frame: destroyed without the lock. + unsafe { rust_release(core::ptr::null_mut(), frame) } +} +unsafe extern "C" fn release_keeps_null_source(source: *mut c_void, frame: *mut c_void) { + if source.is_null() { + return; + } + // SAFETY: a live oracle source and NULL or a live frame. + unsafe { rust_release(source, frame) } +} + +unsafe extern "C" { + fn oracle_grf_frame_drop_ref(frame: *mut c_void); +} + +#[test] +fn get_release_frame_mutants_are_caught() { + if !crate::output::isolated(concat!( + module_path!(), + "::get_release_frame_mutants_are_caught" + )) { + return; + } + let scenario = characterized(); + assert!(agree(&scenario, rust_get, rust_release)); + for get in [get_silent_null as Get, get_without_reference] { + assert!( + !agree(&scenario, get, rust_release), + "a get mutant agreed with C" + ); + } + for release in [release_unlocked as Release, release_keeps_null_source] { + assert!( + !agree(&scenario, rust_get, release), + "a release mutant agreed with C" + ); + } +} + +fn scenarios() -> impl Strategy { + (1usize..5).prop_flat_map(|count| { + let op = prop_oneof![ + any::().prop_map(|null_source| Op::Get { null_source }), + (any::(), proptest::option::of(0..count)) + .prop_map(|(null_source, frame)| Op::Release { null_source, frame }), + ]; + ( + proptest::collection::vec((-1 as c_long..4, any::()), count), + proptest::option::of(0..count), + proptest::collection::vec((0..count, any::(), 0 as c_long..3), 0..6), + proptest::collection::vec(op, 1..12), + ) + .prop_map(|(frames, current, cache, ops)| Scenario { + frames, + current, + cache, + ops, + }) + }) +} + +#[test] +fn get_release_frame_sequences_match_c() { + if !crate::output::isolated(concat!( + module_path!(), + "::get_release_frame_sequences_match_c" + )) { + return; + } + let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig { + cases: obs_c_oracle::parity::cases(256), + failure_persistence: None, + ..ProptestConfig::default() + }); + runner + .run(&scenarios(), |scenario| { + check(&scenario); + Ok(()) + }) + .unwrap(); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 720094de45..88701616cb 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -92,6 +92,8 @@ mod frame_init; mod frame_init_parity; mod frame_wrappers; mod frame_wrappers_parity; +mod get_release_frame; +mod get_release_frame_parity; mod get_weak; mod get_weak_parity; mod handler_getters; diff --git a/test/cmocka/build/rust-static-support.json b/test/cmocka/build/rust-static-support.json index 08c78c656b..df45dfedc0 100644 --- a/test/cmocka/build/rust-static-support.json +++ b/test/cmocka/build/rust-static-support.json @@ -54,6 +54,7 @@ "test/cmocka/set-locale-link-support.c", "test/cmocka/set-video-levels-link-support.c", "test/cmocka/source-audio-capture-callback-link-support.c", + "test/cmocka/source-get-release-frame-link-support.c", "test/cmocka/source-save-load-link-support.c", "test/cmocka/source-settings-getter-link-support.c", "test/cmocka/source-weak-control-link-support.c", diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 43a53f0b66..14a91c4ce3 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -18197,6 +18197,21 @@ "OBS::native-test-cmocka" ] }, + "test_source_get_release_frame": { + "sources": [ + "test/cmocka/test_source_get_release_frame.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ] + }, "test_source_get_weak": { "sources": [ "test/cmocka/test_source_get_weak.c" @@ -30068,6 +30083,13 @@ ] ] }, + "test_source_get_release_frame": { + "target": "test_source_get_release_frame", + "command": [ + "${target}" + ], + "timeout_seconds": 30 + }, "test_source_get_weak": { "target": "test_source_get_weak", "command": [ diff --git a/test/cmocka/source-get-release-frame-link-support.c b/test/cmocka/source-get-release-frame-link-support.c new file mode 100644 index 0000000000..88f0d267fa --- /dev/null +++ b/test/cmocka/source-get-release-frame-link-support.c @@ -0,0 +1,4 @@ +/* The production async-frame adapters (remove_async_frame() included) for + * standalone Rust consumers of obs_source_get_frame() and + * obs_source_release_frame(). */ +#include "libobs/obs-source-get-release-frame-fields.c.h" diff --git a/test/cmocka/test_source_get_release_frame.c b/test/cmocka/test_source_get_release_frame.c new file mode 100644 index 0000000000..eccb15b642 --- /dev/null +++ b/test/cmocka/test_source_get_release_frame.c @@ -0,0 +1,308 @@ +/* Characterize obs_source_get_frame() and obs_source_release_frame() (#5757) + * on stack source fixtures: the NULL early returns (none touches the async + * mutex), the take of cur_async_frame with one added reference, and the + * release: a NULL source destroys the frame whatever its references, the + * last reference destroys it without touching the cache, any other count + * gives the frame back to the async cache (remove_async_frame()). */ +#include +#include +#include +#include +#include +#include +#include "obs-internal.h" +#include "util/threading.h" + +static int setup(void **state) +{ + struct obs_source *source = bzalloc(sizeof(*source)); + /* As obs_source_init(). */ + assert_int_equal(pthread_mutex_init_recursive(&source->async_mutex), 0); + *state = source; + return 0; +} + +static int teardown(void **state) +{ + struct obs_source *source = *state; + da_free(source->async_cache); + assert_int_equal(pthread_mutex_destroy(&source->async_mutex), 0); + bfree(source); + return 0; +} + +/* Two allocations, as obs_source_frame_create(): the frame and its data. */ +static struct obs_source_frame *new_frame(long refs, bool prev_frame) +{ + struct obs_source_frame *frame = bzalloc(sizeof(*frame)); + frame->data[0] = bmalloc(16); + frame->refs = refs; + frame->prev_frame = prev_frame; + return frame; +} + +static void free_frame(struct obs_source_frame *frame) +{ + bfree(frame->data[0]); + bfree(frame); +} + +static void cache_push(struct obs_source *source, struct obs_source_frame *frame, bool used, long unused_count) +{ + struct async_frame entry = {frame, unused_count, used}; + da_push_back(source->async_cache, &entry); +} + +/* async_mutex is recursive, so probe it from another thread. */ +struct probe { + struct obs_source *source; + int result; +}; + +static void *trylock_async(void *data) +{ + struct probe *p = data; + p->result = pthread_mutex_trylock(&p->source->async_mutex); + if (p->result == 0) + pthread_mutex_unlock(&p->source->async_mutex); + return NULL; +} + +static void expect_unlocked(struct obs_source *source) +{ + struct probe p = {source, -1}; + pthread_t thread; + assert_int_equal(pthread_create(&thread, NULL, trylock_async, &p), 0); + pthread_join(thread, NULL); + assert_int_equal(p.result, 0); +} + +/* Holds async_mutex on another thread, so an early return that locked would + * block instead of returning. */ +struct holder { + struct obs_source *source; + os_event_t *held; + os_event_t *release; +}; + +static void *hold_mutex(void *data) +{ + struct holder *h = data; + pthread_mutex_lock(&h->source->async_mutex); + os_event_signal(h->held); + os_event_wait(h->release); + pthread_mutex_unlock(&h->source->async_mutex); + return NULL; +} + +static void release_while_held(struct obs_source *held, obs_source_t *source, struct obs_source_frame *frame) +{ + struct holder h = {held, NULL, NULL}; + pthread_t thread; + assert_int_equal(os_event_init(&h.held, OS_EVENT_TYPE_MANUAL), 0); + assert_int_equal(os_event_init(&h.release, OS_EVENT_TYPE_MANUAL), 0); + assert_int_equal(pthread_create(&thread, NULL, hold_mutex, &h), 0); + os_event_wait(h.held); + obs_source_release_frame(source, frame); + os_event_signal(h.release); + pthread_join(thread, NULL); + os_event_destroy(h.held); + os_event_destroy(h.release); +} + +static void get_null_source(void **state) +{ + (void)state; + assert_null(obs_source_get_frame(NULL)); +} + +static void get_without_frame(void **state) +{ + struct obs_source *source = *state; + assert_null(obs_source_get_frame(source)); + assert_null(source->cur_async_frame); + expect_unlocked(source); +} + +static void get_takes_current_with_a_reference(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(1, true); + struct obs_source_frame *prev = new_frame(1, false); + source->cur_async_frame = frame; + source->prev_async_frame = prev; + cache_push(source, frame, true, 3); + + assert_ptr_equal(obs_source_get_frame(source), frame); + assert_null(source->cur_async_frame); + assert_int_equal(frame->refs, 2); + /* Nothing else is touched. */ + assert_true(frame->prev_frame); + assert_ptr_equal(source->prev_async_frame, prev); + assert_true(source->async_cache.array[0].used); + assert_int_equal(source->async_cache.array[0].unused_count, 3); + expect_unlocked(source); + + /* Taken once: the slot is empty now. */ + assert_null(obs_source_get_frame(source)); + assert_int_equal(frame->refs, 2); + + free_frame(frame); + free_frame(prev); +} + +static void release_null_frame(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(2, true); + cache_push(source, frame, true, 0); + long allocs = bnum_allocs(); + + release_while_held(source, source, NULL); + release_while_held(source, NULL, NULL); + assert_int_equal(bnum_allocs(), allocs); + assert_int_equal(frame->refs, 2); + assert_true(frame->prev_frame); + assert_true(source->async_cache.array[0].used); + expect_unlocked(source); + + free_frame(frame); +} + +/* A NULL source destroys the frame, whatever its references. */ +static void release_null_source_destroys(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(5, true); + long allocs = bnum_allocs(); + + release_while_held(source, NULL, frame); + assert_int_equal(bnum_allocs(), allocs - 2); +} + +/* The last reference destroys the frame and leaves the cache alone + * (characterized, not endorsed: a cached frame keeps its slot). */ +static void release_last_reference_destroys(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(1, true); + cache_push(source, frame, true, 4); + long allocs = bnum_allocs(); + + obs_source_release_frame(source, frame); + assert_int_equal(bnum_allocs(), allocs - 2); + assert_true(source->async_cache.array[0].used); + assert_int_equal(source->async_cache.array[0].unused_count, 4); + expect_unlocked(source); + + source->async_cache.array[0].frame = NULL; +} + +/* Any other count gives the frame back to the cache: prev_frame cleared, + * the first slot that holds it marked unused, nothing else changed. */ +static void release_returns_to_cache(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *other = new_frame(1, true); + struct obs_source_frame *frame = new_frame(3, true); + cache_push(source, other, true, 1); + cache_push(source, frame, true, 2); + cache_push(source, frame, true, 5); + long allocs = bnum_allocs(); + + obs_source_release_frame(source, frame); + assert_int_equal(bnum_allocs(), allocs); + assert_int_equal(frame->refs, 2); + assert_false(frame->prev_frame); + assert_true(other->prev_frame); + assert_true(source->async_cache.array[0].used); + assert_false(source->async_cache.array[1].used); + assert_int_equal(source->async_cache.array[1].unused_count, 2); + assert_true(source->async_cache.array[2].used); + assert_int_equal(source->async_cache.array[2].unused_count, 5); + expect_unlocked(source); + + /* Again: the first holder is already unused and stays so; the walk + * still stops there. */ + obs_source_release_frame(source, frame); + assert_int_equal(frame->refs, 1); + assert_false(source->async_cache.array[1].used); + assert_true(source->async_cache.array[2].used); + + free_frame(other); + free_frame(frame); +} + +/* A frame the cache does not hold only loses its reference and + * prev_frame. */ +static void release_uncached(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *other = new_frame(1, true); + struct obs_source_frame *frame = new_frame(2, true); + cache_push(source, other, true, 0); + + obs_source_release_frame(source, frame); + assert_int_equal(frame->refs, 1); + assert_false(frame->prev_frame); + assert_true(source->async_cache.array[0].used); + assert_true(other->prev_frame); + expect_unlocked(source); + + free_frame(other); + free_frame(frame); +} + +/* Zero references go below zero and are not destroyed (characterized, not + * endorsed). */ +static void release_unreferenced(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(0, true); + cache_push(source, frame, true, 0); + long allocs = bnum_allocs(); + + obs_source_release_frame(source, frame); + assert_int_equal(bnum_allocs(), allocs); + assert_int_equal(frame->refs, -1); + assert_false(frame->prev_frame); + assert_false(source->async_cache.array[0].used); + + free_frame(frame); +} + +/* The pair as obs_source_update_async_video() uses it. */ +static void get_then_release(void **state) +{ + struct obs_source *source = *state; + struct obs_source_frame *frame = new_frame(1, false); + source->cur_async_frame = frame; + cache_push(source, frame, true, 0); + + struct obs_source_frame *got = obs_source_get_frame(source); + assert_ptr_equal(got, frame); + obs_source_release_frame(source, got); + assert_int_equal(frame->refs, 1); + assert_false(source->async_cache.array[0].used); + assert_null(source->cur_async_frame); + expect_unlocked(source); + + free_frame(frame); +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(get_null_source), + cmocka_unit_test_setup_teardown(get_without_frame, setup, teardown), + cmocka_unit_test_setup_teardown(get_takes_current_with_a_reference, setup, teardown), + cmocka_unit_test_setup_teardown(release_null_frame, setup, teardown), + cmocka_unit_test_setup_teardown(release_null_source_destroys, setup, teardown), + cmocka_unit_test_setup_teardown(release_last_reference_destroys, setup, teardown), + cmocka_unit_test_setup_teardown(release_returns_to_cache, setup, teardown), + cmocka_unit_test_setup_teardown(release_uncached, setup, teardown), + cmocka_unit_test_setup_teardown(release_unreferenced, setup, teardown), + cmocka_unit_test_setup_teardown(get_then_release, setup, teardown), + }; + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/tests.d/test_source_get_release_frame.cmake b/test/cmocka/tests.d/test_source_get_release_frame.cmake new file mode 100644 index 0000000000..c98f9a81ac --- /dev/null +++ b/test/cmocka/tests.d/test_source_get_release_frame.cmake @@ -0,0 +1 @@ +# Canonical target and test: test/cmocka/build/test-graph.json.