diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index 1e9cc3e146..ded55252f1 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -56,7 +56,7 @@ #include "libobs/obs-type-catalog-enum.c.h" #include "libobs/obs-ui-task-handler-fields.c.h" #include "libobs/obs-video-info-query-fields.c.h" -#include "libobs/obs-video-level-queries.c.h" +#include "libobs/obs-video-level-queries-fields.c.h" #include "libobs/obs-video-stats-queries.c.h" #include "libobs/obs-weak-object-expired-fields.c.h" #include "libobs/obs-weak-object-identity-fields.c.h" diff --git a/libobs/build/libobs.ported-video-level-queries+.h.c b/libobs/build/libobs.ported-video-level-queries+.h.c new file mode 100644 index 0000000000..dcc53d82bf --- /dev/null +++ b/libobs/build/libobs.ported-video-level-queries+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original video level queries, C reference only. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-video-level-queries.c.h" diff --git a/libobs/build/ported-source-sets/video-level-queries.json b/libobs/build/ported-source-sets/video-level-queries.json new file mode 100644 index 0000000000..afee817ffc --- /dev/null +++ b/libobs/build/ported-source-sets/video-level-queries.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-video-level-queries+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-core-video_level_queries.txt b/libobs/cmake/rust-exports.d/obs-core-video_level_queries.txt new file mode 100644 index 0000000000..6089d4294e --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-core-video_level_queries.txt @@ -0,0 +1,2 @@ +obs_get_video_hdr_nominal_peak_level +obs_get_video_sdr_white_level diff --git a/libobs/cmake/rust-hidden.d/obs-core-video_level_queries.txt b/libobs/cmake/rust-hidden.d/obs-core-video_level_queries.txt new file mode 100644 index 0000000000..b0403a3453 --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-core-video_level_queries.txt @@ -0,0 +1,2 @@ +obs_video_level_queries_hdr_nominal_peak_level_request +obs_video_level_queries_sdr_white_level_request diff --git a/libobs/obs-video-level-queries-fields.c.h b/libobs/obs-video-level-queries-fields.c.h new file mode 100644 index 0000000000..a70044f28d --- /dev/null +++ b/libobs/obs-video-level-queries-fields.c.h @@ -0,0 +1,23 @@ +#include "libobs/build/libobs.pch.h" + +/* Real private field access for the Rust level queries (#5187). The Rust + * shim checks the core for NULL before it asks for the video fields. */ +struct obs_video_level_queries_fields { + const graphics_t *graphics; + float sdr_white_level; + float hdr_nominal_peak_level; +}; + +const struct obs_core *obs_video_level_queries_core(void); +const struct obs_core *obs_video_level_queries_core(void) +{ + return obs; +} + +struct obs_video_level_queries_fields obs_video_level_queries_fields(const struct obs_core *core); +struct obs_video_level_queries_fields obs_video_level_queries_fields(const struct obs_core *core) +{ + const struct obs_core_video *video = &core->video; + return (struct obs_video_level_queries_fields){video->graphics, video->sdr_white_level, + video->hdr_nominal_peak_level}; +} diff --git a/rust/README.md b/rust/README.md index d3bef9d461..7b45cf9883 100644 --- a/rust/README.md +++ b/rust/README.md @@ -578,6 +578,7 @@ and compares their exported symbols. `OBS_LIBOBS_BACKEND=C` is temporary rollbac | `libobs/obs-nix-log-rules.c.h` | `obs-core::nix_system_info` | Swapped in hybrid `libobs` (in the group `libobs.ported-nix-system-info`, with `obs-nix-system-info.c.h`). Five pure functions on strings and flags, declared in `obs-nix-system-info.h` without `EXPORT` and hidden: `obs_nix_system_info_os_release_field` (`read_distribution_info()`'s `strncmp()` checks of `NAME=`, `VERSION_ID=` and `BUILD_ID=` in that order: a pointer after the key, with the key in `*key`, or `NULL` with `*key` untouched), `_os_release_value` (`copy_os_release_value()`'s span to the first CR or LF, with one matching pair of `"` or `'` cut when it is at least two bytes; the caller copies it only when `*len` isn't zero), `_version_fallback` (`NULL` to copy the `BUILD_ID`, else static `"rolling"`, or `"Unknown"` for a distro named exactly that; the name is read only without a `BUILD_ID`), `_extension_name` (`log_flatpak_extensions()`'s name, which replaces its inner `strlist_split()` on `=`) and `_desktop_form` (`log_desktop_session_info()`'s none, one or both). `obs-nix-os-release.h` and `obs-nix.c.h` keep `getline()`, every `dstr` copy, the `;` split, every `getenv()`, the `config_*` reads with their defaults, the session type line and every `blog()`. Intentional difference (#3473): an extension entry with an empty name logs no line, where the C logs its commit hash (`=abc` logs ` - abc`) or ` - (null)` (`=`); the C backend keeps both. Characterized, not endorsed and kept: an os-release value keeps a lone quote and has no escapes or shell quoting, `NAME=Unknown` in the file gives the version `Unknown`, an empty `app-extensions` value logs its heading and no entries, and an empty desktop name counts as set (`Desktop Environment: ()`). `test_nix_log_rules_steps` compiles the C into itself; it has no `_rust` variant, as for `test_context_name_helpers`. `test_distribution_info` (unchanged) builds the C file in, since it compiles the static inline `read_distribution_info()` against libobs; its 4 cases are ported 1:1 to Tier 1 (`distribution_info_*`). `test_nix_startup_log` (Linux) checks the desktop, session and distribution lines through the real libobs's `obs_startup()`, so the hybrid build runs the shims through their callers. Tier 3 compares every result exactly over every os-release line of up to three pieces, every byte after each key, every value from every position, every fallback name of up to two pieces, every extension entry of up to four pieces, the four desktop pairs, `read_distribution_info()`'s loop over saved and generated files, and proptests over all of it; empty-name entries are checked against a model of the C and the port's contract. | | `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-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-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. | diff --git a/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_video_level_queries.json b/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_video_level_queries.json new file mode 100644 index 0000000000..4b126452d8 --- /dev/null +++ b/rust/obs-build/tests/native/registration/rust-static/cases/core-relinked/test_video_level_queries.json @@ -0,0 +1,34 @@ +{ + "schema": 1, + "targets": { + "test_video_level_queries": { + "sources": [ + "test/cmocka/test_video_level_queries.c", + "libobs/obs-video-level-queries-fields.c.h" + ], + "definitions": [ + "obs_get_video_sdr_white_level=obs_video_level_queries_sdr_white_level_request", + "obs_get_video_hdr_nominal_peak_level=obs_video_level_queries_hdr_nominal_peak_level_request" + ], + "libraries": [ + "libobs_rust-static", + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ] + } + }, + "tests": { + "test_video_level_queries": { + "target": "test_video_level_queries", + "command": [ + "${target}" + ] + } + } +} diff --git a/rust/obs-build/tests/native/registration/rust_static_entries.rs b/rust/obs-build/tests/native/registration/rust_static_entries.rs index 83bd3d055d..4c6fc01988 100644 --- a/rust/obs-build/tests/native/registration/rust_static_entries.rs +++ b/rust/obs-build/tests/native/registration/rust_static_entries.rs @@ -26,6 +26,12 @@ fn read(path: &Path) -> Result { .map_err(|e| format!("{}: {e}", path.display())) } +/// Families whose C tests keep their own names (no `_rust` twin) while +/// selecting the real Rust code and C adapter. Hotkey fixtures predate the +/// `_rust` naming convention; core-relinked fixtures are C-source +/// characterizations relinked in place by their swap (#5187). +const UNSUFFIXED: [&str; 2] = ["hotkey-control", "core-relinked"]; + struct Entries { graph: Graph, families: BTreeMap>, @@ -54,6 +60,7 @@ fn load(directory: &Path) -> Result { | "private-parser" | "windows-keys" | "hotkey-control" + | "core-relinked" ) { return Err(format!("unknown registration family {family_name}")); } @@ -62,7 +69,7 @@ fn load(directory: &Path) -> Result { let entry = read(&path)?; let graph = Graph::parse(&entry.to_string())?; let base = path.file_stem().unwrap().to_str().unwrap().to_owned(); - let name = if family_name == "hotkey-control" { + let name = if UNSUFFIXED.contains(&family_name.as_str()) { base.clone() } else { format!("{base}_rust") @@ -235,9 +242,10 @@ fn entries_cover_every_rust_static_target() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let actual = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); assert_coverage(&entries.graph, &actual); - // Hotkey fixtures predate the `_rust` naming convention. Their C tests - // keep their names while selecting the real Rust control and C adapter. - for name in &entries.families["hotkey-control"] { + for name in UNSUFFIXED + .iter() + .flat_map(|family| &entries.families[*family]) + { assert_eq!( format!("{:#?}", entries.graph.targets[name]), format!("{:#?}", actual.targets[name]), diff --git a/rust/obs-c-oracle/oracle/source_deinterlace_links.c b/rust/obs-c-oracle/oracle/source_deinterlace_links.c index bd4182a31e..f1c5ee0fca 100644 --- a/rust/obs-c-oracle/oracle/source_deinterlace_links.c +++ b/rust/obs-c-oracle/oracle/source_deinterlace_links.c @@ -5,10 +5,12 @@ * are oracle/source_deinterlace_getters.c's), and do-nothing definitions * of the libobs calls the deinterlace shims * (rust/obs-source-seam/src/ffi/source_deinterlace.rs) name under libobs's - * own names: the frame cache, the async texture upload, the effect load, - * the SDR white level and the framebuffer sRGB calls. The deinterlace - * texture size is obs-source's own Rust export - * (rust/obs-source/src/ffi/source_deinterlace_texture.rs). + * own names: the frame cache, the async texture upload, the effect load + * and the framebuffer sRGB calls. The SDR white level is obs-core's own + * Rust export (rust/obs-core/src/ffi/video_level_queries.rs), which reads + * oracle/video_level_queries.c's core: NULL outside its parity test, so + * the default 300. The deinterlace texture size is obs-source's own Rust + * export (rust/obs-source/src/ffi/source_deinterlace_texture.rs). * * The seam stays C in libobs.core-source, so the shims call it in the test * binary as they do in the hybrid libobs. Its core reads go to @@ -67,11 +69,6 @@ gs_effect_t *obs_load_effect(gs_effect_t **effect, const char *file) return *effect; } -float obs_get_video_sdr_white_level(void) -{ - return 300.0f; -} - bool gs_framebuffer_srgb_enabled(void) { return false; diff --git a/rust/obs-c-oracle/oracle/video_level_queries.c b/rust/obs-c-oracle/oracle/video_level_queries.c new file mode 100644 index 0000000000..540618d856 --- /dev/null +++ b/rust/obs-c-oracle/oracle/video_level_queries.c @@ -0,0 +1,83 @@ +/* Original C video level queries and the real field adapter (#5187). + * Excludes a dead core and concurrent writes to the levels: the original + * queries require stable caller state. The graphics token is a real + * graphics_t that is never dereferenced. Real core lifecycles stay covered by + * the unchanged actual-library C tests. */ +#include "libobs/build/libobs.pch.h" +#include "libobs/graphics/graphics-internal.h" +#include +#include +#include + +#if defined(_MSC_VER) +static __declspec(thread) struct obs_core *video_levels_current; +#else +static _Thread_local struct obs_core *video_levels_current; +#endif + +float oracle_obs_get_video_sdr_white_level(void); +float oracle_obs_get_video_hdr_nominal_peak_level(void); +#define obs video_levels_current +#define obs_get_video_sdr_white_level oracle_obs_get_video_sdr_white_level +#define obs_get_video_hdr_nominal_peak_level oracle_obs_get_video_hdr_nominal_peak_level +#include "libobs/obs-video-level-queries.c.h" +#undef obs_get_video_hdr_nominal_peak_level +#undef obs_get_video_sdr_white_level +#include "video-level-queries-fields.inc" +#undef obs + +static graphics_t video_levels_graphics; + +void oracle_video_level_queries_layout(size_t *layout); +void oracle_video_level_queries_layout(size_t *layout) +{ + layout[0] = sizeof(struct obs_video_level_queries_fields); + layout[1] = _Alignof(struct obs_video_level_queries_fields); + layout[2] = offsetof(struct obs_video_level_queries_fields, graphics); + layout[3] = offsetof(struct obs_video_level_queries_fields, sdr_white_level); + layout[4] = offsetof(struct obs_video_level_queries_fields, hdr_nominal_peak_level); +} + +static uint32_t video_levels_bits(float value) +{ + uint32_t bits; + memcpy(&bits, &value, sizeof(bits)); + return bits; +} + +typedef float (*video_level_fn)(void); + +/* core: 0 = NULL core, 1 = core without graphics, 2 = core with graphics. + * Writes the original C results' bits to out[0..1]; true when the port + * returns the same bits, the core bytes are unchanged and the global core + * pointer is untouched after every call. */ +bool oracle_video_level_queries_check(int mode, uint32_t white, uint32_t peak, video_level_fn white_fn, + video_level_fn peak_fn, uint32_t *out); +bool oracle_video_level_queries_check(int mode, uint32_t white, uint32_t peak, video_level_fn white_fn, + video_level_fn peak_fn, uint32_t *out) +{ + struct obs_core *core = calloc(1, sizeof(*core)); + struct obs_core *before = malloc(sizeof(*before)); + bool valid = core && before; + if (valid) { + memcpy(&core->video.sdr_white_level, &white, sizeof(white)); + memcpy(&core->video.hdr_nominal_peak_level, &peak, sizeof(peak)); + core->video.graphics = mode == 2 ? &video_levels_graphics : NULL; + struct obs_core *owner = mode ? core : NULL; + video_levels_current = owner; + memcpy(before, core, sizeof(*core)); + out[0] = video_levels_bits(oracle_obs_get_video_sdr_white_level()); + out[1] = video_levels_bits(oracle_obs_get_video_hdr_nominal_peak_level()); + valid = memcmp(before, core, sizeof(*core)) == 0 && video_levels_current == owner; + for (unsigned i = 0; i < 8; ++i) { + valid = valid && video_levels_bits(white_fn()) == out[0]; + valid = valid && memcmp(before, core, sizeof(*core)) == 0 && video_levels_current == owner; + valid = valid && video_levels_bits(peak_fn()) == out[1]; + valid = valid && memcmp(before, core, sizeof(*core)) == 0 && video_levels_current == owner; + } + video_levels_current = NULL; + } + free(before); + free(core); + return valid; +} diff --git a/rust/obs-core/src/ffi/mod.rs b/rust/obs-core/src/ffi/mod.rs index 1c267f4eeb..03c3148cc4 100644 --- a/rust/obs-core/src/ffi/mod.rs +++ b/rust/obs-core/src/ffi/mod.rs @@ -73,6 +73,7 @@ pub mod video_frame_copy; pub mod video_frame_timing; pub mod video_graphics_tasks; pub mod video_info_query; +pub mod video_level_queries; pub mod video_output_step; pub mod video_pacing; pub mod video_plan; diff --git a/rust/obs-core/src/ffi/video_level_queries.rs b/rust/obs-core/src/ffi/video_level_queries.rs new file mode 100644 index 0000000000..9584e7ee1e --- /dev/null +++ b/rust/obs-core/src/ffi/video_level_queries.rs @@ -0,0 +1,71 @@ +//! Thin C ABI shims for the video level queries (#5187). +use core::ffi::c_void; + +use crate::video_level_queries::{VideoLevels, hdr_nominal_peak_level, sdr_white_level}; + +/// Private adapter layout, checked against the real C declaration. +#[repr(C)] +pub struct Fields { + pub graphics: *const c_void, + pub sdr_white_level: f32, + pub hdr_nominal_peak_level: f32, +} + +unsafe extern "C" { + fn obs_video_level_queries_core() -> *const c_void; + fn obs_video_level_queries_fields(core: *const c_void) -> Fields; +} + +/// Read the current core's fields, or `None` for a NULL core. The core is +/// checked before its video fields are touched. +fn current_levels() -> Option { + // SAFETY: the adapter only returns the current global core pointer. + let core = unsafe { obs_video_level_queries_core() }; + if core.is_null() { + return None; + } + // SAFETY: `core` is the non-NULL current core, which the caller keeps + // alive, as the original query requires. + let fields = unsafe { obs_video_level_queries_fields(core) }; + Some(VideoLevels { + graphics: !fields.graphics.is_null(), + sdr_white_level: fields.sdr_white_level, + hdr_nominal_peak_level: fields.hdr_nominal_peak_level, + }) +} + +/// # Safety +/// The current core, when not NULL, must be live for the call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_video_sdr_white_level() -> f32 { + // SAFETY: forwarded unchanged; the caller upholds the same contract. + unsafe { obs_video_level_queries_sdr_white_level_request() } +} + +/// # Safety +/// The current core, when not NULL, must be live for the call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_get_video_hdr_nominal_peak_level() -> f32 { + // SAFETY: forwarded unchanged; the caller upholds the same contract. + unsafe { obs_video_level_queries_hdr_nominal_peak_level_request() } +} + +/// Explicit static entry for fixtures with their own private core. Hidden +/// from libobs's ABI, so a macOS fixture cannot bind it to libobs.dylib's +/// copy, which reads the dylib's own core (two-level namespace). +/// +/// # Safety +/// The current core, when not NULL, must be live for the call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_video_level_queries_sdr_white_level_request() -> f32 { + sdr_white_level(current_levels()) +} + +/// Explicit static entry; see `obs_video_level_queries_sdr_white_level_request`. +/// +/// # Safety +/// The current core, when not NULL, must be live for the call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_video_level_queries_hdr_nominal_peak_level_request() -> f32 { + hdr_nominal_peak_level(current_levels()) +} diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index be355ae810..18d4010ca9 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -183,6 +183,7 @@ pub mod video_frame_copy; pub mod video_frame_timing; pub mod video_graphics_tasks; pub mod video_info_query; +pub mod video_level_queries; pub mod video_output_step; pub mod video_pacing; pub mod video_plan; diff --git a/rust/obs-core/src/video_level_queries.rs b/rust/obs-core/src/video_level_queries.rs new file mode 100644 index 0000000000..58d556ef53 --- /dev/null +++ b/rust/obs-core/src/video_level_queries.rs @@ -0,0 +1,35 @@ +//! Video SDR white and HDR nominal peak level queries (#5187). +//! +//! Without a core or graphics the no-video defaults are returned; otherwise +//! each stored level is returned with its exact bits, with no validation, +//! clamping or arithmetic. + +/// SDR white level without a core or graphics: 300.0 (`0x43960000`). +pub const DEFAULT_SDR_WHITE_LEVEL: f32 = 300.0; +/// HDR nominal peak level without a core or graphics: 1000.0 (`0x447a0000`). +pub const DEFAULT_HDR_NOMINAL_PEAK_LEVEL: f32 = 1000.0; + +/// The core video fields the queries read, borrowed from a live core. +#[derive(Clone, Copy, Debug)] +pub struct VideoLevels { + /// Whether the core has a graphics subsystem. + pub graphics: bool, + pub sdr_white_level: f32, + pub hdr_nominal_peak_level: f32, +} + +/// `obs_get_video_sdr_white_level`: `None` is a NULL core. +pub fn sdr_white_level(levels: Option) -> f32 { + match levels { + Some(levels) if levels.graphics => levels.sdr_white_level, + _ => DEFAULT_SDR_WHITE_LEVEL, + } +} + +/// `obs_get_video_hdr_nominal_peak_level`: `None` is a NULL core. +pub fn hdr_nominal_peak_level(levels: Option) -> f32 { + match levels { + Some(levels) if levels.graphics => levels.hdr_nominal_peak_level, + _ => DEFAULT_HDR_NOMINAL_PEAK_LEVEL, + } +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 10de45f9b7..8eeb0e9d27 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -151,6 +151,8 @@ mod video_graphics_tasks; mod video_graphics_tasks_parity; mod video_info_query; mod video_info_query_parity; +mod video_level_queries; +mod video_level_queries_parity; mod video_output_step; mod video_output_step_parity; mod video_pacing; diff --git a/rust/obs-core/tests/obs_core/video_level_queries.rs b/rust/obs-core/tests/obs_core/video_level_queries.rs new file mode 100644 index 0000000000..1d9c9a75b6 --- /dev/null +++ b/rust/obs-core/tests/obs_core/video_level_queries.rs @@ -0,0 +1,80 @@ +//! Safe mirrors of test_video_level_queries.c (#5168, #5187). Every level is +//! compared by its exact binary32 bits, never approximately. +use obs_core::video_level_queries::{ + DEFAULT_HDR_NOMINAL_PEAK_LEVEL, DEFAULT_SDR_WHITE_LEVEL, VideoLevels, hdr_nominal_peak_level, + sdr_white_level, +}; + +const WHITE_DEFAULT: u32 = 0x4396_0000; +const PEAK_DEFAULT: u32 = 0x447a_0000; + +fn stored(graphics: bool, white: u32, peak: u32) -> VideoLevels { + VideoLevels { + graphics, + sdr_white_level: f32::from_bits(white), + hdr_nominal_peak_level: f32::from_bits(peak), + } +} + +fn expect_levels(levels: Option, white: u32, peak: u32) { + assert_eq!(sdr_white_level(levels).to_bits(), white); + assert_eq!(hdr_nominal_peak_level(levels).to_bits(), peak); +} + +#[test] +fn defaults_are_the_characterized_bits() { + assert_eq!(DEFAULT_SDR_WHITE_LEVEL.to_bits(), WHITE_DEFAULT); + assert_eq!(DEFAULT_HDR_NOMINAL_PEAK_LEVEL.to_bits(), PEAK_DEFAULT); +} + +#[test] +fn no_core_before_and_after() { + expect_levels(None, WHITE_DEFAULT, PEAK_DEFAULT); + expect_levels( + Some(stored(true, 0x4323_4567, 0x45ab_cdef)), + 0x4323_4567, + 0x45ab_cdef, + ); + expect_levels(None, WHITE_DEFAULT, PEAK_DEFAULT); +} + +#[test] +fn no_graphics_ignores_stored_fields() { + expect_levels( + Some(stored(false, 0x4323_4567, 0x45ab_cdef)), + WHITE_DEFAULT, + PEAK_DEFAULT, + ); + expect_levels( + Some(stored(false, 0x7fc1_2345, 0x8000_0000)), + WHITE_DEFAULT, + PEAK_DEFAULT, + ); +} + +#[test] +fn graphics_returns_exact_field_bits() { + // Characterized, not endorsed: no validation, clamping or arithmetic; + // signed zeros and quiet NaN payloads come back verbatim. + const PAIRS: [(u32, u32); 9] = [ + (0x4323_4567, 0x45ab_cdef), + (0x45ab_cdef, 0x4323_4567), + (0x0000_0000, 0x8000_0000), + (0x8000_0000, 0x0000_0000), + (0xbf80_0000, 0xc020_0000), + (0x7f80_0000, 0xff80_0000), + (0x7fc1_2345, 0xffc5_4321), + (0xffc5_4321, 0x7fc1_2345), + (0x0080_0000, 0x7f7f_ffff), + ]; + for (white, peak) in PAIRS { + expect_levels(Some(stored(true, white, peak)), white, peak); + } + // Removing graphics selects defaults even with stored exceptional bits. + let (white, peak) = PAIRS[PAIRS.len() - 1]; + expect_levels( + Some(stored(false, white, peak)), + WHITE_DEFAULT, + PEAK_DEFAULT, + ); +} diff --git a/rust/obs-core/tests/obs_core/video_level_queries_parity.rs b/rust/obs-core/tests/obs_core/video_level_queries_parity.rs new file mode 100644 index 0000000000..7a82e63a67 --- /dev/null +++ b/rust/obs-core/tests/obs_core/video_level_queries_parity.rs @@ -0,0 +1,113 @@ +//! Original-C parity for the video level queries (#5187): the thin ABI shims +//! and real field adapter against the extracted C, by exact binary32 bits. +//! Excludes a dead core and concurrent level writes, matching C's contract. +//! No intentional differences. +use core::mem::{align_of, offset_of, size_of}; +use obs_core::ffi::video_level_queries::{ + Fields, obs_get_video_hdr_nominal_peak_level, obs_get_video_sdr_white_level, +}; +use obs_core::video_level_queries::{VideoLevels, hdr_nominal_peak_level, sdr_white_level}; +use proptest::prelude::*; + +unsafe extern "C" { + fn oracle_video_level_queries_layout(layout: *mut usize); + fn oracle_video_level_queries_check( + mode: i32, + white: u32, + peak: u32, + white_fn: unsafe extern "C" fn() -> f32, + peak_fn: unsafe extern "C" fn() -> f32, + out: *mut u32, + ) -> bool; +} + +#[test] +fn real_c_adapter_layout() { + let mut layout = [0; 5]; + // SAFETY: C writes exactly five layout values into this array. + unsafe { oracle_video_level_queries_layout(layout.as_mut_ptr()) }; + assert_eq!( + layout, + [ + size_of::(), + align_of::(), + offset_of!(Fields, graphics), + offset_of!(Fields, sdr_white_level), + offset_of!(Fields, hdr_nominal_peak_level), + ] + ); +} + +fn check(mode: i32, white: u32, peak: u32) { + let mut out = [0u32; 2]; + // SAFETY: C owns a live real-layout core fixture, installs it as the + // thread's current core and never dereferences the graphics token. + assert!( + unsafe { + oracle_video_level_queries_check( + mode, + white, + peak, + obs_get_video_sdr_white_level, + obs_get_video_hdr_nominal_peak_level, + out.as_mut_ptr(), + ) + }, + "mode {mode} white {white:#010x} peak {peak:#010x}" + ); + // The safe core gives the same bits as the original C. + let levels = (mode != 0).then_some(VideoLevels { + graphics: mode == 2, + sdr_white_level: f32::from_bits(white), + hdr_nominal_peak_level: f32::from_bits(peak), + }); + assert_eq!(sdr_white_level(levels).to_bits(), out[0]); + assert_eq!(hdr_nominal_peak_level(levels).to_bits(), out[1]); +} + +const EDGES: [u32; 14] = [ + 0x0000_0000, // +0 + 0x8000_0000, // -0 + 0x0000_0001, // smallest subnormal + 0x0080_0000, // smallest normal + 0x7f7f_ffff, // largest finite + 0x7f80_0000, // +inf + 0xff80_0000, // -inf + 0x7fc0_0000, // quiet NaN + 0x7fc1_2345, // quiet NaN payload + 0xffc5_4321, // negative quiet NaN payload + 0xbf80_0000, // -1 + 0x4396_0000, // 300 (the SDR default) + 0x447a_0000, // 1000 (the HDR default) + 0x4323_4567, +]; + +#[test] +fn characterized_edges_match_original_c() { + for mode in 0..3 { + for white in EDGES { + for peak in EDGES { + check(mode, white, peak); + } + } + } +} + +// Signaling NaNs are excluded: binary32 returns through x87 on 32-bit x86 +// may quiet them in both implementations alike. +fn not_signaling_nan(bits: u32) -> bool { + let nan = (bits & 0x7f80_0000) == 0x7f80_0000 && (bits & 0x007f_ffff) != 0; + !nan || bits & 0x0040_0000 != 0 +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(256), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn random_level_bits_match_original_c( + mode in 0..3i32, + white in any::().prop_filter("signaling NaN", |b| not_signaling_nan(*b)), + peak in any::().prop_filter("signaling NaN", |b| not_signaling_nan(*b)), + ) { + check(mode, white, peak); + } +} diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 1d1cafe317..c41776987f 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -20003,9 +20003,14 @@ "test_video_level_queries": { "sources": [ "test/cmocka/test_video_level_queries.c", - "libobs/obs-video-level-queries.c.h" + "libobs/obs-video-level-queries-fields.c.h" + ], + "definitions": [ + "obs_get_video_sdr_white_level=obs_video_level_queries_sdr_white_level_request", + "obs_get_video_hdr_nominal_peak_level=obs_video_level_queries_hdr_nominal_peak_level_request" ], "libraries": [ + "libobs_rust-static", "OBS::libobs", "OBS::caption", "Uthash::Uthash", diff --git a/test/cmocka/tests.d/video_level_queries_link_support.cmake b/test/cmocka/tests.d/video_level_queries_link_support.cmake new file mode 100644 index 0000000000..2e16c90c3c --- /dev/null +++ b/test/cmocka/tests.d/video_level_queries_link_support.cmake @@ -0,0 +1,31 @@ +include("${CMAKE_CURRENT_LIST_DIR}/../write-if-different.cmake") +# Link the real private adapter only when a Rust-static consumer needs it. +file(READ "${CMAKE_SOURCE_DIR}/libobs/obs-video-level-queries-fields.c.h" _video_level_queries_adapter) +string( + REPLACE + "#include \"libobs/build/libobs.pch.h\"" + "" + _video_level_queries_adapter + "${_video_level_queries_adapter}" +) +obs_test_write_file("${CMAKE_CURRENT_BINARY_DIR}/video-level-queries-fields.c" "#include \"obs-internal.h\"\n${_video_level_queries_adapter}" +) +function(_video_level_queries_link_support) + add_library(video_level_queries_link_support STATIC "${CMAKE_CURRENT_BINARY_DIR}/video-level-queries-fields.c") + target_include_directories( + video_level_queries_link_support + PRIVATE "${CMAKE_SOURCE_DIR}/libobs" "${CMAKE_BINARY_DIR}/config" + ) + target_link_libraries( + video_level_queries_link_support + PRIVATE OBS::caption Uthash::Uthash "$<$:OBS::w32-pthreads>" + ) + get_directory_property(_targets BUILDSYSTEM_TARGETS) + foreach(_target IN LISTS _targets) + get_target_property(_links ${_target} LINK_LIBRARIES) + if("libobs_rust-static" IN_LIST _links) + target_link_libraries(${_target} PRIVATE video_level_queries_link_support) + endif() + endforeach() +endfunction() +cmake_language(DEFER CALL _video_level_queries_link_support)