diff --git a/libobs/build/libobs.core-output+.h.c b/libobs/build/libobs.core-output+.h.c index 18b1ae0186..bfe1d17ffa 100644 --- a/libobs/build/libobs.core-output+.h.c +++ b/libobs/build/libobs.core-output+.h.c @@ -52,7 +52,6 @@ #include "libobs/obs-output-enum-types-with-protocol.c.h" #include "libobs/obs-output-flags-fields.c.h" #include "libobs/obs-output-frames-dropped-fields.c.h" -#include "libobs/obs-output-get-last-error.c.h" #include "libobs/obs-output-get-name.c.h" #include "libobs/obs-output-handler-getters-fields.c.h" #include "libobs/obs-output-identity-fields.c.h" diff --git a/libobs/build/libobs.ported-output-get-last-error+.h.c b/libobs/build/libobs.ported-output-get-last-error+.h.c new file mode 100644 index 0000000000..7ee266a0b6 --- /dev/null +++ b/libobs/build/libobs.ported-output-get-last-error+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original output last-error query, C reference only. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-output-get-last-error.c.h" diff --git a/libobs/build/ported-source-sets/output-get-last-error.json b/libobs/build/ported-source-sets/output-get-last-error.json new file mode 100644 index 0000000000..7c2d15f94b --- /dev/null +++ b/libobs/build/ported-source-sets/output-get-last-error.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-output-get-last-error+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-output-output_get_last_error.txt b/libobs/cmake/rust-exports.d/obs-output-output_get_last_error.txt new file mode 100644 index 0000000000..b8294475d0 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-output-output_get_last_error.txt @@ -0,0 +1 @@ +obs_output_get_last_error diff --git a/rust/README.md b/rust/README.md index a0d20e968a..eb56ea8d2d 100644 --- a/rust/README.md +++ b/rust/README.md @@ -339,6 +339,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-output-properties.c.h` | `obs-output::output_properties` | Output defaults and type/instance properties (#4300), through opaque callback/context snapshots. Preserves NULL type callback data, instance settings application, temporary defaults release and optional callbacks. Tier 1 mirrors C characterization; Tier 3 compares callback/settings traces and allocation balance. | | `libobs/obs-output-protocol-getter.c.h` | `obs-output::output_protocols` | Public borrowed protocol metadata getter swapped in hybrid libobs (#4062). Preserves service flags, NULL diagnostics, missing/empty and arbitrary-byte metadata, pointer identity and unchanged state. Real-header layout, Tier 1, differential mutation coverage and unchanged actual-library Tier 2. No intentional differences. | | `libobs/obs-output-set-last-error.c.h` | `obs-output::output_last_error` | Public error setter with a private writable-slot adapter. Preserves NULL diagnostics, replacement/clearing and empty or arbitrary-byte strings using libobs allocator ownership. Tier 1 mirrors existing C characterization; Tier 3 compares replacement sequences and untouched output state. Aliasing the old allocation is excluded as undefined in C. | +| `libobs/obs-output-get-last-error.c.h` | `obs-output::output_get_last_error` | Swapped in hybrid `libobs` (group `libobs.ported-output-get-last-error` keeps the original for the C reference). After `obs_output_valid()`'s exact NULL diagnostic, safe Rust returns the output's own `last_error_message`, else the first error of the video encoder slots in ascending order, else of the audio slots, else NULL. Each field is read lazily, so nothing below a hit is read; the pointer is borrowed unchanged (empty and non-UTF-8 strings included), with no copy, cache, reference or lock. Reads go through the existing production adapters (`obs-output-last-error-fields`, `obs-output-video-encoder-getter-fields`, `obs-output-encoder-getters-fields`, `obs-encoder-last-error-fields`), no new layout crosses the ABI. Tier 1 mirrors every assertion of the unchanged `test_output_get_last_error` with read-order traces; Tier 3 compares the original and the shim on real-layout output/encoder fixtures (identity, untouched state, NULL diagnostic, no allocation), checks each adapter addresses the original's field, and catches five mutants. No intentional differences; Tier 4 does not apply. | | `libobs/obs-output-supported-codecs.c.h` | `obs-output::output_supported_codecs` | Public borrowed video/audio codec metadata getters swapped in hybrid libobs (#3958). Preserves NULL diagnostics, absent/empty and arbitrary-byte metadata, pointer identity and unchanged output state. Private field-address adapter with real-header layout checks, Tier 1, differential mutation coverage and unchanged actual-library Tier 2. No intentional differences. | | `libobs/obs-output-size-getters.c.h` | `obs-output::output_size_getters` | Width/height and indexed wrappers through opaque private accessors. Preserves NULL/non-video diagnostics before bounds checks, encoder versus video fallback, independent scaled axes and unchanged output state. Tier 1 and original-C differential coverage; unchanged Tier 2 characterization. No intentional differences; Tier 4 does not apply. | | `libobs/obs-output-type-info.c.h` | `obs-output::output_type_info` | #4678: borrowed type display name, exact flag bits and raw supported codec pointers through the shared existing output-type lookup. Real-header snapshots, Tier 1 characterization, original-C differential/mutation checks and unchanged Tier 2 replay. No intentional differences; Tier 4 inapplicable. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 653d613e9f..7acaaf98bf 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -385,6 +385,8 @@ mod canonical_object_queries_is_registered; mod canonical_object_validity_query_is_registered; #[path = "native/registration/canonical_output_flags_is_registered.rs"] mod canonical_output_flags_is_registered; +#[path = "native/registration/canonical_output_get_last_error_swap_is_registered.rs"] +mod canonical_output_get_last_error_swap_is_registered; #[path = "native/registration/canonical_output_handler_getters_is_registered.rs"] mod canonical_output_handler_getters_is_registered; #[path = "native/registration/canonical_output_identity_getters_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_output_get_last_error_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_output_get_last_error_swap_is_registered.rs new file mode 100644 index 0000000000..7146342c31 --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_output_get_last_error_swap_is_registered.rs @@ -0,0 +1,47 @@ +use super::*; + +#[test] +fn canonical_output_get_last_error_swap_is_registered() { + use obs_build::validation::graph::{Graph, Source}; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut graph = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); + let name = "test_output_get_last_error"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + let selected = graph.select(&[(os.into(), true)].into()).unwrap(); + assert!( + matches!(selected.targets[name].sources.as_slice(), [Source::Path(path)] + if path == "test/cmocka/test_output_get_last_error.c") + ); + assert_eq!(selected.tests[name].target, name); + } + let ported = + fs::read_to_string(root.join("libobs/build/ported-source-sets/output-get-last-error.json")) + .unwrap(); + assert!(ported.contains("build/libobs.ported-output-get-last-error+.h.c")); + let original = "#include \"libobs/obs-output-get-last-error.c.h\""; + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-output-get-last-error+.h.c")) + .unwrap(); + assert!(group.contains(original)); + let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core-output+.h.c")).unwrap(); + assert!(!hybrid.contains(original)); + // The production adapters the Rust query reads through stay in the core. + for adapter in [ + "obs-output-last-error-fields.c.h", + "obs-output-video-encoder-getter-fields.c.h", + "obs-output-encoder-getters-fields.c.h", + "obs-encoder-last-error-fields.c.h", + ] { + assert!(hybrid.contains(&format!("#include \"libobs/{adapter}\""))); + } + let exports = fs::read_to_string( + root.join("libobs/cmake/rust-exports.d/obs-output-output_get_last_error.txt"), + ) + .unwrap(); + assert_eq!( + exports.lines().collect::>(), + ["obs_output_get_last_error"] + ); +} diff --git a/rust/obs-c-oracle/oracle/output_get_last_error.c b/rust/obs-c-oracle/oracle/output_get_last_error.c new file mode 100644 index 0000000000..844e789f7f --- /dev/null +++ b/rust/obs-c-oracle/oracle/output_get_last_error.c @@ -0,0 +1,182 @@ +/* Original output last-error query over the real private output and encoder + * layouts. The field adapters it is compared through are the production ones + * of their own oracles (output_last_error.c, output_video_encoder_getter.c, + * output_encoder_getters.c, encoder_last_error.c). + * + * 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. _NO_CRT_STDIO_INLINE keeps them declarations only, and the + * log capture below reads its arguments without formatting them. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include +#include +#include +#define obs_output_get_last_error oracle_obs_output_get_last_error +#include "obs-output-get-last-error.c.h" +#undef obs_output_get_last_error + +/* Defined by the production adapters of the oracles named above. */ +obs_encoder_t *obs_output_video_encoder_getter_at(const obs_output_t *output, size_t idx); +obs_encoder_t *obs_output_encoder_getters_audio_at(const obs_output_t *output, size_t idx); + +#define OGLE_VIDEO MAX_OUTPUT_VIDEO_ENCODERS +#define OGLE_AUDIO MAX_OUTPUT_AUDIO_ENCODERS +/* The output's own error, then each video, then each audio encoder's. */ +#define OGLE_FIELDS (1 + OGLE_VIDEO + OGLE_AUDIO) + +enum ogle_kind { OGLE_NULL, OGLE_SAME, OGLE_EMPTY, OGLE_BYTES, OGLE_KINDS }; + +struct output_get_last_error_fixture { + struct obs_output output; + struct obs_encoder video[OGLE_VIDEO]; + struct obs_encoder audio[OGLE_AUDIO]; + struct obs_output output_before; + struct obs_encoder video_before[OGLE_VIDEO]; + struct obs_encoder audio_before[OGLE_AUDIO]; + /* Independent storage: equal bytes never share an address. */ + char messages[OGLE_FIELDS][16]; + char messages_before[OGLE_FIELDS][16]; +}; + +static char *ogle_message(struct output_get_last_error_fixture *f, size_t field, uint8_t kind) +{ + static const char bytes[] = "\xff\x80x"; + switch (kind % OGLE_KINDS) { + case OGLE_SAME: + memcpy(f->messages[field], "same error", sizeof("same error")); + return f->messages[field]; + case OGLE_EMPTY: + return f->messages[field]; + case OGLE_BYTES: + memcpy(f->messages[field], bytes, sizeof(bytes)); + return f->messages[field]; + default: + return NULL; + } +} + +/* kinds[OGLE_FIELDS]; bit i of a mask attaches that slot's encoder. Detached + * encoders keep their errors, which the query must never reach. */ +void *oracle_output_get_last_error_new(const uint8_t *kinds, uint32_t video, uint32_t audio); +void *oracle_output_get_last_error_new(const uint8_t *kinds, uint32_t video, uint32_t audio) +{ + struct output_get_last_error_fixture *f = calloc(1, sizeof(*f)); + if (!f) + return NULL; + f->output.context.name = "last-error output"; + f->output.mixer_mask = UINT32_C(0x80000001); + f->output.last_error_message = ogle_message(f, 0, kinds[0]); + for (size_t i = 0; i < OGLE_VIDEO; i++) { + f->video[i].context.name = "video"; + f->video[i].last_error_message = ogle_message(f, 1 + i, kinds[1 + i]); + f->output.video_encoders[i] = (video >> i) & 1 ? &f->video[i] : NULL; + } + for (size_t i = 0; i < OGLE_AUDIO; i++) { + f->audio[i].context.name = "audio"; + f->audio[i].last_error_message = ogle_message(f, 1 + OGLE_VIDEO + i, kinds[1 + OGLE_VIDEO + i]); + f->output.audio_encoders[i] = (audio >> i) & 1 ? &f->audio[i] : NULL; + } + memcpy(&f->output_before, &f->output, sizeof(f->output)); + memcpy(f->video_before, f->video, sizeof(f->video)); + memcpy(f->audio_before, f->audio, sizeof(f->audio)); + memcpy(f->messages_before, f->messages, sizeof(f->messages)); + return f; +} + +/* The storage of one field's message, whatever its kind. */ +const char *oracle_output_get_last_error_storage(const void *fixture, size_t field); +const char *oracle_output_get_last_error_storage(const void *fixture, size_t field) +{ + const struct output_get_last_error_fixture *f = fixture; + return field < OGLE_FIELDS ? f->messages[field] : NULL; +} + +bool oracle_output_get_last_error_unchanged(const void *fixture); +bool oracle_output_get_last_error_unchanged(const void *fixture) +{ + const struct output_get_last_error_fixture *f = fixture; + return memcmp(&f->output, &f->output_before, sizeof(f->output)) == 0 && + memcmp(f->video, f->video_before, sizeof(f->video)) == 0 && + memcmp(f->audio, f->audio_before, sizeof(f->audio)) == 0 && + memcmp(f->messages, f->messages_before, sizeof(f->messages)) == 0; +} + +void oracle_output_get_last_error_free(void *fixture); +void oracle_output_get_last_error_free(void *fixture) +{ + free(fixture); +} + +/* The slot counts the Rust core walks. */ +void oracle_output_get_last_error_layout(size_t *out); +void oracle_output_get_last_error_layout(size_t *out) +{ + out[0] = MAX_OUTPUT_VIDEO_ENCODERS; + out[1] = MAX_OUTPUT_AUDIO_ENCODERS; + out[2] = OGLE_FIELDS; +} + +/* Every adapter the Rust shim reads through addresses exactly the field the + * original reads, on the real private layouts. */ +bool oracle_output_get_last_error_adapters(void *fixture); +bool oracle_output_get_last_error_adapters(void *fixture) +{ + struct output_get_last_error_fixture *f = fixture; + bool ok = obs_output_last_error_fields(&f->output) == &f->output.last_error_message; + for (size_t i = 0; i < OGLE_VIDEO; i++) { + ok &= obs_output_video_encoder_getter_at(&f->output, i) == f->output.video_encoders[i]; + ok &= obs_encoder_last_error_fields(&f->video[i]).message == &f->video[i].last_error_message; + } + for (size_t i = 0; i < OGLE_AUDIO; i++) { + ok &= obs_output_encoder_getters_audio_at(&f->output, i) == f->output.audio_encoders[i]; + ok &= obs_encoder_last_error_fields(&f->audio[i]).message == &f->audio[i].last_error_message; + } + return ok; +} + +struct ogle_log { + unsigned count; + int level; + const char *format; + const char *function; + const char *parameter; +}; + +static void ogle_capture(int level, const char *format, va_list args, void *param) +{ + struct ogle_log *log = param; + log->count++; + log->level = level; + log->format = format; + /* obs_output_valid()'s two %s arguments, read without formatting. */ + log->function = va_arg(args, const char *); + log->parameter = va_arg(args, const char *); +} + +static bool ogle_exact_null_log(const struct ogle_log *log) +{ + return log->count == 1 && log->level == LOG_DEBUG && strcmp(log->format, "%s: Null '%s' parameter") == 0 && + strcmp(log->function, "obs_output_get_last_error") == 0 && strcmp(log->parameter, "output") == 0; +} + +/* A NULL output: NULL, the exact diagnostic once, and no allocation. The + * original runs first on the same capture, so both sides are checked. */ +typedef const char *(*output_get_last_error_getter)(obs_output_t *output); +bool oracle_output_get_last_error_null_log(output_get_last_error_getter getter); +bool oracle_output_get_last_error_null_log(output_get_last_error_getter getter) +{ + log_handler_t old_handler; + void *old_param; + base_get_log_handler(&old_handler, &old_param); + struct ogle_log original = {0}, candidate = {0}; + long allocations = bnum_allocs(); + base_set_log_handler(ogle_capture, &original); + const char *original_result = oracle_obs_output_get_last_error(NULL); + base_set_log_handler(ogle_capture, &candidate); + const char *candidate_result = getter(NULL); + base_set_log_handler(old_handler, old_param); + return !original_result && !candidate_result && ogle_exact_null_log(&original) && + ogle_exact_null_log(&candidate) && bnum_allocs() == allocations; +} diff --git a/rust/obs-output/src/ffi/mod.rs b/rust/obs-output/src/ffi/mod.rs index 64d8fedcad..792235522d 100644 --- a/rust/obs-output/src/ffi/mod.rs +++ b/rust/obs-output/src/ffi/mod.rs @@ -48,6 +48,7 @@ pub mod output_caption_text; pub mod output_congestion; pub mod output_delay; pub mod output_flags; +pub mod output_get_last_error; pub mod output_handler_getters; pub mod output_identity; pub mod output_interleave; diff --git a/rust/obs-output/src/ffi/output_get_last_error.rs b/rust/obs-output/src/ffi/output_get_last_error.rs new file mode 100644 index 0000000000..914bf6c4ac --- /dev/null +++ b/rust/obs-output/src/ffi/output_get_last_error.rs @@ -0,0 +1,64 @@ +//! The public output last-error query over the real private C fields: the +//! existing output error slot, video and audio slot and encoder error +//! adapters. Validation and priority live in the safe core. +use crate::ffi::encoder_last_error::LastErrorFields as EncoderFields; +use crate::output_get_last_error::{LastErrorFields, last_error}; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::NonNull; + +unsafe extern "C" { + fn obs_output_last_error_fields(output: *mut c_void) -> *mut *mut c_char; + fn obs_output_video_encoder_getter_at(output: *const c_void, idx: usize) -> *mut c_void; + fn obs_output_encoder_getters_audio_at(output: *const c_void, idx: usize) -> *mut c_void; + fn obs_encoder_last_error_fields(encoder: *mut c_void) -> EncoderFields; + fn blog(level: c_int, format: *const c_char, ...); +} + +/// A non-NULL output the caller keeps live and readable. +struct Output(*mut c_void); +impl LastErrorFields for Output { + type Encoder = NonNull; + type Error = NonNull; + fn own(&mut self) -> Option> { + // SAFETY: the output is non-NULL and live; the adapter returns the + // address of its error field, which is only read here. + NonNull::new(unsafe { *obs_output_last_error_fields(self.0) }) + } + fn video(&mut self, idx: usize) -> Option> { + // SAFETY: the core asks only below MAX_OUTPUT_VIDEO_ENCODERS. + NonNull::new(unsafe { obs_output_video_encoder_getter_at(self.0, idx) }) + } + fn audio(&mut self, idx: usize) -> Option> { + // SAFETY: the core asks only below MAX_OUTPUT_AUDIO_ENCODERS. + NonNull::new(unsafe { obs_output_encoder_getters_audio_at(self.0, idx) }) + } + fn encoder_error(&mut self, encoder: NonNull) -> Option> { + // SAFETY: a slot of the live output holds this encoder; for a + // non-NULL encoder the adapter returns its error field's address. + let fields = unsafe { obs_encoder_last_error_fields(encoder.as_ptr()) }; + // SAFETY: as above; the field is read without its mutex, as in C. + NonNull::new(unsafe { *fields.message }.cast_mut()) + } +} + +/// Borrow the output's error, else its first encoder error, else NULL. +/// +/// # Safety +/// A non-NULL output and the encoders in its slots must be live and readable +/// during the call. The result borrows C-owned storage, as in C. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_output_get_last_error(output: *mut c_void) -> *const c_char { + let mut fields = (!output.is_null()).then_some(Output(output)); + let error = last_error(fields.as_mut(), || { + // SAFETY: obs_output_valid()'s static format and arguments. + unsafe { + blog( + 400, + c"%s: Null '%s' parameter".as_ptr(), + c"obs_output_get_last_error".as_ptr(), + c"output".as_ptr(), + ) + } + }); + error.map_or(core::ptr::null(), |error| error.as_ptr().cast_const()) +} diff --git a/rust/obs-output/src/lib.rs b/rust/obs-output/src/lib.rs index 6ba4e379f4..c6f11c351c 100644 --- a/rust/obs-output/src/lib.rs +++ b/rust/obs-output/src/lib.rs @@ -193,6 +193,7 @@ pub mod output_caption; pub mod output_caption_queue; pub mod output_congestion; pub mod output_flags; +pub mod output_get_last_error; pub mod output_handler_getters; pub mod output_identity; pub mod output_last_error; diff --git a/rust/obs-output/src/output_get_last_error.rs b/rust/obs-output/src/output_get_last_error.rs new file mode 100644 index 0000000000..ea7f271935 --- /dev/null +++ b/rust/obs-output/src/output_get_last_error.rs @@ -0,0 +1,64 @@ +//! Safe core of `libobs/obs-output-get-last-error.c.h`: which stored error +//! `obs_output_get_last_error()` borrows. +//! +//! The output's own error comes first, then each video encoder slot in +//! ascending order, then each audio encoder slot in ascending order. The +//! first present error is returned unchanged; an empty or non-UTF-8 string +//! is an error like any other. Every read is lazy, so nothing below a hit +//! is read. The core takes no lock, copies nothing and keeps nothing. + +#![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 crate::output_slots::{MAX_OUTPUT_AUDIO_ENCODERS, MAX_OUTPUT_VIDEO_ENCODERS}; + +/// The C-owned fields of one valid output, each read only when asked. +pub trait LastErrorFields { + /// A present encoder. + type Encoder; + /// A present, borrowed error string. + type Error; + /// The output's own `last_error_message`. + fn own(&mut self) -> Option; + /// The encoder in video slot `idx`, below `MAX_OUTPUT_VIDEO_ENCODERS`. + fn video(&mut self, idx: usize) -> Option; + /// The encoder in audio slot `idx`, below `MAX_OUTPUT_AUDIO_ENCODERS`. + fn audio(&mut self, idx: usize) -> Option; + /// A present encoder's `last_error_message`. + fn encoder_error(&mut self, encoder: Self::Encoder) -> Option; +} + +/// `None` for the output is the NULL output: `log_null` emits +/// `obs_output_valid()`'s diagnostic and no field is read. +pub fn last_error( + output: Option<&mut F>, + log_null: impl FnOnce(), +) -> Option { + let Some(output) = output else { + log_null(); + return None; + }; + if let Some(error) = output.own() { + return Some(error); + } + for idx in 0..MAX_OUTPUT_VIDEO_ENCODERS { + if let Some(error) = output.video(idx).and_then(|e| output.encoder_error(e)) { + return Some(error); + } + } + for idx in 0..MAX_OUTPUT_AUDIO_ENCODERS { + if let Some(error) = output.audio(idx).and_then(|e| output.encoder_error(e)) { + return Some(error); + } + } + None +} diff --git a/rust/obs-output/tests/output/main.rs b/rust/obs-output/tests/output/main.rs index 39496e507d..4304abd8bd 100644 --- a/rust/obs-output/tests/output/main.rs +++ b/rust/obs-output/tests/output/main.rs @@ -98,6 +98,8 @@ mod output_congestion; mod output_congestion_parity; mod output_flags; mod output_flags_parity; +mod output_get_last_error; +mod output_get_last_error_parity; mod output_handler_getters; mod output_handler_getters_parity; mod output_identity; diff --git a/rust/obs-output/tests/output/output_get_last_error.rs b/rust/obs-output/tests/output/output_get_last_error.rs new file mode 100644 index 0000000000..d49b90e6dc --- /dev/null +++ b/rust/obs-output/tests/output/output_get_last_error.rs @@ -0,0 +1,235 @@ +//! Tier 1 mirrors every assertion of the unchanged +//! test/cmocka/test_output_get_last_error.c (#5294) on a recording model of +//! the output's fields. Errors are allocation ids, so equal bytes in +//! independent allocations stay distinguishable, as the C test's pointers do. +use obs_output::output_get_last_error::{LastErrorFields, last_error}; +use obs_output::output_slots::{MAX_OUTPUT_AUDIO_ENCODERS, MAX_OUTPUT_VIDEO_ENCODERS}; + +const V: usize = MAX_OUTPUT_VIDEO_ENCODERS; +const A: usize = MAX_OUTPUT_AUDIO_ENCODERS; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Encoder { + Video(usize), + Audio(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Read { + Own, + Video(usize), + Audio(usize), + Error(Encoder), +} + +/// One allocation: its id and bytes (bytes are never compared by the core). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Error { + id: u32, + bytes: &'static [u8], +} + +struct Model { + next: u32, + own: Option, + video_errors: [Option; V], + audio_errors: [Option; A], + video_slots: [bool; V], + audio_slots: [bool; A], + reads: Vec, +} + +impl Model { + fn new() -> Self { + Self { + next: 0, + own: None, + video_errors: [None; V], + audio_errors: [None; A], + video_slots: [false; V], + audio_slots: [false; A], + reads: Vec::new(), + } + } + /// `obs_*_set_last_error()`: a fresh allocation, or NULL. + fn alloc(&mut self, bytes: Option<&'static [u8]>) -> Option { + bytes.map(|bytes| { + self.next += 1; + Error { + id: self.next, + bytes, + } + }) + } + fn set_own(&mut self, bytes: Option<&'static [u8]>) { + self.own = self.alloc(bytes); + } + fn set_video(&mut self, idx: usize, bytes: Option<&'static [u8]>) { + self.video_errors[idx] = self.alloc(bytes); + } + fn set_audio(&mut self, idx: usize, bytes: Option<&'static [u8]>) { + self.audio_errors[idx] = self.alloc(bytes); + } +} + +impl LastErrorFields for Model { + type Encoder = Encoder; + type Error = Error; + fn own(&mut self) -> Option { + self.reads.push(Read::Own); + self.own + } + fn video(&mut self, idx: usize) -> Option { + self.reads.push(Read::Video(idx)); + self.video_slots[idx].then_some(Encoder::Video(idx)) + } + fn audio(&mut self, idx: usize) -> Option { + self.reads.push(Read::Audio(idx)); + self.audio_slots[idx].then_some(Encoder::Audio(idx)) + } + fn encoder_error(&mut self, encoder: Encoder) -> Option { + self.reads.push(Read::Error(encoder)); + match encoder { + Encoder::Video(idx) => self.video_errors[idx], + Encoder::Audio(idx) => self.audio_errors[idx], + } + } +} + +/// The reads the C makes for this model, ending at the hit if there is one. +fn priority_reads(model: &Model) -> Vec { + let mut reads = vec![Read::Own]; + if model.own.is_some() { + return reads; + } + for idx in 0..V { + reads.push(Read::Video(idx)); + if model.video_slots[idx] { + reads.push(Read::Error(Encoder::Video(idx))); + if model.video_errors[idx].is_some() { + return reads; + } + } + } + for idx in 0..A { + reads.push(Read::Audio(idx)); + if model.audio_slots[idx] { + reads.push(Read::Error(Encoder::Audio(idx))); + if model.audio_errors[idx].is_some() { + return reads; + } + } + } + reads +} + +/// `check_query()`: the borrowed result, no diagnostic for a valid output, +/// and every field read once, in priority order, with nothing after the hit. +fn check_query(model: &mut Model, pick: impl Fn(&Model) -> Option) { + let expected = pick(model); + model.reads.clear(); + let before = ( + model.own, + model.video_errors, + model.audio_errors, + model.video_slots, + model.audio_slots, + ); + let mut logs = 0; + let actual = last_error(Some(&mut *model), || logs += 1); + assert_eq!(actual, expected); + assert_eq!(logs, 0); + assert_eq!(model.reads, priority_reads(model)); + let after = ( + model.own, + model.video_errors, + model.audio_errors, + model.video_slots, + model.audio_slots, + ); + assert_eq!(after, before, "the query changed a field"); +} + +#[test] +fn null_diagnostic() { + let mut logs = 0; + assert_eq!(last_error::(None, || logs += 1), None); + assert_eq!(logs, 1); +} + +#[test] +fn fallback_order_and_borrowing() { + let mut m = Model::new(); + check_query(&mut m, |_| None); + // Every slot attached; present encoders with NULL errors are skipped. + m.video_slots = [true; V]; + m.audio_slots = [true; A]; + check_query(&mut m, |_| None); + // Equal bytes in independent allocations. + for idx in 0..A { + m.set_audio(idx, Some(b"same error")); + } + for idx in 0..V { + m.set_video(idx, Some(b"same error")); + } + m.set_own(Some(b"same error")); + check_query(&mut m, |m| m.own); + // Empty strings are errors, not fallback. + m.set_own(Some(b"")); + check_query(&mut m, |m| m.own); + m.set_own(None); + for idx in 0..V { + check_query(&mut m, |m| m.video_errors[idx]); + m.set_video(idx, Some(b"")); + check_query(&mut m, |m| m.video_errors[idx]); + m.set_video(idx, None); + let next = if idx + 1 < V { + m.video_errors[idx + 1] + } else { + m.audio_errors[0] + }; + check_query(&mut m, |_| next); + m.video_slots[idx] = false; + } + for idx in 0..A { + check_query(&mut m, |m| m.audio_errors[idx]); + m.set_audio(idx, Some(b"")); + check_query(&mut m, |m| m.audio_errors[idx]); + m.set_audio(idx, None); + let next = if idx + 1 < A { + m.audio_errors[idx + 1] + } else { + None + }; + check_query(&mut m, |_| next); + m.audio_slots[idx] = false; + } + check_query(&mut m, |_| None); + // Last-slot errors with holes before them, including non-UTF-8 bytes. + let bytes: &'static [u8] = &[0xff, 0x80, b'x']; + m.video_slots[V - 1] = true; + m.audio_slots[A - 1] = true; + m.set_video(V - 1, Some(bytes)); + m.set_audio(A - 1, Some(bytes)); + // The core has no lock to take: the C test's held encoder mutexes + // cannot be reached from here, so no added locking is possible. + check_query(&mut m, |m| m.video_errors[V - 1]); + assert_eq!(m.video_errors[V - 1].map(|e| e.bytes), Some(bytes)); + m.video_slots[V - 1] = false; + check_query(&mut m, |m| m.audio_errors[A - 1]); + m.audio_slots[A - 1] = false; + check_query(&mut m, |_| None); +} + +#[test] +fn encoder_errors_without_an_attached_slot_are_never_read() { + let mut m = Model::new(); + for idx in 0..V { + m.set_video(idx, Some(b"detached")); + } + for idx in 0..A { + m.set_audio(idx, Some(b"detached")); + } + check_query(&mut m, |_| None); + assert!(!m.reads.iter().any(|r| matches!(r, Read::Error(_)))); +} diff --git a/rust/obs-output/tests/output/output_get_last_error_parity.rs b/rust/obs-output/tests/output/output_get_last_error_parity.rs new file mode 100644 index 0000000000..941589f0d4 --- /dev/null +++ b/rust/obs-output/tests/output/output_get_last_error_parity.rs @@ -0,0 +1,263 @@ +//! Tier 3: the unchanged extracted `libobs/obs-output-get-last-error.c.h` +//! against the Rust ABI, both over one real private output and encoder +//! layout. The Rust side reads through the production field adapters, which +//! are checked to address exactly the fields the original reads. Mutants of +//! the query run through the same harness and must be caught. No +//! intentional differences; no input exclusions. +#![allow(unsafe_code)] +use core::ffi::{c_char, c_void}; +use obs_output::ffi::encoder_last_error::LastErrorFields as EncoderFields; +use obs_output::ffi::output_get_last_error::obs_output_get_last_error; +use obs_output::output_slots::{MAX_OUTPUT_AUDIO_ENCODERS, MAX_OUTPUT_VIDEO_ENCODERS}; +use proptest::prelude::*; + +const V: usize = MAX_OUTPUT_VIDEO_ENCODERS; +const A: usize = MAX_OUTPUT_AUDIO_ENCODERS; +const FIELDS: usize = 1 + V + A; +/// NULL, "same error", "", non-UTF-8 bytes (the oracle's `enum ogle_kind`). +const KINDS: u8 = 4; +const SAME: u8 = 1; +const EMPTY: u8 = 2; + +type Getter = unsafe extern "C" fn(*mut c_void) -> *const c_char; +unsafe extern "C" { + fn oracle_obs_output_get_last_error(output: *mut c_void) -> *const c_char; + fn oracle_output_get_last_error_new(kinds: *const u8, video: u32, audio: u32) -> *mut c_void; + fn oracle_output_get_last_error_storage(fixture: *const c_void, field: usize) -> *const c_char; + fn oracle_output_get_last_error_unchanged(fixture: *const c_void) -> bool; + fn oracle_output_get_last_error_free(fixture: *mut c_void); + fn oracle_output_get_last_error_layout(out: *mut usize); + fn oracle_output_get_last_error_adapters(fixture: *mut c_void) -> bool; + fn oracle_output_get_last_error_null_log(getter: Getter) -> bool; + // The production adapters the shim reads through, for the mutants. + fn obs_output_last_error_fields(output: *mut c_void) -> *mut *mut c_char; + fn obs_output_video_encoder_getter_at(output: *const c_void, idx: usize) -> *mut c_void; + fn obs_output_encoder_getters_audio_at(output: *const c_void, idx: usize) -> *mut c_void; + fn obs_encoder_last_error_fields(encoder: *mut c_void) -> EncoderFields; +} + +struct Fixture(*mut c_void); +impl Fixture { + fn new(kinds: &[u8; FIELDS], video: u32, audio: u32) -> Self { + // SAFETY: kinds has one entry per field; the oracle allocates the + // real output and encoder layouts with independent message storage. + let fixture = unsafe { oracle_output_get_last_error_new(kinds.as_ptr(), video, audio) }; + assert!(!fixture.is_null()); + Self(fixture) + } + /// The field whose storage `result` is, if any: identity, never a copy. + fn field_of(&self, result: *const c_char) -> Option { + // SAFETY: the live fixture; every field index is in range. + (0..FIELDS).find(|&f| unsafe { oracle_output_get_last_error_storage(self.0, f) } == result) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + // SAFETY: the fixture owns all of its storage; nothing borrows it now. + unsafe { oracle_output_get_last_error_free(self.0) } + } +} + +/// The field the original returns for this input, or `None` when it is NULL. +fn outcome(getter: Getter, kinds: &[u8; FIELDS], video: u32, audio: u32) -> Option { + let fixture = Fixture::new(kinds, video, audio); + // SAFETY: a live, non-NULL fixture whose slots hold its own encoders. + let result = unsafe { getter(fixture.0) }; + // SAFETY: as above; the query must leave every field and byte unchanged. + assert!(unsafe { oracle_output_get_last_error_unchanged(fixture.0) }); + let field = fixture.field_of(result); + assert!( + result.is_null() || field.is_some(), + "result is not borrowed" + ); + field +} + +fn check(kinds: &[u8; FIELDS], video: u32, audio: u32) { + let fixture = Fixture::new(kinds, video, audio); + // SAFETY: the real-layout adapters of the live fixture. + assert!(unsafe { oracle_output_get_last_error_adapters(fixture.0) }); + drop(fixture); + for _ in 0..2 { + assert_eq!( + outcome(obs_output_get_last_error, kinds, video, audio), + outcome(oracle_obs_output_get_last_error, kinds, video, audio), + "kinds {kinds:?}, video {video:#x}, audio {audio:#x}" + ); + } +} + +/// Characterized shapes: every kind at every field alone, in each slot +/// arrangement, plus the C test's "all equal bytes" and "holes" layouts. +fn characterized() -> Vec<([u8; FIELDS], u32, u32)> { + let masks = [ + (0, 0), + (u32::MAX, u32::MAX), + (1 << (V - 1), 1 << (A - 1)), + (0b10_1010, 0b01_0101), + ]; + let mut cases = Vec::new(); + for (video, audio) in masks { + for field in 0..FIELDS { + for kind in 0..KINDS { + let mut kinds = [0; FIELDS]; + kinds[field] = kind; + cases.push((kinds, video, audio)); + } + } + cases.push(([SAME; FIELDS], video, audio)); + let mut empty_first = [SAME; FIELDS]; + empty_first[0] = 0; + empty_first[1] = EMPTY; + cases.push((empty_first, video, audio)); + let mut audio_only = [0; FIELDS]; + audio_only[1 + V..].fill(SAME); + cases.push((audio_only, video, audio)); + } + cases +} + +#[test] +fn slot_counts_match_the_c_build() { + let mut layout = [0usize; 3]; + // SAFETY: the oracle writes exactly three values. + unsafe { oracle_output_get_last_error_layout(layout.as_mut_ptr()) }; + assert_eq!(layout, [V, A, FIELDS]); +} + +#[test] +fn characterized_edges() { + for (kinds, video, audio) in characterized() { + check(&kinds, video, audio); + } +} + +#[test] +fn exact_null_diagnostic_without_allocation() { + if !super::isolated(concat!( + module_path!(), + "::exact_null_diagnostic_without_allocation" + )) { + return; + } + // SAFETY: the isolated child owns the log handler and allocator counter. + unsafe { + assert!(oracle_output_get_last_error_null_log( + oracle_obs_output_get_last_error + )); + assert!(oracle_output_get_last_error_null_log( + obs_output_get_last_error + )); + let fixture = Fixture::new(&[SAME; FIELDS], u32::MAX, u32::MAX); + let baseline = obs_util::ffi::bmem::bnum_allocs(); + assert!(!obs_output_get_last_error(fixture.0).is_null()); + assert_eq!(obs_util::ffi::bmem::bnum_allocs(), baseline); + } +} + +#[derive(Clone, Copy, Debug)] +enum Mutant { + SkipsOwnError, + AudioBeforeVideo, + DescendingSlots, + EmptyIsMissing, + Copies, +} + +thread_local! { + static COPY: core::cell::RefCell<[u8; 16]> = const { core::cell::RefCell::new([0; 16]) }; +} + +/// A wrong query over the same production adapters. +unsafe fn mutant(kind: Mutant, output: *mut c_void) -> *const c_char { + // SAFETY: the caller passes a live fixture; every index is in range. + unsafe { + let error = |encoder: *mut c_void| -> *const c_char { + if encoder.is_null() { + core::ptr::null() + } else { + *obs_encoder_last_error_fields(encoder).message + } + }; + let present = |message: *const c_char| { + !message.is_null() && !(matches!(kind, Mutant::EmptyIsMissing) && *message == 0) + }; + let own = *obs_output_last_error_fields(output); + if !matches!(kind, Mutant::SkipsOwnError) && present(own) { + return own; + } + let video = |idx| error(obs_output_video_encoder_getter_at(output, idx)); + let audio = |idx| error(obs_output_encoder_getters_audio_at(output, idx)); + let mut order: Vec<*const c_char> = Vec::new(); + let videos: Vec<_> = if matches!(kind, Mutant::DescendingSlots) { + (0..V).rev().map(video).collect() + } else { + (0..V).map(video).collect() + }; + let audios: Vec<_> = (0..A).map(audio).collect(); + if matches!(kind, Mutant::AudioBeforeVideo) { + order.extend(audios); + order.extend(videos); + } else { + order.extend(videos); + order.extend(audios); + } + let found = order + .into_iter() + .find(|&m| present(m)) + .unwrap_or(core::ptr::null()); + if matches!(kind, Mutant::Copies) && !found.is_null() { + return COPY.with(|copy| { + let mut copy = copy.borrow_mut(); + let bytes = core::ffi::CStr::from_ptr(found).to_bytes_with_nul(); + copy[..bytes.len()].copy_from_slice(bytes); + copy.as_ptr().cast() + }); + } + found + } +} + +macro_rules! mutant_getter { + ($name:ident, $kind:expr) => { + unsafe extern "C" fn $name(output: *mut c_void) -> *const c_char { + // SAFETY: forwarded from the harness, which passes a live fixture. + unsafe { mutant($kind, output) } + } + }; +} +mutant_getter!(skips_own_error, Mutant::SkipsOwnError); +mutant_getter!(audio_before_video, Mutant::AudioBeforeVideo); +mutant_getter!(descending_slots, Mutant::DescendingSlots); +mutant_getter!(empty_is_missing, Mutant::EmptyIsMissing); +mutant_getter!(copies, Mutant::Copies); + +#[test] +fn mutants_are_caught() { + let mutants: [(&str, Getter); 5] = [ + ("skips own error", skips_own_error), + ("audio before video", audio_before_video), + ("descending slots", descending_slots), + ("empty is missing", empty_is_missing), + ("copies", copies), + ]; + for (name, getter) in mutants { + let caught = characterized().iter().any(|(kinds, video, audio)| { + std::panic::catch_unwind(|| { + outcome(getter, kinds, *video, *audio) + != outcome(oracle_obs_output_get_last_error, kinds, *video, *audio) + }) + .unwrap_or(true) + }); + assert!(caught, "mutant {name} survived the characterized cases"); + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(256), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn random_fields_and_slots(kinds in prop::collection::vec(0..KINDS, FIELDS), video in any::(), audio in any::()) { + let kinds: [u8; FIELDS] = kinds.try_into().unwrap(); + check(&kinds, video, audio); + } +} diff --git a/test/cmocka/build/rust-static-support.json b/test/cmocka/build/rust-static-support.json index 6b46e56423..cad35dac65 100644 --- a/test/cmocka/build/rust-static-support.json +++ b/test/cmocka/build/rust-static-support.json @@ -35,7 +35,9 @@ "test/cmocka/graphics-indexbuffer-maintenance-link-support.c", "test/cmocka/encoder-get-name-link-support.c", "test/cmocka/output-interleave-name-link-support.c", - "test/cmocka/graphics-device-queries-link-support.c" + "test/cmocka/graphics-device-queries-link-support.c", + "test/cmocka/output-encoder-getters-link-support.c", + "test/cmocka/encoder-last-error-link-support.c" ], "platform_sources": { "OS_WINDOWS": [ diff --git a/test/cmocka/encoder-last-error-link-support.c b/test/cmocka/encoder-last-error-link-support.c new file mode 100644 index 0000000000..4a4d249bf0 --- /dev/null +++ b/test/cmocka/encoder-last-error-link-support.c @@ -0,0 +1,2 @@ +/* Real private adapter for standalone Rust archive consumers. */ +#include "libobs/obs-encoder-last-error-fields.c.h" diff --git a/test/cmocka/output-encoder-getters-link-support.c b/test/cmocka/output-encoder-getters-link-support.c new file mode 100644 index 0000000000..d32c232429 --- /dev/null +++ b/test/cmocka/output-encoder-getters-link-support.c @@ -0,0 +1,2 @@ +/* Real private adapter for standalone Rust archive consumers. */ +#include "libobs/obs-output-encoder-getters-fields.c.h"