diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index cd0415eb49..3f54cb1d33 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -2,7 +2,7 @@ #include "libobs/build/libobs.pch.h" -#include "libobs/obs-audio-info-queries.c.h" +#include "libobs/obs-audio-info-queries-fields.c.h" #include "libobs/obs-base-effect-fields.c.h" #include "libobs/obs-context-runtime.c.h" #include "libobs/obs-core-cmdline-fields.c.h" @@ -63,7 +63,7 @@ #include "libobs/obs-ui-task-handler-fields.c.h" #include "libobs/obs-video-info-query-fields.c.h" #include "libobs/obs-video-level-queries-fields.c.h" -#include "libobs/obs-video-stats-queries.c.h" +#include "libobs/obs-video-stats-queries-fields.c.h" #include "libobs/obs-weak-object-expired-fields.c.h" #include "libobs/obs-weak-object-identity-fields.c.h" #include "libobs/obs-weak-object-refs-fields.c.h" diff --git a/libobs/build/libobs.ported-audio-info-queries+.h.c b/libobs/build/libobs.ported-audio-info-queries+.h.c new file mode 100644 index 0000000000..307c2301c8 --- /dev/null +++ b/libobs/build/libobs.ported-audio-info-queries+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original audio-info queries, C reference only. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-audio-info-queries.c.h" diff --git a/libobs/build/libobs.ported-video-stats-queries+.h.c b/libobs/build/libobs.ported-video-stats-queries+.h.c new file mode 100644 index 0000000000..d7fa0dd65c --- /dev/null +++ b/libobs/build/libobs.ported-video-stats-queries+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original video-statistics queries, C reference only. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-video-stats-queries.c.h" diff --git a/libobs/build/ported-source-sets/audio-info-queries.json b/libobs/build/ported-source-sets/audio-info-queries.json new file mode 100644 index 0000000000..c3b5591313 --- /dev/null +++ b/libobs/build/ported-source-sets/audio-info-queries.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-audio-info-queries+.h.c" + ] +} diff --git a/libobs/build/ported-source-sets/video-stats-queries.json b/libobs/build/ported-source-sets/video-stats-queries.json new file mode 100644 index 0000000000..b2c8f423ad --- /dev/null +++ b/libobs/build/ported-source-sets/video-stats-queries.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-video-stats-queries+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-core-audio_info_queries.txt b/libobs/cmake/rust-exports.d/obs-core-audio_info_queries.txt new file mode 100644 index 0000000000..22783ff38d --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-core-audio_info_queries.txt @@ -0,0 +1,2 @@ +obs_get_audio_info +obs_get_audio_info2 diff --git a/libobs/cmake/rust-exports.d/obs-core-video_stats_queries.txt b/libobs/cmake/rust-exports.d/obs-core-video_stats_queries.txt new file mode 100644 index 0000000000..cf60c22b8f --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-core-video_stats_queries.txt @@ -0,0 +1,5 @@ +obs_get_active_fps +obs_get_average_frame_time_ns +obs_get_lagged_frames +obs_get_total_frames +obs_get_video_frame_time diff --git a/libobs/obs-audio-info-queries-fields.c.h b/libobs/obs-audio-info-queries-fields.c.h new file mode 100644 index 0000000000..39cfa7cfbe --- /dev/null +++ b/libobs/obs-audio-info-queries-fields.c.h @@ -0,0 +1,35 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters for the Rust obs_get_audio_info() and obs_get_audio_info2() + * (#5363): the current core, one read of each audio field, and the output's + * info through the real audio_output_get_info(). The core layout stays in C; + * the Rust shim checks the core for NULL before it asks for any field. */ +const struct obs_core *obs_audio_info_queries_core(void); +const struct obs_core *obs_audio_info_queries_core(void) +{ + return obs; +} + +audio_t *obs_audio_info_queries_output(const struct obs_core *core); +audio_t *obs_audio_info_queries_output(const struct obs_core *core) +{ + return core->audio.audio; +} + +const struct audio_output_info *obs_audio_info_queries_output_info(const audio_t *audio); +const struct audio_output_info *obs_audio_info_queries_output_info(const audio_t *audio) +{ + return audio_output_get_info(audio); +} + +bool obs_audio_info_queries_fixed_buffer(const struct obs_core *core); +bool obs_audio_info_queries_fixed_buffer(const struct obs_core *core) +{ + return core->audio.fixed_buffer; +} + +int obs_audio_info_queries_max_buffering_ticks(const struct obs_core *core); +int obs_audio_info_queries_max_buffering_ticks(const struct obs_core *core) +{ + return core->audio.max_buffering_ticks; +} diff --git a/libobs/obs-video-stats-queries-fields.c.h b/libobs/obs-video-stats-queries-fields.c.h new file mode 100644 index 0000000000..2a3e7ea3fd --- /dev/null +++ b/libobs/obs-video-stats-queries-fields.c.h @@ -0,0 +1,42 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters for the Rust video-statistics queries (#5364): the current + * core's stats, and its five obs_video_stats_* readers, which are static + * inline in obs-video-stats.h. Each reader keeps its one lock/read/unlock + * (#175); the stats layout and mutex stay in C. A live core is required, as + * in the original: the address is formed without a NULL check. */ +struct obs_video_stats *obs_video_stats_queries_stats(void); +struct obs_video_stats *obs_video_stats_queries_stats(void) +{ + return &obs->video.stats; +} + +uint64_t obs_video_stats_queries_frame_time(struct obs_video_stats *stats); +uint64_t obs_video_stats_queries_frame_time(struct obs_video_stats *stats) +{ + return obs_video_stats_frame_time(stats); +} + +double obs_video_stats_queries_fps(struct obs_video_stats *stats); +double obs_video_stats_queries_fps(struct obs_video_stats *stats) +{ + return obs_video_stats_fps(stats); +} + +uint64_t obs_video_stats_queries_avg_frame_time_ns(struct obs_video_stats *stats); +uint64_t obs_video_stats_queries_avg_frame_time_ns(struct obs_video_stats *stats) +{ + return obs_video_stats_avg_frame_time_ns(stats); +} + +uint32_t obs_video_stats_queries_total_frames(struct obs_video_stats *stats); +uint32_t obs_video_stats_queries_total_frames(struct obs_video_stats *stats) +{ + return obs_video_stats_total_frames(stats); +} + +uint32_t obs_video_stats_queries_lagged_frames(struct obs_video_stats *stats); +uint32_t obs_video_stats_queries_lagged_frames(struct obs_video_stats *stats) +{ + return obs_video_stats_lagged_frames(stats); +} diff --git a/rust/README.md b/rust/README.md index 0c8b19732a..32d9b57d79 100644 --- a/rust/README.md +++ b/rust/README.md @@ -604,9 +604,11 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-nix-system-info.c.h` | `obs-core::nix_system_info` | Swapped in hybrid `libobs` (group `libobs.ported-nix-system-info`, in the Linux ported sources, which FreeBSD and OpenBSD build too). Eleven pure functions on lines and sizes, declared in `obs-nix-system-info.h` without `EXPORT` and hidden: `obs_nix_system_info_is_name`, `_is_physical_id` and `_is_speed` (`log_processor_info()`'s `strncmp()` key checks, by the key's length, so `model names` matches), `_value` (a pointer after the first `:`, or `NULL` without one or at the end of the line), `_physical_id` (`atoi()` as glibc defines it: `(int)strtol()`), `_prints` (a line that starts with `\n` and a physical id other than the last printed), `_is_dmesg_cpu` and `_dmesg_speed` (FreeBSD's `CPU: ` line: after the last `(`, its length up to the first `-` in `*len`, untouched on `NULL`), `_total_mb`, `_free_mb` and `_physmem_mb` (wrapping `uint64_t` products over 1024 twice, and OpenBSD's `int64_t` truncated toward zero). Each key check is its own function, so the three checks of a cpuinfo line and each `continue` stay where they were. `obs-nix.c.h` keeps `fopen()`, `getline()`, `fclose()`, `free()`, every `dstr` copy, cut and depad, `sysinfo()` and `sysctl()`, the flatpak, desktop and data file pointer checks, and every `blog()` (the distribution, Flatpak and desktop rules are `obs-nix-log-rules.c.h`'s row). No intentional differences (`atoi()` past `int` is undefined in C; the core follows glibc); characterized, not endorsed and kept: arm64 logs no CPU name or speed (its physical id stays -1, the starting last id), a block that ends before a `model name` or `cpu MHz` line logs them as `NULL`, the last line of a file with no newline loses a byte to the newline cut, `physical id : x` reads as 0, a `dmesg.boot` speed with no `-` runs to the end of the line, and the memory products wrap above 16 EiB. `test_nix_system_info_steps` compiles the C into itself; it has no `_rust` variant, as for `test_canvas_rules_steps`. Tier 3 compares every result exactly over every line of up to three pieces of the cpuinfo and `dmesg.boot` alphabet, every byte after each key, the host's `/proc/cpuinfo`, `atoi()` from -70,000 to 70,000 and around the ends of `int`, the memory sizes over the edges of every field, both callers' loops over saved and generated files, and proptests over all of it; out-of-range `atoi()` is compared on Linux only. | | `libobs/obs-enum-scenes.c.h` | `obs-core::enum_scenes` | Legacy main-canvas scene enumerator (#4802). Forwards the borrowed current canvas, callback identity and opaque parameter exactly once to the existing canvas enumerator, preserving traversal, stopping and ownership. Tier 1 mirrors unchanged C characterization; original-C Tier 3 checks real adapter layout, callback effects and object bytes; Tier 2 exercises both actual libraries. Uninitialized/dead core/canvas, invalid callback/parameter and overflowing references are C UB, excluded; no intentional differences. | | `libobs/obs-video-level-queries.c.h` | `obs-core::video_level_queries` | Video SDR white and HDR nominal peak level queries (#5187). A real private C adapter returns the current core, which safe Rust checks for NULL before a second adapter reads the graphics pointer and both stored levels. Without a core or graphics the queries return exactly 300.0 and 1000.0; otherwise each stored level's exact bits, with no validation, clamping or arithmetic (signed zeros, infinities and NaN payloads verbatim). Tier 1 mirrors the unchanged `test_video_level_queries`, which now links the Rust export and the real adapter; original-C Tier 3 checks real adapter layout, the three core states over edge and random bit patterns, unchanged core bytes and global pointer. `test_no_core_getters` and `test_video_levels_range` keep actual-library coverage. Dead core and concurrent level writes are excluded; signaling NaNs are left out of the random cases (32-bit x86 float returns may quiet them in both). No intentional differences. | +| `libobs/obs-video-stats-queries.c.h` | `obs-core::video_stats_queries` | The five public video-statistics queries swapped in hybrid `libobs` (#5364; group `libobs.ported-video-stats-queries` keeps the original for the C reference): `obs_get_video_frame_time`, `obs_get_active_fps`, `obs_get_average_frame_time_ns`, `obs_get_total_frames` and `obs_get_lagged_frames`. Each is one call of its own `obs_video_stats_*` reader on the current core's `video.stats` (one lock, read and unlock, the synchronization of #175), returned unchanged; never one combined snapshot, and no no-core defaults (a live core is required, as in C). The stats layout and mutex stay in C behind private adapters (`obs-video-stats-queries-fields.c.h`, which call the header's static inline readers; also a shared Rust-static support member). The unchanged `test_video_stats_queries` keeps testing the extracted C source and `test_video_stats_race` the readers; the real library's frame counters keep their actual-library callers. Tier 1 mirrors every assertion over a mutex-guarded host (one locked read of its own field per query, mutex free after each); Tier 3 runs the original and the shim on one real-header core (exact result bits with the FPS as any non-signaling binary64 pattern, mutex free after every query, unchanged values and current core pointer, the adapter's address) with mutants. No intentional differences; Tier 4 does not apply. | | `libobs/obs-get-audio.c.h` | `obs-core::get_audio` | Borrowed current core audio output (#4808). Exact pointer forwarding, including null before setup/after disable, without ownership or activation changes. Safe Tier 1 mirrors the C characterization; original-C Tier 3 checks current-field changes, pointer identity, unchanged bytes and real adapter layout. Unchanged Tier 2 covers real output lifecycles. Initialized core required; no intentional differences. | | `libobs/obs-get-output-source.c.h` | `obs-core::get_output_source` | Legacy main-canvas channel getter (#4756). Forwards the borrowed current canvas and unchanged channel exactly once to the existing getter and returns its acquired source unchanged. Tier 1 mirrors the C characterization; original-C Tier 3 checks return identity, reference effects, full-width forwarding and real adapter layout; unchanged Tier 2 exercises both actual libraries. Uninitialized core, dead canvas/source and overflowing refcounts are original C UB, excluded; no intentional differences. | | `libobs/obs-set-locale.c.h` | `obs-core::set_locale` | Locale replacement and ordered module notifications through private field adapters. Frees old bmem storage before copying, stores the owned copy before callbacks, forwards the original pointer including NULL, and reads each next link after dispatch. Safe Tier 1 mirrors unchanged `test_set_locale`; Tier 3 compares the original C with the actual Rust FFI over bounded locale/list cases, including callback-time link changes. The common reference-only group covers every host; the native test fixture manifest remains unchanged. No intentional behavior differences; Tier 4 does not apply. | +| `libobs/obs-audio-info-queries.c.h` | `obs-core::audio_info_queries` | `obs_get_audio_info` and `obs_get_audio_info2` swapped in hybrid `libobs` (#5363; group `libobs.ported-audio-info-queries` keeps the original for the C reference). A NULL core answers false before any read (#2566, #3363). `obs_get_audio_info` checks its output, then the core's audio output, then reads the output's rate and speakers through the real `audio_output_get_info()`. `obs_get_audio_info2` runs the info read into a local first, then checks its own output and the audio output again, and stores the rate, the speakers, `fixed_buffer` and `obs_core_setup_rules_buffer_ms(max_buffering_ticks, rate)` cast straight to `uint32_t`. Nothing is written on failure; the caller's struct is written field by field. The core layout stays in C behind private adapters (`obs-audio-info-queries-fields.c.h`, also a shared Rust-static support member). The unchanged `test_audio_info_queries` keeps testing the extracted C source; `test_get_audio` and `test_core_setup_rules_steps` run the real library. Tier 1 mirrors every assertion plus the full read order; Tier 3 runs the original and the shim on one real-header core filled with any byte (result, output bytes, info call log, core bytes, current core pointer, real-header layouts) with mutants. The audio-controls oracle's `obs_get_audio_info` stand-in is dropped: obs-core's export answers false there without a current core. No intentional differences; Tier 4 does not apply. | | `libobs/obs-module-load-all.c.h` | `obs-core::module_load_all` | The deprecated `obs_load_all_modules`/`obs_load_all_modules2` stay intentional no-ops: no startup, module discovery, loading, allocation, logging or state change, and the optional failure info (count, pointer array, strings) is never dereferenced. Tier 1 mirrors unchanged `test_module_load_all`; Tier 3 compares the original C over random caller counts and NULL. No intentional differences; Tier 4 does not apply. | | `libobs/obs-set-output-source.c.h` | `obs-core::set_output_source` | Legacy main-canvas channel setter (#4709). Forwards the borrowed current canvas and unchanged channel/source exactly once to the existing canvas setter, preserving bounds, mutable local/global signals and all reference effects. Tier 1 mirrors the C characterization, callback-only original-C Tier 3 checks real adapter layout and unchanged object bytes, and unchanged Tier 2 runs both actual libraries. Uninitialized core and dead canvas/source are original C UB, excluded; no intentional differences. | | `libobs/obs-get-main-canvas.c.h` | `obs-core::get_main_canvas` | Main-canvas acquired getter (#4780). A real private C adapter borrows the current field and supplies the existing canvas reference operation; safe Rust delegates exactly once and preserves its returned identity and ownership effects. Tier 1 mirrors unchanged `test_get_main_canvas`, Tier 3 includes the original C wrapper and real adapter with exact layout and complete fixture-byte comparisons, and Tier 2 replays both actual libraries. Uninitialized core, dead canvases and overflowing counts are excluded; no intentional differences or Tier 4 surface. | diff --git a/rust/obs-c-oracle/oracle/audio_controls.c b/rust/obs-c-oracle/oracle/audio_controls.c index c588e997d8..ef3885353a 100644 --- a/rust/obs-c-oracle/oracle/audio_controls.c +++ b/rust/obs-c-oracle/oracle/audio_controls.c @@ -5,7 +5,8 @@ * stubs them. libobs supplies them when this file is not linked. The signal * calls are stubbed under oracle_* names: obs-callback exports the real * signal_handler_* symbols, and a test that links both would define them - * twice. */ + * twice. obs_get_audio_info is obs-core's export (#5363), which answers false + * here: no current core is installed outside its own parity probe. */ #include @@ -114,12 +115,6 @@ void obs_source_remove_audio_capture_callback(obs_source_t *source, obs_source_a UNUSED_PARAMETER(param); } -bool obs_get_audio_info(struct obs_audio_info *oai) -{ - UNUSED_PARAMETER(oai); - return false; -} - void signal_handler_connect(signal_handler_t *handler, const char *signal, signal_callback_t callback, void *data) { UNUSED_PARAMETER(handler); diff --git a/rust/obs-c-oracle/oracle/audio_info_queries.c b/rust/obs-c-oracle/oracle/audio_info_queries.c new file mode 100644 index 0000000000..545242d5c6 --- /dev/null +++ b/rust/obs-c-oracle/oracle/audio_info_queries.c @@ -0,0 +1,160 @@ +/* Original obs_get_audio_info() and obs_get_audio_info2() (#5363), renamed, + * beside the real adapters of obs-audio-info-queries-fields.c.h. Both read a + * thread-local current core instead of the library's global, and both reach + * audio_output_get_info() through one recording probe, so the original and + * the Rust shim see the same core and the same output info. The milliseconds + * helper is the real obs_core_setup_rules_buffer_ms() for both. The probe + * reports, instead of aborting, any difference in the result, the caller's + * output bytes (sentinel-filled), the info call log, the core bytes or the + * current core pointer, so mutants are observable. Excludes a dead core and + * concurrent writes to the audio fields: the original requires stable caller + * state. Real cores stay covered by the unchanged actual-library C tests. */ +/* The MSVC UCRT headers define snprintf and friends inline in every object + * that includes them, which lets a COFF link pull this member into an + * unrelated test; keep them declarations only. */ +#define _NO_CRT_STDIO_INLINE +#include "libobs/build/libobs.pch.h" +#include +#include +#include +#include + +#if defined(_MSC_VER) +static __declspec(thread) struct obs_core *audio_info_current; +static __declspec(thread) struct audio_output_info audio_info_output; +static __declspec(thread) char audio_info_log[16]; +static __declspec(thread) size_t audio_info_log_len; +#else +static _Thread_local struct obs_core *audio_info_current; +static _Thread_local struct audio_output_info audio_info_output; +static _Thread_local char audio_info_log[16]; +static _Thread_local size_t audio_info_log_len; +#endif + +/* A non-NULL handle the probe compares against; never dereferenced. */ +static char audio_info_fake_storage; +#define AUDIO_INFO_FAKE ((audio_t *)&audio_info_fake_storage) + +static const struct audio_output_info *audio_info_probe_get_info(const audio_t *audio) +{ + /* 'i' for the expected handle, 'x' for any other. */ + char entry = audio == AUDIO_INFO_FAKE ? 'i' : 'x'; + if (audio_info_log_len < sizeof(audio_info_log)) + audio_info_log[audio_info_log_len++] = entry; + return &audio_info_output; +} + +bool oracle_obs_get_audio_info(struct obs_audio_info *oai); +bool oracle_obs_get_audio_info2(struct obs_audio_info2 *oai2); +#define obs audio_info_current +#define audio_output_get_info audio_info_probe_get_info +#define obs_get_audio_info oracle_obs_get_audio_info +#define obs_get_audio_info2 oracle_obs_get_audio_info2 +#include "libobs/obs-audio-info-queries.c.h" +#undef obs_get_audio_info2 +#undef obs_get_audio_info +#include "audio_info_queries_fields.inc" +#undef audio_output_get_info +#undef obs + +/* sizeof/alignof and field offsets of obs_audio_info, obs_audio_info2 and + * the two audio_output_info fields read. */ +void oracle_audio_info_queries_layout(size_t *out); +void oracle_audio_info_queries_layout(size_t *out) +{ + out[0] = sizeof(struct obs_audio_info); + out[1] = _Alignof(struct obs_audio_info); + out[2] = offsetof(struct obs_audio_info, samples_per_sec); + out[3] = offsetof(struct obs_audio_info, speakers); + out[4] = sizeof(struct obs_audio_info2); + out[5] = _Alignof(struct obs_audio_info2); + out[6] = offsetof(struct obs_audio_info2, samples_per_sec); + out[7] = offsetof(struct obs_audio_info2, speakers); + out[8] = offsetof(struct obs_audio_info2, max_buffering_ms); + out[9] = offsetof(struct obs_audio_info2, fixed_buffering); + out[10] = offsetof(struct audio_output_info, samples_per_sec); + out[11] = offsetof(struct audio_output_info, speakers); + out[12] = sizeof(enum speaker_layout); +} + +typedef bool (*audio_info_fn)(struct obs_audio_info *oai); +typedef bool (*audio_info2_fn)(struct obs_audio_info2 *oai2); + +struct audio_info_run { + bool result; + union { + struct obs_audio_info info; + struct obs_audio_info2 info2; + } out; + char log[16]; + size_t log_len; +}; + +/* which: 1 = obs_get_audio_info, 2 = obs_get_audio_info2. */ +static bool audio_info_run(int which, audio_info_fn fn1, audio_info2_fn fn2, bool out_null, uint8_t fill, + struct audio_info_run *run) +{ + memset(run, 0, sizeof(*run)); + memset(&run->out, fill, sizeof(run->out)); + audio_info_log_len = 0; + if (which == 1) + run->result = fn1(out_null ? NULL : &run->out.info); + else + run->result = fn2(out_null ? NULL : &run->out.info2); + memcpy(run->log, audio_info_log, sizeof(run->log)); + run->log_len = audio_info_log_len; + return true; +} + +/* mode: 0 = NULL core, 1 = core without an audio output, 2 = with one. + * 0: match. 1: results differ, 2: output bytes differ, 4: info call logs + * differ, 8: the candidate changed the core, 16: it changed the current + * core pointer, 32: allocation failed. *original receives the original's + * result. */ +unsigned oracle_audio_info_queries_probe(int which, audio_info_fn cand1, audio_info2_fn cand2, int mode, bool out_null, + uint8_t fill, uint32_t rate, int speakers, bool fixed, int ticks, + bool *original); +unsigned oracle_audio_info_queries_probe(int which, audio_info_fn cand1, audio_info2_fn cand2, int mode, bool out_null, + uint8_t fill, uint32_t rate, int speakers, bool fixed, int ticks, + bool *original) +{ + struct obs_core *core = calloc(1, sizeof(*core)); + struct obs_core *before = malloc(sizeof(*before)); + unsigned diff = 0; + if (!core || !before) { + diff = 32; + goto done; + } + memset(core, fill, sizeof(*core)); + core->audio.audio = mode == 2 ? AUDIO_INFO_FAKE : NULL; + core->audio.fixed_buffer = fixed; + core->audio.max_buffering_ticks = ticks; + memset(&audio_info_output, fill, sizeof(audio_info_output)); + audio_info_output.samples_per_sec = rate; + audio_info_output.speakers = (enum speaker_layout)speakers; + struct obs_core *owner = mode ? core : NULL; + audio_info_current = owner; + memcpy(before, core, sizeof(*core)); + + struct audio_info_run want, got; + audio_info_run(which, oracle_obs_get_audio_info, oracle_obs_get_audio_info2, out_null, fill, &want); + audio_info_run(which, cand1, cand2, out_null, fill, &got); + *original = want.result; + + if (want.result != got.result) + diff |= 1; + if (memcmp(&want.out, &got.out, sizeof(want.out)) != 0) + diff |= 2; + if (want.log_len != got.log_len || memcmp(want.log, got.log, sizeof(want.log)) != 0) + diff |= 4; + if (memcmp(before, core, sizeof(*core)) != 0) + diff |= 8; + if (audio_info_current != owner) + diff |= 16; + audio_info_current = NULL; + +done: + free(before); + free(core); + return diff; +} diff --git a/rust/obs-c-oracle/oracle/video_stats_queries.c b/rust/obs-c-oracle/oracle/video_stats_queries.c new file mode 100644 index 0000000000..705b226f48 --- /dev/null +++ b/rust/obs-c-oracle/oracle/video_stats_queries.c @@ -0,0 +1,155 @@ +/* Original video-statistics queries (#5364), renamed, beside the real + * adapters of obs-video-stats-queries-fields.c.h. Both read a thread-local + * current core instead of the library's global, so the original and the Rust + * shim read the same real-header struct obs_video_stats through the same + * obs_video_stats_* readers. The probe reports, instead of aborting, any + * difference in a query's result bits, a stats mutex left locked, a changed + * stats value or a changed current core pointer, so mutants are observable. + * Excludes a NULL or dead core and concurrent stats writes: the original + * requires a live core. Real cores stay covered by the unchanged + * actual-library C tests. */ +/* The MSVC UCRT headers define snprintf and friends inline in every object + * that includes them, which lets a COFF link pull this member into an + * unrelated test; keep them declarations only. */ +#define _NO_CRT_STDIO_INLINE +#include "libobs/build/libobs.pch.h" +#include +#include +#include + +#if defined(_MSC_VER) +static __declspec(thread) struct obs_core *video_stats_current; +#else +static _Thread_local struct obs_core *video_stats_current; +#endif + +uint64_t oracle_obs_get_video_frame_time(void); +double oracle_obs_get_active_fps(void); +uint64_t oracle_obs_get_average_frame_time_ns(void); +uint32_t oracle_obs_get_total_frames(void); +uint32_t oracle_obs_get_lagged_frames(void); +#define obs video_stats_current +#define obs_get_video_frame_time oracle_obs_get_video_frame_time +#define obs_get_active_fps oracle_obs_get_active_fps +#define obs_get_average_frame_time_ns oracle_obs_get_average_frame_time_ns +#define obs_get_total_frames oracle_obs_get_total_frames +#define obs_get_lagged_frames oracle_obs_get_lagged_frames +#include "libobs/obs-video-stats-queries.c.h" +#undef obs_get_lagged_frames +#undef obs_get_total_frames +#undef obs_get_average_frame_time_ns +#undef obs_get_active_fps +#undef obs_get_video_frame_time +#include "video_stats_queries_fields.inc" +#undef obs + +/* The adapter's address against the real field. */ +bool oracle_video_stats_queries_adapter(void); +bool oracle_video_stats_queries_adapter(void) +{ + struct obs_core *core = calloc(1, sizeof(*core)); + if (!core) + return false; + video_stats_current = core; + bool same = obs_video_stats_queries_stats() == &core->video.stats; + video_stats_current = NULL; + free(core); + return same; +} + +typedef uint64_t (*video_stats_u64_fn)(void); +typedef double (*video_stats_f64_fn)(void); +typedef uint32_t (*video_stats_u32_fn)(void); + +struct video_stats_candidates { + video_stats_u64_fn frame_time; + video_stats_f64_fn fps; + video_stats_u64_fn avg_frame_time_ns; + video_stats_u32_fn total_frames; + video_stats_u32_fn lagged_frames; +}; + +static bool video_stats_unlocked(struct obs_video_stats *stats) +{ + if (pthread_mutex_trylock(&stats->mutex) != 0) + return false; + pthread_mutex_unlock(&stats->mutex); + return true; +} + +static bool video_stats_same_values(const struct obs_video_stats *a, const struct obs_video_stats *b) +{ + return a->frame_time_ns == b->frame_time_ns && a->avg_frame_time_ns == b->avg_frame_time_ns && + memcmp(&a->fps, &b->fps, sizeof(a->fps)) == 0 && a->total_frames == b->total_frames && + a->lagged_frames == b->lagged_frames; +} + +/* Bit i (0..4, in the order frame time, FPS, average frame time, total, + * lagged) set: that candidate's result differs from the original's. 32: a + * query left the stats mutex locked. 64: the stats values changed. 128: the + * current core pointer changed. 256: setup failed. out[0..4] receive the + * original's results as raw 64-bit patterns. */ +unsigned oracle_video_stats_queries_probe(const struct video_stats_candidates *cand, uint64_t frame_time_ns, + uint64_t avg_frame_time_ns, uint64_t fps_bits, uint32_t total_frames, + uint32_t lagged_frames, uint64_t *out); +unsigned oracle_video_stats_queries_probe(const struct video_stats_candidates *cand, uint64_t frame_time_ns, + uint64_t avg_frame_time_ns, uint64_t fps_bits, uint32_t total_frames, + uint32_t lagged_frames, uint64_t *out) +{ + struct obs_core *core = calloc(1, sizeof(*core)); + if (!core || obs_video_stats_init(&core->video.stats) != 0) { + free(core); + return 256; + } + struct obs_video_stats *stats = &core->video.stats; + stats->frame_time_ns = frame_time_ns; + stats->avg_frame_time_ns = avg_frame_time_ns; + memcpy(&stats->fps, &fps_bits, sizeof(fps_bits)); + stats->total_frames = total_frames; + stats->lagged_frames = lagged_frames; + struct obs_video_stats before = *stats; + video_stats_current = core; + + unsigned diff = 0; + uint64_t want[5], got[5]; + double fps; + + want[0] = oracle_obs_get_video_frame_time(); + fps = oracle_obs_get_active_fps(); + memcpy(&want[1], &fps, sizeof(fps)); + want[2] = oracle_obs_get_average_frame_time_ns(); + want[3] = oracle_obs_get_total_frames(); + want[4] = oracle_obs_get_lagged_frames(); + + got[0] = cand->frame_time(); + if (!video_stats_unlocked(stats)) + diff |= 32; + fps = cand->fps(); + memcpy(&got[1], &fps, sizeof(fps)); + if (!video_stats_unlocked(stats)) + diff |= 32; + got[2] = cand->avg_frame_time_ns(); + if (!video_stats_unlocked(stats)) + diff |= 32; + got[3] = cand->total_frames(); + if (!video_stats_unlocked(stats)) + diff |= 32; + got[4] = cand->lagged_frames(); + if (!video_stats_unlocked(stats)) + diff |= 32; + + for (unsigned i = 0; i < 5; ++i) { + out[i] = want[i]; + if (want[i] != got[i]) + diff |= 1u << i; + } + if (!video_stats_same_values(&before, stats)) + diff |= 64; + if (video_stats_current != core) + diff |= 128; + + video_stats_current = NULL; + obs_video_stats_destroy(stats); + free(core); + return diff; +} diff --git a/rust/obs-core/src/audio_info_queries.rs b/rust/obs-core/src/audio_info_queries.rs new file mode 100644 index 0000000000..65c5576c5f --- /dev/null +++ b/rust/obs-core/src/audio_info_queries.rs @@ -0,0 +1,86 @@ +//! Safe core of `libobs/obs-audio-info-queries.c.h`: `obs_get_audio_info()` +//! and `obs_get_audio_info2()`, the current audio settings (#5363). +//! +//! A NULL core answers false before anything is read (#2566, #3363). +//! `obs_get_audio_info` checks its output, then the core's audio output, and +//! only then reads the output's info. `obs_get_audio_info2` first runs +//! `obs_get_audio_info` into a local, then checks its own output and the +//! audio output again, and reads the fixed-buffering flag, the buffering +//! ticks and the milliseconds helper in that order; the helper's `int` is +//! cast straight to `uint32_t`. Nothing is written on failure. + +#![deny( + clippy::arithmetic_side_effects, + clippy::as_conversions, + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + +use core::ffi::c_int; + +/// The values `struct obs_audio_info` receives. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AudioInfo { + pub samples_per_sec: u32, + /// `enum speaker_layout`, unchanged. + pub speakers: c_int, +} + +/// The values `struct obs_audio_info2` receives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AudioInfo2 { + pub samples_per_sec: u32, + /// `enum speaker_layout`, unchanged. + pub speakers: c_int, + pub max_buffering_ms: u32, + pub fixed_buffering: bool, +} + +/// A live core's audio state, one read or call per method call. +pub trait AudioCore { + /// `obs->audio.audio != NULL`. + fn has_output(&mut self) -> bool; + /// `audio_output_get_info(obs->audio.audio)`: its rate and speakers. + /// Asked only right after [`AudioCore::has_output`] held. + fn output_info(&mut self) -> AudioInfo; + /// `obs->audio.fixed_buffer`. + fn fixed_buffer(&mut self) -> bool; + /// `obs->audio.max_buffering_ticks`. + fn max_buffering_ticks(&mut self) -> c_int; + /// `obs_core_setup_rules_buffer_ms(ticks, samples_per_sec)`. + fn buffer_ms(&mut self, ticks: c_int, samples_per_sec: u32) -> c_int; +} + +/// `obs_get_audio_info`: `core` is `None` for a NULL core, `output` false +/// for a NULL `oai`. `Some` is a true return with the values to store. +pub fn get_audio_info(core: Option<&mut C>, output: bool) -> Option { + let core = core?; + if !output || !core.has_output() { + return None; + } + Some(core.output_info()) +} + +/// `obs_get_audio_info2`: `core` is `None` for a NULL core, `output` false +/// for a NULL `oai2`. `Some` is a true return with the values to store. +pub fn get_audio_info2(core: Option<&mut C>, output: bool) -> Option { + let core = core?; + let info = get_audio_info(Some(&mut *core), true)?; + if !output || !core.has_output() { + return None; + } + let fixed_buffering = core.fixed_buffer(); + let ticks = core.max_buffering_ticks(); + let max_buffering_ms = core.buffer_ms(ticks, info.samples_per_sec).cast_unsigned(); + Some(AudioInfo2 { + samples_per_sec: info.samples_per_sec, + speakers: info.speakers, + max_buffering_ms, + fixed_buffering, + }) +} diff --git a/rust/obs-core/src/ffi/audio_info_queries.rs b/rust/obs-core/src/ffi/audio_info_queries.rs new file mode 100644 index 0000000000..f409438d8a --- /dev/null +++ b/rust/obs-core/src/ffi/audio_info_queries.rs @@ -0,0 +1,117 @@ +//! `obs_get_audio_info()` and `obs_get_audio_info2()` over the real core, +//! reached through the private adapters of +//! `libobs/obs-audio-info-queries-fields.c.h` (#5363). +//! +//! The core is checked for NULL before any field is read; each field is read +//! when the safe core asks for it, and the output's info comes from the real +//! `audio_output_get_info()`. The caller's struct is written field by field, +//! only on success, so its padding and any untouched bytes stay as they were. +use core::ffi::{c_int, c_void}; +use core::ptr::{addr_of, addr_of_mut}; + +use obs_media_io::ffi::audio_io::audio_output_info; + +use crate::audio_info_queries::{AudioCore, AudioInfo, get_audio_info, get_audio_info2}; +use crate::core_setup_rules::buffer_ms; + +/// Mirrors `struct obs_audio_info` (`obs.h`). +#[repr(C)] +#[allow(non_camel_case_types)] +pub struct obs_audio_info { + pub samples_per_sec: u32, + pub speakers: c_int, +} + +/// Mirrors `struct obs_audio_info2` (`obs.h`). +#[repr(C)] +#[allow(non_camel_case_types)] +pub struct obs_audio_info2 { + pub samples_per_sec: u32, + pub speakers: c_int, + pub max_buffering_ms: u32, + pub fixed_buffering: bool, +} + +unsafe extern "C" { + fn obs_audio_info_queries_core() -> *const c_void; + fn obs_audio_info_queries_output(core: *const c_void) -> *mut c_void; + fn obs_audio_info_queries_output_info(audio: *const c_void) -> *const audio_output_info; + fn obs_audio_info_queries_fixed_buffer(core: *const c_void) -> bool; + fn obs_audio_info_queries_max_buffering_ticks(core: *const c_void) -> c_int; +} + +/// The live, non-NULL current core. +struct Core(*const c_void); + +impl AudioCore for Core { + fn has_output(&mut self) -> bool { + // SAFETY: `self.0` is the live current core (see `current`). + !unsafe { obs_audio_info_queries_output(self.0) }.is_null() + } + fn output_info(&mut self) -> AudioInfo { + // SAFETY: as in `has_output`; the handle was just found non-NULL. + let audio = unsafe { obs_audio_info_queries_output(self.0) }; + // SAFETY: a live audio output's info, valid while the output lives, + // as the original's read of it requires. + let info = unsafe { obs_audio_info_queries_output_info(audio) }; + // SAFETY: `info` points to the output's live `audio_output_info`. + unsafe { + AudioInfo { + samples_per_sec: addr_of!((*info).samples_per_sec).read(), + speakers: addr_of!((*info).speakers).read(), + } + } + } + fn fixed_buffer(&mut self) -> bool { + // SAFETY: as in `has_output`. + unsafe { obs_audio_info_queries_fixed_buffer(self.0) } + } + fn max_buffering_ticks(&mut self) -> c_int { + // SAFETY: as in `has_output`. + unsafe { obs_audio_info_queries_max_buffering_ticks(self.0) } + } + fn buffer_ms(&mut self, ticks: c_int, samples_per_sec: u32) -> c_int { + buffer_ms(ticks, samples_per_sec) + } +} + +/// The current core, `None` when it is NULL. +fn current() -> Option { + // SAFETY: the adapter only returns the current global core pointer. + let core = unsafe { obs_audio_info_queries_core() }; + (!core.is_null()).then_some(Core(core)) +} + +/// # Safety +/// `oai` is NULL or writable for a `struct obs_audio_info`; the current +/// core, when not NULL, is live with a live audio output or none. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_audio_info(oai: *mut obs_audio_info) -> bool { + let Some(info) = get_audio_info(current().as_mut(), !oai.is_null()) else { + return false; + }; + // SAFETY: `oai` is non-NULL (checked by the safe core) and writable. + unsafe { + addr_of_mut!((*oai).samples_per_sec).write(info.samples_per_sec); + addr_of_mut!((*oai).speakers).write(info.speakers); + } + true +} + +/// # Safety +/// `oai2` is NULL or writable for a `struct obs_audio_info2`; the current +/// core, when not NULL, is live with a live audio output or none. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_audio_info2(oai2: *mut obs_audio_info2) -> bool { + let Some(info) = get_audio_info2(current().as_mut(), !oai2.is_null()) else { + return false; + }; + // SAFETY: `oai2` is non-NULL (checked by the safe core) and writable. + unsafe { + addr_of_mut!((*oai2).samples_per_sec).write(info.samples_per_sec); + addr_of_mut!((*oai2).speakers).write(info.speakers); + addr_of_mut!((*oai2).fixed_buffering).write(info.fixed_buffering); + addr_of_mut!((*oai2).max_buffering_ms).write(info.max_buffering_ms); + } + true +} diff --git a/rust/obs-core/src/ffi/mod.rs b/rust/obs-core/src/ffi/mod.rs index 08747868b7..bab5082967 100644 --- a/rust/obs-core/src/ffi/mod.rs +++ b/rust/obs-core/src/ffi/mod.rs @@ -2,6 +2,7 @@ pub mod audio_callback; pub mod audio_discard; +pub mod audio_info_queries; pub mod audio_min_ts; pub mod audio_mix; pub mod audio_render; @@ -87,6 +88,7 @@ pub mod video_plan; pub mod video_render_passes; pub mod video_render_size; pub mod video_scale_effects; +pub mod video_stats_queries; pub mod video_stop_requested; pub mod video_unmap_last_surface; pub mod view; diff --git a/rust/obs-core/src/ffi/video_stats_queries.rs b/rust/obs-core/src/ffi/video_stats_queries.rs new file mode 100644 index 0000000000..5fd67d0771 --- /dev/null +++ b/rust/obs-core/src/ffi/video_stats_queries.rs @@ -0,0 +1,98 @@ +//! The five public video-statistics queries over the current core's real +//! `video.stats`, reached through the private adapters of +//! `libobs/obs-video-stats-queries-fields.c.h` (#5364). +//! +//! The stats layout and its mutex stay in C: each query asks the adapter for +//! the current core's stats and calls the one `obs_video_stats_*` reader the +//! safe core picks, which locks, reads and unlocks as before (#175). A live +//! core is required, as in C. +use core::ffi::c_void; + +use crate::video_stats_queries::{ + VideoStats, active_fps, average_frame_time_ns, lagged_frames, total_frames, video_frame_time, +}; + +unsafe extern "C" { + fn obs_video_stats_queries_stats() -> *mut c_void; + fn obs_video_stats_queries_frame_time(stats: *mut c_void) -> u64; + fn obs_video_stats_queries_fps(stats: *mut c_void) -> f64; + fn obs_video_stats_queries_avg_frame_time_ns(stats: *mut c_void) -> u64; + fn obs_video_stats_queries_total_frames(stats: *mut c_void) -> u32; + fn obs_video_stats_queries_lagged_frames(stats: *mut c_void) -> u32; +} + +/// The current core's `struct obs_video_stats`. +struct Stats(*mut c_void); + +impl VideoStats for Stats { + fn frame_time(&mut self) -> u64 { + // SAFETY: `self.0` is the live core's initialized stats (see `current`). + unsafe { obs_video_stats_queries_frame_time(self.0) } + } + fn fps(&mut self) -> f64 { + // SAFETY: as in `frame_time`. + unsafe { obs_video_stats_queries_fps(self.0) } + } + fn avg_frame_time_ns(&mut self) -> u64 { + // SAFETY: as in `frame_time`. + unsafe { obs_video_stats_queries_avg_frame_time_ns(self.0) } + } + fn total_frames(&mut self) -> u32 { + // SAFETY: as in `frame_time`. + unsafe { obs_video_stats_queries_total_frames(self.0) } + } + fn lagged_frames(&mut self) -> u32 { + // SAFETY: as in `frame_time`. + unsafe { obs_video_stats_queries_lagged_frames(self.0) } + } +} + +/// The current core's stats. +/// +/// # Safety +/// The current core is live, with its stats initialized. +unsafe fn current() -> Stats { + // SAFETY: the adapter only forms the address of the live core's stats. + Stats(unsafe { obs_video_stats_queries_stats() }) +} + +/// # Safety +/// The current core is live, with its stats initialized (NULL is outside +/// the valid domain and faults, as in C). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_video_frame_time() -> u64 { + // SAFETY: the caller upholds the same contract. + video_frame_time(&mut unsafe { current() }) +} + +/// # Safety +/// As for [`obs_get_video_frame_time`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_active_fps() -> f64 { + // SAFETY: the caller upholds the same contract. + active_fps(&mut unsafe { current() }) +} + +/// # Safety +/// As for [`obs_get_video_frame_time`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_average_frame_time_ns() -> u64 { + // SAFETY: the caller upholds the same contract. + average_frame_time_ns(&mut unsafe { current() }) +} + +/// # Safety +/// As for [`obs_get_video_frame_time`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_total_frames() -> u32 { + // SAFETY: the caller upholds the same contract. + total_frames(&mut unsafe { current() }) +} + +/// # Safety +/// As for [`obs_get_video_frame_time`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_lagged_frames() -> u32 { + // SAFETY: the caller upholds the same contract. + lagged_frames(&mut unsafe { current() }) +} diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index 1e61232060..dcc91baadb 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -116,6 +116,7 @@ pub mod audio_callback; pub mod audio_discard; +pub mod audio_info_queries; pub mod audio_min_ts; pub mod audio_mix; pub mod audio_render; @@ -202,6 +203,7 @@ pub mod video_plan; pub mod video_render_passes; pub mod video_render_size; pub mod video_scale_effects; +pub mod video_stats_queries; pub mod video_stop_requested; pub mod video_unmap_last_surface; pub mod view; diff --git a/rust/obs-core/src/video_stats_queries.rs b/rust/obs-core/src/video_stats_queries.rs new file mode 100644 index 0000000000..8635b2da01 --- /dev/null +++ b/rust/obs-core/src/video_stats_queries.rs @@ -0,0 +1,61 @@ +//! Safe core of `libobs/obs-video-stats-queries.c.h`: the five public +//! video-statistics queries (#5364), `obs_get_video_frame_time()`, +//! `obs_get_active_fps()`, `obs_get_average_frame_time_ns()`, +//! `obs_get_total_frames()` and `obs_get_lagged_frames()`. +//! +//! Each query is one call of its own `obs_video_stats_*` reader on the +//! current core's `video.stats` (one lock, one read, one unlock: the +//! synchronization of #175), returned unchanged. The five are independent +//! reads, never one combined snapshot, and a live core is required: there +//! are no no-core defaults. + +#![deny( + clippy::arithmetic_side_effects, + clippy::as_conversions, + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + +/// The current core's `video.stats` readers, each one locked read. +pub trait VideoStats { + /// `obs_video_stats_frame_time()`. + fn frame_time(&mut self) -> u64; + /// `obs_video_stats_fps()`. + fn fps(&mut self) -> f64; + /// `obs_video_stats_avg_frame_time_ns()`. + fn avg_frame_time_ns(&mut self) -> u64; + /// `obs_video_stats_total_frames()`. + fn total_frames(&mut self) -> u32; + /// `obs_video_stats_lagged_frames()`. + fn lagged_frames(&mut self) -> u32; +} + +/// `obs_get_video_frame_time`. +pub fn video_frame_time(stats: &mut impl VideoStats) -> u64 { + stats.frame_time() +} + +/// `obs_get_active_fps`. +pub fn active_fps(stats: &mut impl VideoStats) -> f64 { + stats.fps() +} + +/// `obs_get_average_frame_time_ns`. +pub fn average_frame_time_ns(stats: &mut impl VideoStats) -> u64 { + stats.avg_frame_time_ns() +} + +/// `obs_get_total_frames`. +pub fn total_frames(stats: &mut impl VideoStats) -> u32 { + stats.total_frames() +} + +/// `obs_get_lagged_frames`. +pub fn lagged_frames(stats: &mut impl VideoStats) -> u32 { + stats.lagged_frames() +} diff --git a/rust/obs-core/tests/obs_core/audio_info_queries.rs b/rust/obs-core/tests/obs_core/audio_info_queries.rs new file mode 100644 index 0000000000..110a5716fc --- /dev/null +++ b/rust/obs-core/tests/obs_core/audio_info_queries.rs @@ -0,0 +1,241 @@ +//! Safe mirrors of test_audio_info_queries.c (#5169, #5363), over a +//! recording core. The C test logs only the two calls it can probe ('i' for +//! audio_output_get_info, 'm' for the milliseconds helper); the trace here +//! also logs the core field reads ('h' the audio output handle, 'f' the +//! fixed-buffering flag, 't' the buffering ticks), so the full read order +//! is pinned and the C log is its 'i'/'m' subsequence. +use core::ffi::c_int; + +use obs_core::audio_info_queries::{ + AudioCore, AudioInfo, AudioInfo2, get_audio_info, get_audio_info2, +}; +use proptest::prelude::*; + +// enum speaker_layout values from media-io/audio-io.h. +const SPEAKERS_UNKNOWN: c_int = 0; +const SPEAKERS_MONO: c_int = 1; +const SPEAKERS_STEREO: c_int = 2; +const SPEAKERS_4POINT0: c_int = 4; +const SPEAKERS_5POINT1: c_int = 6; +const SPEAKERS_7POINT1: c_int = 8; + +#[derive(Default)] +struct Core { + has_output: bool, + info: AudioInfo, + fixed_buffer: bool, + ticks: c_int, + ms_result: c_int, + ms_args: Option<(c_int, u32)>, + trace: String, +} + +impl Core { + fn with_output() -> Self { + Core { + has_output: true, + ..Core::default() + } + } + + /// The calls the C test's probes log. + fn c_calls(&self) -> String { + self.trace + .chars() + .filter(|c| matches!(c, 'i' | 'm')) + .collect() + } +} + +impl AudioCore for Core { + fn has_output(&mut self) -> bool { + self.trace.push('h'); + self.has_output + } + fn output_info(&mut self) -> AudioInfo { + assert!(self.has_output, "info read without an audio output"); + self.trace.push('i'); + self.info + } + fn fixed_buffer(&mut self) -> bool { + self.trace.push('f'); + self.fixed_buffer + } + fn max_buffering_ticks(&mut self) -> c_int { + self.trace.push('t'); + self.ticks + } + fn buffer_ms(&mut self, ticks: c_int, samples_per_sec: u32) -> c_int { + self.trace.push('m'); + self.ms_args = Some((ticks, samples_per_sec)); + self.ms_result + } +} + +/// test_no_core: both reject before any read, output or not. +#[test] +fn no_core() { + for output in [true, false] { + assert_eq!(get_audio_info::(None, output), None); + assert_eq!(get_audio_info2::(None, output), None); + } +} + +/// test_info_null_output: a NULL oai reads nothing, not even the handle. +#[test] +fn info_null_output() { + let mut core = Core::with_output(); + assert_eq!(get_audio_info(Some(&mut core), false), None); + assert_eq!(core.trace, ""); +} + +/// test_info_no_audio: no audio output, no info read. +#[test] +fn info_no_audio() { + let mut core = Core::default(); + assert_eq!(get_audio_info(Some(&mut core), true), None); + assert_eq!(core.trace, "h"); + assert_eq!(core.c_calls(), ""); +} + +/// test_info_copies_rate_and_speakers: one info read, both values copied. +#[test] +fn info_copies_rate_and_speakers() { + for (rate, speakers) in [ + (44100, SPEAKERS_STEREO), + (48000, SPEAKERS_7POINT1), + (0, SPEAKERS_UNKNOWN), + (u32::MAX, SPEAKERS_MONO), + ] { + let mut core = Core::with_output(); + core.info = AudioInfo { + samples_per_sec: rate, + speakers, + }; + assert_eq!( + get_audio_info(Some(&mut core), true), + Some(AudioInfo { + samples_per_sec: rate, + speakers, + }) + ); + assert_eq!(core.trace, "hi"); + assert_eq!(core.c_calls(), "i"); + } +} + +/// test_info2_null_output_still_reads_info: the info read into the local +/// comes first; the NULL output then stops it before the handle is read again. +#[test] +fn info2_null_output_still_reads_info() { + let mut core = Core::with_output(); + core.info = AudioInfo { + samples_per_sec: 48000, + speakers: SPEAKERS_STEREO, + }; + assert_eq!(get_audio_info2(Some(&mut core), false), None); + assert_eq!(core.trace, "hi"); + assert_eq!(core.c_calls(), "i"); +} + +/// test_info2_no_audio: the inner info fails, nothing else is read. +#[test] +fn info2_no_audio() { + let mut core = Core::default(); + assert_eq!(get_audio_info2(Some(&mut core), true), None); + assert_eq!(core.trace, "h"); + assert_eq!(core.c_calls(), ""); +} + +/// test_info2_copies_all_fields: rate and speakers from the info read, the +/// flag from the core, then the helper with the core's ticks and the rate. +#[test] +fn info2_copies_all_fields() { + for (rate, speakers, fixed, ticks, ms) in [ + (48000, SPEAKERS_STEREO, false, 1, 21), + (44100, SPEAKERS_5POINT1, true, 45, 1000), + (96000, SPEAKERS_4POINT0, true, 0, 0), + (8000, SPEAKERS_MONO, false, i32::MAX, i32::MAX), + ] { + let mut core = Core::with_output(); + core.info = AudioInfo { + samples_per_sec: rate, + speakers, + }; + core.fixed_buffer = fixed; + core.ticks = ticks; + core.ms_result = ms; + assert_eq!( + get_audio_info2(Some(&mut core), true), + Some(AudioInfo2 { + samples_per_sec: rate, + speakers, + max_buffering_ms: ms.cast_unsigned(), + fixed_buffering: fixed, + }) + ); + assert_eq!(core.ms_args, Some((ticks, rate))); + assert_eq!(core.trace, "hihftm"); + assert_eq!(core.c_calls(), "im"); + } +} + +/// test_info2_casts_helper_result: a negative helper result wraps. +#[test] +fn info2_casts_helper_result() { + let mut core = Core::with_output(); + core.info = AudioInfo { + samples_per_sec: 48000, + speakers: SPEAKERS_STEREO, + }; + core.ms_result = -1; + let got = get_audio_info2(Some(&mut core), true).map(|info| info.max_buffering_ms); + assert_eq!(got, Some(u32::MAX)); + assert_eq!(core.c_calls(), "im"); +} + +proptest! { + /// Any core: the C's decision table and read order. + #[test] + fn any_core_follows_the_c( + output in any::(), + has_output in any::(), + rate in any::(), + speakers in any::(), + fixed in any::(), + ticks in any::(), + ms in any::(), + ) { + let info = AudioInfo { samples_per_sec: rate, speakers }; + let fresh = || Core { has_output, info, fixed_buffer: fixed, ticks, ms_result: ms, ..Core::default() }; + + let mut core = fresh(); + let got = get_audio_info(Some(&mut core), output); + prop_assert_eq!(got, (output && has_output).then_some(info)); + let trace = match (output, has_output) { + (false, _) => "", + (true, false) => "h", + (true, true) => "hi", + }; + prop_assert_eq!(core.trace.as_str(), trace); + + let mut core = fresh(); + let got = get_audio_info2(Some(&mut core), output); + let want = (output && has_output).then_some(AudioInfo2 { + samples_per_sec: rate, + speakers, + max_buffering_ms: ms.cast_unsigned(), + fixed_buffering: fixed, + }); + prop_assert_eq!(got, want); + let trace = match (has_output, output) { + (false, _) => "h", + (true, false) => "hi", + (true, true) => "hihftm", + }; + prop_assert_eq!(core.trace.as_str(), trace); + if want.is_some() { + prop_assert_eq!(core.ms_args, Some((ticks, rate))); + } + } +} diff --git a/rust/obs-core/tests/obs_core/audio_info_queries_parity.rs b/rust/obs-core/tests/obs_core/audio_info_queries_parity.rs new file mode 100644 index 0000000000..80d6aeda85 --- /dev/null +++ b/rust/obs-core/tests/obs_core/audio_info_queries_parity.rs @@ -0,0 +1,246 @@ +//! Original-C parity for the audio-info queries (#5363): the thin ABI shims +//! and real field adapters against the extracted C, on one real-header core +//! filled with any byte. Compared: the result, the caller's sentinel-filled +//! output bytes, the audio_output_get_info call log, the core bytes and the +//! current core pointer. Excludes a dead core and concurrent writes to the +//! audio fields, matching the C contract. No intentional differences. +use core::ffi::c_int; +use core::mem::{align_of, offset_of, size_of}; + +use obs_core::ffi::audio_info_queries::{ + obs_audio_info, obs_audio_info2, obs_get_audio_info, obs_get_audio_info2, +}; +use obs_media_io::ffi::audio_io::audio_output_info; +use proptest::prelude::*; + +type InfoFn = unsafe extern "C" fn(*mut obs_audio_info) -> bool; +type Info2Fn = unsafe extern "C" fn(*mut obs_audio_info2) -> bool; + +unsafe extern "C" { + fn oracle_audio_info_queries_layout(out: *mut usize); + fn oracle_audio_info_queries_probe( + which: c_int, + cand1: InfoFn, + cand2: Info2Fn, + mode: c_int, + out_null: bool, + fill: u8, + rate: u32, + speakers: c_int, + fixed: bool, + ticks: c_int, + original: *mut bool, + ) -> u32; +} + +#[test] +fn real_header_layout() { + let mut layout = [0usize; 13]; + // SAFETY: C writes exactly thirteen values into this array. + unsafe { oracle_audio_info_queries_layout(layout.as_mut_ptr()) }; + assert_eq!( + layout, + [ + size_of::(), + align_of::(), + offset_of!(obs_audio_info, samples_per_sec), + offset_of!(obs_audio_info, speakers), + size_of::(), + align_of::(), + offset_of!(obs_audio_info2, samples_per_sec), + offset_of!(obs_audio_info2, speakers), + offset_of!(obs_audio_info2, max_buffering_ms), + offset_of!(obs_audio_info2, fixed_buffering), + offset_of!(audio_output_info, samples_per_sec), + offset_of!(audio_output_info, speakers), + size_of::(), + ] + ); +} + +struct Case { + mode: c_int, + out_null: bool, + fill: u8, + rate: u32, + speakers: c_int, + fixed: bool, + ticks: c_int, +} + +/// Runs both queries' original and shim; returns the original's results. +fn probe_with(case: &Case, cand1: InfoFn, cand2: Info2Fn) -> ([bool; 2], [u32; 2]) { + let mut original = [false; 2]; + let mut diff = [0u32; 2]; + for (which, (orig, d)) in original.iter_mut().zip(diff.iter_mut()).enumerate() { + let which = c_int::try_from(which).unwrap() + 1; + // SAFETY: the oracle owns a live real-header core, installs it as the + // thread's current core for the call and passes the candidates a + // sentinel-filled output or NULL. + *d = unsafe { + oracle_audio_info_queries_probe( + which, + cand1, + cand2, + case.mode, + case.out_null, + case.fill, + case.rate, + case.speakers, + case.fixed, + case.ticks, + orig, + ) + }; + } + (original, diff) +} + +fn check(case: &Case) { + let (original, diff) = probe_with(case, obs_get_audio_info, obs_get_audio_info2); + assert_eq!( + diff, + [0, 0], + "mode {} out_null {} fill {:#04x} rate {} speakers {} fixed {} ticks {}", + case.mode, + case.out_null, + case.fill, + case.rate, + case.speakers, + case.fixed, + case.ticks + ); + // The original's results are the C decision table. + let ok = case.mode == 2 && !case.out_null; + assert_eq!(original, [ok, ok]); +} + +#[test] +fn characterized_cases_match_original_c() { + for mode in 0..3 { + for out_null in [false, true] { + for (rate, speakers, fixed, ticks) in [ + (48000, 2, false, 1), + (44100, 6, true, 45), + (96000, 4, true, 0), + (8000, 1, false, i32::MAX), + (0, 0, false, 0), + (u32::MAX, 8, true, -1), + (48000, -1, false, i32::MIN), + ] { + for fill in [0x00, 0xa5, 0xff] { + check(&Case { + mode, + out_null, + fill, + rate, + speakers, + fixed, + ticks, + }); + } + } + } + } +} + +// Mutants of the shim, each of which the probe must catch. +unsafe extern "C" fn mutant_info_ignores_audio(oai: *mut obs_audio_info) -> bool { + if oai.is_null() { + return false; + } + // SAFETY: non-NULL caller output. + unsafe { + oai.write(obs_audio_info { + samples_per_sec: 48000, + speakers: 2, + }) + }; + true +} + +unsafe extern "C" fn mutant_info2_skips_inner_read(oai2: *mut obs_audio_info2) -> bool { + if oai2.is_null() { + // The original still reads the info into its local first. + return false; + } + // SAFETY: forwarded unchanged. + unsafe { obs_get_audio_info2(oai2) } +} + +unsafe extern "C" fn mutant_info2_clears_output_on_failure(oai2: *mut obs_audio_info2) -> bool { + // SAFETY: forwarded unchanged. + let ok = unsafe { obs_get_audio_info2(oai2) }; + if !ok && !oai2.is_null() { + // SAFETY: non-NULL caller output. + unsafe { + oai2.write(obs_audio_info2 { + samples_per_sec: 0, + speakers: 0, + max_buffering_ms: 0, + fixed_buffering: false, + }); + } + } + ok +} + +unsafe extern "C" fn mutant_info2_rounds_ms(oai2: *mut obs_audio_info2) -> bool { + // SAFETY: forwarded unchanged. + let ok = unsafe { obs_get_audio_info2(oai2) }; + if ok { + // SAFETY: the shim succeeded, so `oai2` is a written caller output. + unsafe { (*oai2).max_buffering_ms = (*oai2).max_buffering_ms.saturating_add(1) }; + } + ok +} + +#[test] +fn mutants_are_caught() { + let with_audio = Case { + mode: 2, + out_null: false, + fill: 0xa5, + rate: 44100, + speakers: 6, + fixed: true, + ticks: 45, + }; + let no_audio = Case { + mode: 1, + ..with_audio + }; + let null_out = Case { + out_null: true, + ..with_audio + }; + + let (_, diff) = probe_with(&no_audio, mutant_info_ignores_audio, obs_get_audio_info2); + assert_ne!(diff[0], 0, "info that ignores the audio output"); + let (_, diff) = probe_with(&null_out, obs_get_audio_info, mutant_info2_skips_inner_read); + assert_ne!(diff[1], 0, "info2 that skips the inner info read"); + let (_, diff) = probe_with( + &no_audio, + obs_get_audio_info, + mutant_info2_clears_output_on_failure, + ); + assert_ne!(diff[1], 0, "info2 that clears its output on failure"); + let (_, diff) = probe_with(&with_audio, obs_get_audio_info, mutant_info2_rounds_ms); + assert_ne!(diff[1], 0, "info2 with a changed buffering time"); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(256), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn random_cores_match_original_c( + mode in 0..3 as c_int, + out_null in any::(), + fill in any::(), + rate in any::(), + speakers in any::(), + fixed in any::(), + ticks in any::(), + ) { + check(&Case { mode, out_null, fill, rate, speakers, fixed, ticks }); + } +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 75dc2f2334..fa5059021a 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -9,6 +9,8 @@ mod audio_callback_layout; mod audio_callback_parity; mod audio_discard; mod audio_discard_parity; +mod audio_info_queries; +mod audio_info_queries_parity; mod audio_min_ts; mod audio_min_ts_parity; mod audio_mix; @@ -181,6 +183,8 @@ mod video_render_size; mod video_render_size_parity; mod video_scale_effects; mod video_scale_effects_parity; +mod video_stats_queries; +mod video_stats_queries_parity; mod video_stop_requested; mod video_stop_requested_parity; mod video_unmap_last_surface; diff --git a/rust/obs-core/tests/obs_core/video_stats_queries.rs b/rust/obs-core/tests/obs_core/video_stats_queries.rs new file mode 100644 index 0000000000..0799505f25 --- /dev/null +++ b/rust/obs-core/tests/obs_core/video_stats_queries.rs @@ -0,0 +1,189 @@ +//! Safe mirrors of test_video_stats_queries.c (#5171, #5364), over stats +//! guarded by a real mutex as the C's `struct obs_video_stats` is. Each +//! query must take the lock once, read only its own field, return it +//! unchanged and leave the lock free; values are compared exactly (the +//! FPS by its bits). +use std::sync::Mutex; + +use obs_core::video_stats_queries::{ + VideoStats, active_fps, average_frame_time_ns, lagged_frames, total_frames, video_frame_time, +}; +use proptest::prelude::*; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Values { + frame_time_ns: u64, + avg_frame_time_ns: u64, + fps: f64, + total_frames: u32, + lagged_frames: u32, +} + +/// `struct obs_video_stats`: a mutex over the five fields, plus a log of +/// which field each locked read took. +#[derive(Default)] +struct Stats { + values: Mutex, + reads: String, +} + +impl Stats { + fn load(&self, v: Values) { + *self.values.lock().unwrap() = v; + } + /// obs_video_stats_set_frame_time. + fn set_frame_time(&self, frame_time: u64) { + self.values.lock().unwrap().frame_time_ns = frame_time; + } + /// obs_video_stats_set_timing. + fn set_timing(&self, fps: f64, frame_time_ns: u64) { + let mut v = self.values.lock().unwrap(); + v.fps = fps; + v.avg_frame_time_ns = frame_time_ns; + } + /// obs_video_stats_add_frames. + fn add_frames(&self, total: u32, lagged: u32) { + let mut v = self.values.lock().unwrap(); + v.total_frames = v.total_frames.wrapping_add(total); + v.lagged_frames = v.lagged_frames.wrapping_add(lagged); + } + fn read(&mut self, field: char, f: impl FnOnce(&Values) -> T) -> T { + self.reads.push(field); + let v = self.values.lock().unwrap(); + f(&v) + } + fn assert_unlocked(&self) { + assert!(self.values.try_lock().is_ok(), "stats mutex still held"); + } +} + +impl VideoStats for Stats { + fn frame_time(&mut self) -> u64 { + self.read('t', |v| v.frame_time_ns) + } + fn fps(&mut self) -> f64 { + self.read('f', |v| v.fps) + } + fn avg_frame_time_ns(&mut self) -> u64 { + self.read('a', |v| v.avg_frame_time_ns) + } + fn total_frames(&mut self) -> u32 { + self.read('n', |v| v.total_frames) + } + fn lagged_frames(&mut self) -> u32 { + self.read('l', |v| v.lagged_frames) + } +} + +/// assert_queries: each query reads its own field once and unlocks. +fn assert_queries(stats: &mut Stats, v: &Values) { + stats.reads.clear(); + assert_eq!(video_frame_time(stats), v.frame_time_ns); + stats.assert_unlocked(); + assert_eq!(active_fps(stats).to_bits(), v.fps.to_bits()); + stats.assert_unlocked(); + assert_eq!(average_frame_time_ns(stats), v.avg_frame_time_ns); + stats.assert_unlocked(); + assert_eq!(total_frames(stats), v.total_frames); + stats.assert_unlocked(); + assert_eq!(lagged_frames(stats), v.lagged_frames); + stats.assert_unlocked(); + assert_eq!(stats.reads, "tfanl"); +} + +/// test_zeroed_stats. +#[test] +fn zeroed_stats() { + assert_queries(&mut Stats::default(), &Values::default()); +} + +/// test_each_query_reads_its_field. +#[test] +fn each_query_reads_its_field() { + let v = Values { + frame_time_ns: 0x1122_3344_5566_7788, + avg_frame_time_ns: 16_666_667, + fps: 59.94, + total_frames: 123_456, + lagged_frames: 7, + }; + let mut stats = Stats::default(); + stats.load(v); + assert_queries(&mut stats, &v); +} + +/// test_boundary_values. +#[test] +fn boundary_values() { + let v = Values { + frame_time_ns: u64::MAX, + avg_frame_time_ns: u64::MAX - 1, + fps: 1e308, + total_frames: u32::MAX, + lagged_frames: u32::MAX - 1, + }; + let mut stats = Stats::default(); + stats.load(v); + assert_queries(&mut stats, &v); +} + +/// test_reads_current_core: the queries read whichever stats they are given. +#[test] +fn reads_current_core() { + let a = Values { + frame_time_ns: 1, + avg_frame_time_ns: 2, + fps: 30.0, + total_frames: 4, + lagged_frames: 5, + }; + let b = Values { + frame_time_ns: 10, + avg_frame_time_ns: 20, + fps: 0.5, + total_frames: 40, + lagged_frames: 50, + }; + let mut core_a = Stats::default(); + let mut core_b = Stats::default(); + core_a.load(a); + core_b.load(b); + assert_queries(&mut core_a, &a); + assert_queries(&mut core_b, &b); + assert_queries(&mut core_a, &a); +} + +/// test_reads_setter_writes. +#[test] +fn reads_setter_writes() { + let mut stats = Stats::default(); + stats.set_frame_time(1000); + stats.set_timing(29.97, 33_366_700); + stats.add_frames(10, 3); + stats.add_frames(5, 1); + let v = Values { + frame_time_ns: 1000, + avg_frame_time_ns: 33_366_700, + fps: 29.97, + total_frames: 15, + lagged_frames: 4, + }; + assert_queries(&mut stats, &v); +} + +proptest! { + /// Any stored values, the FPS as any bit pattern, pass through unchanged. + #[test] + fn any_values_pass_through( + frame_time_ns in any::(), + avg_frame_time_ns in any::(), + fps_bits in any::(), + total_frames in any::(), + lagged_frames in any::(), + ) { + let v = Values { frame_time_ns, avg_frame_time_ns, fps: f64::from_bits(fps_bits), total_frames, lagged_frames }; + let mut stats = Stats::default(); + stats.load(v); + assert_queries(&mut stats, &v); + } +} diff --git a/rust/obs-core/tests/obs_core/video_stats_queries_parity.rs b/rust/obs-core/tests/obs_core/video_stats_queries_parity.rs new file mode 100644 index 0000000000..a909912957 --- /dev/null +++ b/rust/obs-core/tests/obs_core/video_stats_queries_parity.rs @@ -0,0 +1,218 @@ +//! Original-C parity for the video-statistics queries (#5364): the thin ABI +//! shims and real adapters against the extracted C, on one real-header core +//! with an initialized stats mutex. Compared: each query's exact result bits +//! (the FPS as any binary64 pattern), the mutex free after every query, the +//! stats values unchanged and the current core pointer untouched. Excludes a +//! NULL or dead core and concurrent stats writes, matching the C contract. +//! No intentional differences. +use obs_core::ffi::video_stats_queries::{ + obs_get_active_fps, obs_get_average_frame_time_ns, obs_get_lagged_frames, obs_get_total_frames, + obs_get_video_frame_time, +}; +use proptest::prelude::*; + +#[repr(C)] +#[derive(Clone, Copy)] +struct Candidates { + frame_time: unsafe extern "C" fn() -> u64, + fps: unsafe extern "C" fn() -> f64, + avg_frame_time_ns: unsafe extern "C" fn() -> u64, + total_frames: unsafe extern "C" fn() -> u32, + lagged_frames: unsafe extern "C" fn() -> u32, +} + +const SHIMS: Candidates = Candidates { + frame_time: obs_get_video_frame_time, + fps: obs_get_active_fps, + avg_frame_time_ns: obs_get_average_frame_time_ns, + total_frames: obs_get_total_frames, + lagged_frames: obs_get_lagged_frames, +}; + +unsafe extern "C" { + fn oracle_video_stats_queries_adapter() -> bool; + fn oracle_video_stats_queries_probe( + cand: *const Candidates, + frame_time_ns: u64, + avg_frame_time_ns: u64, + fps_bits: u64, + total_frames: u32, + lagged_frames: u32, + out: *mut u64, + ) -> u32; +} + +#[derive(Clone, Copy, Debug)] +struct Values { + frame_time_ns: u64, + avg_frame_time_ns: u64, + fps_bits: u64, + total_frames: u32, + lagged_frames: u32, +} + +fn probe(cand: &Candidates, v: Values) -> (u32, [u64; 5]) { + let mut out = [0u64; 5]; + // SAFETY: the oracle owns a live real-header core with initialized + // stats, installs it as the thread's current core for the calls and + // writes exactly five results. + let diff = unsafe { + oracle_video_stats_queries_probe( + cand, + v.frame_time_ns, + v.avg_frame_time_ns, + v.fps_bits, + v.total_frames, + v.lagged_frames, + out.as_mut_ptr(), + ) + }; + (diff, out) +} + +fn check(v: Values) { + let (diff, out) = probe(&SHIMS, v); + assert_eq!(diff, 0, "{v:?}"); + // The original returns every stored value unchanged. + assert_eq!( + out, + [ + v.frame_time_ns, + v.fps_bits, + v.avg_frame_time_ns, + u64::from(v.total_frames), + u64::from(v.lagged_frames), + ] + ); +} + +#[test] +fn real_adapter_addresses_the_core_stats() { + // SAFETY: the oracle allocates, installs and frees its own core. + assert!(unsafe { oracle_video_stats_queries_adapter() }); +} + +#[test] +fn characterized_values_match_original_c() { + let cases = [ + Values { + frame_time_ns: 0, + avg_frame_time_ns: 0, + fps_bits: 0, + total_frames: 0, + lagged_frames: 0, + }, + Values { + frame_time_ns: 0x1122_3344_5566_7788, + avg_frame_time_ns: 16_666_667, + fps_bits: 59.94f64.to_bits(), + total_frames: 123_456, + lagged_frames: 7, + }, + Values { + frame_time_ns: u64::MAX, + avg_frame_time_ns: u64::MAX - 1, + fps_bits: 1e308f64.to_bits(), + total_frames: u32::MAX, + lagged_frames: u32::MAX - 1, + }, + Values { + frame_time_ns: 1000, + avg_frame_time_ns: 33_366_700, + fps_bits: 29.97f64.to_bits(), + total_frames: 15, + lagged_frames: 4, + }, + ]; + for v in cases { + check(v); + } + // Signed zero, infinities and a NaN payload pass through by their bits. + for fps_bits in [ + 0x8000_0000_0000_0000, + 0x7ff0_0000_0000_0000, + 0xfff0_0000_0000_0000, + 0x7ff8_0000_0001_2345, + 0x0000_0000_0000_0001, + ] { + check(Values { + fps_bits, + ..cases[1] + }); + } +} + +// Shim mutants, each of which the probe must catch. +unsafe extern "C" fn mutant_fps_from_average() -> f64 { + // SAFETY: forwarded; the probe's core is live. + let ns = unsafe { obs_get_average_frame_time_ns() }; + if ns == 0 { 0.0 } else { 1e9 / ns as f64 } +} +unsafe extern "C" fn mutant_total_reads_lagged() -> u32 { + // SAFETY: forwarded; the probe's core is live. + unsafe { obs_get_lagged_frames() } +} +unsafe extern "C" fn mutant_lagged_narrowed() -> u32 { + // SAFETY: forwarded; the probe's core is live. + let lagged = unsafe { obs_get_lagged_frames() }; + lagged & 0xffff +} +unsafe extern "C" fn mutant_frame_time_is_average() -> u64 { + // SAFETY: forwarded; the probe's core is live. + unsafe { obs_get_average_frame_time_ns() } +} + +#[test] +fn mutants_are_caught() { + let v = Values { + frame_time_ns: 0x1122_3344_5566_7788, + avg_frame_time_ns: 16_666_667, + fps_bits: 59.94f64.to_bits(), + total_frames: 123_456, + lagged_frames: 0x0001_0007, + }; + let mutants = [ + Candidates { + fps: mutant_fps_from_average, + ..SHIMS + }, + Candidates { + total_frames: mutant_total_reads_lagged, + ..SHIMS + }, + Candidates { + lagged_frames: mutant_lagged_narrowed, + ..SHIMS + }, + Candidates { + frame_time: mutant_frame_time_is_average, + ..SHIMS + }, + ]; + for (i, mutant) in mutants.iter().enumerate() { + let (diff, _) = probe(mutant, v); + assert_ne!(diff, 0, "mutant {i} not caught"); + } +} + +// Signaling NaNs are excluded: binary64 returns through x87 on 32-bit x86 +// may quiet them in both implementations alike. +fn not_signaling_nan(bits: u64) -> bool { + let nan = (bits & 0x7ff0_0000_0000_0000) == 0x7ff0_0000_0000_0000 + && (bits & 0x000f_ffff_ffff_ffff) != 0; + !nan || bits & 0x0008_0000_0000_0000 != 0 +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(256), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn random_values_match_original_c( + frame_time_ns in any::(), + avg_frame_time_ns in any::(), + fps_bits in any::().prop_filter("signaling NaN", |b| not_signaling_nan(*b)), + total_frames in any::(), + lagged_frames in any::(), + ) { + check(Values { frame_time_ns, avg_frame_time_ns, fps_bits, total_frames, lagged_frames }); + } +} diff --git a/test/cmocka/audio-info-queries-link-support.c b/test/cmocka/audio-info-queries-link-support.c new file mode 100644 index 0000000000..9731dd5b73 --- /dev/null +++ b/test/cmocka/audio-info-queries-link-support.c @@ -0,0 +1,2 @@ +/* Real private audio-info adapters for standalone Rust-static consumers. */ +#include "libobs/obs-audio-info-queries-fields.c.h" diff --git a/test/cmocka/build/rust-static-support.json b/test/cmocka/build/rust-static-support.json index 3dd5173fc6..4849f344a2 100644 --- a/test/cmocka/build/rust-static-support.json +++ b/test/cmocka/build/rust-static-support.json @@ -41,7 +41,9 @@ "test/cmocka/encoder-last-error-link-support.c", "test/cmocka/hotkey-key-translation-link-support.c", "test/cmocka/output-get-name-link-support.c", - "test/cmocka/canvas-valid-video-info-link-support.c" + "test/cmocka/canvas-valid-video-info-link-support.c", + "test/cmocka/audio-info-queries-link-support.c", + "test/cmocka/video-stats-queries-link-support.c" ], "platform_sources": { "OS_WINDOWS": [ diff --git a/test/cmocka/video-stats-queries-link-support.c b/test/cmocka/video-stats-queries-link-support.c new file mode 100644 index 0000000000..ec6d500d27 --- /dev/null +++ b/test/cmocka/video-stats-queries-link-support.c @@ -0,0 +1,2 @@ +/* Real private video-statistics adapters for standalone Rust-static consumers. */ +#include "libobs/obs-video-stats-queries-fields.c.h"