diff --git a/ci/test_rust_static_link_support.py b/ci/test_rust_static_link_support.py index 47f409fe5a..1c34c17cb6 100644 --- a/ci/test_rust_static_link_support.py +++ b/ci/test_rust_static_link_support.py @@ -57,6 +57,34 @@ def test_non_msvc_preserves_declared_shared_binding(self): def test_non_msvc_preserves_declared_static_binding(self): self.check_fixture(False, False, True) + def test_isolated_recording_fixture_selects_only_needed_support(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) + for name, body in { + "main.c": "int rust_entry(void); int main(void) { return rust_entry() != 22; }\n", + "rust.c": "int adapter_value(void); int rust_entry(void) { return adapter_value(); }\n", + "fallback.c": "int adapter_value(void) { return 99; }\n", + "recording-link-support.c": "int adapter_value(void) { return 22; }\n", + "unused-link-support.c": "int unavailable(void); int unused_adapter(void) { return unavailable(); }\n", + }.items(): + (source / name).write_text(body) + (source / "CMakeLists.txt").write_text( + "cmake_minimum_required(VERSION 3.28)\nproject(isolated_recording C)\n" + "set(MSVC FALSE)\n" + "add_library(libobs_rust-static STATIC rust.c)\n" + "add_library(support STATIC fallback.c)\n" + # The root project reads fragments before creating graph targets. + f'include("{(ROOT / "test/cmocka/tests.d/test_texture_file_data_steps.cmake").as_posix()}")\n' + "add_executable(test_texture_file_data_steps_rust main.c recording-link-support.c unused-link-support.c)\n" + "target_link_libraries(test_texture_file_data_steps_rust PRIVATE libobs_rust-static)\n" + f'include("{HELPER.as_posix()}")\n' + "obs_rust_static_consumers(support missing_owner)\n" + ) + build = source / "build" + self.run_command(["cmake", "-S", str(source), "-B", str(build)]) + self.run_command(["cmake", "--build", str(build)]) + self.run_command([str(build / "test_texture_file_data_steps_rust")]) + def test_real_logger_members_preserve_fixture_owned_guards(self): with tempfile.TemporaryDirectory() as directory: source = Path(directory) diff --git a/libobs/build/libobs.media+.h.c b/libobs/build/libobs.media+.h.c index 922bafb829..b94e306f31 100644 --- a/libobs/build/libobs.media+.h.c +++ b/libobs/build/libobs.media+.h.c @@ -4,6 +4,5 @@ #include "libobs/graphics/graphics-ffmpeg-init-adapter.c.h" #include "libobs/graphics/graphics-ffmpeg.c.h" -#include "libobs/graphics/graphics-texture-file-data.c.h" #include "libobs/media-io/media-remux-ffmpeg.c.h" #include "libobs/media-io/video-scaler-ffmpeg.c.h" diff --git a/libobs/build/libobs.ported-texture-file-data+.h.c b/libobs/build/libobs.ported-texture-file-data+.h.c new file mode 100644 index 0000000000..d776f3dc0c --- /dev/null +++ b/libobs/build/libobs.ported-texture-file-data+.h.c @@ -0,0 +1,4 @@ +/* Original legacy image-file orchestration, C reference only. */ +#include "libobs/build/libobs-media.pch.h" + +#include "libobs/graphics/graphics-texture-file-data.c.h" diff --git a/libobs/build/ported-source-sets/texture-file-data.json b/libobs/build/ported-source-sets/texture-file-data.json new file mode 100644 index 0000000000..dbcf4df89e --- /dev/null +++ b/libobs/build/ported-source-sets/texture-file-data.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-texture-file-data+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-graphics-texture_file_data.txt b/libobs/cmake/rust-exports.d/obs-graphics-texture_file_data.txt new file mode 100644 index 0000000000..d52c2403b8 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-graphics-texture_file_data.txt @@ -0,0 +1 @@ +gs_create_texture_file_data diff --git a/rust/README.md b/rust/README.md index 98fe04f776..dd985b9734 100644 --- a/rust/README.md +++ b/rust/README.md @@ -169,6 +169,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/graphics/graphics-shader-matrix-queries.c.h` | `obs-graphics::shader_matrix_queries` | Swapped in hybrid `libobs` (Refs #5185; prerequisite #5132/#5184). Safe Rust checks context before shader, then private C adapters dispatch the viewproj/world callback with the exact shader pointer and return the borrowed parameter unchanged, NULL included. Exact LOG_DEBUG messages and single dispatch agree with the reference-only C and a verbatim legacy oracle. Tier 1 mirrors unchanged `test_shader_matrix_queries`; Tier 3 compares boundary matrices and bounded random sequences through the real ABI and adapters in the existing Graphics category binary. No intentional differences; Tier 4 does not apply. | | `libobs/graphics/graphics-target-size.c.h` | `obs-graphics::target_size` | Swapped in hybrid `libobs` (Refs #5100; prerequisite #5087/#5107). Safe Rust checks context before private C layout/dispatch adapters, preserves zero scalar defaults and untouched outputs without context, and forwards nullable/aliased outputs unchanged. Exact LOG_DEBUG messages, device/output identities and single matching callbacks agree with the reference-only C and verbatim legacy oracle. Tier 1 mirrors unchanged `test_graphics_target_size`; Tier 3 covers boundary and bounded random queries in the existing Graphics category binary. No intentional differences; Tier 4 does not apply. | | `libobs/graphics/graphics-texture-copy.c.h` | `obs-graphics::texture_copy` | Swapped in hybrid `libobs` (Refs #5062; prerequisite #5074/#5059). Safe Rust preserves context-before-pointer validation, whole-copy destination-then-source guards and region-copy destination-only validation, including NULL sources, aliasing and all six unchanged offsets/extents. Private C adapters own layout and backend dispatch. Exact LOG_DEBUG messages, device and texture identity match the reference-only original C and verbatim Tier 3 legacy oracle. Tier 1 mirrors unchanged `test_graphics_texture_copy`; Tier 3 compares boundary matrices and bounded random inputs through the real ABI and adapters in the existing Graphics category binary. No intentional differences; Tier 4 does not apply. | +| `libobs/graphics/graphics-texture-file-data.c.h` | `obs-graphics::texture_file_data` | Legacy straight-alpha image-file orchestration in safe Rust, behind a thin C ABI shim. The private C session owns FFmpeg layouts, initialization, callback identities and decode; successful metadata is published before cleanup, failures preserve outputs, and the pixel allocation remains caller-owned. Unchanged C characterization plus real-loader coverage run OFF/ON; the Rust-static recording fixture reaches the Rust export. Graphics category tests mirror the characterization and compare the unchanged C oracle against the Rust export with recording dependencies. No intentional differences; Tier 4 is inapplicable. | | `libobs/graphics/graphics-viewport.c.h` | `obs-graphics::viewport` | Full-target viewport, pixel-space projection and optional maximum-texture capability policy (#4429). Context validation and backend dispatch remain C; callback zero overrides API fallbacks. Unchanged public-API C characterization, safe-core tests and exact original-C differential traces. No intentional differences. | | `libobs/graphics/shader-file.c.h` | `obs-graphics::shader_file` | File-backed vertex/pixel shader creation (#4306). Preserves context-first validation, reader semantics, exact logs, constructor argument identity and source cleanup. Tier 1 mirrors the C characterization; Tier 3 compares all control paths with the original C. No intentional differences. | | `libobs/graphics/shader-param-values.c.h` | `obs-graphics::shader_param_values` | Swapped in hybrid `libobs` (group `libobs.ported-graphics`, beside `shader-param-names.c.h`). The number reads of the shader parser (#3468), moved out of `shader-parser.c` first (an extraction into its own live group, checked old against new C over 1,758,330 scripted scenarios in 8 builds), as three functions declared in the internal `graphics/shader-param-values.h` without `EXPORT` and hidden (`shader-parser.h` is public and unchanged): `shader_param_array_count` (the count of `sp_parse_param_array`: `valid_int_str()` on the token's length, then `strtol()`; written only when valid), `shader_param_int_value` and `shader_param_float_value` (the `int` and `float` values of `sp_parse_param_assign_intfloat`: `strtol()` or `(float)os_strtod()` of the number token's text, negated after a `-` token). The `int` is the effect parser's rule (`effect_param_types::int_value_by`, #3464), so both parsers read the same `int` the same way, and the count reads with its `valid_int_str` and `strtol` steps; the float reads what `os_strtod()`'s `strncpy()` copies, each byte once up to the NUL or 63 bytes, and converts the copy with libobs's `os_strtod` through the private adapter `obs_graphics_os_strtod` (`obs-graphics-adapter.c.h`), so obs-graphics never pulls obs-util's host code into the cmocka `*_rust` tests that link the staticlib. `shader-parser.c` keeps every token call, the `CFTOKEN_NUM` tests, the `-` token, the value count of a `floatN` or `floatNxM` default (each byte read in place), the push of each value and every `cf_adderror()`. Characterized, not endorsed, and kept: a float or hex token reads as its leading digits as an `int` or a count; a count checks only the token's length while `strtol()` reads every digit after it; a float past `FLT_MAX` is an infinity, and `os_strtod()` reads at most 63 bytes; a bad row or column digit of `floatNxM` adds its error and still counts (`float5` keeps five values, `float1x` none). Two intentional differences (#3468): past `INT_MAX` the C depends on the width of `long` (an `int` of `4294967297` reads as 1 and a count of `3000000000` as -1294967296 on Linux and macOS; both saturate before the sign on Windows); the port reads the digits exactly and applies the sign, then saturates an `int` to `INT_MIN..INT_MAX` (the effect parser's rule) and refuses a count outside it, so `sp_parse_param_array` fails as for a count that is not a number, on every platform. A null text, which the C hands to `strtol()` or `os_strtod()`, reads as `""` and false. Tests: `test_shader_param_values_steps` (the moved C; no `_rust` variant, as its edge cases are the intentional difference) and `test_shader_number_defaults` (`shader_parse()` through the real libobs), Tier 1 `shader::shader_param_values`, Tier 3 `shader::shader_param_values_parity` (fixed tokens with more digits after them, random texts of up to 25 bytes at every length, float texts around 63 bytes, values outside `int` checked against the fixed contract). | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 0eba442cb5..0e71800347 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -61,6 +61,8 @@ mod canonical_source_show_active_counters_swap_is_registered; mod canonical_source_showing_active_swap_is_registered; #[path = "native/registration/canonical_source_texcoords_centered_setter_swap_is_registered.rs"] mod canonical_source_texcoords_centered_setter_swap_is_registered; +#[path = "native/registration/canonical_texture_file_data_swap_is_registered.rs"] +mod canonical_texture_file_data_swap_is_registered; #[path = "native/registration/canonical_websocket_helpers_is_registered.rs"] mod canonical_websocket_helpers_is_registered; #[path = "native/graph_host_configurations.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_rust_static_graphics_are_registered.rs b/rust/obs-build/tests/native/registration/canonical_rust_static_graphics_are_registered.rs index 0414c22ca6..26fdd2fe15 100644 --- a/rust/obs-build/tests/native/registration/canonical_rust_static_graphics_are_registered.rs +++ b/rust/obs-build/tests/native/registration/canonical_rust_static_graphics_are_registered.rs @@ -8,19 +8,21 @@ static CASES: std::sync::LazyLock> = #[test] fn canonical_rust_static_graphics_are_registered() { let graph = rust_static_entries::assert_family(FAMILY); - assert_eq!(CASES.len(), 6); + assert_eq!(CASES.len(), 7); for windows in [false, true] { for msvc in [false, true] { for available in [false, true] { let facts = [ ("HAVE_LIBOBS_RUST_STATIC".into(), available), ("OS_WINDOWS".into(), windows), + ("OS_LINUX".into(), !windows), + ("OS_FREEBSD".into(), false), ("MSVC".into(), msvc), ] .into(); let selected = graph.select(&facts).unwrap(); - assert_eq!(selected.targets.len(), if available { 6 } else { 0 }); - assert_eq!(selected.tests.len(), if available { 6 } else { 0 }); + assert_eq!(selected.targets.len(), if available { 7 } else { 0 }); + assert_eq!(selected.tests.len(), if available { 7 } else { 0 }); } } } diff --git a/rust/obs-build/tests/native/registration/canonical_texture_file_data_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_texture_file_data_swap_is_registered.rs new file mode 100644 index 0000000000..c87aab90be --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_texture_file_data_swap_is_registered.rs @@ -0,0 +1,268 @@ +use super::*; + +#[test] +fn canonical_texture_file_data_swap_is_registered() { + use obs_build::validation::graph::Graph; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut graph = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); + let name = "test_texture_file_data_steps_rust"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + let selected = graph + .select( + &[ + (os.into(), true), + ("OS_FREEBSD".into(), false), + ("HAVE_LIBOBS_RUST_STATIC".into(), true), + ] + .into(), + ) + .unwrap(); + assert_eq!(selected.tests[name].target, name); + assert!(format!("{:?}", selected.targets[name]).contains("libobs_rust-static")); + // A dylib can satisfy the public entry point before the archive member + // is extracted, bypassing this executable's recording session on Darwin. + let target = &selected.targets[name]; + assert_eq!( + target.sources.len(), + 1, + "{os}: adapters must be demand linked" + ); + assert!( + !format!("{:?}", target.libraries).contains("\"OBS::libobs\""), + "{os}: the recording fixture must have only the static provider" + ); + assert!( + target + .header_libraries + .iter() + .any(|name| name == "OBS::libobs") + ); + } + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-texture-file-data+.h.c")).unwrap(); + assert!(group.contains("libobs/graphics/graphics-texture-file-data.c.h")); + let media = fs::read_to_string(root.join("libobs/build/libobs.media+.h.c")).unwrap(); + assert!(!media.contains("libobs/graphics/graphics-texture-file-data.c.h")); +} + +#[test] +fn standalone_texture_file_data_adapters_supply_private_max_size_callback() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let graph: serde_json::Value = + serde_json::from_slice(&fs::read(root.join("test/cmocka/build/test-graph.json")).unwrap()) + .unwrap(); + let support: serde_json::Value = serde_json::from_slice( + &fs::read(root.join("test/cmocka/build/rust-static-support.json")).unwrap(), + ) + .unwrap(); + let sources = support["sources"].as_array().unwrap(); + for source in [ + "test/cmocka/texture-file-data-session-link-support.c", + "test/cmocka/graphics-image-convert-link-support.c", + "test/cmocka/graphics-image-max-size-link-support.c", + "test/cmocka/vertexbuffer-destroy-link-support.c", + ] { + assert!(sources.contains(&serde_json::json!(source)), "{source}"); + } + let adapter = + fs::read_to_string(root.join("test/cmocka/texture-file-data-session-link-support.c")) + .unwrap(); + assert!(adapter.contains("libobs/graphics/graphics-texture-file-data-adapter.c.h")); + let callback = + fs::read_to_string(root.join("test/cmocka/graphics-image-max-size-link-support.c")) + .unwrap(); + assert!(callback.contains("libobs/graphics/graphics-image-max-size.c.h")); + for (name, target) in graph["targets"].as_object().unwrap() { + let sources = target["sources"].as_array().unwrap(); + assert!( + !sources.contains(&serde_json::json!( + "test/cmocka/texture-file-data-max-size-link-stub.c" + )), + "{name}" + ); + } +} + +#[test] +fn standalone_image_adapter_supplies_windows_host_imports() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let graph: serde_json::Value = + serde_json::from_slice(&fs::read(root.join("test/cmocka/build/test-graph.json")).unwrap()) + .unwrap(); + let graph = serde_json::json!({"targets": { + "test_video_stop_requested_rust": graph["targets"]["test_video_stop_requested_rust"] + }}); + let root = root.to_string_lossy().replace('\\', "/"); + for (system, windows) in [("Windows", true), ("Linux", false)] { + let directory = tempfile::tempdir().unwrap(); + fs::write( + directory.path().join("probe.c"), + "int main(void) { return 0; }\n", + ) + .unwrap(); + fs::write(directory.path().join("graph.json"), graph.to_string()).unwrap(); + fs::write( + directory.path().join("CMakeLists.txt"), + format!( + r##"cmake_minimum_required(VERSION 3.28) +project(image-adapter-link-contract C) +set(CMAKE_SYSTEM_NAME "{system}") +set(CMAKE_SOURCE_DIR "{root}") +set(OS_WINDOWS {windows}) +foreach(dependency IN ITEMS OBS::libobs OBS::caption OBS::w32-pthreads Uthash::Uthash FFmpeg::avcodec FFmpeg::avformat FFmpeg::avutil FFmpeg::swscale) + add_library(${{dependency}} INTERFACE IMPORTED) +endforeach() +add_library(libobs_rust-static INTERFACE) +foreach(consumer IN ITEMS test_video_stop_requested_rust test_texture_file_data_steps_rust) + add_executable(${{consumer}} "${{CMAKE_CURRENT_SOURCE_DIR}}/probe.c") + target_link_libraries(${{consumer}} PRIVATE libobs_rust-static) +endforeach() +add_executable(reference_consumer "${{CMAKE_CURRENT_SOURCE_DIR}}/probe.c") +include("{root}/test/cmocka/native-test-graph.cmake") +add_library(native_owner INTERFACE) +if(OS_WINDOWS) + target_link_libraries(native_owner INTERFACE winmm rpcrt4) +endif() +include("{root}/test/cmocka/rust-static-link-support.cmake") +obs_add_rust_static_support("{root}" native_owner) +"## + ), + ) + .unwrap(); + let build = directory.path().join("build"); + let configure = std::process::Command::new("cmake") + .arg("-S") + .arg(directory.path()) + .arg("-B") + .arg(&build) + .args(["-G", "Ninja"]) + .output() + .unwrap(); + assert!( + configure.status.success(), + "{}", + String::from_utf8_lossy(&configure.stderr) + ); + for consumer in [ + "test_video_stop_requested_rust", + "test_texture_file_data_steps_rust", + "reference_consumer", + ] { + let commands = std::process::Command::new("cmake") + .arg("--build") + .arg(&build) + .args(["--target", consumer, "--", "-n", "-v"]) + .output() + .unwrap(); + assert!(commands.status.success()); + let commands = String::from_utf8_lossy(&commands.stdout); + let lower = commands.to_ascii_lowercase(); + let links = |library| { + lower.split_whitespace().any(|token| { + let token = token.trim_matches('"'); + token == format!("-l{library}") || token == format!("{library}.lib") + }) + }; + assert_eq!( + ( + links("winmm"), + links("rpcrt4"), + commands.contains("base-variadic-link-support.c") + ), + ( + windows && consumer != "reference_consumer", + windows && consumer != "reference_consumer", + consumer != "reference_consumer" + ), + "{system}/{consumer}: {commands}" + ); + } + } +} + +#[test] +fn standalone_graphics_fixtures_bind_the_static_implementation() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let graph: serde_json::Value = + serde_json::from_slice(&fs::read(root.join("test/cmocka/build/test-graph.json")).unwrap()) + .unwrap(); + for name in [ + "test_texture_file_data_steps_rust", + "test_effect_parser_lifecycle_rust", + ] { + let directory = tempfile::tempdir().unwrap(); + fs::write( + directory.path().join("shared.c"), + "int implementation(void) { return 1; }\n", + ) + .unwrap(); + fs::write( + directory.path().join("static.c"), + "int implementation(void) { return 0; }\n", + ) + .unwrap(); + fs::write( + directory.path().join("main.c"), + "int implementation(void); int main(void) { return implementation(); }\n", + ) + .unwrap(); + let libraries: Vec<_> = graph["targets"][name]["libraries"] + .as_array() + .unwrap() + .iter() + .filter_map(|library| match library.as_str() { + Some("OBS::libobs") => Some("shared_provider"), + Some("libobs_rust-static") => Some("static_provider"), + _ => None, + }) + .collect(); + fs::write( + directory.path().join("CMakeLists.txt"), + format!( + r#"cmake_minimum_required(VERSION 3.28) +project(static-implementation-binding C) +set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) +add_library(shared_provider SHARED shared.c) +add_library(static_provider STATIC static.c) +add_executable(probe main.c) +target_link_libraries(probe PRIVATE {}) +"#, + libraries.join(" ") + ), + ) + .unwrap(); + let output = std::process::Command::new("cmake") + .args(["-S", ".", "-B", "build", "-G", "Ninja"]) + .current_dir(directory.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let output = std::process::Command::new("cmake") + .args(["--build", "build"]) + .current_dir(directory.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let status = std::process::Command::new( + directory + .path() + .join(format!("build/probe{}", std::env::consts::EXE_SUFFIX)), + ) + .status() + .unwrap(); + assert!( + status.success(), + "{name} selected shared libobs ahead of the Rust archive" + ); + } +} diff --git a/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_effect_parser_lifecycle.json b/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_effect_parser_lifecycle.json index 76c4d9feae..89212828c1 100644 --- a/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_effect_parser_lifecycle.json +++ b/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_effect_parser_lifecycle.json @@ -6,7 +6,8 @@ "test/cmocka/test_effect_parser_lifecycle.c", "libobs/graphics/effect-parser-lifecycle-adapter.c.h", "libobs/graphics/obs-graphics-adapter.c.h", - "libobs/graphics/graphics-linear-srgb-fields.c.h" + "libobs/graphics/graphics-linear-srgb-fields.c.h", + "libobs/util/cf-lexer.c.h" ], "requires": "HAVE_LIBOBS_RUST_STATIC", "includes": [ @@ -14,10 +15,10 @@ "libobs" ], "libraries": [ + "libobs_rust-static", "OBS::libobs", "OBS::caption", "OBS::native-test-cmocka", - "libobs_rust-static", { "name": "OBS::w32-pthreads", "requires": "OS_WINDOWS" diff --git a/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_texture_file_data_steps.json b/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_texture_file_data_steps.json new file mode 100644 index 0000000000..ebd9f008fe --- /dev/null +++ b/rust/obs-build/tests/native/registration/rust-static/cases/graphics/test_texture_file_data_steps.json @@ -0,0 +1,61 @@ +{ + "schema": 1, + "targets": { + "test_texture_file_data_steps_rust": { + "sources": [ + "test/cmocka/test_texture_file_data_steps.c" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC", + "includes": [ + ".", + "libobs" + ], + "libraries": [ + "libobs_rust-static", + "OBS::caption", + "OBS::native-test-cmocka", + { + "name": "m", + "requires": { + "not": "MSVC" + } + }, + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + }, + "FFmpeg::avcodec", + "FFmpeg::avformat", + "FFmpeg::avutil", + "FFmpeg::swscale", + { + "name": "PkgConfig::_window_match_test_gio", + "requires": "HAVE_WINDOW_MATCH_TEST_GIO" + }, + { + "name": "LibUUID::LibUUID", + "requires": { + "any": [ + "OS_LINUX", + "OS_FREEBSD" + ] + } + } + ], + "sanitizers": "address,undefined", + "header_libraries": [ + "OBS::libobs" + ], + "inherit_header_definitions": true + } + }, + "tests": { + "test_texture_file_data_steps_rust": { + "target": "test_texture_file_data_steps_rust", + "requires": "HAVE_LIBOBS_RUST_STATIC", + "command": [ + "${target}" + ] + } + } +} diff --git a/rust/obs-c-oracle/oracle.d/texture-file-data-adapter.list b/rust/obs-c-oracle/oracle.d/texture-file-data-adapter.list new file mode 100644 index 0000000000..83e2400f04 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/texture-file-data-adapter.list @@ -0,0 +1 @@ +graphics-texture-file-data-adapter.inc|libobs/graphics/graphics-texture-file-data-adapter.c.h|#include "libobs/build/libobs-media.pch.h" diff --git a/rust/obs-c-oracle/oracle.d/texture-file-data.list b/rust/obs-c-oracle/oracle.d/texture-file-data.list new file mode 100644 index 0000000000..c3d1d66ff8 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/texture-file-data.list @@ -0,0 +1 @@ +graphics-texture-file-data.inc|libobs/graphics/graphics-texture-file-data.c.h|#include "libobs/build/libobs-media.pch.h" diff --git a/rust/obs-c-oracle/oracle/texture_file_data.c b/rust/obs-c-oracle/oracle/texture_file_data.c new file mode 100644 index 0000000000..ec2e255867 --- /dev/null +++ b/rust/obs-c-oracle/oracle/texture_file_data.c @@ -0,0 +1,171 @@ +/* The unchanged C loader and real private session adapter share deterministic + * dependencies. No FFmpeg layout is copied: include the real private type. */ +#include +#include +#include +#include +#include +#include "graphics/graphics.h" +#include "util/threading.h" +enum AVPixelFormat { TFD_NONE = -1, TFD_INITIAL, TFD_DECODED }; +typedef struct AVFormatContext AVFormatContext; +typedef struct AVCodecContext AVCodecContext; +typedef struct AVCodec AVCodec; +typedef struct AVFrame AVFrame; +#include "graphics/graphics-ffmpeg-image-private.h" + +struct tfd_record { + const int32_t *config; + uint32_t *out; + enum gs_color_format *format; + uint32_t *width, *height; + const char *file; + struct ffmpeg_image *image; + uint8_t *pixels; + unsigned events; + int allocations; +}; +static THREAD_LOCAL struct tfd_record *tfd_current; +static void tfd_event(uint32_t event) +{ + struct tfd_record *r = tfd_current; + if (r->events < 16) + r->out[8 + r->events] = event; + r->out[7] = ++r->events; +} +static void tfd_check(bool condition) +{ + if (!condition) + tfd_current->out[6]++; +} +static void *tfd_alloc(size_t size) +{ + tfd_current->allocations++; + void *data = calloc(1, size); + if (!data) + abort(); + return data; +} +static void tfd_release(void *data) +{ + if (data) + tfd_current->allocations--; + free(data); +} +static uint32_t tfd_max_size(void) +{ + return 4096; +} +static bool tfd_check_size(struct ffmpeg_image *image, int cx, int cy) +{ + (void)image; + (void)cx; + (void)cy; + tfd_check(false); + return false; +} +static void *tfd_convert(struct ffmpeg_image *image, AVFrame *frame, enum gs_image_alpha_mode alpha) +{ + (void)image; + (void)frame; + (void)alpha; + tfd_check(false); + return NULL; +} +static bool tfd_init(struct ffmpeg_image *image, const char *file, uint32_t (*max_size)(void)) +{ + tfd_event(1); + tfd_check(file == tfd_current->file && max_size == tfd_max_size); + memset(image, 0, sizeof(*image)); + image->cx = 71; + image->cy = 72; + image->format = TFD_INITIAL; + tfd_current->image = image; + return tfd_current->config[0] != 0; +} +static void *tfd_decode(void *context, int alpha) +{ + tfd_event(2); + struct tfd_record *r = tfd_current; + struct gs_image_decode_context *decode = context; + tfd_check(decode->image == r->image && decode->check_size == tfd_check_size && decode->convert == tfd_convert); + tfd_check(alpha == GS_IMAGE_ALPHA_STRAIGHT); + tfd_check(*r->format == GS_BGRX && *r->width == 91 && *r->height == 92); + r->image->format = TFD_DECODED; + r->image->cx = r->config[2]; + r->image->cy = r->config[3]; + if (!r->config[1]) + return NULL; + static const uint8_t bytes[] = {1, 2, 3, 128, 4, 5, 6, 0}; + r->pixels = tfd_alloc(sizeof(bytes)); + memcpy(r->pixels, bytes, sizeof(bytes)); + return r->pixels; +} +static int tfd_format(int format) +{ + tfd_event(3); + tfd_check(format == TFD_DECODED); + return tfd_current->config[4]; +} +static void tfd_free(struct ffmpeg_image *image) +{ + tfd_event(4); + struct tfd_record *r = tfd_current; + tfd_check(image == r->image); + bool ok = r->config[1] != 0; + tfd_check((uint32_t)*r->format == (ok ? (uint32_t)r->config[4] : GS_BGRX)); + tfd_check(*r->width == (ok ? (uint32_t)r->config[2] : 91)); + tfd_check(*r->height == (ok ? (uint32_t)r->config[3] : 92)); +} +#define ffmpeg_image_init tfd_init +#define ffmpeg_image_free tfd_free +#define gs_image_max_texture_size tfd_max_size +#define ffmpeg_image_too_large tfd_check_size +#define ffmpeg_image_reformat_frame tfd_convert +#define gs_ffmpeg_image_decode tfd_decode +#define gs_ffmpeg_image_color_format tfd_format +#define bmalloc tfd_alloc +#define bzalloc tfd_alloc +#define bfree tfd_release +#include "graphics-texture-file-data-adapter.inc" +uint8_t *oracle_gs_create_texture_file_data(const char *, enum gs_color_format *, uint32_t *, uint32_t *); +#define gs_create_texture_file_data oracle_gs_create_texture_file_data +#include "graphics-texture-file-data.inc" +#undef gs_create_texture_file_data +#undef bfree +#undef bzalloc +#undef bmalloc +#undef gs_ffmpeg_image_color_format +#undef gs_ffmpeg_image_decode +#undef ffmpeg_image_reformat_frame +#undef ffmpeg_image_too_large +#undef gs_image_max_texture_size +#undef ffmpeg_image_free +#undef ffmpeg_image_init + +typedef uint8_t *(*tfd_loader)(const char *, enum gs_color_format *, uint32_t *, uint32_t *); +/* Thread-local recording of callback identities, ordering, publication, pixels + * and balanced ownership. Passing NULL selects the original C oracle. */ +void oracle_texture_file_data_run(tfd_loader loader, const int32_t *config, uint32_t *out); +void oracle_texture_file_data_run(tfd_loader loader, const int32_t *config, uint32_t *out) +{ + enum gs_color_format format = GS_BGRX; + uint32_t width = 91, height = 92; + const char file[] = "legacy-image.png"; + memset(out, 0, 24 * sizeof(*out)); + struct tfd_record record = {config, out, &format, &width, &height, file, NULL, NULL, 0, 0}; + tfd_current = &record; + uint8_t *result = (loader ? loader : oracle_gs_create_texture_file_data)(file, &format, &width, &height); + out[0] = (uint32_t)format; + out[1] = width; + out[2] = height; + out[3] = result != NULL; + out[4] = result == record.pixels; + if (result) { + static const uint8_t bytes[] = {1, 2, 3, 128, 4, 5, 6, 0}; + tfd_check(memcmp(result, bytes, sizeof(bytes)) == 0); + tfd_release(result); + } + out[5] = (uint32_t)record.allocations; + tfd_current = NULL; +} diff --git a/rust/obs-graphics/src/ffi/mod.rs b/rust/obs-graphics/src/ffi/mod.rs index 1b3f283168..1a5298b22a 100644 --- a/rust/obs-graphics/src/ffi/mod.rs +++ b/rust/obs-graphics/src/ffi/mod.rs @@ -63,6 +63,7 @@ pub mod stencil; pub mod target_size; pub mod texture_copy; pub mod texture_creators; +pub mod texture_file_data; pub mod texture_file_data2; pub mod texture_metadata; pub mod texture_planar_creators; diff --git a/rust/obs-graphics/src/ffi/texture_file_data.rs b/rust/obs-graphics/src/ffi/texture_file_data.rs new file mode 100644 index 0000000000..c45d8989eb --- /dev/null +++ b/rust/obs-graphics/src/ffi/texture_file_data.rs @@ -0,0 +1,83 @@ +//! Thin C boundary around an opaque, C-owned FFmpeg image session. +use crate::texture_file_data::{Backend, Metadata, create_texture_file_data}; +use crate::texture_render::ColorFormat; +use core::ffi::{c_char, c_void}; + +unsafe extern "C" { + fn obs_texture_file_data_open(file: *const c_char) -> *mut c_void; + fn obs_texture_file_data_decode(session: *mut c_void) -> *mut u8; + fn obs_texture_file_data_format(session: *mut c_void) -> i32; + fn obs_texture_file_data_width(session: *mut c_void) -> u32; + fn obs_texture_file_data_height(session: *mut c_void) -> u32; + fn obs_texture_file_data_close(session: *mut c_void); +} +struct Session { + file: *const c_char, + image: *mut c_void, + format: *mut ColorFormat, + width: *mut u32, + height: *mut u32, +} +impl Backend for Session { + type Pixels = *mut u8; + fn init(&mut self) -> bool { + // SAFETY: file retains the public entry point's C path contract. + self.image = unsafe { obs_texture_file_data_open(self.file) }; + !self.image.is_null() + } + fn decode_straight(&mut self) -> Option { + if self.image.is_null() { + return None; + } + // SAFETY: checked live session; C supplies the original callback pair. + let data = unsafe { obs_texture_file_data_decode(self.image) }; + (!data.is_null()).then_some(data) + } + fn metadata(&mut self) -> Metadata { + assert!(!self.image.is_null()); + // SAFETY: the non-null session remains alive until free, after publication. + unsafe { + Metadata { + format: obs_texture_file_data_format(self.image), + width: obs_texture_file_data_width(self.image), + height: obs_texture_file_data_height(self.image), + } + } + } + fn publish(&mut self, metadata: Metadata) { + // SAFETY: successful loads require writable public output slots. + unsafe { + *self.format = ColorFormat(metadata.format as u32); + *self.width = metadata.width; + *self.height = metadata.height; + } + } + fn free(&mut self) { + if !self.image.is_null() { + // SAFETY: close consumes this initialized session exactly once. + unsafe { obs_texture_file_data_close(self.image) }; + self.image = core::ptr::null_mut(); + } + } +} +/// Decode legacy straight-alpha image pixels. +/// +/// # Safety +/// `file` follows ffmpeg_image_init's path contract. On success all outputs +/// must be writable. The caller frees the returned bmalloc allocation. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn gs_create_texture_file_data( + file: *const c_char, + format: *mut ColorFormat, + width: *mut u32, + height: *mut u32, +) -> *mut u8 { + create_texture_file_data(&mut Session { + file, + image: core::ptr::null_mut(), + format, + width, + height, + }) + .unwrap_or(core::ptr::null_mut()) +} diff --git a/rust/obs-graphics/src/lib.rs b/rust/obs-graphics/src/lib.rs index 88515bdb8e..bdcbe97c95 100644 --- a/rust/obs-graphics/src/lib.rs +++ b/rust/obs-graphics/src/lib.rs @@ -109,6 +109,7 @@ pub mod stencil; pub mod target_size; pub mod texture_copy; pub mod texture_creators; +pub mod texture_file_data; pub mod texture_file_data2; pub mod texture_metadata; pub mod texture_planar_creators; diff --git a/rust/obs-graphics/src/texture_file_data.rs b/rust/obs-graphics/src/texture_file_data.rs new file mode 100644 index 0000000000..4ed2235525 --- /dev/null +++ b/rust/obs-graphics/src/texture_file_data.rs @@ -0,0 +1,35 @@ +//! Legacy image-file orchestration; FFmpeg state and callbacks stay C-owned. + +/// Post-decode metadata, published only when decoding returns pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Metadata { + pub format: i32, + pub width: u32, + pub height: u32, +} + +/// A private image session. Implementations retain ownership of decoder state; +/// the returned pixel allocation belongs to the caller. +pub trait Backend { + type Pixels; + fn init(&mut self) -> bool; + fn decode_straight(&mut self) -> Option; + fn metadata(&mut self) -> Metadata; + fn publish(&mut self, metadata: Metadata); + fn free(&mut self); +} + +/// Load legacy straight-alpha pixels and publish post-decode metadata before +/// releasing an initialized session. Failed initialization owns its cleanup. +pub fn create_texture_file_data(backend: &mut B) -> Option { + if !backend.init() { + return None; + } + let data = backend.decode_straight(); + if data.is_some() { + let metadata = backend.metadata(); + backend.publish(metadata); + } + backend.free(); + data +} diff --git a/rust/obs-graphics/tests/render/main.rs b/rust/obs-graphics/tests/render/main.rs index 6b7e31acc2..6710e1fb5e 100644 --- a/rust/obs-graphics/tests/render/main.rs +++ b/rust/obs-graphics/tests/render/main.rs @@ -77,8 +77,10 @@ mod texture_copy; mod texture_copy_parity; mod texture_creators; mod texture_creators_parity; +mod texture_file_data; mod texture_file_data2; mod texture_file_data2_parity; +mod texture_file_data_parity; mod texture_metadata; mod texture_metadata_parity; mod texture_planar_creators; diff --git a/rust/obs-graphics/tests/render/texture_file_data.rs b/rust/obs-graphics/tests/render/texture_file_data.rs new file mode 100644 index 0000000000..a2d43575fe --- /dev/null +++ b/rust/obs-graphics/tests/render/texture_file_data.rs @@ -0,0 +1,103 @@ +//! Mirrors every assertion in test_texture_file_data_legacy.c over a safe session. +use obs_graphics::texture_file_data::{Backend, Metadata, create_texture_file_data}; + +const BEFORE: Metadata = Metadata { + format: 4, + width: 91, + height: 92, +}; +const AFTER: Metadata = Metadata { + format: 3, + width: 2, + height: 1, +}; +const PIXELS: [u8; 8] = [1, 2, 3, 128, 4, 5, 6, 0]; +struct Recording { + initialized: bool, + decoded: bool, + calls: Vec<&'static str>, + outputs: Metadata, + pixels: Option>, + identity: usize, +} +impl Backend for Recording { + type Pixels = Box<[u8; 8]>; + fn init(&mut self) -> bool { + assert!(self.calls.is_empty()); + self.calls.push("init"); + self.initialized + } + fn decode_straight(&mut self) -> Option { + assert_eq!(self.calls, ["init"]); + assert_eq!(self.outputs, BEFORE); + self.calls.push("decode-straight"); + self.pixels.take() + } + fn metadata(&mut self) -> Metadata { + assert_eq!(self.calls, ["init", "decode-straight"]); + self.calls.push("metadata"); + AFTER + } + fn publish(&mut self, metadata: Metadata) { + self.calls.push("publish"); + self.outputs = metadata; + } + fn free(&mut self) { + assert_eq!(self.outputs, if self.decoded { AFTER } else { BEFORE }); + self.calls.push("free"); + } +} +fn check_load(initialized: bool, decoded: bool) { + let pixels = decoded.then(|| Box::new(PIXELS)); + let identity = pixels.as_ref().map_or(0, |p| p.as_ptr() as usize); + let mut session = Recording { + initialized, + decoded, + calls: vec![], + outputs: BEFORE, + pixels, + identity, + }; + let result = create_texture_file_data(&mut session); + assert_eq!(result.is_some(), initialized && decoded); + if let Some(data) = result { + assert_eq!(data.as_ptr() as usize, session.identity); + assert_eq!(*data, PIXELS); + } + let expected: &[&str] = if !initialized { + &["init"] + } else if !decoded { + &["init", "decode-straight", "free"] + } else { + &["init", "decode-straight", "metadata", "publish", "free"] + }; + assert_eq!(session.calls, expected); + assert_eq!( + session.outputs, + if initialized && decoded { + AFTER + } else { + BEFORE + } + ); +} +#[test] +fn failed_init_has_no_decode_or_second_free() { + check_load(false, false); +} +#[test] +fn failed_decode_frees_without_output_writes() { + check_load(true, false); +} +#[test] +fn successful_decode_publishes_before_free() { + check_load(true, true); +} +#[test] +fn repeated_failure_and_success() { + for _ in 0..8 { + check_load(false, false); + check_load(true, false); + check_load(true, true); + } +} diff --git a/rust/obs-graphics/tests/render/texture_file_data_parity.rs b/rust/obs-graphics/tests/render/texture_file_data_parity.rs new file mode 100644 index 0000000000..5ac3d02b65 --- /dev/null +++ b/rust/obs-graphics/tests/render/texture_file_data_parity.rs @@ -0,0 +1,63 @@ +//! Tier 3: unchanged C orchestration and real C adapter with recording FFmpeg +//! dependencies. No intentional differences. The C recorder is thread-local. +use core::ffi::c_char; +use obs_graphics::ffi::texture_file_data::gs_create_texture_file_data; +use obs_graphics::texture_render::ColorFormat; +use proptest::prelude::*; + +type Loader = unsafe extern "C" fn(*const c_char, *mut ColorFormat, *mut u32, *mut u32) -> *mut u8; +unsafe extern "C" { + fn oracle_texture_file_data_run(loader: Option, config: *const i32, out: *mut u32); +} +fn run(loader: Option, config: [i32; 5]) -> [u32; 24] { + let mut out = [0; 24]; + // SAFETY: recorder borrows these bounded arrays synchronously, and loader + // has the unchanged public C signature and writable outputs. + unsafe { oracle_texture_file_data_run(loader, config.as_ptr(), out.as_mut_ptr()) }; + assert_eq!(out[5], 0, "unbalanced pixel/session allocation"); + assert_eq!( + out[6], 0, + "callback identity, ordering, output or pixels differ" + ); + out +} +#[test] +fn characterization_matches_original_c() { + for _ in 0..8 { + for (init, decode) in [(0, 0), (1, 0), (1, 1)] { + let config = [init, decode, 2, 1, 3]; + let original = run(None, config); + assert_eq!(run(Some(gs_create_texture_file_data), config), original); + assert_eq!(original[3], (init != 0 && decode != 0) as u32); + assert_eq!(original[4], 1, "returned allocation identity"); + let events: &[u32] = if init == 0 { + &[1] + } else if decode == 0 { + &[1, 2, 4] + } else { + &[1, 2, 3, 4] + }; + assert_eq!(&original[8..8 + original[7] as usize], events); + } + } +} +#[test] +fn dimensions_and_formats_match_original_c() { + for size in [i32::MIN, -1, 0, 1, i32::MAX] { + for format in [0, 3, 5, i32::MAX] { + let config = [1, 1, size, size.wrapping_add(1), format]; + assert_eq!( + run(Some(gs_create_texture_file_data), config), + run(None, config) + ); + } + } +} +proptest! { + #![proptest_config(ProptestConfig::with_cases(obs_c_oracle::parity::cases(256)))] + #[test] + fn arbitrary_sessions_match_original_c(init in any::(), decode in any::(), width in any::(), height in any::(), format in 0i32..=i32::MAX) { + let config = [i32::from(init), i32::from(decode), width, height, format]; + prop_assert_eq!(run(Some(gs_create_texture_file_data), config), run(None, config)); + } +} diff --git a/test/cmocka/build/rust-static-support.json b/test/cmocka/build/rust-static-support.json index 57bea7502e..abd5fdedcf 100644 --- a/test/cmocka/build/rust-static-support.json +++ b/test/cmocka/build/rust-static-support.json @@ -32,7 +32,6 @@ "test/cmocka/graphics-indexbuffer-maintenance-link-support.c", "test/cmocka/graphics-preprocessor-link-support.c", "test/cmocka/graphics-runtime-link-support.c", - "test/cmocka/graphics-texture-file-data-link-support.c", "test/cmocka/hotkey-fields-link-support.c", "test/cmocka/hotkey-key-translation-link-support.c", "test/cmocka/load-sources-link-support.c", @@ -59,6 +58,8 @@ "test/cmocka/source-weak-refs-link-support.c", "test/cmocka/task-queue-link-support.c", "test/cmocka/texture-creators-fields-link-support.c", + "test/cmocka/texture-file-data-session-link-support.c", + "test/cmocka/vertexbuffer-destroy-link-support.c", "test/cmocka/video-active-link-support.c", "test/cmocka/video-info-query-link-support.c", "test/cmocka/video-scaler-ffmpeg-link-support.c", diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 163caa36f1..399edb9c52 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -3117,6 +3117,7 @@ "libobs/graphics/effect-parser-lifecycle-adapter.c.h", "libobs/graphics/obs-graphics-adapter.c.h", "libobs/graphics/graphics-linear-srgb-fields.c.h", + "libobs/util/cf-lexer.c.h", "libobs/obs-graphics-effect-file-fields.c.h", "test/cmocka/object-validity-query-link-stubs.c", "test/cmocka/source-update-properties-link-support.c", @@ -3128,10 +3129,10 @@ "libobs" ], "libraries": [ + "libobs_rust-static", "OBS::libobs", "OBS::caption", "OBS::native-test-cmocka", - "libobs_rust-static", { "name": "OBS::w32-pthreads", "requires": "OS_WINDOWS" @@ -19995,6 +19996,53 @@ "libobs/graphics/graphics-texture-file-data.c.h" ] }, + "test_texture_file_data_steps_rust": { + "sources": [ + "test/cmocka/test_texture_file_data_steps.c" + ], + "requires": "HAVE_LIBOBS_RUST_STATIC", + "includes": [ + ".", + "libobs" + ], + "libraries": [ + "libobs_rust-static", + "OBS::caption", + "OBS::native-test-cmocka", + { + "name": "m", + "requires": { + "not": "MSVC" + } + }, + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + }, + "FFmpeg::avcodec", + "FFmpeg::avformat", + "FFmpeg::avutil", + "FFmpeg::swscale", + { + "name": "PkgConfig::_window_match_test_gio", + "requires": "HAVE_WINDOW_MATCH_TEST_GIO" + }, + { + "name": "LibUUID::LibUUID", + "requires": { + "any": [ + "OS_LINUX", + "OS_FREEBSD" + ] + } + } + ], + "sanitizers": "address,undefined", + "header_libraries": [ + "OBS::libobs" + ], + "inherit_header_definitions": true + }, "test_texture_render": { "sources": [ "test/cmocka/test_texture_render.c" @@ -30456,6 +30504,13 @@ "${target}" ] }, + "test_texture_file_data_steps_rust": { + "target": "test_texture_file_data_steps_rust", + "requires": "HAVE_LIBOBS_RUST_STATIC", + "command": [ + "${target}" + ] + }, "test_texture_render": { "target": "test_texture_render", "command": [ diff --git a/test/cmocka/rust-static-link-support.cmake b/test/cmocka/rust-static-link-support.cmake index 29ca67af65..6ae182146d 100644 --- a/test/cmocka/rust-static-link-support.cmake +++ b/test/cmocka/rust-static-link-support.cmake @@ -58,6 +58,10 @@ function(_obs_demand_rust_static_support) if(NOT type STREQUAL "EXECUTABLE") continue() endif() + get_target_property(isolated "${target}" OBS_RUST_STATIC_ISOLATED) + if(NOT MSVC AND NOT isolated) + continue() + endif() _obs_uses_rust_static("${target}" "" uses_rust) if(uses_rust STREQUAL "0") continue() @@ -204,10 +208,9 @@ function(obs_rust_static_consumers support native_owner) endif() endif() endforeach() - if(MSVC) - # Run after every legacy deferred fragment has supplied its real adapters. - cmake_language(DEFER CALL _obs_demand_rust_static_support) - endif() + # Run after every legacy deferred fragment has supplied its real adapters. + # Non-MSVC fixtures opt in when they must exclude a shared implementation. + cmake_language(DEFER CALL _obs_demand_rust_static_support) endfunction() # Shared by the complete cmocka project and independent graph fixture projects. diff --git a/test/cmocka/test_texture_file_data_steps.c b/test/cmocka/test_texture_file_data_steps.c new file mode 100644 index 0000000000..9cffea6495 --- /dev/null +++ b/test/cmocka/test_texture_file_data_steps.c @@ -0,0 +1,183 @@ +/* Rust-export recording characterization. The real private C adapter retains + * FFmpeg layout and callback plumbing; the orchestration comes from Rust. */ +#include +#include +#include +#include +#include "libobs/build/libobs-media.pch.h" + +static const char missing[] = "legacy-missing.png"; +static const char corrupt[] = "legacy-corrupt.png"; +static struct ffmpeg_image *session; +static enum gs_color_format *format_out; +static uint32_t *width_out, *height_out; +static unsigned calls; +static bool init_ok, decode_ok; +static uint8_t *pixels; +static const uint8_t expected_pixels[] = {1, 2, 3, 128, 4, 5, 6, 0}; + +static uint32_t record_max_size(void) +{ + return 4096; +} + +static bool record_size(struct ffmpeg_image *image, int cx, int cy) +{ + (void)image; + (void)cx; + (void)cy; + /* Only callback identity matters to the wrapper. */ + assert_true(false); + return false; +} + +static void *record_convert(struct ffmpeg_image *image, AVFrame *frame, enum gs_image_alpha_mode alpha) +{ + (void)image; + (void)frame; + (void)alpha; + assert_true(false); + return NULL; +} + +static bool record_init(struct ffmpeg_image *image, const char *file, uint32_t (*max_size)(void)) +{ + assert_int_equal(calls++, 0); + assert_ptr_equal(file, init_ok ? corrupt : missing); + assert_ptr_equal(max_size, record_max_size); + session = image; + memset(image, 0, sizeof(*image)); + image->format = AV_PIX_FMT_BGRA; + image->cx = 71; + image->cy = 72; + return init_ok; +} + +static void *record_decode(void *context, int alpha) +{ + assert_int_equal(calls++, 1); + struct gs_image_decode_context *decode = context; + assert_ptr_equal(decode->image, session); + assert_ptr_equal(decode->check_size, record_size); + assert_ptr_equal(decode->convert, record_convert); + assert_int_equal(alpha, GS_IMAGE_ALPHA_STRAIGHT); + assert_int_equal(*format_out, GS_BGRX); + assert_int_equal(*width_out, 91); + assert_int_equal(*height_out, 92); + /* Decode can change the image's dimensions/format (e.g. orientation). */ + session->format = AV_PIX_FMT_RGBA; + session->cx = 2; + session->cy = 1; + if (!decode_ok) + return NULL; + pixels = bmemdup(expected_pixels, sizeof(expected_pixels)); + return pixels; +} + +static int record_format(int format) +{ + assert_int_equal(calls++, 2); + assert_int_equal(format, AV_PIX_FMT_RGBA); + return GS_RGBA; +} + +static void record_free(struct ffmpeg_image *image) +{ + assert_ptr_equal(image, session); + assert_int_equal(calls++, decode_ok ? 3 : 2); + /* Pin publication before cleanup; failure must not write outputs. */ + assert_int_equal(*format_out, decode_ok ? GS_RGBA : GS_BGRX); + assert_int_equal(*width_out, decode_ok ? 2 : 91); + assert_int_equal(*height_out, decode_ok ? 1 : 92); + memset(image, 0, sizeof(*image)); +} + +#define gs_create_texture_file_data record_texture_file_data +#define ffmpeg_image_init record_init +#define ffmpeg_image_free record_free +#define gs_ffmpeg_image_decode record_decode +#define gs_ffmpeg_image_color_format record_format +#define gs_image_max_texture_size record_max_size +#define ffmpeg_image_too_large record_size +#define ffmpeg_image_reformat_frame record_convert +#include "libobs/graphics/graphics-texture-file-data-adapter.c.h" +#undef ffmpeg_image_reformat_frame +#undef ffmpeg_image_too_large +#undef gs_image_max_texture_size +#undef gs_ffmpeg_image_color_format +#undef gs_ffmpeg_image_decode +#undef ffmpeg_image_free +#undef ffmpeg_image_init +#undef gs_create_texture_file_data +#define record_texture_file_data gs_create_texture_file_data + +static void check_load(bool initialized, bool decoded) +{ + const long allocations = bnum_allocs(); + enum gs_color_format format = GS_BGRX; + uint32_t width = 91, height = 92; + format_out = &format; + width_out = &width; + height_out = &height; + calls = 0; + init_ok = initialized; + decode_ok = decoded; + pixels = NULL; + uint8_t *data = record_texture_file_data(initialized ? corrupt : missing, &format, &width, &height); + assert_int_equal(calls, !initialized ? 1 : decoded ? 4 : 3); + if (initialized && decoded) { + assert_ptr_equal(data, pixels); + assert_memory_equal(data, expected_pixels, sizeof(expected_pixels)); + assert_int_equal(format, GS_RGBA); + assert_int_equal(width, 2); + assert_int_equal(height, 1); + /* The caller owns the decode allocation after session cleanup. */ + assert_int_equal(bnum_allocs(), allocations + 1); + bfree(data); + } else { + assert_null(data); + assert_int_equal(format, GS_BGRX); + assert_int_equal(width, 91); + assert_int_equal(height, 92); + } + assert_int_equal(bnum_allocs(), allocations); +} + +static void failed_init_has_no_decode_or_second_free(void **state) +{ + (void)state; + check_load(false, false); +} + +static void failed_decode_frees_without_output_writes(void **state) +{ + (void)state; + check_load(true, false); +} + +static void successful_decode_publishes_before_free(void **state) +{ + (void)state; + check_load(true, true); +} + +static void repeated_failure_and_success(void **state) +{ + (void)state; + for (unsigned i = 0; i < 8; i++) { + check_load(false, false); + check_load(true, false); + check_load(true, true); + } +} + +int main(void) +{ + const struct CMUnitTest tests[] = {cmocka_unit_test(failed_init_has_no_decode_or_second_free), + cmocka_unit_test(failed_decode_frees_without_output_writes), + cmocka_unit_test(successful_decode_publishes_before_free), + cmocka_unit_test(repeated_failure_and_success)}; + return cmocka_run_group_tests(tests, NULL, NULL); +} + +#undef record_texture_file_data diff --git a/test/cmocka/tests.d/test_effect_parser_lifecycle.cmake b/test/cmocka/tests.d/test_effect_parser_lifecycle.cmake index c318421bd1..f472dad2a1 100644 --- a/test/cmocka/tests.d/test_effect_parser_lifecycle.cmake +++ b/test/cmocka/tests.d/test_effect_parser_lifecycle.cmake @@ -1,4 +1,4 @@ # The unchanged C characterization and its Rust-static variant are declared -# in ../build/test-graph.json. Preserve the private graphics adapters and -# conditional Windows pthread imports; hidden functions come from the exact -# production Rust static archive, with public APIs supplied by selected libobs. +# in ../build/test-graph.json. The Rust archive precedes shared libobs so the +# fixture exercises the Rust exports. Compile the real C preprocessor locally: +# its cleanup must use the same allocator as header-inline parser setup on macOS. diff --git a/test/cmocka/tests.d/test_texture_file_data_steps.cmake b/test/cmocka/tests.d/test_texture_file_data_steps.cmake new file mode 100644 index 0000000000..926134f6c9 --- /dev/null +++ b/test/cmocka/tests.d/test_texture_file_data_steps.cmake @@ -0,0 +1,10 @@ +# Recording-session characterization calls the Rust export and real C adapter. +# Both target and test are declared in ../build/test-graph.json. +function(_obs_isolate_texture_file_data_recording) + if(TARGET test_texture_file_data_steps_rust) + set_property(TARGET test_texture_file_data_steps_rust PROPERTY OBS_RUST_STATIC_ISOLATED TRUE) + endif() +endfunction() + +# Fragments are read before canonical graph targets are created. +cmake_language(DEFER CALL _obs_isolate_texture_file_data_recording) diff --git a/test/cmocka/texture-file-data-session-link-support.c b/test/cmocka/texture-file-data-session-link-support.c new file mode 100644 index 0000000000..6278b99c39 --- /dev/null +++ b/test/cmocka/texture-file-data-session-link-support.c @@ -0,0 +1,2 @@ +/* The real opaque session adapter, selected only when Rust needs it. */ +#include "libobs/graphics/graphics-texture-file-data-adapter.c.h"