From f35e3f0e0ad7734b402e0264c40bc3b16d9fd51d Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Thu, 26 Nov 2026 21:23:35 -0500 Subject: [PATCH 1/4] libobs: extract obs_source_restore_filters verbatim (Refs #5801) Move obs_source_restore_filters() unchanged out of obs-source.c.h into obs-source-restore-filters.c.h, still compiled in the live core-source group. It is EXPORT and declared in obs.h, and the filter chain rules it asks are declared in obs-source-filter-chain.h (in the precompiled header), so the earlier position in the unity group needs no new declaration. No Rust, no behavior change. Co-Authored-By: Claude Opus 5.5 --- libobs/build/libobs.core-source+.h.c | 1 + libobs/obs-source-restore-filters.c.h | 80 +++++++++++++++++++++++++++ libobs/obs-source.c.h | 79 -------------------------- 3 files changed, 81 insertions(+), 79 deletions(-) create mode 100644 libobs/obs-source-restore-filters.c.h diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index 29bb8fdb18..f7d702df6f 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -109,6 +109,7 @@ #include "libobs/obs-source-push-to-enable-fields.c.h" #include "libobs/obs-source-remove-fields.c.h" #include "libobs/obs-source-removed-fields.c.h" +#include "libobs/obs-source-restore-filters.c.h" #include "libobs/obs-source-save-load-fields.c.h" #include "libobs/obs-source-set-name-fields.c.h" #include "libobs/obs-source-settings-getter-fields.c.h" diff --git a/libobs/obs-source-restore-filters.c.h b/libobs/obs-source-restore-filters.c.h new file mode 100644 index 0000000000..a521c0cc5e --- /dev/null +++ b/libobs/obs-source-restore-filters.c.h @@ -0,0 +1,80 @@ +#include "libobs/build/libobs.pch.h" + +void obs_source_restore_filters(obs_source_t *source, obs_data_array_t *array) +{ + if (!obs_source_valid(source, "obs_source_restore_filters")) + return; + if (!obs_ptr_valid(array, "obs_source_restore_filters")) + return; + + DARRAY(obs_source_t *) cur_filters; + DARRAY(obs_source_t *) new_filters; + obs_source_t *prev = NULL; + + da_init(cur_filters); + da_init(new_filters); + + pthread_mutex_lock(&source->filter_mutex); + + /* clear filter list */ + da_reserve(cur_filters, source->filters.num); + da_reserve(new_filters, source->filters.num); + for (size_t i = 0; i < source->filters.num; i++) { + obs_source_t *filter = source->filters.array[i]; + da_push_back(cur_filters, &filter); + filter->filter_parent = NULL; + filter->filter_target = NULL; + } + + da_free(source->filters); + pthread_mutex_unlock(&source->filter_mutex); + + /* add backed up filters */ + size_t count = obs_data_array_count(array); + for (size_t i = 0; i < count; i++) { + obs_data_t *data = obs_data_array_item(array, i); + const char *name = obs_data_get_string(data, "name"); + obs_source_t *filter = NULL; + + /* if backed up filter already exists, don't create */ + for (size_t j = 0; j < cur_filters.num; j++) { + obs_source_t *cur = cur_filters.array[j]; + const char *cur_name = cur->context.name; + if (obs_source_filter_chain_restore_matches(cur_name, name)) { + filter = obs_source_get_ref(cur); + break; + } + } + + int restore_step = obs_source_filter_chain_restore_step(filter != NULL); + if (restore_step == OBS_SOURCE_FILTER_CHAIN_RESTORE_LOAD) + filter = obs_load_source(data); + else if (restore_step == OBS_SOURCE_FILTER_CHAIN_RESTORE_LOAD_PRIVATE) + filter = obs_load_private_source(data); + + /* add filter; parents are set once every target is (#2172) */ + if (prev) + prev->filter_target = filter; + prev = filter; + da_push_back(new_filters, &filter); + + obs_data_release(data); + } + + if (prev) + prev->filter_target = source; + for (size_t i = 0; i < new_filters.num; i++) + new_filters.array[i]->filter_parent = source; + + pthread_mutex_lock(&source->filter_mutex); + da_move(source->filters, new_filters); + pthread_mutex_unlock(&source->filter_mutex); + + /* release filters */ + for (size_t i = 0; i < cur_filters.num; i++) { + obs_source_t *filter = cur_filters.array[i]; + obs_source_release(filter); + } + + da_free(cur_filters); +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index 5668f78ea9..b8b53b1d2c 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -2863,85 +2863,6 @@ _Static_assert(OBS_SOURCE_MEDIA_CONTROLLABLE == OBS_SOURCE_CONTROLLABLE_MEDIA, " _Static_assert(OBS_SOURCE_MEDIA_STATE_NONE == OBS_MEDIA_STATE_NONE, "OBS_MEDIA_STATE_NONE"); _Static_assert(sizeof(enum obs_media_state) == sizeof(int), "enum obs_media_state is passed as int"); -void obs_source_restore_filters(obs_source_t *source, obs_data_array_t *array) -{ - if (!obs_source_valid(source, "obs_source_restore_filters")) - return; - if (!obs_ptr_valid(array, "obs_source_restore_filters")) - return; - - DARRAY(obs_source_t *) cur_filters; - DARRAY(obs_source_t *) new_filters; - obs_source_t *prev = NULL; - - da_init(cur_filters); - da_init(new_filters); - - pthread_mutex_lock(&source->filter_mutex); - - /* clear filter list */ - da_reserve(cur_filters, source->filters.num); - da_reserve(new_filters, source->filters.num); - for (size_t i = 0; i < source->filters.num; i++) { - obs_source_t *filter = source->filters.array[i]; - da_push_back(cur_filters, &filter); - filter->filter_parent = NULL; - filter->filter_target = NULL; - } - - da_free(source->filters); - pthread_mutex_unlock(&source->filter_mutex); - - /* add backed up filters */ - size_t count = obs_data_array_count(array); - for (size_t i = 0; i < count; i++) { - obs_data_t *data = obs_data_array_item(array, i); - const char *name = obs_data_get_string(data, "name"); - obs_source_t *filter = NULL; - - /* if backed up filter already exists, don't create */ - for (size_t j = 0; j < cur_filters.num; j++) { - obs_source_t *cur = cur_filters.array[j]; - const char *cur_name = cur->context.name; - if (obs_source_filter_chain_restore_matches(cur_name, name)) { - filter = obs_source_get_ref(cur); - break; - } - } - - int restore_step = obs_source_filter_chain_restore_step(filter != NULL); - if (restore_step == OBS_SOURCE_FILTER_CHAIN_RESTORE_LOAD) - filter = obs_load_source(data); - else if (restore_step == OBS_SOURCE_FILTER_CHAIN_RESTORE_LOAD_PRIVATE) - filter = obs_load_private_source(data); - - /* add filter; parents are set once every target is (#2172) */ - if (prev) - prev->filter_target = filter; - prev = filter; - da_push_back(new_filters, &filter); - - obs_data_release(data); - } - - if (prev) - prev->filter_target = source; - for (size_t i = 0; i < new_filters.num; i++) - new_filters.array[i]->filter_parent = source; - - pthread_mutex_lock(&source->filter_mutex); - da_move(source->filters, new_filters); - pthread_mutex_unlock(&source->filter_mutex); - - /* release filters */ - for (size_t i = 0; i < cur_filters.num; i++) { - obs_source_t *filter = cur_filters.array[i]; - obs_source_release(filter); - } - - da_free(cur_filters); -} - /* File-local macros: keep them out of the next source of a unity build. */ #undef get_weak From 6eef2d6de75479366826347194a3d1622eaef26d Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Thu, 26 Nov 2026 21:30:04 -0500 Subject: [PATCH 2/4] test: characterize obs_source_restore_filters (Refs #5801) New cmocka test through the real core (xvfb-run, skips without a display), against hybrid libobs and the C reference: a NULL source or array logs the validity check's line once (the source first) with filter_mutex free and changes nothing. Otherwise each array item reuses the first current filter whose name matches (the same filter, whatever the item's id; an unnamed filter never matches, not even an item named "", since no filter can have a blank name) or is loaded from its data, while the list is empty, the old filters have no parent and no target, and filter_mutex is free (probed from a second thread when a filter type's create callback runs). Each restored filter targets the next, the last the source; while a later item loads, an earlier one already targets its successor but has no parent yet: the parents are set once every target is (#2172). The new list holds one reference per entry, so a duplicated name lists the same filter twice with two references; the old filters are released once each, in old order, after the new list is in place and with the lock free, and one not reused goes away. No filter signal fires, and nothing logs when every item is reused. Whether a load is public or private is not checked (the C reference loads public, hybrid libobs private, a difference of the filter chain rules, #2981); a current filter whose last reference is gone can't be listed, so it goes to Tier 1 and Tier 3. Co-Authored-By: Claude Opus 5.5 --- test/cmocka/build/test-graph.json | 25 + test/cmocka/test_source_restore_filters.c | 742 ++++++++++++++++++ .../tests.d/test_source_restore_filters.cmake | 9 + 3 files changed, 776 insertions(+) create mode 100644 test/cmocka/test_source_restore_filters.c create mode 100644 test/cmocka/tests.d/test_source_restore_filters.cmake diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 3fecbd463b..6368b10fb4 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -19055,6 +19055,19 @@ } ] }, + "test_source_restore_filters": { + "sources": [ + "test/cmocka/test_source_restore_filters.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ] + }, "test_source_select_list": { "sources": [ "test/cmocka/test_source_select_list.cpp", @@ -30547,6 +30560,18 @@ ], "timeout_seconds": 30 }, + "test_source_restore_filters": { + "target": "test_source_restore_filters", + "command": [ + "${target}" + ], + "optional_prefixes": [ + [ + "xvfb-run", + "-a" + ] + ] + }, "test_source_select_list": { "target": "test_source_select_list", "requires": "HAVE_QT_CORE_TEST_OWNER", diff --git a/test/cmocka/test_source_restore_filters.c b/test/cmocka/test_source_restore_filters.c new file mode 100644 index 0000000000..67b2c10a15 --- /dev/null +++ b/test/cmocka/test_source_restore_filters.c @@ -0,0 +1,742 @@ +/* Characterization of obs_source_restore_filters() (#5801), against the + * hybrid libobs and the C reference through the real core. + * + * - An invalid source or a NULL array logs the validity check's line once + * (the source checked first) with filter_mutex free, and locks or changes + * nothing. + * - Every current filter is taken off the list: while the backed-up filters + * are restored, the source's list is empty and each old filter has no + * parent and no target, and filter_mutex is free. + * - For each array item in order, the first current filter whose name + * matches the item's "name" is reused (the same filter, whatever the + * item's "id"); an unnamed current filter never matches, not even an + * item named "" (no filter can have a blank name). An item with no + * match is loaded from its data (a filter of the item's id and name; the + * C reference loads it public, hybrid libobs private, an intentional + * difference of the filter chain rules (#2981), so neither is checked). + * Each restored filter targets the next one, the last the source; while a + * later item loads, the earlier ones already target their successor but + * have no parent: every parent is set to the source only once every + * target is (#2172). + * - The new list holds one reference to each entry; a duplicate name in the + * array reuses the same current filter each time, so it is listed twice. + * - Afterwards each old filter is released once, in old order, with the new + * list in place and filter_mutex free; a filter not reused goes away. + * - No filter signal fires and, when every item is reused, nothing is + * logged. + * + * A current filter that can't be referenced (its last reference gone) is + * not reachable here: a listed filter holds the list's reference until the + * restore releases it. The Rust port's Tier 1 and Tier 3 tests cover it. + * + * Whether filter_mutex is free is checked from a second thread (the mutex + * is recursive, so the calling thread could always take it): + * obs_source_filter_get_index() takes the mutex there. + * + * obs_startup() needs a display on Linux (run under xvfb-run); the cases + * skip when it cannot start. */ + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#define BOX_ID "restore_filters_box" +#define FILTER_ID "restore_filters_filter" +#define OTHER_FILTER_ID "restore_filters_other_filter" +#define WATCH_ID "restore_filters_watch" + +static bool obs_up; + +/* What happened, in order, while recording: filter signals of the source + * under test, filter loads, old filter releases and the validity lines, + * separated by '|'. */ +static bool recording; +static struct dstr events; +static int null_lines; +static int all_lines; + +/* The source under test. */ +static obs_source_t *watched; +/* A filter whose parent and target a load reports. */ +static obs_source_t *watched_filter; + +/* A probe thread that is still waiting for filter_mutex. */ +static pthread_t stuck_probe; +static bool probe_stuck; + +static void record(const char *text) +{ + if (!recording) + return; + if (events.len) + dstr_cat(&events, "|"); + dstr_cat(&events, text); +} + +struct probe { + obs_source_t *source; + os_event_t *done; +}; + +static void *probe_thread(void *param) +{ + struct probe *p = param; + obs_source_filter_get_index(p->source, p->source); + os_event_signal(p->done); + return NULL; +} + +/* Whether another thread can take source's filter_mutex now. */ +static bool mutex_free(obs_source_t *source) +{ + struct probe *p = bzalloc(sizeof(*p)); + pthread_t thread; + + p->source = source; + assert_int_equal(os_event_init(&p->done, OS_EVENT_TYPE_MANUAL), 0); + assert_int_equal(pthread_create(&thread, NULL, probe_thread, p), 0); + bool free = os_event_timedwait(p->done, 2000) == 0; + if (free) { + pthread_join(thread, NULL); + os_event_destroy(p->done); + bfree(p); + } else { + /* Joined once the call under test has returned; the probe's + * state is left to it. */ + assert_false(probe_stuck); + stuck_probe = thread; + probe_stuck = true; + } + return free; +} + +static void join_stuck_probe(void) +{ + if (probe_stuck) { + pthread_join(stuck_probe, NULL); + probe_stuck = false; + } +} + +static const char *lock_state(void) +{ + if (!watched) + return "-"; + return mutex_free(watched) ? "free" : "held"; +} + +static void log_handler(int lvl, const char *msg, va_list args, void *p) +{ + (void)p; + if (recording) { + char line[256]; + va_list copy; + va_copy(copy, args); + vsnprintf(line, sizeof(line), msg, copy); + va_end(copy); + all_lines++; + if (lvl == LOG_DEBUG && strstr(line, "obs_source_restore_filters")) { + struct dstr text = {0}; + dstr_printf(&text, "%s(%s)", line, lock_state()); + record(text.array); + dstr_free(&text); + null_lines++; + } + } + if (lvl > LOG_WARNING) + return; + vfprintf(stderr, msg, args); + fprintf(stderr, "\n"); +} + +static void record_start(obs_source_t *source) +{ + dstr_free(&events); + null_lines = 0; + all_lines = 0; + watched = source; + recording = true; +} + +static void record_expect(const char *expected) +{ + recording = false; + watched = NULL; + watched_filter = NULL; + join_stuck_probe(); + assert_string_equal(events.array ? events.array : "", expected); + dstr_free(&events); +} + +static const char *name_of(obs_source_t *source) +{ + if (!source) + return "-"; + const char *name = obs_source_get_name(source); + return name ? name : "(unnamed)"; +} + +/* "(,)", for the source under test only. */ +static void on_filter_signal(void *data, calldata_t *cd) +{ + obs_source_t *source = calldata_ptr(cd, "source"); + obs_source_t *filter = calldata_ptr(cd, "filter"); + if (!recording || !watched || source != watched) + return; + struct dstr text = {0}; + dstr_printf(&text, "%s(%s,%s)", (const char *)data, name_of(source), name_of(filter)); + record(text.array); + dstr_free(&text); +} + +static const char *box_name(void *type_data) +{ + (void)type_data; + return "box"; +} + +static const char *filter_name(void *type_data) +{ + (void)type_data; + return "restore test filter"; +} + +/* "load(,,,>)": + * a filter created while recording, the source's filter count and lock + * state then. */ +static void *filter_create(obs_data_t *settings, obs_source_t *source) +{ + (void)settings; + if (recording && watched) { + struct dstr text = {0}; + /* A blank name gets a generated one, numbered across the run. */ + const char *name = name_of(source); + if (strncmp(name, "__unnamed", 9) == 0) + name = "generated"; + dstr_printf(&text, "load(%s,%d,%s,%s>%s)", name, (int)obs_source_filter_count(watched), lock_state(), + name_of(obs_filter_get_parent(watched_filter)), + name_of(obs_filter_get_target(watched_filter))); + record(text.array); + dstr_free(&text); + } + return source; +} + +static void *data_create(obs_data_t *settings, obs_source_t *source) +{ + (void)settings; + return source; +} + +static void data_destroy(void *data) +{ + (void)data; +} + +static uint32_t box_size(void *data) +{ + (void)data; + return 64; +} + +/* "released(,,)": runs when parent, an old filter + * this watch filter sits on, is destroyed, with the count and lock state of + * the source under test then. */ +static void watch_removed(void *data, obs_source_t *parent) +{ + (void)data; + if (!recording || !watched) + return; + struct dstr text = {0}; + dstr_printf(&text, "released(%s,%d,%s)", name_of(parent), (int)obs_source_filter_count(watched), lock_state()); + record(text.array); + dstr_free(&text); +} + +static void register_types(void) +{ + struct obs_source_info box = { + .id = BOX_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_VIDEO, + .get_name = box_name, + .create = data_create, + .destroy = data_destroy, + .get_width = box_size, + .get_height = box_size, + }; + struct obs_source_info filter = { + .id = FILTER_ID, + .type = OBS_SOURCE_TYPE_FILTER, + .output_flags = OBS_SOURCE_VIDEO, + .get_name = filter_name, + .create = filter_create, + .destroy = data_destroy, + }; + struct obs_source_info other_filter = { + .id = OTHER_FILTER_ID, + .type = OBS_SOURCE_TYPE_FILTER, + .output_flags = OBS_SOURCE_VIDEO, + .get_name = filter_name, + .create = filter_create, + .destroy = data_destroy, + }; + struct obs_source_info watch = { + .id = WATCH_ID, + .type = OBS_SOURCE_TYPE_FILTER, + .output_flags = OBS_SOURCE_VIDEO, + .get_name = filter_name, + .create = data_create, + .destroy = data_destroy, + .filter_remove = watch_removed, + }; + obs_register_source(&box); + obs_register_source(&filter); + obs_register_source(&other_filter); + obs_register_source(&watch); +} + +/* The filter signals recorded; each name is also its handler's data. */ +static const char *const source_signals[] = {"filter_add", "filter_remove", "reorder_filters"}; +static const char *const global_signals[] = {"source_filter_add", "source_filter_remove"}; +#define SIGNAL_COUNT(list) (sizeof(list) / sizeof((list)[0])) + +static obs_source_t *box(const char *name) +{ + obs_source_t *source = obs_source_create(BOX_ID, name, NULL, NULL); + assert_non_null(source); + signal_handler_t *handler = obs_source_get_signal_handler(source); + for (size_t i = 0; i < SIGNAL_COUNT(source_signals); i++) + signal_handler_connect(handler, source_signals[i], on_filter_signal, (void *)source_signals[i]); + return source; +} + +static void drop(obs_source_t *source) +{ + signal_handler_t *handler = obs_source_get_signal_handler(source); + for (size_t i = 0; i < SIGNAL_COUNT(source_signals); i++) + signal_handler_disconnect(handler, source_signals[i], on_filter_signal, (void *)source_signals[i]); + obs_source_remove(source); + obs_source_release(source); +} + +/* A new filter on source (added at the front of its list), with a + * reference the caller owns. */ +static obs_source_t *add_filter(obs_source_t *source, const char *id, const char *name) +{ + obs_source_t *filter = obs_source_create_private(id, name, NULL); + assert_non_null(filter); + obs_source_filter_add(source, filter); + return filter; +} + +/* Puts a watch filter on filter, so its destruction is recorded. */ +static void watch(obs_source_t *filter) +{ + obs_source_t *w = obs_source_create_private(WATCH_ID, "watch", NULL); + assert_non_null(w); + obs_source_filter_add(filter, w); + obs_source_release(w); +} + +static void describe(obs_source_t *parent, obs_source_t *child, void *param) +{ + struct dstr *text = param; + struct dstr entry = {0}; + dstr_printf(&entry, "%s>%s", name_of(child), name_of(obs_filter_get_target(child))); + /* Every listed filter has the source as its parent. */ + assert_ptr_equal(obs_filter_get_parent(child), parent); + /* obs_source_enum_filters() walks the list from the last entry. */ + if (text->len) + dstr_insert(text, 0, ","); + dstr_insert(text, 0, entry.array); + dstr_free(&entry); +} + +/* The source's list from the first entry, each as ">". */ +static void expect_chain(obs_source_t *source, const char *expected) +{ + struct dstr listed = {0}; + obs_source_enum_filters(source, describe, &listed); + assert_string_equal(listed.array ? listed.array : "", expected); + dstr_free(&listed); +} + +struct find { + const char *name; + obs_source_t *found; +}; + +static void find_named(obs_source_t *parent, obs_source_t *child, void *param) +{ + struct find *f = param; + (void)parent; + if (!f->found && strcmp(name_of(child), f->name) == 0) + f->found = child; +} + +/* A new reference to the listed filter called name. */ +static obs_source_t *listed(obs_source_t *source, const char *name) +{ + struct find f = {name, NULL}; + obs_source_enum_filters(source, find_named, &f); + assert_non_null(f.found); + return obs_source_get_ref(f.found); +} + +/* An array of backed-up filters: pairs of name and id, ending in NULL. */ +static obs_data_array_t *backup_of(const char *name, ...) +{ + obs_data_array_t *array = obs_data_array_create(); + va_list args; + va_start(args, name); + for (const char *n = name; n; n = va_arg(args, const char *)) { + const char *id = va_arg(args, const char *); + obs_data_t *item = obs_data_create(); + obs_data_set_string(item, "name", n); + obs_data_set_string(item, "id", id); + obs_data_set_string(item, "versioned_id", id); + obs_data_array_push_back(array, item); + obs_data_release(item); + } + va_end(args); + return array; +} + +/* Whether the list's reference is the only one left on filter: dropping + * the caller's keeps it alive, removing it from source frees it. */ +static void expect_one_list_reference(obs_source_t *source, obs_source_t *filter) +{ + obs_weak_source_t *weak = obs_source_get_weak_source(filter); + obs_source_release(filter); + assert_false(obs_weak_source_expired(weak)); + obs_source_filter_remove(source, filter); + assert_true(obs_weak_source_expired(weak)); + obs_weak_source_release(weak); +} + +static bool skip_without_core(void) +{ + if (!obs_up) { + skip(); + return true; + } + return false; +} + +static void null_arguments(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + obs_data_array_t *array = backup_of("b", FILTER_ID, NULL); + + record_start(src); + obs_source_restore_filters(NULL, array); + obs_source_restore_filters(src, NULL); + obs_source_restore_filters(NULL, NULL); + assert_int_equal(null_lines, 3); + record_expect("obs_source_restore_filters: Null 'source' parameter(free)|" + "obs_source_restore_filters: Null 'array' parameter(free)|" + "obs_source_restore_filters: Null 'source' parameter(free)"); + + expect_chain(src, "a>src"); + assert_true(mutex_free(src)); + obs_data_array_release(array); + expect_one_list_reference(src, a); + drop(src); +} + +static void reuses_matching_filters(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *c = add_filter(src, FILTER_ID, "c"); + obs_source_t *b = add_filter(src, FILTER_ID, "b"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + expect_chain(src, "a>b,b>c,c>src"); + /* The array's ids don't matter for a filter that is reused. */ + obs_data_array_t *array = backup_of("c", OTHER_FILTER_ID, "a", FILTER_ID, "b", FILTER_ID, NULL); + + record_start(src); + obs_source_restore_filters(src, array); + record_expect(""); + /* Nothing logs when every item is reused. */ + assert_int_equal(all_lines, 0); + + expect_chain(src, "c>a,a>b,b>src"); + assert_string_equal(obs_source_get_id(c), FILTER_ID); + assert_true(mutex_free(src)); + obs_data_array_release(array); + /* The old reference was released, the new one kept. */ + expect_one_list_reference(src, a); + expect_one_list_reference(src, b); + expect_one_list_reference(src, c); + drop(src); +} + +static void loads_unmatched_items_with_the_lock_free(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *b = add_filter(src, FILTER_ID, "b"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + expect_chain(src, "a>b,b>src"); + obs_data_array_t *array = + backup_of("n1", FILTER_ID, "a", FILTER_ID, "n2", OTHER_FILTER_ID, "b", FILTER_ID, NULL); + + /* While n1 loads, the list is empty and a (reused next) has no parent + * and no target. While n2 loads, a still has neither: its target is + * set once n2 is loaded, its parent at the end. */ + record_start(src); + watched_filter = a; + obs_source_restore_filters(src, array); + record_expect("load(n1,0,free,->-)|load(n2,0,free,->-)"); + + expect_chain(src, "n1>a,a>n2,n2>b,b>src"); + obs_source_t *n1 = listed(src, "n1"); + obs_source_t *n2 = listed(src, "n2"); + assert_string_equal(obs_source_get_id(n1), FILTER_ID); + assert_string_equal(obs_source_get_id(n2), OTHER_FILTER_ID); + obs_data_array_release(array); + expect_one_list_reference(src, a); + expect_one_list_reference(src, b); + expect_one_list_reference(src, n1); + expect_one_list_reference(src, n2); + drop(src); +} + +static void targets_are_set_before_parents(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + obs_data_array_t *array = backup_of("a", FILTER_ID, "n1", FILTER_ID, "n2", FILTER_ID, NULL); + + /* While n2 loads, a targets n1 (set once n1 was loaded) but has no + * parent yet (#2172). */ + record_start(src); + watched_filter = a; + obs_source_restore_filters(src, array); + record_expect("load(n1,0,free,->-)|load(n2,0,free,->n1)"); + + expect_chain(src, "a>n1,n1>n2,n2>src"); + obs_data_array_release(array); + expect_one_list_reference(src, a); + drop(src); +} + +static void releases_old_filters_in_old_order(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *z = add_filter(src, FILTER_ID, "z"); + obs_source_t *y = add_filter(src, FILTER_ID, "y"); + obs_source_t *x = add_filter(src, FILTER_ID, "x"); + watch(x); + watch(z); + expect_chain(src, "x>y,y>z,z>src"); + /* Only the list holds x and z. */ + obs_source_release(x); + obs_source_release(z); + obs_data_array_t *array = backup_of("y", FILTER_ID, NULL); + + /* x and z go away once the new list is in place and the lock free. */ + record_start(src); + obs_source_restore_filters(src, array); + record_expect("released(x,1,free)|released(z,1,free)"); + + expect_chain(src, "y>src"); + obs_data_array_release(array); + expect_one_list_reference(src, y); + drop(src); +} + +static void empty_array_drops_every_filter(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *b = add_filter(src, FILTER_ID, "b"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + obs_weak_source_t *weak_a = obs_source_get_weak_source(a); + obs_weak_source_t *weak_b = obs_source_get_weak_source(b); + obs_data_array_t *array = obs_data_array_create(); + + record_start(src); + obs_source_restore_filters(src, array); + record_expect(""); + + expect_chain(src, ""); + assert_null(obs_filter_get_parent(a)); + assert_null(obs_filter_get_target(a)); + assert_null(obs_filter_get_parent(b)); + assert_null(obs_filter_get_target(b)); + /* The list's references are gone: the caller's were the last. */ + obs_source_release(a); + obs_source_release(b); + assert_true(obs_weak_source_expired(weak_a)); + assert_true(obs_weak_source_expired(weak_b)); + obs_weak_source_release(weak_a); + obs_weak_source_release(weak_b); + + /* An empty array on an empty list: still nothing. */ + record_start(src); + obs_source_restore_filters(src, array); + record_expect(""); + assert_int_equal(all_lines, 0); + expect_chain(src, ""); + + obs_data_array_release(array); + drop(src); +} + +static void duplicate_names_reuse_the_same_filter(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *b = add_filter(src, FILTER_ID, "b"); + obs_source_t *a = add_filter(src, FILTER_ID, "a"); + obs_data_array_t *array = backup_of("a", FILTER_ID, "a", OTHER_FILTER_ID, NULL); + + record_start(src); + obs_source_restore_filters(src, array); + record_expect(""); + + /* a is listed twice; the last target written (the source) wins. */ + expect_chain(src, "a>src,a>src"); + obs_data_array_release(array); + /* Two list references: the first remove leaves a listed. */ + obs_weak_source_t *weak = obs_source_get_weak_source(a); + obs_source_release(a); + obs_source_filter_remove(src, a); + assert_false(obs_weak_source_expired(weak)); + assert_int_equal(obs_source_filter_count(src), 1); + obs_source_filter_remove(src, a); + assert_true(obs_weak_source_expired(weak)); + obs_weak_source_release(weak); + /* b, not in the array, was dropped. */ + assert_null(obs_filter_get_parent(b)); + obs_source_release(b); + drop(src); +} + +static void unnamed_filter_never_matches(void **state) +{ + (void)state; + if (skip_without_core()) + return; + obs_source_t *src = box("src"); + obs_source_t *x = add_filter(src, FILTER_ID, "x"); + obs_source_t *unnamed = add_filter(src, FILTER_ID, NULL); + assert_null(obs_source_get_name(unnamed)); + obs_weak_source_t *weak = obs_source_get_weak_source(unnamed); + /* No filter can be named "" (a blank name gets a generated one), so + * an item named "" matches no current filter, the unnamed one + * included: it is loaded. */ + obs_data_array_t *array = backup_of("", FILTER_ID, "x", FILTER_ID, NULL); + + record_start(src); + watched_filter = x; + obs_source_restore_filters(src, array); + record_expect("load(generated,0,free,->-)"); + + assert_int_equal(obs_source_filter_count(src), 2); + obs_source_t *loaded = listed(src, "x"); + assert_ptr_equal(loaded, x); + obs_source_release(loaded); + assert_null(obs_filter_get_parent(unnamed)); + assert_null(obs_filter_get_target(unnamed)); + obs_source_release(unnamed); + assert_true(obs_weak_source_expired(weak)); + obs_weak_source_release(weak); + obs_data_array_release(array); + expect_one_list_reference(src, x); + drop(src); +} + +static void no_task(void *param) +{ + (void)param; +} + +static int teardown(void **state) +{ + (void)state; + recording = false; + watched = NULL; + watched_filter = NULL; + dstr_free(&events); + join_stuck_probe(); + if (obs_up) + obs_queue_task(OBS_TASK_DESTROY, no_task, NULL, true); + return 0; +} + +static int group_setup(void **state) +{ + (void)state; + base_set_log_handler(log_handler, NULL); + obs_up = obs_startup("en-US", NULL, NULL); + if (obs_up) { + register_types(); + signal_handler_t *handler = obs_get_signal_handler(); + for (size_t i = 0; i < SIGNAL_COUNT(global_signals); i++) + signal_handler_connect(handler, global_signals[i], on_filter_signal, (void *)global_signals[i]); + } else { + fprintf(stderr, "obs_startup failed (no display?), skipping\n"); + } + return 0; +} + +static int group_teardown(void **state) +{ + (void)state; + if (obs_up) { + signal_handler_t *handler = obs_get_signal_handler(); + for (size_t i = 0; i < SIGNAL_COUNT(global_signals); i++) + signal_handler_disconnect(handler, global_signals[i], on_filter_signal, + (void *)global_signals[i]); + obs_shutdown(); + } + return 0; +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test_teardown(null_arguments, teardown), + cmocka_unit_test_teardown(reuses_matching_filters, teardown), + cmocka_unit_test_teardown(loads_unmatched_items_with_the_lock_free, teardown), + cmocka_unit_test_teardown(targets_are_set_before_parents, teardown), + cmocka_unit_test_teardown(releases_old_filters_in_old_order, teardown), + cmocka_unit_test_teardown(empty_array_drops_every_filter, teardown), + cmocka_unit_test_teardown(duplicate_names_reuse_the_same_filter, teardown), + cmocka_unit_test_teardown(unnamed_filter_never_matches, teardown), + }; + + return cmocka_run_group_tests(tests, group_setup, group_teardown); +} diff --git a/test/cmocka/tests.d/test_source_restore_filters.cmake b/test/cmocka/tests.d/test_source_restore_filters.cmake new file mode 100644 index 0000000000..062c6b1ef9 --- /dev/null +++ b/test/cmocka/tests.d/test_source_restore_filters.cmake @@ -0,0 +1,9 @@ +# obs_source_restore_filters (#5801): an invalid source or a NULL array logs +# the validity check's line once and changes nothing; otherwise the current +# filters are taken off the list, each array item reuses the first current +# filter of its name (never an unnamed one) or is loaded with filter_mutex +# free, each restored filter targets the next (the last the source), every +# parent is set once every target is, and the old filters are released once +# each, in old order, after the new list is in place. No signals. Real core +# under xvfb-run. Registered once in build/test-graph.json, consumed by CMake +# and Cargo. From e103198a33fe65f8a1b8766f6f2f1dbd8ab1eaeb Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Thu, 26 Nov 2026 21:30:21 -0500 Subject: [PATCH 3/4] test: RED obs_source_restore_filters safe core (Refs #5801) New obs-source module restore_filters with a todo!() core over a RestoreList trait, and Tier 1 mirrors of test_source_restore_filters.c on a model that records every call and checks the lock state of each: the NULL lines (source first) with nothing touched; on every chain of up to 6 current filters (an unnamed one, an empty name, a repeated name) with every array of up to 3 items, with no filter or each listed one unreferenceable, the C's order: under the lock each filter read and unlinked and the list freed; with the lock free, per item the item and its name, each current name until the first match and its reference, the load (private, by the chain rule) when there is none or the reference fails, the previous filter's target, the item's release; then the last target, every parent, the new list stored under the lock, and each old filter released in old order. Also the end state: the chain of targets, the parents, one reference per listing, the old filters unlinked and released, every item released. soldr cargo test -p obs-data --test obs-tests-core -- source::restore_filters:: test result: FAILED. 0 passed; 7 failed panicked at rust/obs-source/src/restore_filters.rs:104:5: not yet implemented: #5801 Co-Authored-By: Claude Opus 5.5 --- rust/obs-source/src/lib.rs | 1 + rust/obs-source/src/restore_filters.rs | 105 +++++ rust/obs-source/tests/source/main.rs | 1 + .../tests/source/restore_filters.rs | 408 ++++++++++++++++++ 4 files changed, 515 insertions(+) create mode 100644 rust/obs-source/src/restore_filters.rs create mode 100644 rust/obs-source/tests/source/restore_filters.rs diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 8dd506f667..f28215b2f6 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -281,6 +281,7 @@ pub mod push_to_enable; pub mod removed; pub mod render_route; pub mod replace_missing_file; +pub mod restore_filters; pub mod save_load; pub mod set_name; pub mod settings_getter; diff --git a/rust/obs-source/src/restore_filters.rs b/rust/obs-source/src/restore_filters.rs new file mode 100644 index 0000000000..f8db42f58a --- /dev/null +++ b/rust/obs-source/src/restore_filters.rs @@ -0,0 +1,105 @@ +//! `obs_source_restore_filters()`: the filter restore behind the filters +//! dialog's undo and redo and the paste of copied filters +//! (`frontend/utility/filter-clipboard.c.h`), the partner of +//! `obs_source_backup_filters()` ([`crate::filter_backup`]). +//! +//! The name match and how a backed-up filter with no current one is loaded +//! are [`crate::source_filter_chain`]'s rules ([`restore_matches`], +//! [`restore_step`]); this is the C around them: the lock, taking the +//! current filters off the list, the array reads, the references and +//! loads, the target and parent writes, the move of the new list into the +//! source and the releases, each through [`RestoreList`]. +#![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 public function named in the NULL diagnostics. +pub const RESTORE_FUNCTION: &CStr = c"obs_source_restore_filters"; +/// The parameter a NULL source is logged as. +pub const SOURCE_PARAMETER: &CStr = c"source"; +/// The parameter a NULL array is logged as. +pub const ARRAY_PARAMETER: &CStr = c"array"; + +/// What the restore does with a live source's filter list and the +/// backed-up array, in the order it asks. +pub trait RestoreList { + /// A source handle (a filter, or what a filter targets), compared by + /// identity. + type Source: Copy + PartialEq; + /// One item of the array (an `obs_data_t`), held until + /// [`Self::release_item`]. + type Item: Copy; + /// The source itself, what the last restored filter targets and every + /// restored filter's parent. + fn this(&self) -> Self::Source; + /// Takes `filter_mutex`. + fn lock(&self); + /// `filters.num`, read now. + fn count(&self) -> usize; + /// `filters.array[index]`, read now; `index` is below [`Self::count`]. + fn filter(&self, index: usize) -> Self::Source; + /// `filter->filter_parent = NULL`, then `filter->filter_target = NULL`. + fn unlink(&self, filter: Self::Source); + /// `da_free(source->filters)`. + fn free_list(&self); + /// Releases `filter_mutex`. + fn unlock(&self); + /// `obs_data_array_count(array)`. + fn item_count(&self) -> usize; + /// `obs_data_array_item(array, index)`: a new reference to the item. + fn item(&self, index: usize) -> Self::Item; + /// `obs_data_get_string(item, "name")`, without its NUL; `None` for a + /// NULL string (which `obs_data_get_string()` never returns). + fn item_name(&self, item: Self::Item) -> Option<&[u8]>; + /// `filter->context.name`, without its NUL; `None` when unnamed. + fn name(&self, filter: Self::Source) -> Option<&[u8]>; + /// `obs_source_get_ref(filter)`: `None` for a filter whose last + /// reference is gone. + fn get_ref(&self, filter: Self::Source) -> Option; + /// `obs_load_source(item)`: the new filter, holding its reference. + fn load(&self, item: Self::Item) -> Self::Source; + /// `obs_load_private_source(item)`: the new filter, holding its + /// reference. + fn load_private(&self, item: Self::Item) -> Self::Source; + /// `filter->filter_target = target`. + fn set_target(&self, filter: Self::Source, target: Self::Source); + /// `filter->filter_parent = source`. + fn set_parent(&self, filter: Self::Source); + /// `da_move(source->filters, new_filters)`: the source's list becomes + /// `filters`, which takes over the references the restore holds. + fn store(&self, filters: Vec); + /// `obs_data_release(item)`. + fn release_item(&self, item: Self::Item); + /// `obs_source_release(filter)`. + fn release(&self, filter: Self::Source); +} + +/// `obs_source_restore_filters()`: `None` is a NULL source, logged as +/// ([`RESTORE_FUNCTION`], [`SOURCE_PARAMETER`]); then a NULL array +/// (`array` false) is logged as ([`RESTORE_FUNCTION`], [`ARRAY_PARAMETER`]). +/// Under the lock every current filter is kept aside in order, unlinked, +/// and the list freed. With the lock free, each item reuses the first +/// current filter whose name matches (through a new reference) or, when +/// there is none or it can't be referenced, is loaded as the chain rule +/// says; each restored filter becomes the previous one's target and the +/// item is released. The last restored filter targets the source, then +/// every restored filter gets the source as its parent, and the new list +/// goes into the source under the lock. Then each old filter is released +/// once, in old order. +pub fn restore( + source: Option<&L>, + array: bool, + log: impl FnOnce(&'static CStr, &'static CStr), +) { + let _ = (source, array, log); + todo!("#5801") +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index d662597f59..565af02bdf 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -151,6 +151,7 @@ mod render_route; mod render_route_parity; mod replace_missing_file; mod replace_missing_file_parity; +mod restore_filters; mod save_load; mod save_load_parity; mod set_name; diff --git a/rust/obs-source/tests/source/restore_filters.rs b/rust/obs-source/tests/source/restore_filters.rs new file mode 100644 index 0000000000..d76eaf3502 --- /dev/null +++ b/rust/obs-source/tests/source/restore_filters.rs @@ -0,0 +1,408 @@ +//! Tier 1 mirrors of test_source_restore_filters.c without FFI or unsafe +//! code. +use core::ffi::CStr; +use obs_source::restore_filters::{ + ARRAY_PARAMETER, RESTORE_FUNCTION, RestoreList, SOURCE_PARAMETER, restore, +}; +use std::cell::{Cell, RefCell}; + +/// The longest chain a case starts with. +const CHAIN: usize = 6; +/// The current filters' names: an unnamed one, an empty one and a repeated +/// one (the first of the two matches). +const NAMES: [Option<&[u8]>; CHAIN] = [ + Some(b"a"), + Some(b"bb"), + None, + Some(b""), + Some(b"e"), + Some(b"a"), +]; +/// The names an array item can have: every current name, and one that no +/// current filter has. +const ITEM_NAMES: [&[u8]; 5] = [b"a", b"bb", b"", b"e", b"zz"]; +/// The handle of the source itself. +const SOURCE: usize = 100; +/// No parent, no target. +const NONE: usize = 101; +/// The filter loaded for array item `k` is `LOADED + k`. +const LOADED: usize = 200; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Event { + Lock, + Count, + At(usize), + Unlink(usize), + FreeList, + Unlock, + ItemCount, + Item(usize), + ItemName(usize), + Name(usize), + GetRef(usize), + Load(usize), + LoadPrivate(usize), + SetTarget(usize, usize), + SetParent(usize), + Store(Vec), + ReleaseItem(usize), + Release(usize), +} + +/// A model source: its list holds filter ids 0 to count - 1 (filter `i` +/// targets the next one, the last the source), named after [`NAMES`]; the +/// array's items are named as given; references and item holds are +/// counted, and every call is recorded with the lock state checked. +struct Model { + list: RefCell>, + targets: RefCell>, + parents: RefCell>, + refs: RefCell>, + items: Vec>>, + held: RefCell>, + dying: Option, + locked: Cell, + events: RefCell>, +} + +/// Filter ids the model tracks: the chain's and every loaded one. +const IDS: usize = LOADED + 8; + +impl Model { + fn new(count: usize, items: &[Option<&[u8]>], dying: Option) -> Self { + let mut targets = vec![NONE; IDS]; + let mut parents = vec![NONE; IDS]; + let mut refs = vec![0; IDS]; + for i in 0..count { + targets[i] = if i + 1 < count { i + 1 } else { SOURCE }; + parents[i] = SOURCE; + refs[i] = 1; + } + Self { + list: RefCell::new((0..count).collect()), + targets: RefCell::new(targets), + parents: RefCell::new(parents), + refs: RefCell::new(refs), + items: items.iter().map(|n| n.map(<[u8]>::to_vec)).collect(), + held: RefCell::new(vec![0; items.len()]), + dying, + locked: Cell::new(false), + events: RefCell::new(Vec::new()), + } + } + fn push(&self, event: Event) { + self.events.borrow_mut().push(event); + } + fn events(&self) -> Vec { + self.events.borrow().clone() + } + fn list(&self) -> Vec { + self.list.borrow().clone() + } + fn unlocked(&self) { + assert!(!self.locked.get(), "called under filter_mutex"); + } + fn locked(&self) { + assert!(self.locked.get(), "called without filter_mutex"); + } +} + +impl RestoreList for Model { + type Source = usize; + type Item = usize; + fn this(&self) -> usize { + SOURCE + } + fn lock(&self) { + assert!(!self.locked.replace(true), "locked twice"); + self.push(Event::Lock); + } + fn count(&self) -> usize { + self.locked(); + self.push(Event::Count); + self.list.borrow().len() + } + fn filter(&self, index: usize) -> usize { + self.locked(); + self.push(Event::At(index)); + self.list.borrow()[index] + } + fn unlink(&self, filter: usize) { + self.locked(); + self.push(Event::Unlink(filter)); + self.parents.borrow_mut()[filter] = NONE; + self.targets.borrow_mut()[filter] = NONE; + } + fn free_list(&self) { + self.locked(); + self.push(Event::FreeList); + self.list.borrow_mut().clear(); + } + fn unlock(&self) { + assert!(self.locked.replace(false), "unlocked while not locked"); + self.push(Event::Unlock); + } + fn item_count(&self) -> usize { + self.unlocked(); + self.push(Event::ItemCount); + self.items.len() + } + fn item(&self, index: usize) -> usize { + self.unlocked(); + self.push(Event::Item(index)); + self.held.borrow_mut()[index] += 1; + index + } + fn item_name(&self, item: usize) -> Option<&[u8]> { + self.unlocked(); + assert!(self.held.borrow()[item] > 0, "read a released item"); + self.push(Event::ItemName(item)); + self.items[item].as_deref() + } + fn name(&self, filter: usize) -> Option<&[u8]> { + self.unlocked(); + self.push(Event::Name(filter)); + NAMES[filter] + } + fn get_ref(&self, filter: usize) -> Option { + self.unlocked(); + self.push(Event::GetRef(filter)); + if self.dying == Some(filter) { + return None; + } + self.refs.borrow_mut()[filter] += 1; + Some(filter) + } + fn load(&self, item: usize) -> usize { + self.unlocked(); + self.push(Event::Load(item)); + self.refs.borrow_mut()[LOADED + item] += 1; + LOADED + item + } + fn load_private(&self, item: usize) -> usize { + self.unlocked(); + // The list is still empty while an item loads. + assert!(self.list.borrow().is_empty()); + self.push(Event::LoadPrivate(item)); + self.refs.borrow_mut()[LOADED + item] += 1; + LOADED + item + } + fn set_target(&self, filter: usize, target: usize) { + self.unlocked(); + self.push(Event::SetTarget(filter, target)); + self.targets.borrow_mut()[filter] = target; + } + fn set_parent(&self, filter: usize) { + self.unlocked(); + self.push(Event::SetParent(filter)); + self.parents.borrow_mut()[filter] = SOURCE; + } + fn store(&self, filters: Vec) { + self.locked(); + self.push(Event::Store(filters.clone())); + *self.list.borrow_mut() = filters; + } + fn release_item(&self, item: usize) { + self.unlocked(); + self.push(Event::ReleaseItem(item)); + self.held.borrow_mut()[item] -= 1; + } + fn release(&self, filter: usize) { + self.unlocked(); + self.push(Event::Release(filter)); + self.refs.borrow_mut()[filter] -= 1; + } +} + +fn no_log(function: &'static CStr, parameter: &'static CStr) { + panic!("logged {function:?}: {parameter:?}"); +} + +/// What the C does on a chain of `count` (with `dying` unreferenceable) +/// for the array: its calls, and the new list. +fn expected( + count: usize, + items: &[Option<&[u8]>], + dying: Option, +) -> (Vec, Vec) { + use Event::*; + let mut events = vec![Lock, Count]; + for index in 0..count { + events.extend([Count, At(index), Unlink(index)]); + } + events.extend([Count, FreeList, Unlock, ItemCount]); + let mut list = Vec::new(); + let mut prev = None; + for (k, item) in items.iter().enumerate() { + events.extend([Item(k), ItemName(k)]); + let mut found = None; + for (j, name) in NAMES.iter().enumerate().take(count) { + events.push(Name(j)); + if item.is_some() && name == item { + events.push(GetRef(j)); + found = (dying != Some(j)).then_some(j); + break; + } + } + let filter = found.unwrap_or_else(|| { + events.push(LoadPrivate(k)); + LOADED + k + }); + if let Some(prev) = prev { + events.push(SetTarget(prev, filter)); + } + prev = Some(filter); + list.push(filter); + events.push(ReleaseItem(k)); + } + if let Some(prev) = prev { + events.push(SetTarget(prev, SOURCE)); + } + events.extend(list.iter().map(|&f| SetParent(f))); + events.extend([Lock, Store(list.clone()), Unlock]); + events.extend((0..count).map(Release)); + (events, list) +} + +/// Runs one restore and checks it against the C's calls and end state. +fn check(count: usize, items: &[Option<&[u8]>], dying: Option) -> Vec { + let model = Model::new(count, items, dying); + restore(Some(&model), true, no_log); + let (events, list) = expected(count, items, dying); + assert_eq!(model.events(), events, "{count} {items:?} {dying:?}"); + assert_eq!(model.list(), list); + assert!(!model.locked.get()); + let targets = model.targets.borrow(); + let parents = model.parents.borrow(); + let refs = model.refs.borrow(); + // Each listed filter targets the next, the last the source; every one + // has the source as its parent and one reference per listing. + for (i, &filter) in list.iter().enumerate() { + let next = list.get(i + 1).copied().unwrap_or(SOURCE); + // A filter listed twice keeps the target written last. + if !list[i + 1..].contains(&filter) { + assert_eq!(targets[filter], next, "{list:?}"); + } + assert_eq!(parents[filter], SOURCE); + let listed = list.iter().filter(|&&f| f == filter).count(); + assert_eq!(refs[filter], i32::try_from(listed).unwrap(), "{list:?}"); + } + // An old filter not listed again is unlinked and lost the list's + // reference. + for old in (0..count).filter(|f| !list.contains(f)) { + assert_eq!((targets[old], parents[old], refs[old]), (NONE, NONE, 0)); + } + // Every item was released as often as it was taken. + assert!(model.held.borrow().iter().all(|&h| h == 0)); + list +} + +/// Mirrors null_arguments. +#[test] +fn null_arguments_log_once_and_do_nothing() { + let model = Model::new(3, &[Some(b"a")], None); + let mut logs = Vec::new(); + + restore(None::<&Model>, true, |f, p| logs.push((f, p))); + restore(Some(&model), false, |f, p| logs.push((f, p))); + // The source is checked first. + restore(None::<&Model>, false, |f, p| logs.push((f, p))); + + assert_eq!( + logs, + [ + (RESTORE_FUNCTION, SOURCE_PARAMETER), + (RESTORE_FUNCTION, ARRAY_PARAMETER), + (RESTORE_FUNCTION, SOURCE_PARAMETER), + ] + ); + // Nothing of the source or the array was read, locked or written. + assert!(model.events().is_empty()); + assert_eq!(model.list(), [0, 1, 2]); + assert_eq!(RESTORE_FUNCTION, c"obs_source_restore_filters"); + assert_eq!(SOURCE_PARAMETER, c"source"); + assert_eq!(ARRAY_PARAMETER, c"array"); +} + +/// Mirrors reuses_matching_filters: a reordered, shortened array reuses +/// the filters it names, and drops the rest. +#[test] +fn reuses_matching_filters() { + let list = check(5, &[Some(b"e"), Some(b"a"), Some(b"bb")], None); + assert_eq!(list, [4, 0, 1]); +} + +/// Mirrors loads_unmatched_items_with_the_lock_free and +/// targets_are_set_before_parents. +#[test] +fn loads_unmatched_items() { + let list = check( + 2, + &[Some(b"zz"), Some(b"a"), Some(b"yy"), Some(b"bb")], + None, + ); + assert_eq!(list, [LOADED, 0, LOADED + 2, 1]); + // Nothing loads public: the chain rule loads private (#2981). + let model = Model::new(0, &[Some(b"zz")], None); + restore(Some(&model), true, no_log); + assert!(!model.events().iter().any(|e| matches!(e, Event::Load(_)))); +} + +/// Mirrors empty_array_drops_every_filter. +#[test] +fn empty_array_drops_every_filter() { + for count in 0..=CHAIN { + assert!(check(count, &[], None).is_empty()); + } +} + +/// Mirrors duplicate_names_reuse_the_same_filter and +/// unnamed_filter_never_matches; the first of two current filters of one +/// name is the one reused. +#[test] +fn duplicates_and_unnamed_filters() { + assert_eq!(check(2, &[Some(b"a"), Some(b"a")], None), [0, 0]); + assert_eq!(check(6, &[Some(b"a")], None), [0]); + // Filter 2 is unnamed: an empty name matches filter 3 only. + assert_eq!(check(4, &[Some(b""), Some(b"")], None), [3, 3]); + // A NULL item name (never given by obs_data_get_string()) matches + // nothing. + assert_eq!(check(4, &[None], None), [LOADED]); +} + +/// A current filter whose last reference is gone is loaded instead (not +/// reachable through the real core; Tier 3 covers it against the C). +#[test] +fn unreferenceable_filter_is_loaded() { + assert_eq!(check(3, &[Some(b"bb"), Some(b"a")], Some(1)), [LOADED, 0]); + // The lookup stops at the first match even when it can't be + // referenced: the second "a" (filter 5) is not tried. + assert_eq!(check(6, &[Some(b"a")], Some(0)), [LOADED]); +} + +/// Every chain of up to 6 current filters with every array of up to 3 +/// items over [`ITEM_NAMES`], with no filter or each listed one +/// unreferenceable. +#[test] +fn every_chain_and_array() { + let mut arrays: Vec>> = vec![Vec::new()]; + for len in 1..=3 { + let mut next = Vec::new(); + for array in arrays.iter().filter(|a| a.len() == len - 1) { + for name in ITEM_NAMES { + let mut longer = array.clone(); + longer.push(Some(name)); + next.push(longer); + } + } + arrays.extend(next); + } + for count in 0..=CHAIN { + for array in &arrays { + for dying in std::iter::once(None).chain((0..count).map(Some)) { + check(count, array, dying); + } + } + } +} From 000eb16aa0b4810da68d950cb1935213763671ef Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Thu, 26 Nov 2026 21:54:43 -0500 Subject: [PATCH 4/4] obs-source: port obs_source_restore_filters to Rust (Fixes #5801) Safe core restore_filters::restore over the RestoreList trait, with source_filter_chain's restore match and restore step, and the shim in ffi::source_restore_filters: the exported obs_source_restore_filters() (rust-exports.d). The shim rejects NULL before any adapter runs; the lock, the list reads, the unlinks, da_free(), the name reads, obs_source_get_ref(), obs_load_source() and obs_load_private_source(), the target and parent writes, the move of the new list into the source, obs_source_release() and the obs_data array and item calls stay C in the new obs-source-restore-filters-fields.c.h (live core-source group, no EXPORT). The extracted C moves to the reference-only group libobs.ported-source-restore-filters. Tier 3 (restore_filters_parity, oracle source_restore_filters.c): the original C and the Rust export on noise-filled real-header sources with a stand-in array and recording references, loads and releases, over every chain of 0 to 6 current filters (an unnamed one, a repeated name) with every array of up to 3 items over 7 names plus longer patterns (reusing, loading, duplicating and dropping filters), with no filter or each listed one unreferenceable, and a proptest of up to 6 items. It compares the new list, every target and parent, each item read, name read and item release, reference, load and release in order with the lock state and a digest of the list and every link at that moment, the NULL lines, every other byte, the lock after and the item holds, and rejects seven mutants. Registration test in obs-build; rust/README row. soldr cargo test -p obs-data --test obs-tests-core -- source::restore_filters test result: ok. 8 passed; 0 failed Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795768045,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":95,"stamp":"92eba974e1ece5c8891f92c0beca9581","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795768045,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":95,"stamp":"0c5b3123b94f39ab68d033c2782bd5ad","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795768045,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":95,"stamp":"c5b1a844764aa1233b96083dfc054af8","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795768045,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":95,"stamp":"e7f0306f8bb64b3b65d5d9db3ab07cf2","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767948,"gate":"general/all/client-lint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"932c69a5bd4c3e05d56ac7ab43ff590c","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795768045,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":95,"stamp":"0f8e186c499bd4635e9122f272b4f648","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"0e7a26dd59cba6ceec2c72d421a19b3d","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"348dca7d135c5c08f39e95e823f5d9dd","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"597967026e038b02160ea166a5d3a1f3","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"95482b3a3342c8c9d71d27352c5b3c0f","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"77a64358b37aed9c1f06daeba44e66d0","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"0f95cded713930eca10005e392f16328","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"f8a017f5830c53988be4d7889605b607","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"515e1dc4ad39b45da879d4f3a321f9dc","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"6d57232f5533ce0dd42d09c972f6a702","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767949,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"d7158e2e0fd273d9107426d3ed56ae2c","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767948,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"bb95a366de0d7329f0d5d59be55a37e7","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795767948,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"654254869fdde294ac20c0aa79f7e78803489e5e7d1d8a2b11b4531529206646","lane":"client-lint","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":65,"stamp":"810a9aa9139f264a126627142eb4df6f","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Ci-Attestation: {"at":1795768305,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"c0a1b8675b84ad7474fd7c46d9143975033a8a667335d09f5ebcd30401ac9393","lane":"client-test-x86_64-unknown-linux-gnu","parents":["09be301526b7cfe0aea40c00a169db7b1d6613b2"],"secs":260,"stamp":"74d5869676e4d0bfb954ca3a78c98e16","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76","v":1,"via":"run"} Client-Checks: {"checks":{"base":"723cd1c803bdee2e57f782a969203de768d45677","coverage":"all-tracked-applicable-files","diff":["libobs/build/libobs.core-source+.h.c","libobs/build/libobs.ported-source-restore-filters+.h.c","libobs/build/ported-source-sets/source-restore-filters.json","libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt","libobs/obs-source-restore-filters-fields.c.h","libobs/obs-source-restore-filters.c.h","libobs/obs-source.c.h","rust/README.md","rust/obs-build/tests/native.rs","rust/obs-build/tests/native/registration/canonical_source_restore_filters_swap_is_registered.rs","rust/obs-c-oracle/oracle.d/source-restore-filters.list","rust/obs-c-oracle/oracle/source_restore_filters.c","rust/obs-source/Cargo.toml","rust/obs-source/src/ffi/mod.rs","rust/obs-source/src/ffi/source_restore_filters.rs","rust/obs-source/src/lib.rs","rust/obs-source/src/restore_filters.rs","rust/obs-source/tests/source/main.rs","rust/obs-source/tests/source/restore_filters.rs","rust/obs-source/tests/source/restore_filters_parity.rs","test/cmocka/build/test-graph.json","test/cmocka/test_source_restore_filters.c","test/cmocka/tests.d/test_source_restore_filters.cmake"],"head":"04b12d50daddfd4a758c3283cfa4ed7ad3e49d4e","tools":{"orchestrator-python":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]","schema-dependencies":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]\n{'jsonschema': '4.26.0', 'json_source_map': '1.0.5'}","uv":"uv 0.13.5 (x86_64-unknown-linux-gnu)","xmllint":"xmllint: using libxml version 21504-GITv2.15.4\n compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib"},"tracked-digest":"663cce4d0285db6663ba0457beeefc38ed2915f544fd3158f3dc0ea061726ed2","tree":"a17d3dc91777467c45032df16f9c8ac3dcd7be76"}} --- libobs/build/libobs.core-source+.h.c | 2 +- .../libobs.ported-source-restore-filters+.h.c | 4 + .../source-restore-filters.json | 5 + .../obs-source-source_restore_filters.txt | 1 + libobs/obs-source-restore-filters-fields.c.h | 114 ++++ rust/README.md | 1 + rust/obs-build/tests/native.rs | 2 + ...urce_restore_filters_swap_is_registered.rs | 43 ++ .../oracle.d/source-restore-filters.list | 1 + .../oracle/source_restore_filters.c | 473 ++++++++++++++ rust/obs-source/Cargo.toml | 2 +- rust/obs-source/src/ffi/mod.rs | 1 + .../src/ffi/source_restore_filters.rs | 168 +++++ rust/obs-source/src/lib.rs | 3 + rust/obs-source/src/restore_filters.rs | 75 ++- rust/obs-source/tests/source/main.rs | 1 + .../tests/source/restore_filters_parity.rs | 600 ++++++++++++++++++ 17 files changed, 1492 insertions(+), 4 deletions(-) create mode 100644 libobs/build/libobs.ported-source-restore-filters+.h.c create mode 100644 libobs/build/ported-source-sets/source-restore-filters.json create mode 100644 libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt create mode 100644 libobs/obs-source-restore-filters-fields.c.h create mode 100644 rust/obs-build/tests/native/registration/canonical_source_restore_filters_swap_is_registered.rs create mode 100644 rust/obs-c-oracle/oracle.d/source-restore-filters.list create mode 100644 rust/obs-c-oracle/oracle/source_restore_filters.c create mode 100644 rust/obs-source/src/ffi/source_restore_filters.rs create mode 100644 rust/obs-source/tests/source/restore_filters_parity.rs diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index f7d702df6f..ec46f1ac2f 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -109,7 +109,7 @@ #include "libobs/obs-source-push-to-enable-fields.c.h" #include "libobs/obs-source-remove-fields.c.h" #include "libobs/obs-source-removed-fields.c.h" -#include "libobs/obs-source-restore-filters.c.h" +#include "libobs/obs-source-restore-filters-fields.c.h" #include "libobs/obs-source-save-load-fields.c.h" #include "libobs/obs-source-set-name-fields.c.h" #include "libobs/obs-source-settings-getter-fields.c.h" diff --git a/libobs/build/libobs.ported-source-restore-filters+.h.c b/libobs/build/libobs.ported-source-restore-filters+.h.c new file mode 100644 index 0000000000..9d7305051b --- /dev/null +++ b/libobs/build/libobs.ported-source-restore-filters+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original source restore filters for C reference. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-restore-filters.c.h" diff --git a/libobs/build/ported-source-sets/source-restore-filters.json b/libobs/build/ported-source-sets/source-restore-filters.json new file mode 100644 index 0000000000..59efd3d56c --- /dev/null +++ b/libobs/build/ported-source-sets/source-restore-filters.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-restore-filters+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt b/libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt new file mode 100644 index 0000000000..9e038c9de6 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt @@ -0,0 +1 @@ +obs_source_restore_filters diff --git a/libobs/obs-source-restore-filters-fields.c.h b/libobs/obs-source-restore-filters-fields.c.h new file mode 100644 index 0000000000..f88d43a347 --- /dev/null +++ b/libobs/obs-source-restore-filters-fields.c.h @@ -0,0 +1,114 @@ +#include "libobs/build/libobs.pch.h" + +/* What obs_source_restore_filters() reads, writes, loads and releases (the + * obs-source shim). The caller rejects a NULL source and array, keeps both + * alive, touches the list only between lock and unlock, at indexes below a + * count read under the lock, and holds a reference to every filter it + * passes (an old filter until it releases it, a restored one from its + * reference or load); each call is one read, one write or one libobs + * call. */ +void obs_source_restore_filters_lock(obs_source_t *source); +void obs_source_restore_filters_lock(obs_source_t *source) +{ + pthread_mutex_lock(&source->filter_mutex); +} + +size_t obs_source_restore_filters_count(const obs_source_t *source); +size_t obs_source_restore_filters_count(const obs_source_t *source) +{ + return source->filters.num; +} + +obs_source_t *obs_source_restore_filters_at(const obs_source_t *source, size_t index); +obs_source_t *obs_source_restore_filters_at(const obs_source_t *source, size_t index) +{ + return source->filters.array[index]; +} + +void obs_source_restore_filters_set_parent(obs_source_t *filter, obs_source_t *parent); +void obs_source_restore_filters_set_parent(obs_source_t *filter, obs_source_t *parent) +{ + filter->filter_parent = parent; +} + +void obs_source_restore_filters_set_target(obs_source_t *filter, obs_source_t *target); +void obs_source_restore_filters_set_target(obs_source_t *filter, obs_source_t *target) +{ + filter->filter_target = target; +} + +void obs_source_restore_filters_free_list(obs_source_t *source); +void obs_source_restore_filters_free_list(obs_source_t *source) +{ + da_free(source->filters); +} + +void obs_source_restore_filters_unlock(obs_source_t *source); +void obs_source_restore_filters_unlock(obs_source_t *source) +{ + pthread_mutex_unlock(&source->filter_mutex); +} + +size_t obs_source_restore_filters_item_count(obs_data_array_t *array); +size_t obs_source_restore_filters_item_count(obs_data_array_t *array) +{ + return obs_data_array_count(array); +} + +obs_data_t *obs_source_restore_filters_item(obs_data_array_t *array, size_t index); +obs_data_t *obs_source_restore_filters_item(obs_data_array_t *array, size_t index) +{ + return obs_data_array_item(array, index); +} + +const char *obs_source_restore_filters_item_name(obs_data_t *item); +const char *obs_source_restore_filters_item_name(obs_data_t *item) +{ + return obs_data_get_string(item, "name"); +} + +const char *obs_source_restore_filters_name(const obs_source_t *filter); +const char *obs_source_restore_filters_name(const obs_source_t *filter) +{ + return filter->context.name; +} + +obs_source_t *obs_source_restore_filters_get_ref(obs_source_t *filter); +obs_source_t *obs_source_restore_filters_get_ref(obs_source_t *filter) +{ + return obs_source_get_ref(filter); +} + +obs_source_t *obs_source_restore_filters_load(obs_data_t *item); +obs_source_t *obs_source_restore_filters_load(obs_data_t *item) +{ + return obs_load_source(item); +} + +obs_source_t *obs_source_restore_filters_load_private(obs_data_t *item); +obs_source_t *obs_source_restore_filters_load_private(obs_data_t *item) +{ + return obs_load_private_source(item); +} + +/* da_move(source->filters, new_filters) for the shim's list: the old array + * is freed and the source's list becomes a copy of the count filters. */ +void obs_source_restore_filters_store(obs_source_t *source, obs_source_t *const *filters, size_t count); +void obs_source_restore_filters_store(obs_source_t *source, obs_source_t *const *filters, size_t count) +{ + da_free(source->filters); + if (count) + da_push_back_array(source->filters, filters, count); +} + +void obs_source_restore_filters_release_item(obs_data_t *item); +void obs_source_restore_filters_release_item(obs_data_t *item) +{ + obs_data_release(item); +} + +void obs_source_restore_filters_release(obs_source_t *filter); +void obs_source_restore_filters_release(obs_source_t *filter) +{ + obs_source_release(filter); +} diff --git a/rust/README.md b/rust/README.md index 374957589d..ae2d94923d 100644 --- a/rust/README.md +++ b/rust/README.md @@ -506,6 +506,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-source-removed.c.h` | `obs-source::removed` | #5587: `obs_source_removed()` answers the source's `removed` flag, read once with a sequentially consistent atomic load of the C `volatile bool` (as `os_atomic_load_bool()` does), and changes nothing; a NULL source answers true (a missing source counts as removed), logs its `LOG_DEBUG` line `obs_source_removed: Null 'source' parameter` and reads nothing. Safe Rust core; the shim rejects NULL before calling the new flag address adapter of `obs-source-removed-fields.c.h` (live group `libobs.core-source`, one read, no `EXPORT`). The original moves to the reference-only group `libobs.ported-source-removed`, and the oracle's do-nothing `obs_source_removed()` link stand-in in `audio_callback_links.c` is gone: `obs-tests-core` now links the real Rust export, whose adapter the oracle compiles. The unchanged `test_source_removed` (NULL, the flag alone under 0x00/0xff/0x5a fill with no writes, reads while another thread flips the flag) runs against hybrid and reference libraries through the real libobs. Tier 3 runs the original C and the Rust export on noise-filled sources over both flag values and a proptest, comparing results, logs and every source byte, pins the expected answers and rejects three shim mutants. | None. | | `libobs/obs-source-render-route.c.h` | `obs-source::render_route` | Swapped in hybrid `libobs` (group `libobs.ported-source-render-route`). The source and filter render routing of `source_render_video()`, `obs_source_main_render()`, `can_bypass()`, `obs_source_process_filter_begin_with_color_space()`, `obs_source_process_filter_tech_end()` and `obs_source_skip_video_filter()`, as 23 functions on plain values: `obs_source_render_route_filter()` (the target and parent check, no target first, #2177), the "no video", async update and inactive checks of `source_render_video()` with a `_reads_` function for each value the old short circuits read on one side only, the draw as a route over `enum obs_source_render_route_draw` (`_draw()`, `_skip()` and `_filter_render()` start it, `_draw_next()` takes the one value a `READ_` step asks for and returns the next step or the draw: default render, filters, main render, filter target, deinterlace or async video), `obs_source_main_render()`'s custom draw, sRGB-aware and default-effect rules, `can_bypass()` (`_bypass_reads_space()`, then `_bypass()`; the SRGB and space rules of #1493's filter colour space class), the zero size skip, the texrender format check, and the tech end's linear sRGB flag, technique name (`"Draw"` for NULL) and bypass or texture. They are declared in `obs-source-render-route.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `gs_*` call and texrender, the refs, the render calls, `get_base_width()` and `get_base_height()` (it passes the sizes), the debug markers and every field read in its order and under its conditions; that is why the decisions are many small calls and not one plan per function. Types, the direct render choice, colour spaces and formats cross as `int`; `obs-source.c.h` checks the four enums are `int`-sized. A draw step outside the enum comes back unchanged. Kept, characterized, not endorsed: `ASYNC` without `VIDEO` is no video; a direct render choice outside the enum is not direct; a size of 2^31 or more is negative in the C's `int` and does not skip. One pointer crosses: the technique name, returned as given or as a static `"Draw"`, never read. No other intentional differences. `test_source_render_route_steps` compiles the C into itself, and `test_source_render_route_steps_rust` runs the same test source against `libobs_rust-static`; `test_filter_color_space`, `test_filter_skip_removed`, `test_scroll_filter_wide_source`, `test_color_correction_16f`, `test_darken_transparent`, `test_scene_rotated_scale_filter`, `test_slideshow_size` and `test_texture_render` see the swap through the real libobs. Tier 3 compares the result bytes of every function over every boolean, sweeps of types, choices, spaces, formats and sizes over all of `i32`, every 16-bit flag pattern, 17 million bypass inputs, every draw step value, and each caller's decisions in its order (19.9 million filters, 166,400 sources), plus full-range proptests. | | `libobs/obs-source-replace-missing-file.c.h` | `obs-source::replace_missing_file` | #5635: `obs_source_replace_missing_file()` calls the callback once with the source's private data, the path and the data argument unchanged; a NULL source logs the original debug line, a source without private data does nothing. Safe Rust core with a NULL-checked shim over the missing-files getter's private-layout adapter; unchanged C characterization and original-C differential coverage. No intentional differences (a NULL callback with live data crashes both); Tier 4 does not apply. | +| `libobs/obs-source-restore-filters.c.h` | `obs-source::restore_filters`, shim in `obs-source::ffi::source_restore_filters` | #5801: swapped in hybrid `libobs` (group `libobs.ported-source-restore-filters`). `obs_source_restore_filters()`, the filters dialog's undo and redo and the paste of copied filters: a NULL source or array logs one `LOG_DEBUG` line (source first) and touches nothing. Under `filter_mutex` every current filter is kept aside in order, its `filter_parent` and `filter_target` cleared, and the list freed; then the lock is dropped. For each array item in order, with the lock free: the first current filter whose name matches the item's `name` (`obs-source::source_filter_chain`'s match: an unnamed filter never matches) is reused through `obs_source_get_ref()`; when none matches or the reference fails, the item is loaded as the chain rule's restore step says; each restored filter becomes the previous one's `filter_target`, and the item is released. The last restored filter targets the source, then every restored filter gets the source as `filter_parent` (only after every target, #2172), and the new list is moved into the source under `filter_mutex`. Afterwards each old filter is released once, in old order. No signals; no log line on the success path. A duplicated name lists the same filter twice. Safe Rust core over a `RestoreList` trait; the shim rejects NULL before calling the adapters of `obs-source-restore-filters-fields.c.h` (live group `libobs.core-source`, no `EXPORT`): the lock, the list reads, the unlinks, `da_free()`, the move of the new list, the name reads, `obs_source_get_ref()`, `obs_load_source()` and `obs_load_private_source()`, the parent and target writes, `obs_source_release()` and the `obs_data` array and item calls. The new `test_source_restore_filters` runs against hybrid and reference libraries through the real core (a current filter whose last reference is gone can't be listed there, so Tier 1 and Tier 3 cover it). Tier 3 runs the original C and the Rust export on noise-filled real-header sources with a stand-in array and recording references, loads and releases over every chain of 0 to 6 current filters (an unnamed one, a repeated name) with every array of up to 3 items over 7 names and longer patterns (reusing, loading, duplicating and dropping filters), with each listed filter unreferenceable, plus a proptest of up to 6 items, comparing the new list, every target and parent, each item read, name read and item release, reference, load and release in order with the lock state and the list and links at that moment, the NULL lines, every other byte, the lock and the item holds; it rejects seven mutants. | None of its own; loading an unmatched filter private is `source_filter_chain`'s (#2981). | | `libobs/obs-source-save-load.c.h` | `obs-source::save_load` | Source save/load callback and signal ordering, invalid plugin-data guards and parent-first reverse direct-filter traversal (#4353). Private live adapter preserves callbacks, settings identity and existing signal privacy. Tier 1 mirrors the C characterization; Tier 3 exercises actual exports against original C. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-set-name.c.h` | `obs-source::set_name` | Swapped in hybrid `libobs`; the C reference keeps the unchanged extracted setter (its own ported group). Rejects NULL with its original debug line; a NULL or empty request or a NULL current name always renames. A public source that requires a canvas goes through `obs_canvas_rename_source()`; otherwise the previous name is copied, the context is renamed through the public table (or with none, for private sources), privacy is read again before the global `source_rename`, the local `rename` follows, and the payload and copy are freed after both. C keeps the layouts, name tables, canvas rename and signal delivery behind the live adapter `obs-source-set-name-fields.c.h`. Tier 1 ports `test_source_set_name.c` 1:1 with the read and call order; Tier 3 compares the unchanged C and the Rust ABI over the real private layout with tracing stand-ins, privacy flips and payload edits. No intentional differences or new test binary. |# Rust ports of OBS Studio internals | `libobs/obs-source-settings-getter.c.h` | `obs-source::settings_getter` | Source settings getter (#4162): stored pointer identity, exactly one added reference, unchanged source/settings and NULL diagnostic. Thin private accessor rejects NULL in Rust first; Tier 1 and original-C Tier 3 with live settings reference counts, unchanged scene Tier 2 tests. No layout mirrored, no protocol changes or intentional differences. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index f68836073d..700ca6c3e7 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -91,6 +91,8 @@ mod canonical_source_remove_swap_is_registered; mod canonical_source_removed_swap_is_registered; #[path = "native/registration/canonical_source_replace_missing_file_swap_is_registered.rs"] mod canonical_source_replace_missing_file_swap_is_registered; +#[path = "native/registration/canonical_source_restore_filters_swap_is_registered.rs"] +mod canonical_source_restore_filters_swap_is_registered; #[path = "native/registration/canonical_source_show_active_counters_swap_is_registered.rs"] mod canonical_source_show_active_counters_swap_is_registered; #[path = "native/registration/canonical_source_show_preloaded_video_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_restore_filters_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_restore_filters_swap_is_registered.rs new file mode 100644 index 0000000000..2e043959bd --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_restore_filters_swap_is_registered.rs @@ -0,0 +1,43 @@ +use super::*; + +#[test] +fn canonical_source_restore_filters_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_restore_filters"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + let selected = graph.select(&[(os.into(), true)].into()).unwrap(); + // The test compiles no copy of the C: it calls the exported function + // 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_restore_filters.c") + ); + assert!(selected.targets[name].definitions.is_empty()); + assert_eq!(selected.tests[name].target, name); + } + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/source-restore-filters.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-restore-filters+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-restore-filters+.h.c")) + .unwrap(); + assert!(group.contains("#include \"libobs/obs-source-restore-filters.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-restore-filters.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source-restore-filters-fields.c.h\"")); + let exports = fs::read_to_string( + root.join("libobs/cmake/rust-exports.d/obs-source-source_restore_filters.txt"), + ) + .unwrap(); + assert_eq!( + exports.lines().collect::>(), + ["obs_source_restore_filters"] + ); +} diff --git a/rust/obs-c-oracle/oracle.d/source-restore-filters.list b/rust/obs-c-oracle/oracle.d/source-restore-filters.list new file mode 100644 index 0000000000..9a011f706d --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-restore-filters.list @@ -0,0 +1 @@ +source-restore-filters.inc|libobs/obs-source-restore-filters.c.h|auto diff --git a/rust/obs-c-oracle/oracle/source_restore_filters.c b/rust/obs-c-oracle/oracle/source_restore_filters.c new file mode 100644 index 0000000000..8e4b09e2f3 --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_restore_filters.c @@ -0,0 +1,473 @@ +/* Tier 3: the unchanged extracted obs_source_restore_filters() + * (libobs/obs-source-restore-filters.c.h) over the real private layout, and + * the production field adapters the Rust shim calls + * (obs-source-restore-filters-fields.c.h, defined once, here). + * + * The original calls the filter chain rules by their libobs names, so it + * runs on the rules hybrid libobs ships (obs-source's source_filter_chain). + * For both sides, the array and its items are stand-ins of this file, and so + * are obs_source_get_ref(), obs_source_release(), obs_load_source() and + * obs_load_private_source(): each item read, name read, item release, + * reference, load and release is recorded in order with the lock state and + * a digest of the source's list and every filter's target and parent at + * that moment. The real calls run through the real core in + * test_source_restore_filters. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include +#define obs_source_restore_filters oracle_obs_source_restore_filters +#include "libobs/build/libobs.pch.h" + +/* Current filters on the fixture, and array items (one loaded filter + * each). */ +#define SRF_SLOTS 6 +#define SRF_ITEMS 6 +#define SRF_LIST (SRF_SLOTS + SRF_ITEMS) +#define SRF_EVENTS 96 +/* One event: kind, two values, the digest, and whether filter_mutex was + * held. */ +#define SRF_EVENT_WIDTH 5 + +/* Source ids: current filter i is i, the filter loaded for item k is + * SRF_LOADED + k. */ +enum { + SRF_NULL = -1, + SRF_OTHER = -2, + SRF_PARENT = -3, + SRF_UNTOUCHED = -4, + SRF_LOADED = 100, +}; + +/* Event kinds. */ +enum { + SRF_EV_ITEM_COUNT = 1, + SRF_EV_ITEM, + SRF_EV_ITEM_NAME, + SRF_EV_ITEM_RELEASE, + SRF_EV_REF, + SRF_EV_LOAD, + SRF_EV_RELEASE, + SRF_EV_LOG, +}; + +struct srf_item { + const char *name; +}; + +struct srf_fixture { + struct obs_source parent; + struct obs_source filters[SRF_SLOTS]; + struct obs_source loaded[SRF_ITEMS]; + struct obs_source parent_before; + struct obs_source filters_before[SRF_SLOTS]; + struct obs_source loaded_before[SRF_ITEMS]; + struct srf_item items[SRF_ITEMS]; + size_t item_count; + char array_marker; + long dying; + long held; + int64_t events[SRF_EVENTS][SRF_EVENT_WIDTH]; + size_t event_count; + bool overflow; + char message[128]; +}; + +/* Per thread: the Rust test harness may run cases on several threads. */ +static _Thread_local struct srf_fixture *srf_current; + +static long srf_id(const void *source) +{ + struct srf_fixture *f = srf_current; + if (!source) + return SRF_NULL; + if (source == &f->parent) + return SRF_PARENT; + for (long i = 0; i < SRF_SLOTS; i++) { + if (source == &f->filters[i]) + return i; + } + for (long i = 0; i < SRF_ITEMS; i++) { + if (source == &f->loaded[i]) + return SRF_LOADED + i; + } + return SRF_OTHER; +} + +static bool srf_locked(void) +{ + int busy = pthread_mutex_trylock(&srf_current->parent.filter_mutex); + if (busy == 0) + pthread_mutex_unlock(&srf_current->parent.filter_mutex); + return busy != 0; +} + +/* FNV-1a over the list (read only when the lock is free: it is the + * fixture's own thread) and every filter's target and parent. */ +static int64_t srf_digest(void) +{ + struct srf_fixture *f = srf_current; + uint64_t h = 1469598103934665603ull; +#define SRF_MIX(v) \ + do { \ + h ^= (uint64_t)(int64_t)(v); \ + h *= 1099511628211ull; \ + } while (false) + SRF_MIX(f->parent.filters.num); + for (size_t i = 0; i < f->parent.filters.num && i < 64; i++) + SRF_MIX(srf_id(f->parent.filters.array[i])); + for (size_t i = 0; i < SRF_SLOTS; i++) { + SRF_MIX(srf_id(f->filters[i].filter_target)); + SRF_MIX(srf_id(f->filters[i].filter_parent)); + } + for (size_t i = 0; i < SRF_ITEMS; i++) { + SRF_MIX(srf_id(f->loaded[i].filter_target)); + SRF_MIX(srf_id(f->loaded[i].filter_parent)); + } +#undef SRF_MIX + return (int64_t)h; +} + +static void srf_event(int64_t kind, int64_t a, int64_t b) +{ + struct srf_fixture *f = srf_current; + if (f->event_count >= SRF_EVENTS) { + f->overflow = true; + return; + } + int64_t *e = f->events[f->event_count++]; + e[0] = kind; + e[1] = a; + e[2] = b; + e[3] = srf_digest(); + e[4] = srf_locked(); +} + +static long srf_item_index(const obs_data_t *data) +{ + struct srf_fixture *f = srf_current; + const struct srf_item *item = (const struct srf_item *)(const void *)data; + if (item < f->items || item >= f->items + SRF_ITEMS) + return SRF_OTHER; + return (long)(item - f->items); +} + +static size_t srf_array_count(obs_data_array_t *array) +{ + struct srf_fixture *f = srf_current; + srf_event(SRF_EV_ITEM_COUNT, array == (obs_data_array_t *)(void *)&f->array_marker, 0); + return f->item_count; +} + +static obs_data_t *srf_array_item(obs_data_array_t *array, size_t idx) +{ + struct srf_fixture *f = srf_current; + srf_event(SRF_EV_ITEM, (int64_t)idx, array == (obs_data_array_t *)(void *)&f->array_marker); + if (idx >= f->item_count) + return NULL; + f->held++; + return (obs_data_t *)(void *)&f->items[idx]; +} + +static const char *srf_get_string(obs_data_t *data, const char *name) +{ + long i = srf_item_index(data); + srf_event(SRF_EV_ITEM_NAME, i, strcmp(name, "name") == 0); + return i >= 0 ? srf_current->items[i].name : NULL; +} + +static void srf_data_release(obs_data_t *data) +{ + srf_current->held--; + srf_event(SRF_EV_ITEM_RELEASE, srf_item_index(data), 0); +} + +/* obs_source_get_ref(): NULL for the fixture's dying filter. */ +static obs_source_t *srf_get_ref(obs_source_t *source) +{ + struct srf_fixture *f = srf_current; + long id = srf_id(source); + srf_event(SRF_EV_REF, id, id == f->dying); + return id == f->dying ? NULL : source; +} + +static void srf_release(obs_source_t *source) +{ + srf_event(SRF_EV_RELEASE, srf_id(source), 0); +} + +/* The filter loaded for an item; public tells the two loads apart. */ +static obs_source_t *srf_load_as(obs_data_t *data, bool public) +{ + long i = srf_item_index(data); + srf_event(SRF_EV_LOAD, i, public); + return i >= 0 ? &srf_current->loaded[i] : NULL; +} + +static obs_source_t *srf_load(obs_data_t *data) +{ + return srf_load_as(data, true); +} + +static obs_source_t *srf_load_private(obs_data_t *data) +{ + return srf_load_as(data, false); +} + +#define obs_data_array_count srf_array_count +#define obs_data_array_item srf_array_item +#define obs_data_get_string srf_get_string +#define obs_data_release srf_data_release +#define obs_source_get_ref srf_get_ref +#define obs_source_release srf_release +#define obs_load_source srf_load +#define obs_load_private_source srf_load_private +#include "source-restore-filters.inc" +#undef obs_source_restore_filters +#include "source_restore_filters_fields.inc" +#undef obs_load_private_source +#undef obs_load_source +#undef obs_source_release +#undef obs_source_get_ref +#undef obs_data_release +#undef obs_data_get_string +#undef obs_data_array_item +#undef obs_data_array_count + +static char srf_parent_name[] = "parent"; +/* Current filter names: an unnamed one and a repeated one. */ +static char srf_names[SRF_SLOTS][3] = {"a", "bb", "", "e", "a", "g"}; +static const bool srf_unnamed[SRF_SLOTS] = {false, false, true, false, false, false}; +/* Item names, by selector: every current name, and two no filter has. */ +static const char *const srf_item_names[] = {"a", "bb", "e", "g", "zz", "", "x"}; +#define SRF_ITEM_NAMES (sizeof(srf_item_names) / sizeof(srf_item_names[0])) + +static void srf_free(struct srf_fixture *f, bool *ok) +{ + da_free(f->parent.filters); + if (pthread_mutex_destroy(&f->parent.filter_mutex) != 0) + *ok = false; + free(f); +} + +/* A fresh fixture: filters 0 to count - 1 listed (filter i targets the next + * one, the last the parent), item k named after selector (items >> 3k) & 7 + * for k below item_count; dying is the id that can't be referenced (or + * SRF_NULL). */ +static struct srf_fixture *srf_new(uint8_t noise, size_t count, size_t item_count, uint32_t items, long dying) +{ + struct srf_fixture *f = malloc(sizeof(*f)); + if (!f) + return NULL; + memset(f, noise, sizeof(*f)); + if (pthread_mutex_init(&f->parent.filter_mutex, NULL) != 0) { + free(f); + return NULL; + } + f->parent.context.name = srf_parent_name; + f->parent.filters.array = NULL; + f->parent.filters.num = 0; + f->parent.filters.capacity = 0; + for (size_t i = 0; i < SRF_SLOTS; i++) { + struct obs_source *filter = &f->filters[i]; + filter->context.name = srf_unnamed[i] ? NULL : srf_names[i]; + if (i < count) { + obs_source_t *entry = filter; + da_push_back(f->parent.filters, &entry); + filter->filter_parent = &f->parent; + filter->filter_target = i + 1 < count ? &f->filters[i + 1] : &f->parent; + } else { + filter->filter_parent = NULL; + filter->filter_target = NULL; + } + } + for (size_t i = 0; i < SRF_ITEMS; i++) { + f->loaded[i].filter_parent = NULL; + f->loaded[i].filter_target = NULL; + f->loaded[i].context.name = NULL; + uint32_t selector = (items >> (3 * i)) & 7; + f->items[i].name = srf_item_names[selector % SRF_ITEM_NAMES]; + } + f->item_count = item_count; + f->dying = dying; + f->held = 0; + f->event_count = 0; + f->overflow = false; + f->message[0] = '\0'; + memcpy(&f->parent_before, &f->parent, sizeof(f->parent)); + memcpy(f->filters_before, f->filters, sizeof(f->filters)); + memcpy(f->loaded_before, f->loaded, sizeof(f->loaded)); + return f; +} + +/* Whether before and after differ only inside the given field ranges. */ +static bool srf_equal_except(const void *before, const void *after, size_t size, size_t at1, size_t len1, size_t at2, + size_t len2) +{ + const unsigned char *b = before; + const unsigned char *a = after; + for (size_t i = 0; i < size; i++) { + if ((i >= at1 && i < at1 + len1) || (i >= at2 && i < at2 + len2)) + continue; + if (a[i] != b[i]) + return false; + } + return true; +} + +/* What a filter_target or filter_parent holds after the call. */ +static long srf_link(const void *before, const void *after) +{ + const obs_source_t *value; + if (memcmp(before, after, sizeof(value)) == 0) + return SRF_UNTOUCHED; + memcpy(&value, after, sizeof(value)); + return srf_id(value); +} + +struct srf_log { + unsigned count; +}; +#if defined(__GNUC__) || defined(__clang__) +static void srf_capture(int level, const char *format, va_list args, void *param) __attribute__((format(printf, 2, 0))); +#endif +static void srf_capture(int level, const char *format, va_list args, void *param) +{ + struct srf_log *captured = param; + captured->count++; + vsnprintf(srf_current->message, sizeof(srf_current->message), format, args); + srf_event(SRF_EV_LOG, level, (int64_t)captured->count); +} + +static void srf_copy(char *dst, size_t size, const char *src) +{ + size_t len = strlen(src); + if (len >= size) + len = size - 1; + memcpy(dst, src, len); + dst[len] = '\0'; +} + +typedef void (*srf_restore)(obs_source_t *, obs_data_array_t *); +typedef void (*srf_get_log)(log_handler_t *, void **); +typedef void (*srf_set_log)(log_handler_t, void *); + +/* The out array, by index. */ +enum { + SRF_OUT_COUNT_AFTER = 0, + SRF_OUT_ORDER, + SRF_OUT_TARGETS = SRF_OUT_ORDER + SRF_LIST, + SRF_OUT_PARENTS = SRF_OUT_TARGETS + SRF_LIST, + SRF_OUT_UNCHANGED = SRF_OUT_PARENTS + SRF_LIST, + SRF_OUT_UNLOCKED, + SRF_OUT_LOGS, + SRF_OUT_HELD, + SRF_OUT_EVENTS, + SRF_OUT_OVERFLOW, + SRF_OUT_HEAD, + SRF_OUT_COUNT = SRF_OUT_HEAD + SRF_EVENTS * SRF_EVENT_WIDTH, +}; + +/* Runs one obs_source_restore_filters() through `restore` (the Rust export + * or a mutant; NULL for the original) on a fresh fixture (see srf_new()), on + * the parent (NULL when present is false) and the array (NULL when + * with_array is false). Writes SRF_OUT_COUNT values to out and the last log + * line to message; false when the fixture could not be built. */ +bool oracle_srf_run(srf_restore restore, srf_get_log get_log, srf_set_log set_log, bool present, bool with_array, + uint8_t noise, size_t count, size_t item_count, uint32_t items, long dying, int64_t *out, + char *message, size_t message_size); +bool oracle_srf_run(srf_restore restore, srf_get_log get_log, srf_set_log set_log, bool present, bool with_array, + uint8_t noise, size_t count, size_t item_count, uint32_t items, long dying, int64_t *out, + char *message, size_t message_size) +{ + if (count > SRF_SLOTS || item_count > SRF_ITEMS || message_size == 0) + return false; + struct srf_fixture *f = srf_new(noise, count, item_count, items, dying); + if (!f) + return false; + obs_source_t *source = present ? &f->parent : NULL; + obs_data_array_t *array = with_array ? (obs_data_array_t *)(void *)&f->array_marker : NULL; + struct srf_log captured = {0}; + log_handler_t previous; + void *param; + + srf_current = f; + get_log(&previous, ¶m); + set_log(srf_capture, &captured); + if (restore) + restore(source, array); + else + oracle_obs_source_restore_filters(source, array); + set_log(previous, param); + + memset(out, 0, sizeof(int64_t) * SRF_OUT_COUNT); + out[SRF_OUT_COUNT_AFTER] = (int64_t)f->parent.filters.num; + for (size_t i = 0; i < SRF_LIST; i++) + out[SRF_OUT_ORDER + i] = i < f->parent.filters.num ? srf_id(f->parent.filters.array[i]) : SRF_UNTOUCHED; + for (size_t i = 0; i < SRF_SLOTS; i++) { + out[SRF_OUT_TARGETS + i] = srf_link(&f->filters_before[i].filter_target, &f->filters[i].filter_target); + out[SRF_OUT_PARENTS + i] = srf_link(&f->filters_before[i].filter_parent, &f->filters[i].filter_parent); + } + for (size_t i = 0; i < SRF_ITEMS; i++) { + out[SRF_OUT_TARGETS + SRF_SLOTS + i] = + srf_link(&f->loaded_before[i].filter_target, &f->loaded[i].filter_target); + out[SRF_OUT_PARENTS + SRF_SLOTS + i] = + srf_link(&f->loaded_before[i].filter_parent, &f->loaded[i].filter_parent); + } + + /* The list may change its array, length and capacity (compared above + * by its entries); nothing else of the parent, and of each filter + * only its target and parent. */ + bool unchanged = srf_equal_except(&f->parent_before, &f->parent, sizeof(f->parent), + offsetof(struct obs_source, filter_mutex), sizeof(f->parent.filter_mutex), + offsetof(struct obs_source, filters), sizeof(f->parent.filters)); + for (size_t i = 0; i < SRF_SLOTS; i++) + unchanged = unchanged && srf_equal_except(&f->filters_before[i], &f->filters[i], sizeof(f->filters[i]), + offsetof(struct obs_source, filter_target), + sizeof(f->filters[i].filter_target), + offsetof(struct obs_source, filter_parent), + sizeof(f->filters[i].filter_parent)); + for (size_t i = 0; i < SRF_ITEMS; i++) + unchanged = unchanged && srf_equal_except(&f->loaded_before[i], &f->loaded[i], sizeof(f->loaded[i]), + offsetof(struct obs_source, filter_target), + sizeof(f->loaded[i].filter_target), + offsetof(struct obs_source, filter_parent), + sizeof(f->loaded[i].filter_parent)); + out[SRF_OUT_UNCHANGED] = unchanged; + out[SRF_OUT_UNLOCKED] = !srf_locked(); + out[SRF_OUT_LOGS] = (int64_t)captured.count; + out[SRF_OUT_HELD] = f->held; + out[SRF_OUT_EVENTS] = (int64_t)f->event_count; + out[SRF_OUT_OVERFLOW] = f->overflow; + for (size_t i = 0; i < f->event_count; i++) + memcpy(&out[SRF_OUT_HEAD + i * SRF_EVENT_WIDTH], f->events[i], sizeof(f->events[i])); + srf_copy(message, message_size, f->message); + + bool ok = true; + srf_current = NULL; + if (!out[SRF_OUT_UNLOCKED]) + pthread_mutex_unlock(&f->parent.filter_mutex); + srf_free(f, &ok); + return ok; +} + +/* The sizes the Rust side mirrors: 0 the out array, 1 the filter slots, + * 2 the item slots, 3 the event width, 4 the item name selectors. */ +size_t oracle_srf_layout(size_t which); +size_t oracle_srf_layout(size_t which) +{ + switch (which) { + case 0: + return SRF_OUT_COUNT; + case 1: + return SRF_SLOTS; + case 2: + return SRF_ITEMS; + case 3: + return SRF_EVENT_WIDTH; + case 4: + return SRF_ITEM_NAMES; + default: + return 0; + } +} diff --git a/rust/obs-source/Cargo.toml b/rust/obs-source/Cargo.toml index f661655787..de59031730 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-activate.c.h (obs_source_activate and obs_source_deactivate), libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-copy-filters.c.h (obs_source_copy_filters and obs_source_copy_single_filter), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-duplicate-entry.c.h (obs_source_duplicate), libobs/obs-source-filter-add.c.h (obs_source_filter_add), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-filter-remove.c.h (obs_source_filter_remove and its refless step), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-frame-copy-data.c.h (obs_source_frame_copy, running the copy plan), libobs/obs-source-frame-wrappers.c.h (the six async-frame entry points), libobs/obs-source-get-release-frame.c.h (obs_source_get_frame and obs_source_release_frame), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-output-cea708.c.h (obs_source_output_cea708), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-remove.c.h (obs_source_remove), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-set-name.c.h (the source rename), libobs/obs-source-show-preloaded-video.c.h (obs_source_show_preloaded_video), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-access.c.h (the transition getters and manual controls; C shims in obs-source-seam), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-load.c.h (the transition load, scale type and swap checks), libobs/obs-source-transition-restore.c.h (the transition load; C shim in obs-source-seam), libobs/obs-source-transition-render.c.h (the transition render and audio steps), libobs/obs-source-transition-sample-time.c.h (the transition's per-sample audio time), libobs/obs-source-transition-settings.c.h (the transition settings; C shims in obs-source-seam), libobs/obs-source-transition-size.c.h (the transition size, child matrices and tick; C shims in obs-source-seam), libobs/obs-source-transition-slots.c.h (the transition child slots and swap; C shims in obs-source-seam), libobs/obs-source-transition-start.c.h (the transition start checks and child handover), libobs/obs-source-transition-stop.c.h (the transition clock read and stop; C shims in obs-source-seam), libobs/obs-source-transition-switch.c.h (the transition start and set; C shims in obs-source-seam), libobs/obs-source-transition-video.c.h (the transition video render; C shims in obs-source-seam), the rest of libobs/obs-source-transition.c.h (the transition audio render, init and free; C shims in obs-source-seam), libobs/obs-source-video-tick.c.h (the per-frame video tick decisions) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions), libobs/obs-source-volume-mul.c.h (the source volume multiply kernels)" +description = "Rust ports of libobs/obs-source-activate.c.h (obs_source_activate and obs_source_deactivate), libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-copy-filters.c.h (obs_source_copy_filters and obs_source_copy_single_filter), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-duplicate-entry.c.h (obs_source_duplicate), libobs/obs-source-filter-add.c.h (obs_source_filter_add), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-filter-remove.c.h (obs_source_filter_remove and its refless step), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-frame-copy-data.c.h (obs_source_frame_copy, running the copy plan), libobs/obs-source-frame-wrappers.c.h (the six async-frame entry points), libobs/obs-source-get-release-frame.c.h (obs_source_get_frame and obs_source_release_frame), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-output-cea708.c.h (obs_source_output_cea708), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-remove.c.h (obs_source_remove), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-restore-filters.c.h (obs_source_restore_filters), 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 2f7796e48f..eec28a1533 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -82,6 +82,7 @@ pub mod source_remove; pub mod source_removed; pub mod source_render_route; pub mod source_replace_missing_file; +pub mod source_restore_filters; pub mod source_save_load; pub mod source_set_name; pub mod source_settings_getter; diff --git a/rust/obs-source/src/ffi/source_restore_filters.rs b/rust/obs-source/src/ffi/source_restore_filters.rs new file mode 100644 index 0000000000..20b9817b38 --- /dev/null +++ b/rust/obs-source/src/ffi/source_restore_filters.rs @@ -0,0 +1,168 @@ +//! `obs_source_restore_filters()`; the lock, the filter list, the links, +//! the array reads, the references, the loads and the releases stay behind +//! the adapters of `obs-source-restore-filters-fields.c.h`. +use crate::restore_filters::{RestoreList, restore}; +use core::ffi::{CStr, c_char, c_int, c_void}; +use core::ptr::{NonNull, null_mut}; + +unsafe extern "C" { + fn obs_source_restore_filters_lock(source: *mut c_void); + fn obs_source_restore_filters_count(source: *const c_void) -> usize; + fn obs_source_restore_filters_at(source: *const c_void, index: usize) -> *mut c_void; + fn obs_source_restore_filters_set_parent(filter: *mut c_void, parent: *mut c_void); + fn obs_source_restore_filters_set_target(filter: *mut c_void, target: *mut c_void); + fn obs_source_restore_filters_free_list(source: *mut c_void); + fn obs_source_restore_filters_unlock(source: *mut c_void); + fn obs_source_restore_filters_item_count(array: *mut c_void) -> usize; + fn obs_source_restore_filters_item(array: *mut c_void, index: usize) -> *mut c_void; + fn obs_source_restore_filters_item_name(item: *mut c_void) -> *const c_char; + fn obs_source_restore_filters_name(filter: *const c_void) -> *const c_char; + fn obs_source_restore_filters_get_ref(filter: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_load(item: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_load_private(item: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_store( + source: *mut c_void, + filters: *const *mut c_void, + count: usize, + ); + fn obs_source_restore_filters_release_item(item: *mut c_void); + fn obs_source_restore_filters_release(filter: *mut c_void); + fn blog(level: c_int, format: *const c_char, ...); +} + +/// Constructed only for a live, non-NULL source; the core reads `array` +/// only once it has been told it is not NULL. +struct Live { + source: NonNull, + array: *mut c_void, +} + +/// The bytes of a C string, or `None` for NULL. +/// +/// # Safety +/// A non-NULL `text` must be NUL-terminated and stay valid and unchanged +/// while the returned slice is used. +unsafe fn bytes<'a>(text: *const c_char) -> Option<&'a [u8]> { + // SAFETY: the caller's contract. + (!text.is_null()).then(|| unsafe { CStr::from_ptr(text) }.to_bytes()) +} + +impl RestoreList for Live { + type Source = *mut c_void; + type Item = *mut c_void; + fn this(&self) -> *mut c_void { + self.source.as_ptr() + } + fn lock(&self) { + // SAFETY: a live source owns an initialized filter_mutex. + unsafe { obs_source_restore_filters_lock(self.source.as_ptr()) } + } + fn count(&self) -> usize { + // SAFETY: a live source, read under its filter_mutex. + unsafe { obs_source_restore_filters_count(self.source.as_ptr()) } + } + fn filter(&self, index: usize) -> *mut c_void { + // SAFETY: the core asks only below a count read under the held + // filter_mutex, the original C's contract for the array. + unsafe { obs_source_restore_filters_at(self.source.as_ptr(), index) } + } + fn unlink(&self, filter: *mut c_void) { + // SAFETY: a listed filter, alive (the list's reference, which the + // core keeps until it releases it), written under the held lock. + unsafe { + obs_source_restore_filters_set_parent(filter, null_mut()); + obs_source_restore_filters_set_target(filter, null_mut()); + } + } + fn free_list(&self) { + // SAFETY: a live source's list, under the held lock; the core holds + // the listed references. + unsafe { obs_source_restore_filters_free_list(self.source.as_ptr()) } + } + fn unlock(&self) { + // SAFETY: matches the lock the core took on this live source. + unsafe { obs_source_restore_filters_unlock(self.source.as_ptr()) } + } + fn item_count(&self) -> usize { + // SAFETY: the caller's live, non-NULL array. + unsafe { obs_source_restore_filters_item_count(self.array) } + } + fn item(&self, index: usize) -> *mut c_void { + // SAFETY: the caller's live, non-NULL array, below its count. + unsafe { obs_source_restore_filters_item(self.array, index) } + } + fn item_name(&self, item: *mut c_void) -> Option<&[u8]> { + // SAFETY: an item the core holds until after its last use of the + // name; obs_data_get_string() returns a NUL-terminated string the + // item owns (never NULL). + unsafe { bytes(obs_source_restore_filters_item_name(item)) } + } + fn name(&self, filter: *mut c_void) -> Option<&[u8]> { + // SAFETY: an old filter the core still holds; its name is NULL or + // NUL-terminated and nothing renames it during the compare (the + // original read it the same way). + unsafe { bytes(obs_source_restore_filters_name(filter)) } + } + fn get_ref(&self, filter: *mut c_void) -> Option<*mut c_void> { + // SAFETY: an old filter the core still holds. + let referenced = unsafe { obs_source_restore_filters_get_ref(filter) }; + (!referenced.is_null()).then_some(referenced) + } + fn load(&self, item: *mut c_void) -> *mut c_void { + // SAFETY: an item the core holds. + unsafe { obs_source_restore_filters_load(item) } + } + fn load_private(&self, item: *mut c_void) -> *mut c_void { + // SAFETY: an item the core holds. + unsafe { obs_source_restore_filters_load_private(item) } + } + fn set_target(&self, filter: *mut c_void, target: *mut c_void) { + // SAFETY: a restored filter the core holds a reference to (a load + // reads the new source's fields before it returns, so it is never + // NULL), as in the original. + unsafe { obs_source_restore_filters_set_target(filter, target) } + } + fn set_parent(&self, filter: *mut c_void) { + // SAFETY: as for set_target. + unsafe { obs_source_restore_filters_set_parent(filter, self.source.as_ptr()) } + } + fn store(&self, filters: Vec<*mut c_void>) { + // SAFETY: a live source's list, replaced under the held lock; the + // adapter copies the filters before the vector is dropped, and the + // list takes over the references they carry. + unsafe { + obs_source_restore_filters_store(self.source.as_ptr(), filters.as_ptr(), filters.len()); + } + } + fn release_item(&self, item: *mut c_void) { + // SAFETY: the item's reference from obs_data_array_item(). + unsafe { obs_source_restore_filters_release_item(item) } + } + fn release(&self, filter: *mut c_void) { + // SAFETY: the old list's reference, released once. + unsafe { obs_source_restore_filters_release(filter) } + } +} + +fn null_log(function: &'static CStr, parameter: &'static CStr) { + // SAFETY: static strings match the two %s arguments of the format. + unsafe { + blog( + 400, + c"%s: Null '%s' parameter".as_ptr(), + function.as_ptr(), + parameter.as_ptr(), + ); + } +} + +/// # Safety +/// A non-NULL source must be live with an initialized filter list under +/// the original libobs contract; a non-NULL array must be a live +/// `obs_data_array_t` of `obs_data_t` items. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_restore_filters(source: *mut c_void, array: *mut c_void) { + // No adapter runs until NULL has been rejected. + let live = NonNull::new(source).map(|source| Live { source, array }); + restore(live.as_ref(), !array.is_null(), null_log); +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index f28215b2f6..a8bbe02282 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -110,6 +110,9 @@ //! `libobs/obs-source-render-route.c.h`, the source and filter render //! routing (which draw a source or a filter takes, the filter bypass, the //! default effect and the linear sRGB flags); +//! `libobs/obs-source-restore-filters.c.h`, `obs_source_restore_filters()` +//! (the lock, list, array reads, references, loads and releases stay in a C +//! fields adapter); //! `libobs/obs-source-set-name.c.h`, the source rename //! `obs_source_set_name()` (the unchanged-name check, the canvas or table //! rename, and its signals); diff --git a/rust/obs-source/src/restore_filters.rs b/rust/obs-source/src/restore_filters.rs index f8db42f58a..afa0e3be02 100644 --- a/rust/obs-source/src/restore_filters.rs +++ b/rust/obs-source/src/restore_filters.rs @@ -20,6 +20,7 @@ clippy::unreachable )] +use crate::source_filter_chain::{Restore, restore_matches, restore_step}; use core::ffi::CStr; /// The public function named in the NULL diagnostics. @@ -100,6 +101,76 @@ pub fn restore( array: bool, log: impl FnOnce(&'static CStr, &'static CStr), ) { - let _ = (source, array, log); - todo!("#5801") + let Some(source) = source else { + log(RESTORE_FUNCTION, SOURCE_PARAMETER); + return; + }; + if !array { + log(RESTORE_FUNCTION, ARRAY_PARAMETER); + return; + } + + source.lock(); + let reserve = source.count(); + let mut current = Vec::with_capacity(reserve); + let mut restored = Vec::with_capacity(reserve); + let mut index = 0; + while index < source.count() { + let filter = source.filter(index); + current.push(filter); + source.unlink(filter); + index = index.wrapping_add(1); + } + source.free_list(); + source.unlock(); + + let mut prev = None; + for index in 0..source.item_count() { + let item = source.item(index); + let found = reuse(source, ¤t, source.item_name(item)); + let filter = match (restore_step(found.is_some()), found) { + (Restore::Reuse, Some(filter)) => filter, + (Restore::Load, _) => source.load(item), + (Restore::LoadPrivate | Restore::Reuse, _) => source.load_private(item), + }; + if let Some(prev) = prev { + source.set_target(prev, filter); + } + prev = Some(filter); + restored.push(filter); + source.release_item(item); + } + + if let Some(prev) = prev { + source.set_target(prev, source.this()); + } + for &filter in &restored { + source.set_parent(filter); + } + + source.lock(); + source.store(restored); + source.unlock(); + + for filter in current { + source.release(filter); + } +} + +/// The first current filter whose name matches `name` (a NULL current +/// name never does, nor a NULL item name), referenced: `None` when there +/// is none or it can't be referenced. The search stops at the first match +/// either way. +fn reuse( + source: &L, + current: &[L::Source], + name: Option<&[u8]>, +) -> Option { + for &filter in current { + let cur_name = source.name(filter); + if name.is_some_and(|name| restore_matches(cur_name, name)) { + return source.get_ref(filter); + } + } + None } diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 565af02bdf..62c78afd31 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -152,6 +152,7 @@ mod render_route_parity; mod replace_missing_file; mod replace_missing_file_parity; mod restore_filters; +mod restore_filters_parity; mod save_load; mod save_load_parity; mod set_name; diff --git a/rust/obs-source/tests/source/restore_filters_parity.rs b/rust/obs-source/tests/source/restore_filters_parity.rs new file mode 100644 index 0000000000..d0da7d6170 --- /dev/null +++ b/rust/obs-source/tests/source/restore_filters_parity.rs @@ -0,0 +1,600 @@ +//! Tier 3: the original C `obs_source_restore_filters()` against the Rust +//! export on noise-filled real-header sources, with a stand-in array and +//! stand-in references, loads and releases: the new list, every filter's +//! target and parent, each item read, name read and item release, each +//! reference, load and release in order with the lock state and the list +//! and links at that moment, the NULL log lines, every other byte, the lock +//! afterwards and the item holds. +use core::ffi::{CStr, c_char, c_long, c_void}; +use core::ptr::{NonNull, null_mut}; +use obs_source::ffi::source_restore_filters::obs_source_restore_filters; +use obs_source::restore_filters::{RestoreList, restore}; +use obs_util::ffi::base::{base_get_log_handler, base_set_log_handler}; +use proptest::prelude::*; + +type Restore = unsafe extern "C" fn(*mut c_void, *mut c_void); +type GetLog = unsafe extern "C" fn(*mut *mut c_void, *mut *mut c_void); +type SetLog = unsafe extern "C" fn(*mut c_void, *mut c_void); + +unsafe extern "C" { + fn oracle_srf_run( + restore: Option, + get: GetLog, + set: SetLog, + present: bool, + with_array: bool, + noise: u8, + count: usize, + item_count: usize, + items: u32, + dying: c_long, + out: *mut i64, + message: *mut c_char, + message_size: usize, + ) -> bool; + fn oracle_srf_layout(which: usize) -> usize; + fn obs_source_restore_filters_lock(source: *mut c_void); + fn obs_source_restore_filters_count(source: *const c_void) -> usize; + fn obs_source_restore_filters_at(source: *const c_void, index: usize) -> *mut c_void; + fn obs_source_restore_filters_set_parent(filter: *mut c_void, parent: *mut c_void); + fn obs_source_restore_filters_set_target(filter: *mut c_void, target: *mut c_void); + fn obs_source_restore_filters_free_list(source: *mut c_void); + fn obs_source_restore_filters_unlock(source: *mut c_void); + fn obs_source_restore_filters_item_count(array: *mut c_void) -> usize; + fn obs_source_restore_filters_item(array: *mut c_void, index: usize) -> *mut c_void; + fn obs_source_restore_filters_item_name(item: *mut c_void) -> *const c_char; + fn obs_source_restore_filters_name(filter: *const c_void) -> *const c_char; + fn obs_source_restore_filters_get_ref(filter: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_load(item: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_load_private(item: *mut c_void) -> *mut c_void; + fn obs_source_restore_filters_store( + source: *mut c_void, + filters: *const *mut c_void, + count: usize, + ); + fn obs_source_restore_filters_release_item(item: *mut c_void); + fn obs_source_restore_filters_release(filter: *mut c_void); +} + +/// The current filter slots (`SRF_SLOTS`) and item slots (`SRF_ITEMS`). +const SLOTS: usize = 6; +const ITEMS: usize = 6; +const LIST: usize = SLOTS + ITEMS; +/// The event width (`SRF_EVENT_WIDTH`) and the out array's layout. +const EVENT_WIDTH: usize = 5; +const EVENTS: usize = 96; +const COUNT_AFTER: usize = 0; +const ORDER: usize = 1; +const TARGETS: usize = ORDER + LIST; +const PARENTS: usize = TARGETS + LIST; +const UNCHANGED: usize = PARENTS + LIST; +const UNLOCKED: usize = UNCHANGED + 1; +const LOGS: usize = UNCHANGED + 2; +const HELD: usize = UNCHANGED + 3; +const EVENT_COUNT: usize = UNCHANGED + 4; +const OVERFLOW: usize = UNCHANGED + 5; +const HEAD: usize = UNCHANGED + 6; +const OUT: usize = HEAD + EVENTS * EVENT_WIDTH; +/// Event kinds (`SRF_EV_*`). +const EV_REF: i64 = 5; +const EV_LOAD: i64 = 6; +const EV_RELEASE: i64 = 7; +const EV_LOG: i64 = 8; +/// Source ids (`SRF_NULL`, `SRF_PARENT`, `SRF_UNTOUCHED`, `SRF_LOADED`). +const NULL: c_long = -1; +/// `SRF_NULL` as a recorded id (`c_long` is 32 bits on Windows). +const NULL_ID: i64 = -1; +const PARENT: i64 = -3; +const UNTOUCHED: i64 = -4; +const LOADED: i64 = 100; +/// `LOG_DEBUG`. +const LOG_DEBUG: i64 = 400; +/// The current filters' names (`srf_names`, slot 2 unnamed) and the item +/// names by selector (`srf_item_names`). +const NAMES: [Option<&str>; SLOTS] = [Some("a"), Some("bb"), None, Some("e"), Some("a"), Some("g")]; +const ITEM_NAMES: [&str; 7] = ["a", "bb", "e", "g", "zz", "", "x"]; + +/// What one call left: the out array and the last log line. +type Seen = (Vec, String); + +#[derive(Clone, Copy, Debug)] +struct Case { + present: bool, + with_array: bool, + noise: u8, + count: usize, + item_count: usize, + items: u32, + dying: c_long, +} + +fn run(restore: Option, case: Case) -> Seen { + let mut out: [i64; OUT] = [0; OUT]; + let mut buffer = [0 as c_char; 128]; + // SAFETY: the isolated child owns the log handler. C builds a live + // fixture, runs the call, records and frees it, and restores logging; + // both buffers are as long as passed. + let built = unsafe { + oracle_srf_run( + restore, + base_get_log_handler, + base_set_log_handler, + case.present, + case.with_array, + case.noise, + case.count, + case.item_count, + case.items, + case.dying, + out.as_mut_ptr(), + buffer.as_mut_ptr(), + buffer.len(), + ) + }; + assert!(built, "{case:?}: fixture"); + // SAFETY: the oracle NUL-terminated the buffer. + let message = unsafe { CStr::from_ptr(buffer.as_ptr()) } + .to_str() + .unwrap() + .to_owned(); + (out.to_vec(), message) +} + +/// Both sides alike on `case`; the original's observation. +fn compare_with(restore: Restore, case: Case) -> Option { + let c = run(None, case); + let rust = run(Some(restore), case); + (c == rust).then_some(c) +} + +/// Each recorded event as (kind, a, b, locked), in order. +fn events(out: &[i64]) -> Vec<(i64, i64, i64, i64)> { + let count = usize::try_from(out[EVENT_COUNT]).unwrap(); + (0..count) + .map(|i| { + let e = &out[HEAD + i * EVENT_WIDTH..HEAD + (i + 1) * EVENT_WIDTH]; + (e[0], e[1], e[2], e[4]) + }) + .collect() +} + +/// The item names of a case, in order. +fn item_names(case: Case) -> Vec<&'static str> { + (0..case.item_count) + .map(|k| { + ITEM_NAMES[usize::try_from((case.items >> (3 * k)) & 7).unwrap() % ITEM_NAMES.len()] + }) + .collect() +} + +/// The list the C builds: per item, the first current filter of its name +/// unless it can't be referenced, else the item's loaded filter. +fn expected_list(case: Case) -> Vec { + item_names(case) + .into_iter() + .enumerate() + .map(|(k, name)| { + let k = i64::try_from(k).unwrap(); + match NAMES[..case.count].iter().position(|n| *n == Some(name)) { + Some(j) if c_long::try_from(j).unwrap() != case.dying => i64::try_from(j).unwrap(), + _ => LOADED + k, + } + }) + .collect() +} + +fn compare(case: Case) -> Seen { + let seen = compare_with(obs_source_restore_filters, case).unwrap_or_else(|| { + panic!( + "{case:?}: C {:?}, Rust {:?}", + run(None, case), + run(Some(obs_source_restore_filters), case) + ) + }); + let out = &seen.0; + // Nothing else written, the lock free, no event lost, every item + // released. + assert_eq!( + (out[UNCHANGED], out[UNLOCKED], out[OVERFLOW], out[HELD]), + (1, 1, 0, 0), + "{case:?}" + ); + seen +} + +/// One case with a source and an array, compared and checked against the +/// contract. +fn restore_case(case: Case) { + let (out, _) = compare(case); + let seen = events(&out); + let list = expected_list(case); + let count = i64::try_from(case.count).unwrap(); + // The new list, chained to the source, every entry parented. + assert_eq!( + out[COUNT_AFTER], + i64::try_from(list.len()).unwrap(), + "{case:?}" + ); + assert_eq!(&out[ORDER..ORDER + list.len()], list.as_slice(), "{case:?}"); + let slot = |id: i64| { + let id = if id >= LOADED { + id - LOADED + i64::try_from(SLOTS).unwrap() + } else { + id + }; + usize::try_from(id).unwrap() + }; + // A link left as it was reads UNTOUCHED: before the call, a listed + // filter targets the next (the last the parent) with the parent as its + // parent, and every other filter has neither. + let links = |id: i64| { + let before = if id < count { + (if id + 1 < count { id + 1 } else { PARENT }, PARENT) + } else { + (NULL_ID, NULL_ID) + }; + let read = |value: i64, before: i64| if value == UNTOUCHED { before } else { value }; + ( + read(out[TARGETS + slot(id)], before.0), + read(out[PARENTS + slot(id)], before.1), + ) + }; + for (i, &filter) in list.iter().enumerate() { + let (target, parent) = links(filter); + if !list[i + 1..].contains(&filter) { + let next = list.get(i + 1).copied().unwrap_or(PARENT); + assert_eq!(target, next, "{case:?}"); + } + assert_eq!(parent, PARENT, "{case:?}"); + } + // An old filter not listed again is unlinked. + for old in (0..count).filter(|f| !list.contains(f)) { + assert_eq!(links(old), (NULL_ID, NULL_ID), "{case:?}"); + } + // No log line; every load private (the chain rule) and every call + // after the first lock with the lock free; the old filters released + // last, once each, in old order. + assert!(seen.iter().all(|e| e.0 != EV_LOG), "{case:?}"); + assert!(seen.iter().all(|e| e.3 == 0), "{case:?}"); + assert!(seen.iter().filter(|e| e.0 == EV_LOAD).all(|e| e.2 == 0)); + let releases: Vec<_> = seen + .iter() + .filter(|e| e.0 == EV_RELEASE) + .map(|e| e.1) + .collect(); + assert_eq!(releases, (0..count).collect::>(), "{case:?}"); + assert!( + seen[seen.len() - releases.len()..] + .iter() + .all(|e| e.0 == EV_RELEASE) + ); + let refs = seen.iter().filter(|e| e.0 == EV_REF).count(); + assert!(refs <= case.item_count); +} + +/// Mutants of the export: the real core over a list that breaks one call. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Break { + NoUnlink, + SourceTarget, + LoadPublic, + ReleaseLocked, + Unnamed, + NoRelease, + ParentWithTarget, +} + +struct Mutant { + source: NonNull, + array: *mut c_void, + broken: Break, +} + +/// The bytes of a C string, or `None` for NULL. +/// +/// # Safety +/// As the export's. +unsafe fn bytes<'a>(text: *const c_char) -> Option<&'a [u8]> { + // SAFETY: the caller's contract. + (!text.is_null()).then(|| unsafe { CStr::from_ptr(text) }.to_bytes()) +} + +impl RestoreList for Mutant { + type Source = *mut c_void; + type Item = *mut c_void; + fn this(&self) -> *mut c_void { + self.source.as_ptr() + } + fn lock(&self) { + // SAFETY: a live fixture source. + unsafe { obs_source_restore_filters_lock(self.source.as_ptr()) } + } + fn count(&self) -> usize { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_count(self.source.as_ptr()) } + } + fn filter(&self, index: usize) -> *mut c_void { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_at(self.source.as_ptr(), index) } + } + fn unlink(&self, filter: *mut c_void) { + if self.broken != Break::NoUnlink { + // SAFETY: as the export's. + unsafe { + obs_source_restore_filters_set_parent(filter, null_mut()); + obs_source_restore_filters_set_target(filter, null_mut()); + } + } + } + fn free_list(&self) { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_free_list(self.source.as_ptr()) } + } + fn unlock(&self) { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_unlock(self.source.as_ptr()) } + } + fn item_count(&self) -> usize { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_item_count(self.array) } + } + fn item(&self, index: usize) -> *mut c_void { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_item(self.array, index) } + } + fn item_name(&self, item: *mut c_void) -> Option<&[u8]> { + // SAFETY: as the export's. + unsafe { bytes(obs_source_restore_filters_item_name(item)) } + } + fn name(&self, filter: *mut c_void) -> Option<&[u8]> { + // SAFETY: as the export's. + let name = unsafe { bytes(obs_source_restore_filters_name(filter)) }; + name.filter(|_| self.broken != Break::Unnamed) + } + fn get_ref(&self, filter: *mut c_void) -> Option<*mut c_void> { + // SAFETY: as the export's. + let referenced = unsafe { obs_source_restore_filters_get_ref(filter) }; + (!referenced.is_null()).then_some(referenced) + } + fn load(&self, item: *mut c_void) -> *mut c_void { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_load(item) } + } + fn load_private(&self, item: *mut c_void) -> *mut c_void { + if self.broken == Break::LoadPublic { + return self.load(item); + } + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_load_private(item) } + } + fn set_target(&self, filter: *mut c_void, target: *mut c_void) { + let target = if self.broken == Break::SourceTarget { + self.source.as_ptr() + } else { + target + }; + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_set_target(filter, target) } + if self.broken == Break::ParentWithTarget { + self.set_parent(filter); + } + } + fn set_parent(&self, filter: *mut c_void) { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_set_parent(filter, self.source.as_ptr()) } + } + fn store(&self, filters: Vec<*mut c_void>) { + // SAFETY: as the export's. + unsafe { + obs_source_restore_filters_store(self.source.as_ptr(), filters.as_ptr(), filters.len()); + } + } + fn release_item(&self, item: *mut c_void) { + // SAFETY: as the export's. + unsafe { obs_source_restore_filters_release_item(item) } + } + fn release(&self, filter: *mut c_void) { + match self.broken { + Break::NoRelease => {} + // SAFETY: as the export's, but under the lock. + Break::ReleaseLocked => unsafe { + obs_source_restore_filters_lock(self.source.as_ptr()); + obs_source_restore_filters_release(filter); + obs_source_restore_filters_unlock(self.source.as_ptr()); + }, + // SAFETY: as the export's. + _ => unsafe { obs_source_restore_filters_release(filter) }, + } + } +} + +unsafe extern "C" fn mutant_restore(source: *mut c_void, array: *mut c_void) { + let (Some(source), false) = (NonNull::new(source), array.is_null()) else { + // SAFETY: as the export's. + return unsafe { obs_source_restore_filters(source, array) }; + }; + let broken = match B { + 0 => Break::NoUnlink, + 1 => Break::SourceTarget, + 2 => Break::LoadPublic, + 3 => Break::ReleaseLocked, + 4 => Break::Unnamed, + 5 => Break::NoRelease, + _ => Break::ParentWithTarget, + }; + let mutant = Mutant { + source, + array, + broken, + }; + restore(Some(&mutant), true, |_, _| panic!("logged")); +} + +/// Selectors packed three bits each, item 0 lowest. +fn pack(selectors: &[u32]) -> u32 { + selectors + .iter() + .rev() + .fold(0, |packed, &s| (packed << 3) | s) +} + +fn case(count: usize, selectors: &[u32], dying: c_long) -> Case { + Case { + present: true, + with_array: true, + noise: 0x5a, + count, + item_count: selectors.len(), + items: pack(selectors), + dying, + } +} + +/// Each mutant disagrees with the original C on a chain of 4 restored as +/// "zz", "a", "x", "bb" (a load, a reuse, a load, a reuse; "e" dropped). +fn rejects_mutants() { + let mutants: [Restore; 7] = [ + mutant_restore::<0>, + mutant_restore::<1>, + mutant_restore::<2>, + mutant_restore::<3>, + mutant_restore::<4>, + mutant_restore::<5>, + mutant_restore::<6>, + ]; + let probe = case(4, &[4, 0, 6, 1], NULL); + restore_case(probe); + for (i, mutant) in mutants.into_iter().enumerate() { + assert!( + compare_with(mutant, probe).is_none(), + "restore_filters mutant {i} agreed with the original C" + ); + } +} + +const SOURCE_LINE: &str = "obs_source_restore_filters: Null 'source' parameter"; +const ARRAY_LINE: &str = "obs_source_restore_filters: Null 'array' parameter"; + +/// NULL source or array: one line, nothing else. +fn null_arguments() { + for (present, with_array, line) in [ + (false, true, SOURCE_LINE), + (false, false, SOURCE_LINE), + (true, false, ARRAY_LINE), + ] { + let (out, message) = compare(Case { + present, + with_array, + ..case(3, &[0, 1], NULL) + }); + assert_eq!(message, line); + assert_eq!(events(&out), [(EV_LOG, LOG_DEBUG, 1, 0)]); + assert_eq!(out[LOGS], 1); + assert_eq!(out[COUNT_AFTER], 3); + assert_eq!(&out[ORDER..ORDER + 3], [0, 1, 2]); + assert!(out[TARGETS..UNCHANGED].iter().all(|&l| l == UNTOUCHED)); + } +} + +/// Every chain of 0 to 6 current filters (an unnamed one, a repeated name) +/// with every array of up to 3 items over the 7 item names (reusing, +/// loading, duplicating and dropping filters), with no filter or each +/// listed one unreferenceable (sampled past 4 filters), and arrays of 4 to +/// 6 items over a few patterns. +fn every_chain() { + let mut arrays: Vec> = vec![Vec::new()]; + let mut last = vec![Vec::new()]; + for _ in 0..3 { + let next: Vec> = last + .iter() + .flat_map(|a: &Vec| { + (0..7).map(move |s| { + let mut longer = a.clone(); + longer.push(s); + longer + }) + }) + .collect(); + arrays.extend(next.iter().cloned()); + last = next; + } + arrays.extend([ + vec![0, 0, 0, 0], + vec![3, 2, 1, 0, 4], + vec![4, 5, 6, 4, 5, 6], + vec![0, 1, 2, 3, 0, 1], + ]); + let mut grid = 0u64; + for count in 0..=SLOTS { + for array in &arrays { + for dying in + std::iter::once(NULL).chain((0..count).map(|d| c_long::try_from(d).unwrap())) + { + grid += 1; + if count >= 5 && !obs_c_oracle::parity::keep(grid) { + continue; + } + let noise = u8::try_from(grid % 256).unwrap().wrapping_mul(37); + restore_case(Case { + noise, + ..case(count, array, dying) + }); + } + } + } +} + +#[test] +fn restore_filters_matches_c() { + if !crate::output::isolated(concat!(module_path!(), "::restore_filters_matches_c")) { + return; + } + // SAFETY: plain reads of the oracle's constants. + assert_eq!( + unsafe { + [ + oracle_srf_layout(0), + oracle_srf_layout(1), + oracle_srf_layout(2), + oracle_srf_layout(3), + oracle_srf_layout(4), + ] + }, + [OUT, SLOTS, ITEMS, EVENT_WIDTH, ITEM_NAMES.len()] + ); + null_arguments(); + every_chain(); + rejects_mutants(); + let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig { + cases: obs_c_oracle::parity::cases(256), + failure_persistence: None, + ..ProptestConfig::default() + }); + runner + .run( + &( + any::<(bool, bool, u8, u32)>(), + 0..=SLOTS, + 0..=ITEMS, + -1..=c_long::try_from(SLOTS).unwrap(), + ), + |((present, with_array, noise, items), count, item_count, dying)| { + let case = Case { + present, + with_array, + noise, + count, + item_count, + items, + dying, + }; + if present && with_array { + restore_case(case); + } else { + compare(case); + } + Ok(()) + }, + ) + .unwrap(); +}