From c4a3e11875b7d4812bfd87ab4e33d2562e9926bd Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Mon, 23 Nov 2026 00:11:47 -0500 Subject: [PATCH 1/2] obs-core: RED Tier 1 mirrors of obs_set_audio_monitoring_device (Refs #5491) Safe mirrors of every case of the unchanged test_set_audio_monitoring_device.c over a model core (stored name and id, live monitors that remember the device each reset put them on, public and private sources with output flags and a device_id, and a model of the deduplication signal their notices drive): a reset with no monitors touches nothing; each live monitor is reset once per reset; a new device is stored by copy and resets every monitor onto it; the same id keeps the old name, resets nothing and tells nobody; every public Audio Output Capture source is told with its own device_id, which starts and stops the deduplication as in the C test. Plus the refusals of test_monitoring_device and what the C test cannot see: NULL or empty name or id refused before any other step, availability next, then lock, compare, copies, unlock, the resets under their own lock and availability check, and one notice per capture source in enumeration order. Against a todo!() core: soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring_device:: test result: FAILED. 0 passed; 10 failed Co-Authored-By: Claude Opus 5.5 --- rust/obs-core/src/audio_monitoring_device.rs | 91 ++++ rust/obs-core/src/lib.rs | 1 + .../tests/obs_core/audio_monitoring_device.rs | 472 ++++++++++++++++++ rust/obs-core/tests/obs_core/main.rs | 1 + 4 files changed, 565 insertions(+) create mode 100644 rust/obs-core/src/audio_monitoring_device.rs create mode 100644 rust/obs-core/tests/obs_core/audio_monitoring_device.rs diff --git a/rust/obs-core/src/audio_monitoring_device.rs b/rust/obs-core/src/audio_monitoring_device.rs new file mode 100644 index 0000000000..6566df5c42 --- /dev/null +++ b/rust/obs-core/src/audio_monitoring_device.rs @@ -0,0 +1,91 @@ +//! Safe core of `libobs/obs-audio-monitoring-device.c.h`: +//! `obs_set_audio_monitoring_device()` and `obs_reset_audio_monitoring()` +//! (#5491). +//! +//! Setting the device refuses, before anything else, a missing name, a +//! missing id, an empty name and an empty id, asked in that order through +//! [`monitor_missing`]; then refuses when monitoring is unavailable. Under +//! the monitoring mutex an id equal to the stored one +//! ([`monitor_same`] of the `strcmp()`) unlocks and answers true with +//! nothing changed. Otherwise the stored name and id are replaced by copies, +//! the mutex is released, every live monitor is reset +//! ([`reset_monitoring`]), and each source the core enumerates is offered to +//! [`aoc_source`], which tells an Audio Output Capture source +//! ([`aoc_check`] of its output flags) about the change with its own +//! `device_id` setting. +//! +//! Resetting does nothing when monitoring is unavailable; otherwise it +//! resets each live monitor once under the monitoring mutex, reading the +//! monitor count again before each step, as the C loop does. +//! +//! The monitoring fields, their mutex and copies, the monitor list, +//! `audio_monitor_reset()`, the source enumeration and the notice stay with +//! the caller ([`Monitors`], [`Device`]). + +#![deny( + clippy::arithmetic_side_effects, + clippy::as_conversions, + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + +/// The live monitors as `obs_reset_audio_monitoring()` sees them: +/// `obs_audio_monitoring_available()`, `obs->audio.monitoring_mutex`, +/// `monitors.num` and `audio_monitor_reset(monitors.array[i])`. +pub trait Monitors { + /// One call of `obs_audio_monitoring_available()`. + fn available(&mut self) -> bool; + fn lock(&mut self); + fn unlock(&mut self); + /// One read of `monitors.num`. + fn count(&mut self) -> usize; + /// Reset monitor `index`, for `index < count()`. + fn reset(&mut self, index: usize); +} + +/// The stored device and the sources, as `obs_set_audio_monitoring_device()` +/// sees them. +pub trait Device: Monitors { + /// A caller's `const char *`, non-NULL. + type Str: Copy; + /// An `obs_source_t *` the enumeration hands over. + type Source: Copy; + /// `*s == '\0'`. + fn empty(&mut self, s: Self::Str) -> bool; + /// `strcmp(id, obs->audio.monitoring_device_id)`. + fn compare(&mut self, id: Self::Str) -> i32; + /// Free the stored name and id, then store copies of `name` and `id`. + fn store(&mut self, name: Self::Str, id: Self::Str); + /// `obs_enum_sources()`: hand each source to [`aoc_source`] in order, + /// stopping at the first false. + fn enum_sources(&mut self); + /// `source->info.output_flags`. + fn output_flags(&mut self, source: Self::Source) -> u32; + /// Tell `source` about the new device with its own `device_id` setting. + fn notify(&mut self, source: Self::Source); +} + +/// `obs_reset_audio_monitoring()`. +pub fn reset_monitoring(_monitors: &mut M) { + todo!() +} + +/// The enumeration callback: tell an Audio Output Capture source; always +/// continue. +pub fn aoc_source(_device: &mut D, _source: D::Source) -> bool { + todo!() +} + +/// `obs_set_audio_monitoring_device(name, id)`; `None` is NULL. +pub fn set_device( + _device: &mut D, + _name: Option, + _id: Option, +) -> bool { + todo!() +} diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index 39e1921c3c..1b7f1cf561 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -119,6 +119,7 @@ pub mod audio_discard; pub mod audio_info_queries; pub mod audio_min_ts; pub mod audio_mix; +pub mod audio_monitoring_device; pub mod audio_render; pub mod base_effect; pub mod canvas_channel_getter; diff --git a/rust/obs-core/tests/obs_core/audio_monitoring_device.rs b/rust/obs-core/tests/obs_core/audio_monitoring_device.rs new file mode 100644 index 0000000000..c28f84b8e8 --- /dev/null +++ b/rust/obs-core/tests/obs_core/audio_monitoring_device.rs @@ -0,0 +1,472 @@ +//! Safe mirrors of test_set_audio_monitoring_device.c (and the refusals of +//! test_core_setup_rules_steps' test_monitoring_device) over a model core: +//! a stored name and id it owns, live monitors that remember the device each +//! reset put them on, and public and private sources with output flags and a +//! `device_id` setting, whose notices drive a model of the deduplication +//! signal (a capture of `.monitor` starts it, the deduplicating source +//! that no longer matches stops it). Plus what the C test cannot see: the +//! refusals come before any other step, availability next, then the lock, +//! the compare, the copies, the unlock, the resets under their own lock and +//! one notice per Audio Output Capture source in enumeration order. +use obs_core::audio_monitoring_device::{ + Device, Monitors, aoc_source, reset_monitoring, set_device, +}; +use obs_core::core_setup_rules::DO_NOT_SELF_MONITOR; + +const AUDIO: u32 = 1 << 1; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Step { + Empty(String), + Available, + Lock, + Unlock, + Compare(String), + Store(String, String), + Count, + Reset(usize), + Enum, + Flags(usize), + Notify(usize, String), +} + +struct Source { + flags: u32, + device_id: &'static str, + public: bool, +} + +struct Model { + available: bool, + name: String, + id: String, + locked: bool, + /// The device each monitor was last reset onto, and how often. + monitors: Vec<(String, usize)>, + sources: Vec, + duplicating: Option, + signals: Vec>, + steps: Vec, +} + +impl Model { + fn new() -> Self { + Self { + available: true, + name: "Default".into(), + id: "default".into(), + locked: false, + monitors: Vec::new(), + sources: Vec::new(), + duplicating: None, + signals: Vec::new(), + steps: Vec::new(), + } + } + + fn with_monitors(count: usize) -> Self { + let mut model = Self::new(); + model.monitors = vec![(String::new(), 0); count]; + model + } + + /// The caller's strings live on (leaked, a few bytes per call), as a C + /// caller's do for the call; the model stores its own copies. + fn set(&mut self, name: Option<&str>, id: Option<&str>) -> bool { + set_device(self, name.map(leak), id.map(leak)) + } + + fn device(&self) -> (&str, &str) { + (&self.name, &self.id) + } + + fn resets(&self) -> Vec { + self.monitors.iter().map(|(_, n)| *n).collect() + } + + fn take_steps(&mut self) -> Vec { + core::mem::take(&mut self.steps) + } +} + +impl Monitors for Model { + fn available(&mut self) -> bool { + self.steps.push(Step::Available); + self.available + } + fn lock(&mut self) { + assert!(!self.locked, "the monitoring mutex is not recursive here"); + self.locked = true; + self.steps.push(Step::Lock); + } + fn unlock(&mut self) { + assert!(self.locked); + self.locked = false; + self.steps.push(Step::Unlock); + } + fn count(&mut self) -> usize { + assert!(self.locked, "the monitor list is read under the lock"); + self.steps.push(Step::Count); + self.monitors.len() + } + fn reset(&mut self, index: usize) { + assert!(self.locked, "monitors are reset under the lock"); + self.steps.push(Step::Reset(index)); + let id = self.id.clone(); + let monitor = &mut self.monitors[index]; + monitor.0 = id; + monitor.1 += 1; + } +} + +impl Device for Model { + type Str = &'static str; + type Source = usize; + fn empty(&mut self, s: &'static str) -> bool { + self.steps.push(Step::Empty(s.into())); + s.is_empty() + } + fn compare(&mut self, id: &'static str) -> i32 { + assert!(self.locked, "the stored id is compared under the lock"); + self.steps.push(Step::Compare(id.into())); + match id.cmp(self.id.as_str()) { + core::cmp::Ordering::Less => -1, + core::cmp::Ordering::Equal => 0, + core::cmp::Ordering::Greater => 1, + } + } + fn store(&mut self, name: &'static str, id: &'static str) { + assert!(self.locked, "the copies are stored under the lock"); + self.steps.push(Step::Store(name.into(), id.into())); + self.name = name.into(); + self.id = id.into(); + } + fn enum_sources(&mut self) { + assert!(!self.locked, "sources are enumerated after the unlock"); + self.steps.push(Step::Enum); + let public: Vec = (0..self.sources.len()) + .filter(|&i| self.sources[i].public) + .collect(); + for index in public { + if !aoc_source(self, index) { + break; + } + } + } + fn output_flags(&mut self, source: usize) -> u32 { + self.steps.push(Step::Flags(source)); + self.sources[source].flags + } + fn notify(&mut self, source: usize) { + let device_id = self.sources[source].device_id; + self.steps.push(Step::Notify(source, device_id.into())); + if device_id == format!("{}.monitor", self.id) { + self.signals.push(Some(source)); + self.duplicating = Some(source); + } else if self.duplicating == Some(source) { + self.signals.push(None); + self.duplicating = None; + } + } +} + +fn s(text: &str) -> String { + text.into() +} + +fn leak(text: &str) -> &'static str { + Box::leak(text.to_owned().into_boxed_str()) +} + +#[test] +fn reset_without_monitors_is_noop() { + let mut model = Model::new(); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + model.take_steps(); + reset_monitoring(&mut model); + reset_monitoring(&mut model); + let once = [Step::Available, Step::Lock, Step::Count, Step::Unlock]; + assert_eq!(model.take_steps(), [once.clone(), once].concat()); + assert_eq!(model.device(), ("Sink A", "sink_a")); +} + +#[test] +fn reset_resets_each_live_monitor_once() { + let mut model = Model::with_monitors(2); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + assert_eq!(model.resets(), [1, 1]); + reset_monitoring(&mut model); + assert_eq!(model.resets(), [2, 2]); + reset_monitoring(&mut model); + assert_eq!(model.resets(), [3, 3]); + assert!(model.monitors.iter().all(|(device, _)| device == "sink_a")); + assert_eq!(model.device(), ("Sink A", "sink_a")); +} + +#[test] +fn new_device_is_copied_and_resets_monitors() { + let mut model = Model::with_monitors(2); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + let mut name = String::from("Sink B"); + let mut id = String::from("sink_b"); + assert!(model.set(Some(&name), Some(&id))); + assert_eq!(model.resets(), [2, 2]); + assert!(model.monitors.iter().all(|(device, _)| device == "sink_b")); + // The core keeps its own copies, not the caller's storage. + name.replace_range(.., "Overwritten"); + id.replace_range(.., "overwritten"); + assert_eq!(model.device(), ("Sink B", "sink_b")); + // A later reset uses the stored id. + reset_monitoring(&mut model); + assert_eq!(model.resets(), [3, 3]); + assert!(model.monitors.iter().all(|(device, _)| device == "sink_b")); +} + +#[test] +fn same_device_keeps_name_and_resets_nothing() { + let mut model = Model::with_monitors(1); + model.sources.push(Source { + flags: AUDIO | DO_NOT_SELF_MONITOR, + device_id: "sink_a.monitor", + public: true, + }); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + let resets = model.resets(); + model.signals.clear(); + model.take_steps(); + assert!(model.set(Some("Renamed"), Some("sink_a"))); + assert_eq!(model.device(), ("Sink A", "sink_a")); + assert_eq!(model.resets(), resets); + assert!(model.signals.is_empty()); + assert_eq!( + model.take_steps(), + [ + Step::Empty(s("Renamed")), + Step::Empty(s("sink_a")), + Step::Available, + Step::Lock, + Step::Compare(s("sink_a")), + Step::Unlock, + ] + ); +} + +#[test] +fn aoc_sources_told_with_their_device_id() { + let mut model = Model::new(); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + let aoc = AUDIO | DO_NOT_SELF_MONITOR; + for (flags, device_id, public) in [ + (aoc, "sink_b.monitor", true), + (aoc, "sink_c.monitor", true), + (AUDIO, "sink_b.monitor", true), + (aoc, "sink_b.monitor", false), + ] { + model.sources.push(Source { + flags, + device_id, + public, + }); + } + let (aoc_b, aoc_c) = (0, 1); + + // Only the public capture source of the new device starts it. + assert!(model.set(Some("Sink B"), Some("sink_b"))); + assert_eq!(model.signals, [Some(aoc_b)]); + + // aoc b no longer matches and was deduplicating: it stops it; then aoc + // c, which matches, starts it. + model.signals.clear(); + assert!(model.set(Some("Sink C"), Some("sink_c"))); + assert_eq!(model.signals, [None, Some(aoc_c)]); + + // No capture source matches: only the deduplicating one is stopped. + model.signals.clear(); + assert!(model.set(Some("Sink D"), Some("sink_d"))); + assert_eq!(model.signals, [None]); + + // Neither is deduplicating any more: a new id tells nobody. + model.signals.clear(); + model.take_steps(); + assert!(model.set(Some("Sink A"), Some("sink_a"))); + assert!(model.signals.is_empty()); + + // Every public source is asked for its flags; only the two capture + // sources are told, each with its own device_id, in enumeration order. + let steps = model.take_steps(); + let tail = steps + .iter() + .skip_while(|step| **step != Step::Enum) + .cloned() + .collect::>(); + assert_eq!( + tail, + [ + Step::Enum, + Step::Flags(0), + Step::Notify(0, s("sink_b.monitor")), + Step::Flags(1), + Step::Notify(1, s("sink_c.monitor")), + Step::Flags(2), + ] + ); +} + +#[test] +fn missing_or_empty_name_or_id_refused_before_anything() { + let cases: [(Option<&str>, Option<&str>, Vec); 6] = [ + (None, Some("sink"), vec![]), + (Some("Sink"), None, vec![]), + (None, None, vec![]), + (Some(""), Some("sink"), vec![Step::Empty(s(""))]), + ( + Some("Sink"), + Some(""), + vec![Step::Empty(s("Sink")), Step::Empty(s(""))], + ), + (Some(""), Some(""), vec![Step::Empty(s(""))]), + ]; + for (name, id, steps) in cases { + let mut model = Model::with_monitors(1); + assert!(!model.set(name, id), "{name:?} {id:?}"); + assert_eq!(model.take_steps(), steps, "{name:?} {id:?}"); + assert_eq!(model.device(), ("Default", "default")); + assert_eq!(model.resets(), [0]); + } +} + +#[test] +fn unavailable_monitoring_refused_after_the_checks() { + let mut model = Model::with_monitors(1); + model.available = false; + assert!(!model.set(Some("Sink"), Some("sink"))); + assert_eq!( + model.take_steps(), + [ + Step::Empty(s("Sink")), + Step::Empty(s("sink")), + Step::Available + ] + ); + assert_eq!(model.device(), ("Default", "default")); + + reset_monitoring(&mut model); + assert_eq!(model.take_steps(), [Step::Available]); + assert_eq!(model.resets(), [0]); +} + +#[test] +fn new_device_runs_every_step_in_order() { + let mut model = Model::with_monitors(2); + model.sources.push(Source { + flags: AUDIO | DO_NOT_SELF_MONITOR, + device_id: "x", + public: true, + }); + model.sources.push(Source { + flags: AUDIO, + device_id: "y", + public: true, + }); + assert!(model.set(Some("Name"), Some("id"))); + assert_eq!( + model.take_steps(), + [ + Step::Empty(s("Name")), + Step::Empty(s("id")), + Step::Available, + Step::Lock, + Step::Compare(s("id")), + Step::Store(s("Name"), s("id")), + Step::Unlock, + Step::Available, + Step::Lock, + Step::Count, + Step::Reset(0), + Step::Count, + Step::Reset(1), + Step::Count, + Step::Unlock, + Step::Enum, + Step::Flags(0), + Step::Notify(0, s("x")), + Step::Flags(1), + ] + ); +} + +#[test] +fn monitoring_lost_between_store_and_reset_skips_the_resets() { + // Availability is asked again by the reset, as the C calls + // obs_reset_audio_monitoring(): the store stands, no monitor is reset, + // and the sources are still told. + struct Flaky(Model, usize); + impl Monitors for Flaky { + fn available(&mut self) -> bool { + self.1 += 1; + self.0.steps.push(Step::Available); + self.1 == 1 + } + fn lock(&mut self) { + self.0.lock(); + } + fn unlock(&mut self) { + self.0.unlock(); + } + fn count(&mut self) -> usize { + self.0.count() + } + fn reset(&mut self, index: usize) { + self.0.reset(index); + } + } + impl Device for Flaky { + type Str = &'static str; + type Source = usize; + fn empty(&mut self, s: &'static str) -> bool { + self.0.empty(s) + } + fn compare(&mut self, id: &'static str) -> i32 { + self.0.compare(id) + } + fn store(&mut self, name: &'static str, id: &'static str) { + self.0.store(name, id); + } + fn enum_sources(&mut self) { + self.0.enum_sources(); + } + fn output_flags(&mut self, source: usize) -> u32 { + self.0.output_flags(source) + } + fn notify(&mut self, source: usize) { + self.0.notify(source); + } + } + let mut flaky = Flaky(Model::with_monitors(1), 0); + assert!(set_device(&mut flaky, Some("N"), Some("i"))); + assert_eq!(flaky.0.device(), ("N", "i")); + assert_eq!(flaky.0.resets(), [0]); + assert_eq!(flaky.1, 2); + assert_eq!(flaky.0.steps.last(), Some(&Step::Enum)); +} + +#[test] +fn aoc_source_always_continues() { + let mut model = Model::new(); + model.sources.push(Source { + flags: 0, + device_id: "a", + public: true, + }); + model.sources.push(Source { + flags: DO_NOT_SELF_MONITOR, + device_id: "b", + public: true, + }); + assert!(aoc_source(&mut model, 0)); + assert!(aoc_source(&mut model, 1)); + assert_eq!( + model.take_steps(), + [Step::Flags(0), Step::Flags(1), Step::Notify(1, s("b"))] + ); +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 1da1d75437..77f5d20479 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -15,6 +15,7 @@ mod audio_min_ts; mod audio_min_ts_parity; mod audio_mix; mod audio_mix_parity; +mod audio_monitoring_device; mod audio_render; mod audio_render_parity; mod base_effect; From 173c3f5f9f51fd7dab24e0a0b02ab2fae9dc8ade Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Mon, 23 Nov 2026 00:36:33 -0500 Subject: [PATCH 2/2] obs-core: swap obs_set_audio_monitoring_device and obs_reset_audio_monitoring to Rust (Refs #5491) Both now come from obs-core in hybrid libobs. The safe core decides the order: a NULL name, NULL id, empty name and empty id are refused, in that order through core_setup_rules::monitor_missing, before anything else; then unavailable monitoring is refused; under monitoring_mutex the same id (monitor_same of the strcmp) unlocks and answers true; otherwise the stored name and id are replaced by copies, the mutex is released, every live monitor is reset (obs_reset_audio_monitoring, which asks for availability again and reads the count before each step under the mutex), and each enumerated source whose flags pass aoc_check is told with its own device_id. The fields, mutex, bmem copies, monitor list, audio_monitor_reset, obs_enum_sources and the notice stay C behind private adapters (obs-audio-monitoring-device-fields.c.h, in the core group). The original moves to libobs.ported-audio-monitoring-device for the C reference. Tier 3 runs the original and the shims on one recording real-header core (oracle/audio_monitoring_device.c) over fixed and proptest names, ids, stored ids, availability, up to eight monitors and up to eight sources: the result, the trace of every core read, availability check, lock, compare, free, copy, reset, enumeration and per-source settings read, notice and release, and the stored strings. Ten mutants are caught. soldr cargo test -p obs-data --test obs-tests-core -- audio_monitoring_device test result: ok. 16 passed; 0 failed Mutation of the safe core (notify every source; store after the unlock): 11 passed; 5 failed and 7 passed; 9 failed. OBS_CTEST_JOBS=10 uv run rust/tools/linux-validate/run.py --repeat 2 \ --tests test_set_audio_monitoring_device,test_core_setup_rules_steps,test_pulse_monitor_reset 100% tests passed, 0 tests failed out of 1086 (C reference and hybrid) Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795412414,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":98,"stamp":"2b0a9dd9ef9bd6ee2eb8304f4c1da972","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412414,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":98,"stamp":"000cd0b5d55454863f2e09822db9acdd","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412414,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":98,"stamp":"b3506ee49e4b6a17968e6dc3e917e788","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412414,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":98,"stamp":"60991024640a501a7917a6dbfc41b5ee","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"general/all/client-lint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"4ff658d4ee8a4746225228d36dff7292","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412414,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":98,"stamp":"f34ed47a7b90ccea282f301a7e523734","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"a642f540d732b56f8946f14d5db65b2c","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"310429cfa115be903f0a6cc5f75b8167","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"6811fa130ce827029ba4192770f165b3","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"9b08980821f6a01818e9bac868b7f7cd","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"1af9f1b511c1cd63eb9d39ddcdc3fc07","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"91a476ad000387c378b7d5b7d66938a3","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"21532ac34d9199bdb61d152ab8819773","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"ab8e1f3477e830e1001cb749490d1c7f","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"6f02e31093eb207c6ddb18186ceff741","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412316,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"0ee6b6aad162b35bbb0f7c630a5fcbfb","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"957f8fefdc6c971ef4f691cfdfc08ec7","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412315,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"8e255b387583e1072a8e3b3c2f730d421d80f5061881f7b402dfe24fa9e56ed7","lane":"client-lint","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":8,"stamp":"0228308aaaf1383923ffde624834cb56","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Ci-Attestation: {"at":1795412629,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"7ebec0a08939587d99dca18e5aa31acd2914b84e4fbc27e0ef7f7eb005b76d68","lane":"client-test-x86_64-unknown-linux-gnu","parents":["c4a3e11875b7d4812bfd87ab4e33d2562e9926bd"],"secs":214,"stamp":"9b418a0239f4fe9158da1652d365d567","tree":"ffd204a13a50b00a1a113843083076aed8405d82","v":1,"via":"run"} Client-Checks: {"checks":{"base":"b0806bb796050bb254015051233dbebbd53440e2","coverage":"all-tracked-applicable-files","diff":["libobs/build/libobs.core+.h.c","libobs/build/libobs.ported-audio-monitoring-device+.h.c","libobs/build/ported-source-sets/audio-monitoring-device.json","libobs/cmake/rust-exports.d/obs-core-audio_monitoring_device.txt","libobs/obs-audio-monitoring-device-fields.c.h","rust/README.md","rust/obs-c-oracle/oracle/audio_monitoring_device.c","rust/obs-core/src/audio_monitoring_device.rs","rust/obs-core/src/ffi/audio_monitoring_device.rs","rust/obs-core/src/ffi/mod.rs","rust/obs-core/src/lib.rs","rust/obs-core/tests/obs_core/audio_monitoring_device.rs","rust/obs-core/tests/obs_core/audio_monitoring_device_parity.rs","rust/obs-core/tests/obs_core/main.rs"],"head":"969848e17167fe765c6d14a64143d8c334b49892","tools":{"orchestrator-python":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]","schema-dependencies":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]\n{'jsonschema': '4.26.0', 'json_source_map': '1.0.5'}","uv":"uv 0.13.5 (x86_64-unknown-linux-gnu)","xmllint":"xmllint: using libxml version 21504-GITv2.15.4\n compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib"},"tracked-digest":"339b5b3dd75ff82d7eeb4a1db970a1f3358d18f19da9b3263271460bc65a33f2","tree":"ffd204a13a50b00a1a113843083076aed8405d82"}} --- libobs/build/libobs.core+.h.c | 2 +- ...libobs.ported-audio-monitoring-device+.h.c | 4 + .../audio-monitoring-device.json | 5 + .../obs-core-audio_monitoring_device.txt | 2 + libobs/obs-audio-monitoring-device-fields.c.h | 77 +++ rust/README.md | 1 + .../oracle/audio_monitoring_device.c | 418 +++++++++++++++ rust/obs-core/src/audio_monitoring_device.rs | 52 +- .../src/ffi/audio_monitoring_device.rs | 123 +++++ rust/obs-core/src/ffi/mod.rs | 1 + .../audio_monitoring_device_parity.rs | 492 ++++++++++++++++++ rust/obs-core/tests/obs_core/main.rs | 1 + 12 files changed, 1169 insertions(+), 9 deletions(-) create mode 100644 libobs/build/libobs.ported-audio-monitoring-device+.h.c create mode 100644 libobs/build/ported-source-sets/audio-monitoring-device.json create mode 100644 libobs/cmake/rust-exports.d/obs-core-audio_monitoring_device.txt create mode 100644 libobs/obs-audio-monitoring-device-fields.c.h create mode 100644 rust/obs-c-oracle/oracle/audio_monitoring_device.c create mode 100644 rust/obs-core/src/ffi/audio_monitoring_device.rs create mode 100644 rust/obs-core/tests/obs_core/audio_monitoring_device_parity.rs diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index 89f02c83aa..9089ccc52f 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -3,7 +3,7 @@ #include "libobs/build/libobs.pch.h" #include "libobs/obs-audio-info-queries-fields.c.h" -#include "libobs/obs-audio-monitoring-device.c.h" +#include "libobs/obs-audio-monitoring-device-fields.c.h" #include "libobs/obs-base-effect-fields.c.h" #include "libobs/obs-context-profiler-name-store.c.h" #include "libobs/obs-context-runtime.c.h" diff --git a/libobs/build/libobs.ported-audio-monitoring-device+.h.c b/libobs/build/libobs.ported-audio-monitoring-device+.h.c new file mode 100644 index 0000000000..eb0d8b339b --- /dev/null +++ b/libobs/build/libobs.ported-audio-monitoring-device+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original monitoring device setter and reset, C reference only. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-audio-monitoring-device.c.h" diff --git a/libobs/build/ported-source-sets/audio-monitoring-device.json b/libobs/build/ported-source-sets/audio-monitoring-device.json new file mode 100644 index 0000000000..c4de3b3926 --- /dev/null +++ b/libobs/build/ported-source-sets/audio-monitoring-device.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-audio-monitoring-device+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-core-audio_monitoring_device.txt b/libobs/cmake/rust-exports.d/obs-core-audio_monitoring_device.txt new file mode 100644 index 0000000000..5e70698143 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-core-audio_monitoring_device.txt @@ -0,0 +1,2 @@ +obs_reset_audio_monitoring +obs_set_audio_monitoring_device diff --git a/libobs/obs-audio-monitoring-device-fields.c.h b/libobs/obs-audio-monitoring-device-fields.c.h new file mode 100644 index 0000000000..1deb1c6eba --- /dev/null +++ b/libobs/obs-audio-monitoring-device-fields.c.h @@ -0,0 +1,77 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters for the Rust obs_set_audio_monitoring_device() and + * obs_reset_audio_monitoring() (#5491). The monitoring fields, their mutex + * and bmem copies, the monitor list and audio_monitor_reset(), the source + * enumeration and the Audio Output Capture notice stay in C; Rust decides + * which runs, and in what order. */ + +_Static_assert(OBS_CORE_SETUP_RULES_DO_NOT_SELF_MONITOR == OBS_SOURCE_DO_NOT_SELF_MONITOR, + "OBS_SOURCE_DO_NOT_SELF_MONITOR"); + +bool obs_audio_monitoring_device_available(void); +bool obs_audio_monitoring_device_available(void) +{ + return obs_audio_monitoring_available(); +} + +void obs_audio_monitoring_device_lock(void); +void obs_audio_monitoring_device_lock(void) +{ + pthread_mutex_lock(&obs->audio.monitoring_mutex); +} + +void obs_audio_monitoring_device_unlock(void); +void obs_audio_monitoring_device_unlock(void) +{ + pthread_mutex_unlock(&obs->audio.monitoring_mutex); +} + +int obs_audio_monitoring_device_compare(const char *id); +int obs_audio_monitoring_device_compare(const char *id) +{ + return strcmp(id, obs->audio.monitoring_device_id); +} + +void obs_audio_monitoring_device_store(const char *name, const char *id); +void obs_audio_monitoring_device_store(const char *name, const char *id) +{ + bfree(obs->audio.monitoring_device_name); + bfree(obs->audio.monitoring_device_id); + + obs->audio.monitoring_device_name = bstrdup(name); + obs->audio.monitoring_device_id = bstrdup(id); +} + +size_t obs_audio_monitoring_device_monitor_count(void); +size_t obs_audio_monitoring_device_monitor_count(void) +{ + return obs->audio.monitors.num; +} + +void obs_audio_monitoring_device_reset_monitor(size_t index); +void obs_audio_monitoring_device_reset_monitor(size_t index) +{ + audio_monitor_reset(obs->audio.monitors.array[index]); +} + +void obs_audio_monitoring_device_enum_sources(bool (*visit)(void *, obs_source_t *), void *param); +void obs_audio_monitoring_device_enum_sources(bool (*visit)(void *, obs_source_t *), void *param) +{ + obs_enum_sources(visit, param); +} + +uint32_t obs_audio_monitoring_device_output_flags(const obs_source_t *source); +uint32_t obs_audio_monitoring_device_output_flags(const obs_source_t *source) +{ + return source->info.output_flags; +} + +void obs_audio_monitoring_device_notify(obs_source_t *source); +void obs_audio_monitoring_device_notify(obs_source_t *source) +{ + obs_data_t *settings = obs_source_get_settings(source); + const char *device_id = obs_data_get_string(settings, "device_id"); + obs_source_audio_output_capture_device_changed(source, device_id); + obs_data_release(settings); +} diff --git a/rust/README.md b/rust/README.md index 7b2dfa4657..315959e833 100644 --- a/rust/README.md +++ b/rust/README.md @@ -634,6 +634,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-audio-info-queries.c.h` | `obs-core::audio_info_queries` | `obs_get_audio_info` and `obs_get_audio_info2` swapped in hybrid `libobs` (#5363; group `libobs.ported-audio-info-queries` keeps the original for the C reference). A NULL core answers false before any read (#2566, #3363). `obs_get_audio_info` checks its output, then the core's audio output, then reads the output's rate and speakers through the real `audio_output_get_info()`. `obs_get_audio_info2` runs the info read into a local first, then checks its own output and the audio output again, and stores the rate, the speakers, `fixed_buffer` and `obs_core_setup_rules_buffer_ms(max_buffering_ticks, rate)` cast straight to `uint32_t`. Nothing is written on failure; the caller's struct is written field by field. The core layout stays in C behind private adapters (`obs-audio-info-queries-fields.c.h`, also a shared Rust-static support member). The unchanged `test_audio_info_queries` keeps testing the extracted C source; `test_get_audio` and `test_core_setup_rules_steps` run the real library. Tier 1 mirrors every assertion plus the full read order; Tier 3 runs the original and the shim on one real-header core filled with any byte (result, output bytes, info call log, core bytes, current core pointer, real-header layouts) with mutants. The audio-controls oracle's `obs_get_audio_info` stand-in is dropped: obs-core's export answers false there without a current core. No intentional differences; Tier 4 does not apply. | | `libobs/obs-module-load-all.c.h` | `obs-core::module_load_all` | The deprecated `obs_load_all_modules`/`obs_load_all_modules2` stay intentional no-ops: no startup, module discovery, loading, allocation, logging or state change, and the optional failure info (count, pointer array, strings) is never dereferenced. Tier 1 mirrors unchanged `test_module_load_all`; Tier 3 compares the original C over random caller counts and NULL. No intentional differences; Tier 4 does not apply. | | `libobs/obs-reset-audio2.c.h` | `obs-core::reset_audio2` | `obs_reset_audio2` swapped in hybrid `libobs` (#5486; group `libobs.ported-reset-audio2` keeps the original for the C reference, reaching the static `obs_init_audio`/`obs_free_audio` of `obs.c.h` through the adapters, `obs-reset-audio2-reference-steps.c.h`). In order: with no core it returns false before anything else (`core_setup_rules::audio_refused`, #3363); with an audio output it asks `audio_output_active()` once and refuses an active one with nothing changed and nothing logged; otherwise it frees the audio (`obs_free_audio()`), and a NULL info returns true there. With an info it reads the info after the free, stores `max_buffering_ticks` (`buffer_ticks` of a set `max_buffering_ms`, else `buffer_default_ticks`, the `uint32_t` cast to `int`) and then `fixed_buffer`, logs the separator and the "audio settings reset" message at `LOG_INFO` with the original's format strings (rate cast to `int`, layout, the stored ticks back in milliseconds through `buffer_ms`, "fixed" or "dynamically increasing"), and returns `obs_init_audio()` on the "Audio", float planar info at the rate and layout given with `audio_callback`. The core pointer, the output, the free, the two fields and the open stay C behind private adapters (`obs-reset-audio2-fields.c.h`, core group); the decisions, the ticks and the message are Rust. Tier 1 mirrors every case of unchanged `test_reset_audio2` plus the step order, the open's result and the buffering and message edges; Tier 3 runs the original and the shim on one recording fixture core (result, every step in order: the handle asked about, the free, the info passed to `obs_init_audio()` with the fields stored when it is called, each `blog` level, format, `%d` and `%s`; the output and fields after) over every gate path, the C test's cases and edges and proptest setups, with six mutants. Unchanged Tier 2 runs both actual libraries. A dead core or unreadable info is outside the contract. No intentional differences beyond `buffer_ms`'s zero-rate rule (#3272); Tier 4 does not apply. | +| `libobs/obs-audio-monitoring-device.c.h` | `obs-core::audio_monitoring_device` | `obs_set_audio_monitoring_device` and `obs_reset_audio_monitoring` swapped in hybrid `libobs` (#5491; group `libobs.ported-audio-monitoring-device` keeps the original for the C reference). Setting refuses a NULL name, a NULL id, an empty name and an empty id, asked in that order through `core_setup_rules::monitor_missing` before anything else is touched, then refuses when monitoring is unavailable. Under `monitoring_mutex` an id equal to the stored one (`monitor_same` of the `strcmp`) unlocks and answers true with nothing changed; otherwise the stored name and id are freed and replaced by `bstrdup` copies, the mutex is released, every live monitor is reset (`obs_reset_audio_monitoring`, which asks for availability again), and each source `obs_enum_sources` hands over whose output flags pass `aoc_check` (`OBS_SOURCE_DO_NOT_SELF_MONITOR`) is told through `obs_source_audio_output_capture_device_changed` with its own `device_id` setting. Resetting does nothing when monitoring is unavailable, otherwise resets each live monitor once under `monitoring_mutex`, reading the count again before each step. The fields, the mutex, the copies, the monitor list, `audio_monitor_reset`, the enumeration and the notice stay in C behind private adapters (`obs-audio-monitoring-device-fields.c.h`, in the core group). Tier 1 mirrors every case of unchanged `test_set_audio_monitoring_device` and the refusals of `test_monitoring_device` over a model core, plus the full step order; Tier 3 runs the original and the shims on one recording real-header core over fixed and proptest names, ids, stored ids, availability, monitor counts and source sets (result, every core read, lock, compare, free, copy, reset, enumeration and per-source settings read, notice and release, the stored strings) with ten mutants. Unchanged Tier 2 (`test_set_audio_monitoring_device`, `test_core_setup_rules_steps`, `test_pulse_monitor_reset`) runs both actual libraries. An uninitialized core and a NULL stored id are outside the contract (the original dereferences both). No intentional differences; Tier 4 does not apply. | | `libobs/obs-set-output-source.c.h` | `obs-core::set_output_source` | Legacy main-canvas channel setter (#4709). Forwards the borrowed current canvas and unchanged channel/source exactly once to the existing canvas setter, preserving bounds, mutable local/global signals and all reference effects. Tier 1 mirrors the C characterization, callback-only original-C Tier 3 checks real adapter layout and unchanged object bytes, and unchanged Tier 2 runs both actual libraries. Uninitialized core and dead canvas/source are original C UB, excluded; no intentional differences. | | `libobs/obs-get-main-canvas.c.h` | `obs-core::get_main_canvas` | Main-canvas acquired getter (#4780). A real private C adapter borrows the current field and supplies the existing canvas reference operation; safe Rust delegates exactly once and preserves its returned identity and ownership effects. Tier 1 mirrors unchanged `test_get_main_canvas`, Tier 3 includes the original C wrapper and real adapter with exact layout and complete fixture-byte comparisons, and Tier 2 replays both actual libraries. Uninitialized core, dead canvases and overflowing counts are excluded; no intentional differences or Tier 4 surface. | | `libobs/obs-win-crash-report.c.h` | `obs-core::win_crash_report` | Swapped in hybrid `libobs` (group `libobs.ported-win-crash-report`, in the Windows ported sources). Nine pure functions on integers, declared in `obs-win-crash-report.h` without `EXPORT` and hidden; they take no Windows type, so the file, its C test and its oracle build on every OS: `obs_win_crash_report_contains` (`enum_all_modules()`'s and `enum_module()`'s `base <= addr < base + size`, the end a wrapping `uint64_t`), `_is_crashed`, `_in_pass` and `_other_process` (`write_thread_trace()`'s id against `GetCurrentThreadId()`, the crashed thread in the first pass and every other in the second, and the owner against `GetCurrentProcessId()`), `_names_symbol` (`walk_stack()`'s line with the symbol unless `SYMFLAG_EXPORT`, 0x200, `_Static_assert`ed against `dbghelp.h`; the flags still read only after a successful lookup), `_mask_address` and `_mask_param` (a 32-bit build's masks: 36 bits on the stack and PC, 32 on the parameters), `_name_prefix` (`get_thread_name()`'s leading space for a non-empty name) and `_pass_on` (`exception_handler()`'s two early returns: a debugger, or re-entered, reading `*inside` only without a debugger). Each check of `write_thread_trace()` is its own function, so `GetCurrentProcessId()` is still called only for a thread in its pass. `obs-win-crash-handler.c.h` keeps every DbgHelp, toolhelp and thread call, `os_wcs_to_utf8()`, `strlwr()`, `strrchr()`, every `dstr` call and format string, `bcrash()` and both static flags. The core runs inside the unhandled exception filter: no allocation, indexing or panic path, and a per-thread counting allocator in the core test binary checks that no shim or core rule allocates. No intentional differences; characterized, not endorsed and kept: a module whose end wraps past 2^64, or lands on it, holds nothing; the stack and PC masks keep 36 bits where the parameters keep 32; the crashed thread's id under another process is left out of both passes. `test_win_crash_report_steps` compiles the C into itself on every OS; it has no `_rust` variant, as for `test_nix_system_info_steps`. `test_win_crash_sym_info` (Windows) compiles it with the handler. Tier 3 compares every result exactly over every combination of edge bases, sizes and addresses at each module's edges, every pair of edge thread ids, `write_thread_traces()`'s two passes over every snapshot of up to three threads, every flag of the low 16 bits under four high patterns and every pair of bits, both masks around every power of two, name lengths 0 to 4096, the filter with NULL for the flag under a debugger, and proptests over all of it; nothing is skipped on any host. | diff --git a/rust/obs-c-oracle/oracle/audio_monitoring_device.c b/rust/obs-c-oracle/oracle/audio_monitoring_device.c new file mode 100644 index 0000000000..2508dc89a8 --- /dev/null +++ b/rust/obs-c-oracle/oracle/audio_monitoring_device.c @@ -0,0 +1,418 @@ +/* Original obs_set_audio_monitoring_device() and + * obs_reset_audio_monitoring() (#5491), and the real-header adapters of + * obs-audio-monitoring-device-fields.c.h, on one recording fixture core. + * Under cargo test these adapters are the only definitions of their real + * names, so the Rust shim reaches this fixture. Every core read, the + * availability check, the mutex, the compare, the frees and copies, each + * monitor reset, the enumeration and each source's settings read, notice + * and release are traced; the probe runs the original and a candidate on + * the same fixture and reports any difference in the trace, the result or + * the stored strings, so mutants are observable. The monitoring mutex is + * recorded, never taken, so a mutant that locks twice shows in the trace + * instead of deadlocking. */ +/* The MSVC UCRT headers define snprintf and friends inline in every object + * that includes them, which lets a COFF link pull this member into an + * unrelated test; keep them declarations only. */ +#define _NO_CRT_STDIO_INLINE +#include "libobs/build/libobs.pch.h" +#include +#include + +#define AMD_MONITORS 8 +#define AMD_SOURCES 8 +#define AMD_COPIES 4 +#define AMD_TEXT 48 +#define AMD_TRACE 512 + +static _Thread_local struct obs_core amd_core; +static _Thread_local struct obs_core *amd_current; +static _Thread_local struct obs_source amd_sources[AMD_SOURCES]; +static _Thread_local size_t amd_source_count; +static _Thread_local const char *amd_device_ids[AMD_SOURCES]; +static _Thread_local char amd_settings[AMD_SOURCES]; +static _Thread_local char amd_monitor_tokens[AMD_MONITORS]; +static _Thread_local struct audio_monitor *amd_monitors[AMD_MONITORS]; +static _Thread_local bool amd_is_available; +static _Thread_local bool amd_locked; +static _Thread_local char amd_old_name[AMD_TEXT]; +static _Thread_local char amd_old_id[AMD_TEXT]; +static _Thread_local char amd_copies[AMD_COPIES][AMD_TEXT]; +static _Thread_local size_t amd_copy_count; +static _Thread_local char amd_trace[AMD_TRACE]; +static _Thread_local size_t amd_trace_len; + +static void amd_event(char value) +{ + if (amd_trace_len + 1 < sizeof(amd_trace)) { + amd_trace[amd_trace_len++] = value; + amd_trace[amd_trace_len] = '\0'; + } +} + +static char amd_digit(size_t index) +{ + return index < 10 ? (char)('0' + index) : '?'; +} + +static void amd_copy(char *out, size_t size, const char *text) +{ + if (!size) + return; + if (!text) + text = ""; + size_t n = strlen(text); + if (n >= size) + n = size - 1; + memcpy(out, text, n); + out[n] = '\0'; +} + +/* 'o' reads the core. */ +static struct obs_core *amd_read_core(void) +{ + amd_event('o'); + return amd_current; +} + +/* 'A' asks whether monitoring is available. */ +static bool amd_available(void) +{ + amd_event('A'); + return amd_is_available; +} + +/* 'L' locks; 'R' marks a lock already held or another mutex. */ +static int amd_lock(pthread_mutex_t *mutex) +{ + if (mutex != &amd_core.audio.monitoring_mutex || amd_locked) + amd_event('R'); + amd_event('L'); + amd_locked = true; + return 0; +} + +/* 'U' unlocks; 'R' marks a lock not held or another mutex. */ +static int amd_unlock(pthread_mutex_t *mutex) +{ + if (mutex != &amd_core.audio.monitoring_mutex || !amd_locked) + amd_event('R'); + amd_event('U'); + amd_locked = false; + return 0; +} + +/* 'X' marks a step on the monitoring fields outside the lock. */ +static void amd_need_lock(void) +{ + if (!amd_locked) + amd_event('X'); +} + +/* 'C' compares the id. */ +static int amd_strcmp(const char *a, const char *b) +{ + amd_need_lock(); + amd_event('C'); + return strcmp(a, b); +} + +/* 'F' frees, then 'n' the stored name, 'i' the stored id, 'c' a copy. */ +static void amd_bfree(void *ptr) +{ + amd_need_lock(); + amd_event('F'); + if (ptr == amd_old_name) + amd_event('n'); + else if (ptr == amd_old_id) + amd_event('i'); + else if (ptr) + amd_event('c'); + else + amd_event('0'); +} + +/* 'S' copies a string into the next copy slot. */ +static char *amd_bstrdup(const char *text) +{ + amd_need_lock(); + amd_event('S'); + if (!text || amd_copy_count >= AMD_COPIES) { + amd_event('!'); + return NULL; + } + char *copy = amd_copies[amd_copy_count++]; + amd_copy(copy, AMD_TEXT, text); + return copy; +} + +/* 'M' resets the monitor named next. */ +static void amd_monitor_reset(struct audio_monitor *monitor) +{ + amd_need_lock(); + amd_event('M'); + for (size_t i = 0; i < AMD_MONITORS; i++) { + if (monitor == (struct audio_monitor *)&amd_monitor_tokens[i]) { + amd_event(amd_digit(i)); + return; + } + } + amd_event('?'); +} + +static size_t amd_source_index(const obs_source_t *source) +{ + for (size_t i = 0; i < AMD_SOURCES; i++) { + if (source == &amd_sources[i]) + return i; + } + return AMD_SOURCES; +} + +static size_t amd_settings_index(const obs_data_t *settings) +{ + for (size_t i = 0; i < AMD_SOURCES; i++) { + if ((const void *)settings == (const void *)&amd_settings[i]) + return i; + } + return AMD_SOURCES; +} + +/* 'E' enumerates the sources in order; '!' marks a parameter, 'R' the lock + * held, 'b' a callback that stopped it. */ +static void amd_enum_sources(bool (*visit)(void *, obs_source_t *), void *param) +{ + amd_event('E'); + if (param) + amd_event('!'); + if (amd_locked) + amd_event('R'); + for (size_t i = 0; i < amd_source_count; i++) { + if (!visit(param, &amd_sources[i])) { + amd_event('b'); + break; + } + } +} + +/* 'g' reads the settings of the source named next. */ +static obs_data_t *amd_get_settings(const obs_source_t *source) +{ + size_t index = amd_source_index(source); + amd_event('g'); + amd_event(amd_digit(index)); + return index < AMD_SOURCES ? (obs_data_t *)(void *)&amd_settings[index] : NULL; +} + +/* 's' reads a string of those settings; '?' marks another key. */ +static const char *amd_get_string(obs_data_t *settings, const char *name) +{ + size_t index = amd_settings_index(settings); + amd_event('s'); + amd_event(amd_digit(index)); + if (strcmp(name, "device_id") != 0) + amd_event('?'); + return index < AMD_SOURCES ? amd_device_ids[index] : NULL; +} + +/* 'N' tells the source named next; '?' marks another device id. */ +static void amd_device_changed(obs_source_t *source, const char *device_id) +{ + size_t index = amd_source_index(source); + amd_event('N'); + amd_event(amd_digit(index)); + if (index >= AMD_SOURCES || device_id != amd_device_ids[index]) + amd_event('?'); +} + +/* 'r' releases the settings named next. */ +static void amd_data_release(obs_data_t *settings) +{ + amd_event('r'); + amd_event(amd_digit(amd_settings_index(settings))); +} + +void oracle_obs_reset_audio_monitoring(void); +bool oracle_obs_set_audio_monitoring_device(const char *name, const char *id); + +/* The mingw build renames every pthread function on the command line + * (w32-pthreads): keep that name for the rest of the file and use the + * recorders only for the original and the adapters. */ +#pragma push_macro("pthread_mutex_lock") +#pragma push_macro("pthread_mutex_unlock") +#pragma push_macro("strcmp") +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#undef strcmp +#define pthread_mutex_lock amd_lock +#define pthread_mutex_unlock amd_unlock +#define strcmp amd_strcmp +#define obs amd_read_core() +#define obs_audio_monitoring_available amd_available +#define bfree amd_bfree +#define bstrdup amd_bstrdup +#define audio_monitor_reset amd_monitor_reset +#define obs_enum_sources amd_enum_sources +#define obs_source_get_settings amd_get_settings +#define obs_data_get_string amd_get_string +#define obs_source_audio_output_capture_device_changed amd_device_changed +#define obs_data_release amd_data_release +#define obs_reset_audio_monitoring oracle_obs_reset_audio_monitoring +#define obs_set_audio_monitoring_device oracle_obs_set_audio_monitoring_device +#include "libobs/obs-audio-monitoring-device.c.h" +#undef obs_set_audio_monitoring_device +#undef obs_reset_audio_monitoring +#include "audio_monitoring_device_fields.inc" +#undef obs_data_release +#undef obs_source_audio_output_capture_device_changed +#undef obs_data_get_string +#undef obs_source_get_settings +#undef obs_enum_sources +#undef audio_monitor_reset +#undef bstrdup +#undef bfree +#undef obs_audio_monitoring_available +#undef obs +#undef strcmp +#undef pthread_mutex_unlock +#undef pthread_mutex_lock +#pragma pop_macro("strcmp") +#pragma pop_macro("pthread_mutex_unlock") +#pragma pop_macro("pthread_mutex_lock") + +typedef bool (*amd_set_fn)(const char *name, const char *id); +typedef void (*amd_reset_fn)(void); + +struct amd_result { + char trace[AMD_TRACE]; + char name[AMD_TEXT]; + char id[AMD_TEXT]; + bool result; + bool locked; +}; + +/* A fixture core storing "Old name" and `stored_id`, `monitors` live + * monitors, and `sources` enumerated sources with `flags` and + * `device_ids`. */ +static bool amd_arm(bool available, const char *stored_id, size_t monitors, const uint32_t *flags, + const char *const *device_ids, size_t sources) +{ + if (monitors > AMD_MONITORS || sources > AMD_SOURCES) + return false; + memset(&amd_core, 0, sizeof(amd_core)); + memset(amd_sources, 0, sizeof(amd_sources)); + memset(amd_copies, 0, sizeof(amd_copies)); + amd_copy(amd_old_name, AMD_TEXT, "Old name"); + amd_copy(amd_old_id, AMD_TEXT, stored_id); + amd_core.audio.monitoring_device_name = amd_old_name; + amd_core.audio.monitoring_device_id = amd_old_id; + for (size_t i = 0; i < monitors; i++) + amd_monitors[i] = (struct audio_monitor *)(void *)&amd_monitor_tokens[i]; + amd_core.audio.monitors.array = amd_monitors; + amd_core.audio.monitors.num = monitors; + amd_core.audio.monitors.capacity = AMD_MONITORS; + for (size_t i = 0; i < sources; i++) { + amd_sources[i].info.output_flags = flags[i]; + amd_device_ids[i] = device_ids[i]; + } + amd_source_count = sources; + amd_is_available = available; + amd_current = &amd_core; + amd_locked = false; + amd_copy_count = 0; + amd_trace_len = 0; + amd_trace[0] = '\0'; + return true; +} + +static void amd_collect(bool result, struct amd_result *out) +{ + memcpy(out->trace, amd_trace, sizeof(out->trace)); + amd_copy(out->name, AMD_TEXT, amd_core.audio.monitoring_device_name); + amd_copy(out->id, AMD_TEXT, amd_core.audio.monitoring_device_id); + out->result = result; + out->locked = amd_locked; + amd_current = NULL; +} + +/* 0: match. 1: the traces differ, 2: the results differ, 4: the stored + * strings differ, 8: the mutex was left held. 0x100: fixture too large. */ +static unsigned amd_diff(const struct amd_result *original, const struct amd_result *actual) +{ + unsigned diff = 0; + if (strcmp(original->trace, actual->trace) != 0) + diff |= 1; + if (original->result != actual->result) + diff |= 2; + if (strcmp(original->name, actual->name) != 0 || strcmp(original->id, actual->id) != 0) + diff |= 4; + if (original->locked || actual->locked) + diff |= 8; + return diff; +} + +static bool amd_run_set(amd_set_fn set, const char *name, const char *id, bool available, const char *stored_id, + size_t monitors, const uint32_t *flags, const char *const *device_ids, size_t sources, + struct amd_result *out) +{ + if (!amd_arm(available, stored_id, monitors, flags, device_ids, sources)) + return false; + bool result = set(name, id); + amd_collect(result, out); + return true; +} + +unsigned oracle_audio_monitoring_device_set_probe(amd_set_fn candidate, const char *name, const char *id, + bool available, const char *stored_id, size_t monitors, + const uint32_t *flags, const char *const *device_ids, size_t sources); +unsigned oracle_audio_monitoring_device_set_probe(amd_set_fn candidate, const char *name, const char *id, + bool available, const char *stored_id, size_t monitors, + const uint32_t *flags, const char *const *device_ids, size_t sources) +{ + static _Thread_local struct amd_result original, actual; + if (!amd_run_set(oracle_obs_set_audio_monitoring_device, name, id, available, stored_id, monitors, flags, + device_ids, sources, &original) || + !amd_run_set(candidate, name, id, available, stored_id, monitors, flags, device_ids, sources, &actual)) + return 0x100; + return amd_diff(&original, &actual); +} + +unsigned oracle_audio_monitoring_device_reset_probe(amd_reset_fn candidate, bool available, size_t monitors); +unsigned oracle_audio_monitoring_device_reset_probe(amd_reset_fn candidate, bool available, size_t monitors) +{ + static _Thread_local struct amd_result original, actual; + if (!amd_arm(available, "id", monitors, NULL, NULL, 0)) + return 0x100; + oracle_obs_reset_audio_monitoring(); + amd_collect(false, &original); + amd_arm(available, "id", monitors, NULL, NULL, 0); + candidate(); + amd_collect(false, &actual); + return amd_diff(&original, &actual); +} + +/* The original setter's trace, result and stored strings, for the + * characterization checks. */ +bool oracle_audio_monitoring_device_set_original(const char *name, const char *id, bool available, + const char *stored_id, size_t monitors, const uint32_t *flags, + const char *const *device_ids, size_t sources, char *trace, + size_t trace_size, char *stored, size_t stored_size); +bool oracle_audio_monitoring_device_set_original(const char *name, const char *id, bool available, + const char *stored_id, size_t monitors, const uint32_t *flags, + const char *const *device_ids, size_t sources, char *trace, + size_t trace_size, char *stored, size_t stored_size) +{ + static _Thread_local struct amd_result result; + if (!amd_run_set(oracle_obs_set_audio_monitoring_device, name, id, available, stored_id, monitors, flags, + device_ids, sources, &result)) + return false; + amd_copy(trace, trace_size, result.trace); + if (stored_size) { + amd_copy(stored, stored_size, result.name); + size_t n = strlen(stored); + if (n + 1 < stored_size) { + stored[n] = '/'; + amd_copy(stored + n + 1, stored_size - n - 1, result.id); + } + } + return result.result; +} diff --git a/rust/obs-core/src/audio_monitoring_device.rs b/rust/obs-core/src/audio_monitoring_device.rs index 6566df5c42..dcaae38a25 100644 --- a/rust/obs-core/src/audio_monitoring_device.rs +++ b/rust/obs-core/src/audio_monitoring_device.rs @@ -34,6 +34,8 @@ clippy::unreachable )] +use crate::core_setup_rules::{aoc_check, monitor_missing, monitor_same}; + /// The live monitors as `obs_reset_audio_monitoring()` sees them: /// `obs_audio_monitoring_available()`, `obs->audio.monitoring_mutex`, /// `monitors.num` and `audio_monitor_reset(monitors.array[i])`. @@ -71,21 +73,55 @@ pub trait Device: Monitors { } /// `obs_reset_audio_monitoring()`. -pub fn reset_monitoring(_monitors: &mut M) { - todo!() +pub fn reset_monitoring(monitors: &mut M) { + if !monitors.available() { + return; + } + monitors.lock(); + let mut index: usize = 0; + while index < monitors.count() { + monitors.reset(index); + // `index < count()`, a `usize`, so this never wraps. + index = index.wrapping_add(1); + } + monitors.unlock(); } /// The enumeration callback: tell an Audio Output Capture source; always /// continue. -pub fn aoc_source(_device: &mut D, _source: D::Source) -> bool { - todo!() +pub fn aoc_source(device: &mut D, source: D::Source) -> bool { + if aoc_check(device.output_flags(source)) { + device.notify(source); + } + true } /// `obs_set_audio_monitoring_device(name, id)`; `None` is NULL. pub fn set_device( - _device: &mut D, - _name: Option, - _id: Option, + device: &mut D, + name: Option, + id: Option, ) -> bool { - todo!() + if monitor_missing(name.is_some()) || monitor_missing(id.is_some()) { + return false; + } + let (Some(name), Some(id)) = (name, id) else { + return false; + }; + if monitor_missing(!device.empty(name)) || monitor_missing(!device.empty(id)) { + return false; + } + if monitor_missing(device.available()) { + return false; + } + device.lock(); + if monitor_same(device.compare(id)) { + device.unlock(); + return true; + } + device.store(name, id); + device.unlock(); + reset_monitoring(device); + device.enum_sources(); + true } diff --git a/rust/obs-core/src/ffi/audio_monitoring_device.rs b/rust/obs-core/src/ffi/audio_monitoring_device.rs new file mode 100644 index 0000000000..500d5ad2a5 --- /dev/null +++ b/rust/obs-core/src/ffi/audio_monitoring_device.rs @@ -0,0 +1,123 @@ +//! `obs_set_audio_monitoring_device()` and `obs_reset_audio_monitoring()` +//! over C-owned state: the monitoring fields, their mutex and bmem copies, +//! the monitor list and `audio_monitor_reset()`, the source enumeration and +//! the Audio Output Capture notice, behind the private adapters of +//! `libobs/obs-audio-monitoring-device-fields.c.h` (#5491). Which run, and +//! in what order, is the safe core's ([`crate::audio_monitoring_device`]). +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::{NonNull, null_mut}; + +use crate::audio_monitoring_device::{Device, Monitors, aoc_source, reset_monitoring, set_device}; + +/// `bool (*)(void *, obs_source_t *)`, the `obs_enum_sources()` callback. +pub type Visit = unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool; + +unsafe extern "C" { + fn obs_audio_monitoring_device_available() -> bool; + fn obs_audio_monitoring_device_lock(); + fn obs_audio_monitoring_device_unlock(); + fn obs_audio_monitoring_device_compare(id: *const c_char) -> c_int; + fn obs_audio_monitoring_device_store(name: *const c_char, id: *const c_char); + fn obs_audio_monitoring_device_monitor_count() -> usize; + fn obs_audio_monitoring_device_reset_monitor(index: usize); + fn obs_audio_monitoring_device_enum_sources(visit: Visit, param: *mut c_void); + fn obs_audio_monitoring_device_output_flags(source: *const c_void) -> u32; + fn obs_audio_monitoring_device_notify(source: *mut c_void); +} + +/// The live core, reached only through the adapters. +struct Libobs; + +impl Monitors for Libobs { + fn available(&mut self) -> bool { + // SAFETY: asks the monitoring backend only. + unsafe { obs_audio_monitoring_device_available() } + } + fn lock(&mut self) { + // SAFETY: the live core's monitoring_mutex, which the core takes once + // and releases once. + unsafe { obs_audio_monitoring_device_lock() } + } + fn unlock(&mut self) { + // SAFETY: called once, after `lock`. + unsafe { obs_audio_monitoring_device_unlock() } + } + fn count(&mut self) -> usize { + // SAFETY: read under monitoring_mutex, which `lock` holds. + unsafe { obs_audio_monitoring_device_monitor_count() } + } + fn reset(&mut self, index: usize) { + // SAFETY: `index < count()` under the same hold of monitoring_mutex. + unsafe { obs_audio_monitoring_device_reset_monitor(index) } + } +} + +impl Device for Libobs { + type Str = NonNull; + type Source = *mut c_void; + fn empty(&mut self, s: NonNull) -> bool { + // SAFETY: the caller's non-NULL string, readable at its first byte. + unsafe { *s.as_ptr() == 0 } + } + fn compare(&mut self, id: NonNull) -> i32 { + // SAFETY: the caller's NUL-terminated id; the stored id is read under + // monitoring_mutex, which `lock` holds. + unsafe { obs_audio_monitoring_device_compare(id.as_ptr()) } + } + fn store(&mut self, name: NonNull, id: NonNull) { + // SAFETY: the caller's NUL-terminated strings, copied under + // monitoring_mutex; the stored ones are freed once. + unsafe { obs_audio_monitoring_device_store(name.as_ptr(), id.as_ptr()) } + } + fn enum_sources(&mut self) { + // SAFETY: `visit` only reads the flags of and notifies each source + // the enumeration hands it; the original passes no parameter. + unsafe { obs_audio_monitoring_device_enum_sources(visit, null_mut()) } + } + fn output_flags(&mut self, source: *mut c_void) -> u32 { + // SAFETY: a live source handed over by `obs_enum_sources()`. + unsafe { obs_audio_monitoring_device_output_flags(source) } + } + fn notify(&mut self, source: *mut c_void) { + // SAFETY: as in `output_flags`. + unsafe { obs_audio_monitoring_device_notify(source) } + } +} + +/// The `obs_enum_sources()` callback: tells an Audio Output Capture source +/// about the new device; always continues. +/// +/// # Safety +/// `source` is a live source handed over by the enumeration. +unsafe extern "C" fn visit(_param: *mut c_void, source: *mut c_void) -> bool { + aoc_source(&mut Libobs, source) +} + +/// Reset every live monitor onto the current device. +/// +/// # Safety +/// As for the C function: the core is live and its monitoring_mutex is not +/// held by this thread. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_reset_audio_monitoring() { + reset_monitoring(&mut Libobs); +} + +/// Store a new monitoring device, reset the monitors onto it and tell the +/// Audio Output Capture sources. +/// +/// # Safety +/// As for the C function: `name` and `id` are NULL or NUL-terminated +/// strings; once both are non-empty the core is live, its monitoring_mutex +/// is not held by this thread and its stored id is a string. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_set_audio_monitoring_device( + name: *const c_char, + id: *const c_char, +) -> bool { + set_device( + &mut Libobs, + NonNull::new(name.cast_mut()), + NonNull::new(id.cast_mut()), + ) +} diff --git a/rust/obs-core/src/ffi/mod.rs b/rust/obs-core/src/ffi/mod.rs index 462cf34885..4dbfd4fab8 100644 --- a/rust/obs-core/src/ffi/mod.rs +++ b/rust/obs-core/src/ffi/mod.rs @@ -5,6 +5,7 @@ pub mod audio_discard; pub mod audio_info_queries; pub mod audio_min_ts; pub mod audio_mix; +pub mod audio_monitoring_device; pub mod audio_render; pub mod base_effect; pub mod canvas_channel_getter; diff --git a/rust/obs-core/tests/obs_core/audio_monitoring_device_parity.rs b/rust/obs-core/tests/obs_core/audio_monitoring_device_parity.rs new file mode 100644 index 0000000000..6e7ab589a5 --- /dev/null +++ b/rust/obs-core/tests/obs_core/audio_monitoring_device_parity.rs @@ -0,0 +1,492 @@ +//! Tier 3: the original extracted `obs_set_audio_monitoring_device()` and +//! `obs_reset_audio_monitoring()` versus the shims on one recording fixture +//! core (oracle/audio_monitoring_device.c), through the real-named adapters +//! of `obs-audio-monitoring-device-fields.c.h`. Compared: the result, the +//! trace of every core read, availability check, lock, compare, free, copy +//! (each step on the fields checked to run under the lock), monitor reset, +//! enumeration (checked to run after the unlock) and each source's settings +//! read, notice (with its own `device_id`) and release, and the stored name +//! and id. Inputs: NULL, empty and short names and ids, the same id as +//! stored or not, monitoring available or not, up to eight monitors and up +//! to eight sources with and without `OBS_SOURCE_DO_NOT_SELF_MONITOR`. +//! +//! Excluded: an uninitialized core (both dereference it once the name and +//! id pass) and a NULL stored id (both pass it to `strcmp`). No intentional +//! differences. Mutants show the probe catches each broken step. +use core::cell::Cell; +use core::ffi::{CStr, c_char, c_int, c_void}; +use core::ptr::null; +use std::ffi::CString; + +use obs_core::core_setup_rules::DO_NOT_SELF_MONITOR; +use obs_core::ffi::audio_monitoring_device::{ + Visit, obs_reset_audio_monitoring, obs_set_audio_monitoring_device, +}; +use proptest::prelude::*; + +type SetFn = unsafe extern "C" fn(*const c_char, *const c_char) -> bool; +type ResetFn = unsafe extern "C" fn(); + +unsafe extern "C" { + fn oracle_audio_monitoring_device_set_probe( + candidate: SetFn, + name: *const c_char, + id: *const c_char, + available: bool, + stored_id: *const c_char, + monitors: usize, + flags: *const u32, + device_ids: *const *const c_char, + sources: usize, + ) -> u32; + fn oracle_audio_monitoring_device_reset_probe( + candidate: ResetFn, + available: bool, + monitors: usize, + ) -> u32; + fn oracle_audio_monitoring_device_set_original( + name: *const c_char, + id: *const c_char, + available: bool, + stored_id: *const c_char, + monitors: usize, + flags: *const u32, + device_ids: *const *const c_char, + sources: usize, + trace: *mut c_char, + trace_size: usize, + stored: *mut c_char, + stored_size: usize, + ) -> bool; + fn obs_audio_monitoring_device_available() -> bool; + fn obs_audio_monitoring_device_lock(); + fn obs_audio_monitoring_device_unlock(); + fn obs_audio_monitoring_device_compare(id: *const c_char) -> c_int; + fn obs_audio_monitoring_device_store(name: *const c_char, id: *const c_char); + fn obs_audio_monitoring_device_monitor_count() -> usize; + fn obs_audio_monitoring_device_reset_monitor(index: usize); + fn obs_audio_monitoring_device_enum_sources(visit: Visit, param: *mut c_void); + fn obs_audio_monitoring_device_output_flags(source: *const c_void) -> u32; + fn obs_audio_monitoring_device_notify(source: *mut c_void); +} + +const AUDIO: u32 = 1 << 1; +const AOC: u32 = AUDIO | DO_NOT_SELF_MONITOR; + +/// One fixture: the arguments, availability, the stored id, the monitor +/// count and the sources (flags and `device_id`). +#[derive(Clone, Debug)] +struct Case { + name: Option, + id: Option, + available: bool, + stored_id: String, + monitors: usize, + sources: Vec<(u32, String)>, +} + +impl Case { + fn new(name: Option<&str>, id: Option<&str>) -> Self { + Self { + name: name.map(str::to_owned), + id: id.map(str::to_owned), + available: true, + stored_id: "old".into(), + monitors: 2, + sources: vec![ + (AOC, "old.monitor".into()), + (AUDIO, "new.monitor".into()), + (AOC, "new.monitor".into()), + ], + } + } + + /// Runs `body` with the C strings and arrays the oracle takes. + fn with( + &self, + body: impl FnOnce(*const c_char, *const c_char, *const c_char, &[u32], &[*const c_char]) -> R, + ) -> R { + let c = |text: &str| CString::new(text).unwrap(); + let name = self.name.as_deref().map(c); + let id = self.id.as_deref().map(c); + let stored = c(&self.stored_id); + let flags: Vec = self.sources.iter().map(|(flags, _)| *flags).collect(); + let ids: Vec = self.sources.iter().map(|(_, id)| c(id)).collect(); + let id_ptrs: Vec<*const c_char> = ids.iter().map(|id| id.as_ptr()).collect(); + body( + name.as_ref().map_or(null(), |name| name.as_ptr()), + id.as_ref().map_or(null(), |id| id.as_ptr()), + stored.as_ptr(), + &flags, + &id_ptrs, + ) + } + + fn probe(&self, candidate: SetFn) -> u32 { + self.with(|name, id, stored, flags, ids| { + // SAFETY: every string is NUL-terminated or NULL and outlives + // the call; `flags` and `ids` hold `sources` entries; the oracle + // owns the fixture core every adapter reaches. + unsafe { + oracle_audio_monitoring_device_set_probe( + candidate, + name, + id, + self.available, + stored, + self.monitors, + flags.as_ptr(), + ids.as_ptr(), + flags.len(), + ) + } + }) + } + + /// The original's trace without the core reads, its result and the + /// stored `name/id`. + fn original(&self) -> (String, bool, String) { + let mut trace = [0 as c_char; 512]; + let mut stored = [0 as c_char; 128]; + let result = self.with(|name, id, stored_id, flags, ids| { + // SAFETY: as in `probe`; both buffers are writable for their + // sizes and the oracle writes NUL-terminated text. + unsafe { + oracle_audio_monitoring_device_set_original( + name, + id, + self.available, + stored_id, + self.monitors, + flags.as_ptr(), + ids.as_ptr(), + flags.len(), + trace.as_mut_ptr(), + trace.len(), + stored.as_mut_ptr(), + stored.len(), + ) + } + }); + // SAFETY: NUL-terminated by the oracle. + let text = |buffer: &[c_char]| { + unsafe { CStr::from_ptr(buffer.as_ptr()) } + .to_str() + .unwrap() + .to_owned() + }; + (text(&trace).replace('o', ""), result, text(&stored)) + } +} + +fn reset_probe(candidate: ResetFn, available: bool, monitors: usize) -> u32 { + // SAFETY: the oracle owns the fixture core every adapter reaches. + unsafe { oracle_audio_monitoring_device_reset_probe(candidate, available, monitors) } +} + +#[test] +fn original_matches_the_characterization() { + // NULL or empty name or id: nothing else is asked. + for (name, id) in [ + (None, Some("new")), + (Some("New"), None), + (Some(""), Some("new")), + (Some("New"), Some("")), + ] { + assert_eq!( + Case::new(name, id).original(), + (String::new(), false, "Old name/old".into()) + ); + } + // Unavailable: one check. + let mut case = Case::new(Some("New"), Some("new")); + case.available = false; + assert_eq!(case.original(), ("A".into(), false, "Old name/old".into())); + // The same id: lock, compare, unlock. + assert_eq!( + Case::new(Some("New"), Some("old")).original(), + ("ALCU".into(), true, "Old name/old".into()) + ); + // A new id: copies under the lock, both monitors reset under their own + // lock, then the two capture sources told, the plain one only asked. + assert_eq!( + Case::new(Some("New"), Some("new")).original(), + ( + "ALCFnFiSSUALM0M1UEg0s0N0r0g2s2N2r2".into(), + true, + "New/new".into() + ) + ); +} + +fn names() -> impl Strategy> { + prop_oneof![ + 1 => Just(None), + 1 => Just(Some(String::new())), + 8 => "[a-c]{1,6}".prop_map(Some), + ] +} + +fn cases() -> impl Strategy { + ( + names(), + names(), + any::(), + "[a-c]{1,6}", + 0..=8usize, + prop::collection::vec( + ( + prop_oneof![Just(0), Just(AUDIO), Just(AOC), Just(DO_NOT_SELF_MONITOR)], + "[a-c]{0,6}", + ), + 0..=8, + ), + ) + .prop_map(|(name, id, available, stored_id, monitors, sources)| Case { + name, + id, + available, + stored_id, + monitors, + sources, + }) +} + +#[test] +fn characterized_edges() { + for name in [None, Some(""), Some("New")] { + for id in [None, Some(""), Some("old"), Some("new")] { + for available in [false, true] { + for monitors in [0, 1, 8] { + let mut case = Case::new(name, id); + case.available = available; + case.monitors = monitors; + assert_eq!(case.probe(obs_set_audio_monitoring_device), 0, "{case:?}"); + } + } + } + } + for available in [false, true] { + for monitors in 0..=8 { + assert_eq!( + reset_probe(obs_reset_audio_monitoring, available, monitors), + 0, + "{available} {monitors}" + ); + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: obs_c_oracle::parity::cases(512), failure_persistence: None, ..ProptestConfig::default() })] + #[test] + fn any_device_matches_c(case in cases()) { + prop_assert_eq!(case.probe(obs_set_audio_monitoring_device), 0, "{:?}", case); + } + + #[test] + fn any_reset_matches_c(available in any::(), monitors in 0..=8usize) { + prop_assert_eq!(reset_probe(obs_reset_audio_monitoring, available, monitors), 0); + } +} + +// --------------------------------------------------------------------------- +// mutants, over the same adapters + +/// The original's steps, with switches for each broken contract. +#[derive(Clone, Copy, Default)] +struct Breaks { + available_first: bool, + no_same_shortcut: bool, + same_is_false: bool, + reset_before_unlock: bool, + no_reset: bool, + notify_all: bool, + stop_after_first: bool, + reset_without_check: bool, + count_once_less: bool, +} + +thread_local! { + static BREAKS: Cell = Cell::new(Breaks::default()); +} + +fn breaks() -> Breaks { + BREAKS.with(Cell::get) +} + +unsafe extern "C" fn mutant_reset() { + let b = breaks(); + // SAFETY: the probe's fixture core; each adapter is used as the shim + // does. + unsafe { + if !b.reset_without_check && !obs_audio_monitoring_device_available() { + return; + } + obs_audio_monitoring_device_lock(); + let mut index = 0; + while index + < obs_audio_monitoring_device_monitor_count() + .saturating_sub(usize::from(b.count_once_less)) + { + obs_audio_monitoring_device_reset_monitor(index); + index += 1; + } + obs_audio_monitoring_device_unlock(); + } +} + +unsafe extern "C" fn mutant_visit(_param: *mut c_void, source: *mut c_void) -> bool { + let b = breaks(); + // SAFETY: a fixture source handed over by the enumeration. + unsafe { + if b.notify_all + || obs_audio_monitoring_device_output_flags(source) & DO_NOT_SELF_MONITOR != 0 + { + obs_audio_monitoring_device_notify(source); + } + } + !b.stop_after_first +} + +unsafe extern "C" fn mutant_set(name: *const c_char, id: *const c_char) -> bool { + let b = breaks(); + // SAFETY: the probe's strings and fixture core; each adapter is used as + // the shim does. + unsafe { + if b.available_first && !obs_audio_monitoring_device_available() { + return false; + } + if name.is_null() || id.is_null() || *name == 0 || *id == 0 { + return false; + } + if !b.available_first && !obs_audio_monitoring_device_available() { + return false; + } + obs_audio_monitoring_device_lock(); + if !b.no_same_shortcut && obs_audio_monitoring_device_compare(id) == 0 { + obs_audio_monitoring_device_unlock(); + return !b.same_is_false; + } + obs_audio_monitoring_device_store(name, id); + if b.reset_before_unlock { + mutant_reset(); + obs_audio_monitoring_device_unlock(); + } else { + obs_audio_monitoring_device_unlock(); + if !b.no_reset { + mutant_reset(); + } + } + obs_audio_monitoring_device_enum_sources(mutant_visit, core::ptr::null_mut()); + true + } +} + +#[test] +fn unbroken_mutant_matches() { + BREAKS.with(|cell| cell.set(Breaks::default())); + for name in [None, Some(""), Some("New")] { + for id in [None, Some(""), Some("old"), Some("new")] { + assert_eq!(Case::new(name, id).probe(mutant_set), 0); + } + } + assert_eq!(reset_probe(mutant_reset, true, 3), 0); +} + +#[test] +fn mutants_are_caught() { + let set_mutants: [(&str, Breaks); 8] = [ + ( + "availability before the name and id", + Breaks { + available_first: true, + ..Breaks::default() + }, + ), + ( + "no same-id shortcut", + Breaks { + no_same_shortcut: true, + ..Breaks::default() + }, + ), + ( + "same id answers false", + Breaks { + same_is_false: true, + ..Breaks::default() + }, + ), + ( + "resets before the unlock", + Breaks { + reset_before_unlock: true, + ..Breaks::default() + }, + ), + ( + "no resets", + Breaks { + no_reset: true, + ..Breaks::default() + }, + ), + ( + "every source told", + Breaks { + notify_all: true, + ..Breaks::default() + }, + ), + ( + "enumeration stopped after one source", + Breaks { + stop_after_first: true, + ..Breaks::default() + }, + ), + ( + "one monitor fewer", + Breaks { + count_once_less: true, + ..Breaks::default() + }, + ), + ]; + let fixtures = [ + Case::new(None, Some("new")), + Case::new(Some(""), Some("new")), + Case::new(Some("New"), Some("old")), + Case::new(Some("New"), Some("new")), + ]; + for (label, b) in set_mutants { + BREAKS.with(|cell| cell.set(b)); + let caught = fixtures.iter().any(|case| case.probe(mutant_set) != 0); + assert!(caught, "mutant not caught: {label}"); + } + let reset_mutants: [(&str, Breaks); 2] = [ + ( + "reset without the availability check", + Breaks { + reset_without_check: true, + ..Breaks::default() + }, + ), + ( + "reset one monitor fewer", + Breaks { + count_once_less: true, + ..Breaks::default() + }, + ), + ]; + for (label, b) in reset_mutants { + BREAKS.with(|cell| cell.set(b)); + let caught = [false, true] + .iter() + .any(|&available| reset_probe(mutant_reset, available, 2) != 0); + assert!(caught, "mutant not caught: {label}"); + } + BREAKS.with(|cell| cell.set(Breaks::default())); +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 77f5d20479..7e5d3bce1a 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -16,6 +16,7 @@ mod audio_min_ts_parity; mod audio_mix; mod audio_mix_parity; mod audio_monitoring_device; +mod audio_monitoring_device_parity; mod audio_render; mod audio_render_parity; mod base_effect;