From 1e6511fd6f6b7bd9a53d460701aaafda63e378b3 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:54:08 -0400 Subject: [PATCH 1/7] libobs: Move the media action admission decisions into obs-source-media-admission.c Behaviour-neutral extraction before the Rust port. The media action decisions of obs-source.c.h move to libobs/obs-source-media-admission.c.h, as eight functions on plain values declared in the new libobs/obs-source-media-admission.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_source_media_admit(), _admit_flags() and _admit_callback(): whether each obs_source_media_*() call is accepted, one step at a time in the old order. An invalid source is rejected, then one without OBS_SOURCE_CONTROLLABLE_MEDIA, then, for every call but _started() and _ended(), one without the call's callback. Each step that needs a value answers READ_FLAGS or READ_CALLBACK, and obs-source.c.h reads that value then, so the output flags are read only for a valid source and a callback only for a controllable one, as before; - obs_source_media_time_fallback() and _state_fallback(): what the getters return when rejected, 0 and OBS_MEDIA_STATE_NONE; - obs_source_media_dispatch(): what process_media_actions() does with a queued action type, the matching callback, RETURN for MEDIA_ACTION_NONE and SKIP for a type outside the enum (no case matched, so the loop took the next action); - obs_source_media_signal_reads_pause() and obs_source_media_signal(): the signal emitted after the callback, media_pause or media_play by action.pause, media_restart, media_stopped, media_next and media_previous, none for a set-time. action.pause is read only for a play/pause, as before (the union holds the time for a set-time). obs-source.c.h keeps data_valid() and obs_source_valid() (they log), every field read, the action queue and its mutex, the callbacks, the signals and the refs: each callback still runs before its signal and reads action.pause and action.ms where it did. The header mirrors OBS_SOURCE_CONTROLLABLE_MEDIA, OBS_MEDIA_STATE_NONE and enum media_action_type as defines, so the moved file needs no libobs header; obs-source.c.h checks each value, and that enum media_action_type and enum obs_media_state are int-sized. The new file joins libobs.core-source, before obs-source.c.h, with libobs.pch.h, which includes the new header; source-sets.json lists it. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. The exported symbol set is unchanged (1766); the eight functions are local. Checked in a scratch harness (not committed) that compiles origin/master's process_media_actions() and eleven obs_source_media_*() functions verbatim next to this branch's and the moved file, on a stand-in source, with every call they make logged (the validity checks, the mutex, the queue push and pop with the pushed action, the callbacks with their arguments, the signals) and every field and action read rewritten into a logged read the same way on both sides. Every call x valid or NULL source x data or none x 8 output flag sets (none, the flag alone, all bits, all but it, its neighbours) x all 512 sets of the nine callbacks x both pause values, with the getters returning the int64 and state ends; process_media_actions() over every queued type (0 to 8, -1, 100, INT_MAX, INT_MIN) alone and in pairs with both pauses and set-time values at the int64 ends, and an empty queue; then 2,000,000 random calls and 2,000,000 random queues of up to eight actions: 4,361,177 runs, 119,511,308 logged calls and reads, identical under GCC and clang at -O0 and -O2 with ASan and UBSan (one trace hash per compiler, as the two evaluate a call's arguments in different orders). Each of 19 planted changes is caught (the flag test inverted and on another bit, _started() or _ended() needing a callback, _get_state() not needing one, the callback test inverted, the flags read for an invalid source, either fallback, stop dispatched as next, set-time skipped, an unknown type returning, play and pause swapped, the stopped signal's name, a set-time signal, action.pause read for every action, and in obs-source.c the flags read before the validity check, a callback read before the flags and action.pause read always); the callback test written as has_callback == false, which is equivalent, passes. Refs #2239 --- libobs/build/libobs.core-source+.h.c | 1 + libobs/build/libobs.pch.h | 1 + libobs/build/source-sets.json | 1 + libobs/obs-source-media-admission.c.h | 129 ++++++++++++++++++ libobs/obs-source-media-admission.h | 142 +++++++++++++++++++ libobs/obs-source.c.h | 187 ++++++++++++++------------ 6 files changed, 377 insertions(+), 84 deletions(-) create mode 100644 libobs/obs-source-media-admission.c.h create mode 100644 libobs/obs-source-media-admission.h diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index c4cf0c47b3..e1785c667a 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -7,6 +7,7 @@ #include "libobs/obs-scene-item-audio-actions.c.h" #include "libobs/obs-scene.c.h" #include "libobs/obs-source-deinterlace.c.h" +#include "libobs/obs-source-media-admission.c.h" #include "libobs/obs-source-transition.c.h" #include "libobs/obs-source.c.h" #include "libobs/obs-view.c.h" diff --git a/libobs/build/libobs.pch.h b/libobs/build/libobs.pch.h index 925837df88..a4cb6e7ef4 100644 --- a/libobs/build/libobs.pch.h +++ b/libobs/build/libobs.pch.h @@ -150,6 +150,7 @@ #include "obs-source-conversion-plan.h" #include "obs-source-draw-plan.h" #include "obs-source-frame-copy.h" +#include "obs-source-media-admission.h" #include "obs-source-ptm-gate.h" #include "obs-source-render-route.h" #include "obs-source-size.h" diff --git a/libobs/build/source-sets.json b/libobs/build/source-sets.json index 4dc5fbf3e3..86a44a1cc0 100644 --- a/libobs/build/source-sets.json +++ b/libobs/build/source-sets.json @@ -57,6 +57,7 @@ "obs-source-draw-technique.h", "obs-source-frame-copy.h", "obs-source-load.h", + "obs-source-media-admission.h", "obs-source-ptm-gate.h", "obs-source-render-route.h", "obs-source-size.h", diff --git a/libobs/obs-source-media-admission.c.h b/libobs/obs-source-media-admission.c.h new file mode 100644 index 0000000000..7ebc8135d5 --- /dev/null +++ b/libobs/obs-source-media-admission.c.h @@ -0,0 +1,129 @@ +/****************************************************************************** + Copyright (C) 2023 by Lain Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "libobs/build/libobs.pch.h" + +/* The media action admission decisions of obs-source.c, moved from the + * obs_source_media_*() functions (the controllable and callback checks and + * the getters' fallbacks) and process_media_actions() (the callback and + * signal of each queued action): the decisions, on plain values. + * obs-source.c keeps data_valid(), every field read, the action queue and + * its mutex, the callbacks and the signals, and acts on what comes back. + * Declared in obs-source-media-admission.h without EXPORT. In hybrid libobs + * the Rust port (rust/obs-source, media_admission) replaces this file. */ + +enum obs_source_media_admit obs_source_media_admit(bool valid) +{ + if (!valid) + return OBS_SOURCE_MEDIA_ADMIT_REJECT; + + return OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS; +} + +enum obs_source_media_admit obs_source_media_admit_flags(enum obs_source_media_call call, uint32_t output_flags) +{ + if ((output_flags & OBS_SOURCE_MEDIA_CONTROLLABLE) == 0) + return OBS_SOURCE_MEDIA_ADMIT_REJECT; + + switch (call) { + case OBS_SOURCE_MEDIA_CALL_STARTED: + case OBS_SOURCE_MEDIA_CALL_ENDED: + return OBS_SOURCE_MEDIA_ADMIT_ACCEPT; + case OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE: + case OBS_SOURCE_MEDIA_CALL_RESTART: + case OBS_SOURCE_MEDIA_CALL_STOP: + case OBS_SOURCE_MEDIA_CALL_NEXT: + case OBS_SOURCE_MEDIA_CALL_PREVIOUS: + case OBS_SOURCE_MEDIA_CALL_GET_DURATION: + case OBS_SOURCE_MEDIA_CALL_GET_TIME: + case OBS_SOURCE_MEDIA_CALL_SET_TIME: + case OBS_SOURCE_MEDIA_CALL_GET_STATE: + break; + } + + return OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK; +} + +enum obs_source_media_admit obs_source_media_admit_callback(bool has_callback) +{ + if (!has_callback) + return OBS_SOURCE_MEDIA_ADMIT_REJECT; + + return OBS_SOURCE_MEDIA_ADMIT_ACCEPT; +} + +int64_t obs_source_media_time_fallback(void) +{ + return 0; +} + +int obs_source_media_state_fallback(void) +{ + return OBS_SOURCE_MEDIA_STATE_NONE; +} + +enum obs_source_media_dispatch obs_source_media_dispatch(int type) +{ + switch (type) { + case OBS_SOURCE_MEDIA_ACTION_NONE: + return OBS_SOURCE_MEDIA_DISPATCH_RETURN; + case OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE: + return OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE; + case OBS_SOURCE_MEDIA_ACTION_RESTART: + return OBS_SOURCE_MEDIA_DISPATCH_RESTART; + case OBS_SOURCE_MEDIA_ACTION_STOP: + return OBS_SOURCE_MEDIA_DISPATCH_STOP; + case OBS_SOURCE_MEDIA_ACTION_NEXT: + return OBS_SOURCE_MEDIA_DISPATCH_NEXT; + case OBS_SOURCE_MEDIA_ACTION_PREVIOUS: + return OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS; + case OBS_SOURCE_MEDIA_ACTION_SET_TIME: + return OBS_SOURCE_MEDIA_DISPATCH_SET_TIME; + default: + return OBS_SOURCE_MEDIA_DISPATCH_SKIP; + } +} + +bool obs_source_media_signal_reads_pause(enum obs_source_media_dispatch dispatch) +{ + return dispatch == OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE; +} + +const char *obs_source_media_signal(enum obs_source_media_dispatch dispatch, bool pause) +{ + switch (dispatch) { + case OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE: + if (pause) + return "media_pause"; + else + return "media_play"; + case OBS_SOURCE_MEDIA_DISPATCH_RESTART: + return "media_restart"; + case OBS_SOURCE_MEDIA_DISPATCH_STOP: + return "media_stopped"; + case OBS_SOURCE_MEDIA_DISPATCH_NEXT: + return "media_next"; + case OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS: + return "media_previous"; + case OBS_SOURCE_MEDIA_DISPATCH_RETURN: + case OBS_SOURCE_MEDIA_DISPATCH_SET_TIME: + case OBS_SOURCE_MEDIA_DISPATCH_SKIP: + break; + } + + return NULL; +} diff --git a/libobs/obs-source-media-admission.h b/libobs/obs-source-media-admission.h new file mode 100644 index 0000000000..f001682412 --- /dev/null +++ b/libobs/obs-source-media-admission.h @@ -0,0 +1,142 @@ +/****************************************************************************** + Copyright (C) 2023 by Lain Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#pragma once + +#include +#include +#include + +/* The media action admission decisions of obs-source.c, on plain values + * (obs-source-media-admission.c): + * - the obs_source_media_*() functions: whether a call is accepted, in the + * old order. A source that is not valid (data_valid(), or + * obs_source_valid() for _started() and _ended()) is rejected, then one + * without OBS_SOURCE_CONTROLLABLE_MEDIA, then, for every call but + * _started() and _ended(), one without the call's callback. A READ_ step + * asks obs-source.c for the next value, so a field is read only where it + * was read before; + * - the getters' fallbacks: 0 for the duration and the time, + * OBS_MEDIA_STATE_NONE for the state; + * - process_media_actions(): what each queued action does, the callback it + * calls and the signal it emits after it. + * + * obs-source.c keeps data_valid() and obs_source_valid() (they log), every + * field read, the action queue and its mutex, the callbacks, the signals + * and the source refs. None of these functions takes a lock, calls into + * libobs or keeps state. + * + * Hidden in libobs: not EXPORT. */ + +/* obs-source.c checks that these are OBS_SOURCE_CONTROLLABLE_MEDIA, + * OBS_MEDIA_STATE_NONE and enum media_action_type (obs-internal.h). */ +#define OBS_SOURCE_MEDIA_CONTROLLABLE (1u << 13) +#define OBS_SOURCE_MEDIA_STATE_NONE 0 +#define OBS_SOURCE_MEDIA_ACTION_NONE 0 +#define OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE 1 +#define OBS_SOURCE_MEDIA_ACTION_RESTART 2 +#define OBS_SOURCE_MEDIA_ACTION_STOP 3 +#define OBS_SOURCE_MEDIA_ACTION_NEXT 4 +#define OBS_SOURCE_MEDIA_ACTION_PREVIOUS 5 +#define OBS_SOURCE_MEDIA_ACTION_SET_TIME 6 + +/* The public obs_source_media_*() function being admitted. */ +enum obs_source_media_call { + OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE, + OBS_SOURCE_MEDIA_CALL_RESTART, + OBS_SOURCE_MEDIA_CALL_STOP, + OBS_SOURCE_MEDIA_CALL_NEXT, + OBS_SOURCE_MEDIA_CALL_PREVIOUS, + OBS_SOURCE_MEDIA_CALL_GET_DURATION, + OBS_SOURCE_MEDIA_CALL_GET_TIME, + OBS_SOURCE_MEDIA_CALL_SET_TIME, + OBS_SOURCE_MEDIA_CALL_GET_STATE, + OBS_SOURCE_MEDIA_CALL_STARTED, + OBS_SOURCE_MEDIA_CALL_ENDED, +}; + +/* An admission answer, or the value to read before it is known. */ +enum obs_source_media_admit { + /* return (a getter returns its fallback) */ + OBS_SOURCE_MEDIA_ADMIT_REJECT, + /* queue the action, call the getter or emit the signal */ + OBS_SOURCE_MEDIA_ADMIT_ACCEPT, + /* read source->info.output_flags */ + OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS, + /* read the call's callback in source->info (!= NULL) */ + OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK, +}; + +/* What process_media_actions() does with an action it took off the + * queue. */ +enum obs_source_media_dispatch { + /* MEDIA_ACTION_NONE, the queue was empty: return */ + OBS_SOURCE_MEDIA_DISPATCH_RETURN, + /* media_play_pause(data, action.pause) */ + OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE, + /* media_restart(data) */ + OBS_SOURCE_MEDIA_DISPATCH_RESTART, + /* media_stop(data) */ + OBS_SOURCE_MEDIA_DISPATCH_STOP, + /* media_next(data) */ + OBS_SOURCE_MEDIA_DISPATCH_NEXT, + /* media_previous(data) */ + OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS, + /* media_set_time(data, action.ms) */ + OBS_SOURCE_MEDIA_DISPATCH_SET_TIME, + /* a type outside the enum: nothing, take the next action */ + OBS_SOURCE_MEDIA_DISPATCH_SKIP, +}; + +/* --- the obs_source_media_*() functions -------------------------------- */ + +/* The first step: READ_FLAGS for a valid source, else REJECT. */ +enum obs_source_media_admit obs_source_media_admit(bool valid); + +/* The step after reading the output flags: REJECT without + * OBS_SOURCE_CONTROLLABLE_MEDIA, ACCEPT for _started() and _ended(), else + * READ_CALLBACK (a call outside the enum included). */ +enum obs_source_media_admit obs_source_media_admit_flags(enum obs_source_media_call call, uint32_t output_flags); + +/* The step after reading the callback: ACCEPT when it is set, else + * REJECT. */ +enum obs_source_media_admit obs_source_media_admit_callback(bool has_callback); + +/* What obs_source_media_get_duration() and _get_time() return when the + * call is rejected: 0. */ +int64_t obs_source_media_time_fallback(void); + +/* What obs_source_media_get_state() returns when the call is rejected: + * OBS_MEDIA_STATE_NONE, as int (obs-source.c checks the enum's size). */ +int obs_source_media_state_fallback(void); + +/* --- process_media_actions() -------------------------------------------- */ + +/* The dispatch of a queued action's type (enum media_action_type, as + * int): RETURN for MEDIA_ACTION_NONE, the matching callback for the + * others, SKIP for a value outside the enum. */ +enum obs_source_media_dispatch obs_source_media_dispatch(int type); + +/* Whether the signal reads action.pause: only for PLAY_PAUSE (the union + * holds the time for SET_TIME). */ +bool obs_source_media_signal_reads_pause(enum obs_source_media_dispatch dispatch); + +/* The signal emitted after the callback: "media_pause" or "media_play" + * (by pause), "media_restart", "media_stopped", "media_next", + * "media_previous"; NULL for SET_TIME, RETURN, SKIP and a value outside + * the enum. pause is false when not read. */ +const char *obs_source_media_signal(enum obs_source_media_dispatch dispatch, bool pause); diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index 5437dbc4bd..0ed7b23c71 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -1303,6 +1303,19 @@ static void filter_frame(obs_source_t *source, struct obs_source_frame **ref_fra *ref_frame = frame; } +_Static_assert(MEDIA_ACTION_NONE == OBS_SOURCE_MEDIA_ACTION_NONE, "MEDIA_ACTION_NONE"); +_Static_assert(MEDIA_ACTION_PLAY_PAUSE == OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, "MEDIA_ACTION_PLAY_PAUSE"); +_Static_assert(MEDIA_ACTION_RESTART == OBS_SOURCE_MEDIA_ACTION_RESTART, "MEDIA_ACTION_RESTART"); +_Static_assert(MEDIA_ACTION_STOP == OBS_SOURCE_MEDIA_ACTION_STOP, "MEDIA_ACTION_STOP"); +_Static_assert(MEDIA_ACTION_NEXT == OBS_SOURCE_MEDIA_ACTION_NEXT, "MEDIA_ACTION_NEXT"); +_Static_assert(MEDIA_ACTION_PREVIOUS == OBS_SOURCE_MEDIA_ACTION_PREVIOUS, "MEDIA_ACTION_PREVIOUS"); +_Static_assert(MEDIA_ACTION_SET_TIME == OBS_SOURCE_MEDIA_ACTION_SET_TIME, "MEDIA_ACTION_SET_TIME"); +_Static_assert(sizeof(enum media_action_type) == sizeof(int), "enum media_action_type is passed as int"); + +/* What each queued action calls and the signal it emits go through + * obs-source-media-admission.c. The queue and its mutex, the callbacks and + * the signals stay here, the callback before the signal as before; + * action.pause is read only for a play/pause. */ void process_media_actions(obs_source_t *source) { struct media_action action = {0}; @@ -1317,39 +1330,37 @@ void process_media_actions(obs_source_t *source) } pthread_mutex_unlock(&source->media_actions_mutex); - switch (action.type) { - case MEDIA_ACTION_NONE: + enum obs_source_media_dispatch dispatch = obs_source_media_dispatch((int)action.type); + + switch (dispatch) { + case OBS_SOURCE_MEDIA_DISPATCH_RETURN: return; - case MEDIA_ACTION_PLAY_PAUSE: + case OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE: source->info.media_play_pause(source->context.data, action.pause); - - if (action.pause) - obs_source_dosignal(source, NULL, "media_pause"); - else - obs_source_dosignal(source, NULL, "media_play"); break; - - case MEDIA_ACTION_RESTART: + case OBS_SOURCE_MEDIA_DISPATCH_RESTART: source->info.media_restart(source->context.data); - obs_source_dosignal(source, NULL, "media_restart"); break; - - case MEDIA_ACTION_STOP: + case OBS_SOURCE_MEDIA_DISPATCH_STOP: source->info.media_stop(source->context.data); - obs_source_dosignal(source, NULL, "media_stopped"); break; - case MEDIA_ACTION_NEXT: + case OBS_SOURCE_MEDIA_DISPATCH_NEXT: source->info.media_next(source->context.data); - obs_source_dosignal(source, NULL, "media_next"); break; - case MEDIA_ACTION_PREVIOUS: + case OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS: source->info.media_previous(source->context.data); - obs_source_dosignal(source, NULL, "media_previous"); break; - case MEDIA_ACTION_SET_TIME: + case OBS_SOURCE_MEDIA_DISPATCH_SET_TIME: source->info.media_set_time(source->context.data, action.ms); break; + case OBS_SOURCE_MEDIA_DISPATCH_SKIP: + break; } + + const char *signal = obs_source_media_signal(dispatch, obs_source_media_signal_reads_pause(dispatch) && + action.pause); + if (signal) + obs_source_dosignal(source, NULL, signal); } } @@ -5323,14 +5334,29 @@ const char *obs_source_get_light_icon(const char *id) return (info && info->get_light_icon) ? info->get_light_icon(info->type_data) : NULL; } -void obs_source_media_play_pause(obs_source_t *source, bool pause) +_Static_assert(OBS_SOURCE_MEDIA_CONTROLLABLE == OBS_SOURCE_CONTROLLABLE_MEDIA, "OBS_SOURCE_CONTROLLABLE_MEDIA"); +_Static_assert(OBS_SOURCE_MEDIA_STATE_NONE == OBS_MEDIA_STATE_NONE, "OBS_MEDIA_STATE_NONE"); +_Static_assert(sizeof(enum obs_media_state) == sizeof(int), "enum obs_media_state is passed as int"); + +/* Whether a media call is accepted goes through + * obs-source-media-admission.c, in the old order: the validity check (it + * logs), then the output flags, then (in the caller, for the calls that + * have one) the callback, each read only when the step before passed. */ +static inline enum obs_source_media_admit media_admit(obs_source_t *source, bool valid, enum obs_source_media_call call) { - if (!data_valid(source, "obs_source_media_play_pause")) - return; + enum obs_source_media_admit admit = obs_source_media_admit(valid); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS) + admit = obs_source_media_admit_flags(call, source->info.output_flags); + return admit; +} - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_play_pause) +void obs_source_media_play_pause(obs_source_t *source, bool pause) +{ + enum obs_source_media_admit admit = media_admit(source, data_valid(source, "obs_source_media_play_pause"), + OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_play_pause != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5345,12 +5371,11 @@ void obs_source_media_play_pause(obs_source_t *source, bool pause) void obs_source_media_restart(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_restart")) - return; - - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_restart) + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_restart"), OBS_SOURCE_MEDIA_CALL_RESTART); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_restart != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5364,12 +5389,11 @@ void obs_source_media_restart(obs_source_t *source) void obs_source_media_stop(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_stop")) - return; - - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_stop) + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_stop"), OBS_SOURCE_MEDIA_CALL_STOP); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_stop != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5383,12 +5407,11 @@ void obs_source_media_stop(obs_source_t *source) void obs_source_media_next(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_next")) - return; - - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_next) + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_next"), OBS_SOURCE_MEDIA_CALL_NEXT); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_next != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5402,12 +5425,11 @@ void obs_source_media_next(obs_source_t *source) void obs_source_media_previous(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_previous")) - return; - - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_previous) + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_previous"), OBS_SOURCE_MEDIA_CALL_PREVIOUS); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_previous != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5421,37 +5443,35 @@ void obs_source_media_previous(obs_source_t *source) int64_t obs_source_media_get_duration(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_get_duration")) - return 0; + enum obs_source_media_admit admit = media_admit(source, data_valid(source, "obs_source_media_get_duration"), + OBS_SOURCE_MEDIA_CALL_GET_DURATION); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_get_duration != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) + return obs_source_media_time_fallback(); - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return 0; - if (source->info.media_get_duration) - return source->info.media_get_duration(source->context.data); - else - return 0; + return source->info.media_get_duration(source->context.data); } int64_t obs_source_media_get_time(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_get_time")) - return 0; + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_get_time"), OBS_SOURCE_MEDIA_CALL_GET_TIME); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_get_time != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) + return obs_source_media_time_fallback(); - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return 0; - if (source->info.media_get_time) - return source->info.media_get_time(source->context.data); - else - return 0; + return source->info.media_get_time(source->context.data); } void obs_source_media_set_time(obs_source_t *source, int64_t ms) { - if (!data_valid(source, "obs_source_media_set_time")) - return; - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return; - if (!source->info.media_set_time) + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_set_time"), OBS_SOURCE_MEDIA_CALL_SET_TIME); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_set_time != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; struct media_action action = { @@ -5466,22 +5486,21 @@ void obs_source_media_set_time(obs_source_t *source, int64_t ms) enum obs_media_state obs_source_media_get_state(obs_source_t *source) { - if (!data_valid(source, "obs_source_media_get_state")) - return OBS_MEDIA_STATE_NONE; - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) - return OBS_MEDIA_STATE_NONE; + enum obs_source_media_admit admit = + media_admit(source, data_valid(source, "obs_source_media_get_state"), OBS_SOURCE_MEDIA_CALL_GET_STATE); + if (admit == OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK) + admit = obs_source_media_admit_callback(source->info.media_get_state != NULL); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) + return (enum obs_media_state)obs_source_media_state_fallback(); - if (source->info.media_get_state) - return source->info.media_get_state(source->context.data); - else - return OBS_MEDIA_STATE_NONE; + return source->info.media_get_state(source->context.data); } void obs_source_media_started(obs_source_t *source) { - if (!obs_source_valid(source, "obs_source_media_started")) - return; - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) + enum obs_source_media_admit admit = media_admit(source, obs_source_valid(source, "obs_source_media_started"), + OBS_SOURCE_MEDIA_CALL_STARTED); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; obs_source_dosignal(source, NULL, "media_started"); @@ -5489,9 +5508,9 @@ void obs_source_media_started(obs_source_t *source) void obs_source_media_ended(obs_source_t *source) { - if (!obs_source_valid(source, "obs_source_media_ended")) - return; - if ((source->info.output_flags & OBS_SOURCE_CONTROLLABLE_MEDIA) == 0) + enum obs_source_media_admit admit = + media_admit(source, obs_source_valid(source, "obs_source_media_ended"), OBS_SOURCE_MEDIA_CALL_ENDED); + if (admit != OBS_SOURCE_MEDIA_ADMIT_ACCEPT) return; obs_source_dosignal(source, NULL, "media_ended"); From e52c0ad23309a1a0d621a724759c64c1d8765cd4 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:57:16 -0400 Subject: [PATCH 2/7] test: Characterize the media action admission decisions test_source_media_admission_steps compiles libobs/obs-source-media-admission.c.h (ASan and UBSan) and calls only its eight hidden functions. 12 cases: - enum_values: the mirrors obs-source.c checks (OBS_SOURCE_CONTROLLABLE_MEDIA, OBS_MEDIA_STATE_NONE and the seven media_action_type values), the call, step and dispatch numbers the port will return, and that the enums are int-sized; - admit_valid: an invalid source is rejected before its flags are read; - admit_flags_every_call, admit_flags_outside_enum: every call with 8 output flag sets (none, the flag alone, every bit, every bit but it, its neighbours, the flag with others) and each of the 32 bits alone: only OBS_SOURCE_CONTROLLABLE_MEDIA admits, _started() and _ended() are then accepted and every other call reads its callback, as does a call outside the enum; - admit_callback: accepted with the callback, rejected without; - admission_every_input: the steps in the callers' order for every call, valid or not, every flag set and with or without the callback: accepted exactly when valid, controllable and (for the calls that have one) the callback is set, the flags read once for a valid source and the callback once for a controllable one; - getter_fallbacks: 0 for the duration and the time, OBS_MEDIA_STATE_NONE for the state; - dispatch_every_type, dispatch_outside_enum: each media_action_type to its callback, MEDIA_ACTION_NONE to return, 7, 8, -1, 100 and the ends of int to skip; - signal_every_dispatch, signal_outside_enum: action.pause is read only for a play/pause; media_play or media_pause by it, media_restart, media_stopped, media_next and media_previous, none for the rest and for values outside the enum; - process_every_action: process_media_actions() written out with the moved functions over every action alone (both pauses) and a mixed queue, the callback before the signal, in queue order. Characterized, not endorsed: - _started() and _ended() emit their signal for any controllable source, with no callback to check (and obs-source.c checks them with obs_source_valid(), so a source with no data too); - a set-time emits no signal; - a queued type outside the enum is dropped without a word and the loop takes the next action; a queued MEDIA_ACTION_NONE stops the loop with actions still queued. The test is in the native test graph in name order, in the core suite (no suite size is pinned in rust/obs-build/tests/native.rs); it uses no libm. On the C backend it passes 12 of 12; flipping media_play and media_pause in the moved file fails two cases. Refs #2239 --- test/cmocka/build/test-graph.json | 23 + .../test_source_media_admission_steps.c | 440 ++++++++++++++++++ .../test_source_media_admission_steps.cmake | 12 + 3 files changed, 475 insertions(+) create mode 100644 test/cmocka/test_source_media_admission_steps.c create mode 100644 test/cmocka/tests.d/test_source_media_admission_steps.cmake diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index a85fa3cf93..80dfd53e68 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -2887,6 +2887,23 @@ ], "sanitizers": "address,undefined" }, + "test_source_media_admission_steps": { + "sources": [ + "test/cmocka/test_source_media_admission_steps.c", + "libobs/obs-source-media-admission.c.h" + ], + "includes": [ + "libobs", + "deps/libcaption" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka" + ], + "sanitizers": "address,undefined" + }, "test_source_profiler": { "sources": [ "test/cmocka/test_source_profiler.c" @@ -4810,6 +4827,12 @@ "${target}" ] }, + "test_source_media_admission_steps": { + "target": "test_source_media_admission_steps", + "command": [ + "${target}" + ] + }, "test_source_profiler": { "target": "test_source_profiler", "command": [ diff --git a/test/cmocka/test_source_media_admission_steps.c b/test/cmocka/test_source_media_admission_steps.c new file mode 100644 index 0000000000..d6e6476d29 --- /dev/null +++ b/test/cmocka/test_source_media_admission_steps.c @@ -0,0 +1,440 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "obs.h" +#include "obs-source-media-admission.h" + +/* + * Characterization of the media action admission decisions of + * libobs/obs-source.c, moved to libobs/obs-source-media-admission.c before + * its Rust port: + * - obs_source_media_admit(), _admit_flags() and _admit_callback(): whether + * each obs_source_media_*() call is accepted, one step at a time (valid, + * OBS_SOURCE_CONTROLLABLE_MEDIA, then the call's callback for every call + * but _started() and _ended()), and which value each step reads next; + * - obs_source_media_time_fallback() and _state_fallback(): what the + * getters return when a call is rejected; + * - obs_source_media_dispatch(), _signal_reads_pause() and _signal(): what + * process_media_actions() does with each queued action, the callback it + * calls and the signal it emits after it. + * Cases marked "characterized, not endorsed" are odd but real. + * + * The functions are hidden in libobs, so this test compiles the C source + * into itself and calls only them. test_media_play_after_stop, + * test_media_restart_first_frame, test_media_restart_stale_frame, + * test_media_seek_keyframe, test_media_time, test_slideshow_manual_end and + * test_stinger_media_duration cover the callers through the real libobs. + */ + +enum { REJECT = OBS_SOURCE_MEDIA_ADMIT_REJECT, ACCEPT = OBS_SOURCE_MEDIA_ADMIT_ACCEPT }; +enum { READ_FLAGS = OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS, READ_CALLBACK = OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK }; + +#define CALL_COUNT 11 + +/* output flags: none, the flag alone, every bit, every bit but it, its + * neighbours alone, and the flag with others */ +static const uint32_t FLAGS[] = {0, + OBS_SOURCE_CONTROLLABLE_MEDIA, + UINT32_MAX, + ~(uint32_t)OBS_SOURCE_CONTROLLABLE_MEDIA, + (uint32_t)OBS_SOURCE_CONTROLLABLE_MEDIA << 1, + (uint32_t)OBS_SOURCE_CONTROLLABLE_MEDIA >> 1, + OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_ASYNC, + OBS_SOURCE_CONTROLLABLE_MEDIA | OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO}; +#define FLAG_COUNT (sizeof(FLAGS) / sizeof(FLAGS[0])) + +/* calls, action types and dispatches outside their enums */ +static const int OUTSIDE_CALLS[] = {-1, 11, 12, 99, INT_MIN, INT_MAX}; +#define OUTSIDE_CALL_COUNT (sizeof(OUTSIDE_CALLS) / sizeof(OUTSIDE_CALLS[0])) +static const int OUTSIDE_TYPES[] = {7, 8, -1, 100, INT_MIN, INT_MAX}; +#define OUTSIDE_TYPE_COUNT (sizeof(OUTSIDE_TYPES) / sizeof(OUTSIDE_TYPES[0])) +static const int OUTSIDE_DISPATCHES[] = {8, 9, -1, 99, INT_MIN, INT_MAX}; +#define OUTSIDE_DISPATCH_COUNT (sizeof(OUTSIDE_DISPATCHES) / sizeof(OUTSIDE_DISPATCHES[0])) + +static void check_int(long long actual, long long expected, const char *what, int line) +{ + if (actual != expected) { + fprintf(stderr, "line %d: %s is %lld, expected %lld\n", line, what, actual, expected); + fail(); + } +} + +static void check_bool(bool actual, bool expected, const char *what, int line) +{ + if (actual != expected) { + fprintf(stderr, "line %d: %s is %s, expected %s\n", line, what, actual ? "true" : "false", + expected ? "true" : "false"); + fail(); + } +} + +static void check_str(const char *actual, const char *expected, const char *what, int line) +{ + if ((actual == NULL) != (expected == NULL) || (actual && strcmp(actual, expected) != 0)) { + fprintf(stderr, "line %d: %s is %s, expected %s\n", line, what, actual ? actual : "NULL", + expected ? expected : "NULL"); + fail(); + } +} + +#define CHECK_INT(actual, expected) check_int((long long)(actual), (long long)(expected), #actual, __LINE__) +#define CHECK_BOOL(actual, expected) check_bool((actual), (expected), #actual, __LINE__) +#define CHECK_STR(actual, expected) check_str((actual), (expected), #actual, __LINE__) + +/* The callers' rule, written out: the calls that need a callback. */ +static bool needs_callback(int call) +{ + return call != OBS_SOURCE_MEDIA_CALL_STARTED && call != OBS_SOURCE_MEDIA_CALL_ENDED; +} + +/* --- enum values ------------------------------------------------------- */ + +static void enum_values(void **state) +{ + (void)state; + + /* the mirrors obs-source.c checks against libobs */ + CHECK_INT(OBS_SOURCE_MEDIA_CONTROLLABLE, OBS_SOURCE_CONTROLLABLE_MEDIA); + CHECK_INT(OBS_SOURCE_MEDIA_CONTROLLABLE, 1u << 13); + CHECK_INT(OBS_SOURCE_MEDIA_STATE_NONE, OBS_MEDIA_STATE_NONE); + CHECK_INT(OBS_SOURCE_MEDIA_STATE_NONE, 0); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_NONE, 0); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, 1); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_RESTART, 2); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_STOP, 3); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_NEXT, 4); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_PREVIOUS, 5); + CHECK_INT(OBS_SOURCE_MEDIA_ACTION_SET_TIME, 6); + + CHECK_INT(OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE, 0); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_RESTART, 1); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_STOP, 2); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_NEXT, 3); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_PREVIOUS, 4); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_GET_DURATION, 5); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_GET_TIME, 6); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_SET_TIME, 7); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_GET_STATE, 8); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_STARTED, 9); + CHECK_INT(OBS_SOURCE_MEDIA_CALL_ENDED, 10); + + CHECK_INT(OBS_SOURCE_MEDIA_ADMIT_REJECT, 0); + CHECK_INT(OBS_SOURCE_MEDIA_ADMIT_ACCEPT, 1); + CHECK_INT(OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS, 2); + CHECK_INT(OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK, 3); + + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_RETURN, 0); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE, 1); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_RESTART, 2); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_STOP, 3); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_NEXT, 4); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS, 5); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_SET_TIME, 6); + CHECK_INT(OBS_SOURCE_MEDIA_DISPATCH_SKIP, 7); + + /* the enums cross as int */ + CHECK_INT(sizeof(enum obs_source_media_call), sizeof(int)); + CHECK_INT(sizeof(enum obs_source_media_admit), sizeof(int)); + CHECK_INT(sizeof(enum obs_source_media_dispatch), sizeof(int)); + CHECK_INT(sizeof(enum obs_media_state), sizeof(int)); +} + +/* --- admission --------------------------------------------------------- */ + +static void admit_valid(void **state) +{ + (void)state; + + /* an invalid source (NULL, or no data for every call but _started() + * and _ended()) is rejected before its flags are read */ + CHECK_INT(obs_source_media_admit(false), REJECT); + CHECK_INT(obs_source_media_admit(true), READ_FLAGS); +} + +static void admit_flags_every_call(void **state) +{ + (void)state; + + for (int call = 0; call < CALL_COUNT; call++) + for (size_t f = 0; f < FLAG_COUNT; f++) { + const bool controllable = (FLAGS[f] & OBS_SOURCE_CONTROLLABLE_MEDIA) != 0; + const int expected = !controllable ? REJECT : needs_callback(call) ? READ_CALLBACK : ACCEPT; + CHECK_INT(obs_source_media_admit_flags((enum obs_source_media_call)call, FLAGS[f]), expected); + } + + /* every single bit: only OBS_SOURCE_CONTROLLABLE_MEDIA admits */ + for (int bit = 0; bit < 32; bit++) { + const uint32_t flags = 1u << bit; + CHECK_INT(obs_source_media_admit_flags(OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE, flags), + bit == 13 ? READ_CALLBACK : REJECT); + CHECK_INT(obs_source_media_admit_flags(OBS_SOURCE_MEDIA_CALL_STARTED, flags), + bit == 13 ? ACCEPT : REJECT); + } +} + +static void admit_flags_outside_enum(void **state) +{ + (void)state; + + /* a call outside the enum is treated as one with a callback */ + for (size_t c = 0; c < OUTSIDE_CALL_COUNT; c++) { + const enum obs_source_media_call call = (enum obs_source_media_call)OUTSIDE_CALLS[c]; + CHECK_INT(obs_source_media_admit_flags(call, OBS_SOURCE_CONTROLLABLE_MEDIA), READ_CALLBACK); + CHECK_INT(obs_source_media_admit_flags(call, UINT32_MAX), READ_CALLBACK); + CHECK_INT(obs_source_media_admit_flags(call, 0), REJECT); + CHECK_INT(obs_source_media_admit_flags(call, ~(uint32_t)OBS_SOURCE_CONTROLLABLE_MEDIA), REJECT); + } +} + +static void admit_callback(void **state) +{ + (void)state; + + CHECK_INT(obs_source_media_admit_callback(true), ACCEPT); + CHECK_INT(obs_source_media_admit_callback(false), REJECT); +} + +/* The steps in the callers' order (media_admit() and the callback check of + * obs-source.c) for one call; counts the values read. */ +static int admit_in_order(int call, bool valid, uint32_t flags, bool has_callback, int *flag_reads, int *callback_reads) +{ + int admit = (int)obs_source_media_admit(valid); + if (admit == READ_FLAGS) { + (*flag_reads)++; + admit = (int)obs_source_media_admit_flags((enum obs_source_media_call)call, flags); + } + if (admit == READ_CALLBACK) { + (*callback_reads)++; + admit = (int)obs_source_media_admit_callback(has_callback); + } + return admit; +} + +static void admission_every_input(void **state) +{ + (void)state; + + for (int call = 0; call < CALL_COUNT; call++) + for (int valid = 0; valid < 2; valid++) + for (size_t f = 0; f < FLAG_COUNT; f++) + for (int cb = 0; cb < 2; cb++) { + int flag_reads = 0, callback_reads = 0; + const int admit = + admit_in_order(call, valid, FLAGS[f], cb, &flag_reads, &callback_reads); + const bool controllable = (FLAGS[f] & OBS_SOURCE_CONTROLLABLE_MEDIA) != 0; + const bool accepted = valid && controllable && (!needs_callback(call) || cb); + + CHECK_INT(admit, accepted ? ACCEPT : REJECT); + /* the flags only for a valid source, a callback only + * for a controllable one that has one to check */ + CHECK_INT(flag_reads, valid ? 1 : 0); + CHECK_INT(callback_reads, + valid && controllable && needs_callback(call) ? 1 : 0); + } + + /* characterized, not endorsed: _started() and _ended() emit their + * signal for any controllable source, with no callback to check (and + * obs-source.c checks them with obs_source_valid(), so a source with + * no data too) */ + int flag_reads = 0, callback_reads = 0; + CHECK_INT(admit_in_order(OBS_SOURCE_MEDIA_CALL_STARTED, true, OBS_SOURCE_CONTROLLABLE_MEDIA, false, &flag_reads, + &callback_reads), + ACCEPT); + CHECK_INT(admit_in_order(OBS_SOURCE_MEDIA_CALL_ENDED, true, OBS_SOURCE_CONTROLLABLE_MEDIA, false, &flag_reads, + &callback_reads), + ACCEPT); + CHECK_INT(callback_reads, 0); +} + +/* --- fallbacks ---------------------------------------------------------- */ + +static void getter_fallbacks(void **state) +{ + (void)state; + + /* obs_source_media_get_duration() and _get_time() */ + CHECK_INT(obs_source_media_time_fallback(), 0); + /* obs_source_media_get_state() */ + CHECK_INT(obs_source_media_state_fallback(), OBS_MEDIA_STATE_NONE); +} + +/* --- process_media_actions() ---------------------------------------------- */ + +static void dispatch_every_type(void **state) +{ + (void)state; + + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_NONE), OBS_SOURCE_MEDIA_DISPATCH_RETURN); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE), OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_RESTART), OBS_SOURCE_MEDIA_DISPATCH_RESTART); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_STOP), OBS_SOURCE_MEDIA_DISPATCH_STOP); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_NEXT), OBS_SOURCE_MEDIA_DISPATCH_NEXT); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_PREVIOUS), OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS); + CHECK_INT(obs_source_media_dispatch(OBS_SOURCE_MEDIA_ACTION_SET_TIME), OBS_SOURCE_MEDIA_DISPATCH_SET_TIME); +} + +static void dispatch_outside_enum(void **state) +{ + (void)state; + + /* characterized, not endorsed: the switch has no case for it, so the + * action is dropped without a word and the next one is taken */ + for (size_t t = 0; t < OUTSIDE_TYPE_COUNT; t++) + CHECK_INT(obs_source_media_dispatch(OUTSIDE_TYPES[t]), OBS_SOURCE_MEDIA_DISPATCH_SKIP); +} + +static void signal_every_dispatch(void **state) +{ + (void)state; + + static const char *const SIGNALS[][2] = { + /* by pause: false, true */ + [OBS_SOURCE_MEDIA_DISPATCH_RETURN] = {NULL, NULL}, + [OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE] = {"media_play", "media_pause"}, + [OBS_SOURCE_MEDIA_DISPATCH_RESTART] = {"media_restart", "media_restart"}, + [OBS_SOURCE_MEDIA_DISPATCH_STOP] = {"media_stopped", "media_stopped"}, + [OBS_SOURCE_MEDIA_DISPATCH_NEXT] = {"media_next", "media_next"}, + [OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS] = {"media_previous", "media_previous"}, + /* characterized, not endorsed: a set-time emits nothing */ + [OBS_SOURCE_MEDIA_DISPATCH_SET_TIME] = {NULL, NULL}, + [OBS_SOURCE_MEDIA_DISPATCH_SKIP] = {NULL, NULL}, + }; + + for (int d = OBS_SOURCE_MEDIA_DISPATCH_RETURN; d <= OBS_SOURCE_MEDIA_DISPATCH_SKIP; d++) { + const enum obs_source_media_dispatch dispatch = (enum obs_source_media_dispatch)d; + CHECK_BOOL(obs_source_media_signal_reads_pause(dispatch), d == OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE); + CHECK_STR(obs_source_media_signal(dispatch, false), SIGNALS[d][0]); + CHECK_STR(obs_source_media_signal(dispatch, true), SIGNALS[d][1]); + } +} + +static void signal_outside_enum(void **state) +{ + (void)state; + + for (size_t d = 0; d < OUTSIDE_DISPATCH_COUNT; d++) { + const enum obs_source_media_dispatch dispatch = (enum obs_source_media_dispatch)OUTSIDE_DISPATCHES[d]; + CHECK_BOOL(obs_source_media_signal_reads_pause(dispatch), false); + CHECK_STR(obs_source_media_signal(dispatch, false), NULL); + CHECK_STR(obs_source_media_signal(dispatch, true), NULL); + } +} + +/* process_media_actions() over a queue, written out with the moved + * functions in its order: the callback, then the signal, until the queue + * is empty. Each step goes into the trace. */ +struct queued { + int type; + bool pause; +}; + +static void run_queue(const struct queued *queue, size_t count, char *trace, size_t size) +{ + static const char *const CALLBACKS[] = { + [OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE] = "play_pause", + [OBS_SOURCE_MEDIA_DISPATCH_RESTART] = "restart", + [OBS_SOURCE_MEDIA_DISPATCH_STOP] = "stop", + [OBS_SOURCE_MEDIA_DISPATCH_NEXT] = "next", + [OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS] = "previous", + [OBS_SOURCE_MEDIA_DISPATCH_SET_TIME] = "set_time", + }; + size_t next = 0; + + trace[0] = 0; + for (;;) { + const int type = next < count ? queue[next].type : OBS_SOURCE_MEDIA_ACTION_NONE; + const bool pause = next < count ? queue[next].pause : false; + next++; + + const enum obs_source_media_dispatch dispatch = obs_source_media_dispatch(type); + if (dispatch == OBS_SOURCE_MEDIA_DISPATCH_RETURN) { + strncat(trace, "return", size - strlen(trace) - 1); + return; + } + if (dispatch >= OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE && + dispatch <= OBS_SOURCE_MEDIA_DISPATCH_SET_TIME) { + strncat(trace, CALLBACKS[dispatch], size - strlen(trace) - 1); + strncat(trace, " ", size - strlen(trace) - 1); + } + const char *signal = + obs_source_media_signal(dispatch, obs_source_media_signal_reads_pause(dispatch) && pause); + if (signal) { + strncat(trace, signal, size - strlen(trace) - 1); + strncat(trace, " ", size - strlen(trace) - 1); + } + } +} + +static void process_every_action(void **state) +{ + (void)state; + + static const struct { + struct queued action; + const char *trace; + } ONE[] = { + {{OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, false}, "play_pause media_play return"}, + {{OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, true}, "play_pause media_pause return"}, + {{OBS_SOURCE_MEDIA_ACTION_RESTART, false}, "restart media_restart return"}, + {{OBS_SOURCE_MEDIA_ACTION_STOP, false}, "stop media_stopped return"}, + {{OBS_SOURCE_MEDIA_ACTION_NEXT, false}, "next media_next return"}, + {{OBS_SOURCE_MEDIA_ACTION_PREVIOUS, false}, "previous media_previous return"}, + {{OBS_SOURCE_MEDIA_ACTION_SET_TIME, false}, "set_time return"}, + /* the pause is not read for any other action */ + {{OBS_SOURCE_MEDIA_ACTION_RESTART, true}, "restart media_restart return"}, + {{OBS_SOURCE_MEDIA_ACTION_SET_TIME, true}, "set_time return"}, + /* characterized, not endorsed: skipped, the loop goes on */ + {{7, true}, "return"}, + {{-1, false}, "return"}, + {{INT_MAX, false}, "return"}, + /* a queued MEDIA_ACTION_NONE ends the loop like an empty queue */ + {{OBS_SOURCE_MEDIA_ACTION_NONE, false}, "return"}, + }; + char trace[256]; + + for (size_t i = 0; i < sizeof(ONE) / sizeof(ONE[0]); i++) { + run_queue(&ONE[i].action, 1, trace, sizeof(trace)); + CHECK_STR(trace, ONE[i].trace); + } + + run_queue(NULL, 0, trace, sizeof(trace)); + CHECK_STR(trace, "return"); + + /* in queue order; an unknown type in the middle is skipped, a queued + * MEDIA_ACTION_NONE stops the loop with actions still queued */ + const struct queued mixed[] = { + {OBS_SOURCE_MEDIA_ACTION_STOP, false}, {99, true}, + {OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, true}, {OBS_SOURCE_MEDIA_ACTION_SET_TIME, false}, + {OBS_SOURCE_MEDIA_ACTION_NONE, false}, {OBS_SOURCE_MEDIA_ACTION_NEXT, false}, + }; + run_queue(mixed, sizeof(mixed) / sizeof(mixed[0]), trace, sizeof(trace)); + CHECK_STR(trace, "stop media_stopped play_pause media_pause set_time return"); +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(enum_values), + cmocka_unit_test(admit_valid), + cmocka_unit_test(admit_flags_every_call), + cmocka_unit_test(admit_flags_outside_enum), + cmocka_unit_test(admit_callback), + cmocka_unit_test(admission_every_input), + cmocka_unit_test(getter_fallbacks), + cmocka_unit_test(dispatch_every_type), + cmocka_unit_test(dispatch_outside_enum), + cmocka_unit_test(signal_every_dispatch), + cmocka_unit_test(signal_outside_enum), + cmocka_unit_test(process_every_action), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/tests.d/test_source_media_admission_steps.cmake b/test/cmocka/tests.d/test_source_media_admission_steps.cmake new file mode 100644 index 0000000000..7df08e6571 --- /dev/null +++ b/test/cmocka/tests.d/test_source_media_admission_steps.cmake @@ -0,0 +1,12 @@ +# Characterization of the media action admission decisions of +# libobs/obs-source.c (the obs_source_media_*() functions and +# process_media_actions()), moved to libobs/obs-source-media-admission.c +# before its Rust port: every call with every output flag set, valid or not +# and with or without its callback, in the callers' order with the values +# each step reads, the getters' fallbacks, the dispatch and signal of every +# queued action type in the enum and out, and a queue run through in order. +# Builds the moved file into itself. The functions are hidden in libobs, so +# this characterizes that C source; the test calls only them. +# test_media_play_after_stop, test_media_time, test_slideshow_manual_end and +# test_stinger_media_duration cover the callers through the real libobs. +# Target and test are declared in ../build/test-graph.json. From a3b1fe507a87f4d3fe9b1f1028e96efd41874669 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:05:19 -0400 Subject: [PATCH 3/7] obs-source: Add Tier 1 tests for the media action admission port Tests for the port of libobs/obs-source-media-admission.c.h to the media_admission module of rust/obs-source. The safe core is a stub (todo!()): - admit(), admit_flags() (the call as Option, None outside the enum) and admit_callback(), each an Admit (Reject, Accept, ReadFlags, ReadCallback with the C's numbers); - time_fallback() (i64) and state_fallback() (the C's int); - dispatch() (the action type as the C's int) to a Dispatch (Return, the six callbacks, Skip), signal_reads_pause() and signal() (an Option<&'static CStr>, the dispatch as Option); - Call and Dispatch with value() and from_value(), Admit with value(); CONTROLLABLE_MEDIA, MEDIA_STATE_NONE and the action module's enum media_action_type values. tests/source/media_admission.rs ports test_source_media_admission_steps 1:1: its 12 cases under the same names (steps_*), in the same order, with the same inputs and expectations; enum_values' check of the mirrors against libobs's headers is Tier 3's, where the oracle compiles them. Edge cases (edge_*): every call value from -1000 to 1000, the ends of i32 and a few powers of two, against the enum; every one of them with each output flag bit alone and every bit but it, against the rule written out; the steps in the callers' order for each with both validities, the characterization's flag sets and both callbacks, every step answered and the flags and callback read at most once and in order; every action type and dispatch value over the same range, the signal for both pauses against the C's table; the signal names the same pointer each time. Proptests (4000 cases each): admission over any call value, flags and inputs; the dispatch and signal over any type; process_media_actions() written out with the port against the C written out, over random queues of up to 11 actions of any type. soldr cargo test -p obs-data --test obs-tests-core source::media_admission fails 20 of 20 with "not yet implemented". Refs #2239 --- rust/obs-source/src/lib.rs | 1 + rust/obs-source/src/media_admission.rs | 254 ++++++++ rust/obs-source/tests/source/main.rs | 1 + .../tests/source/media_admission.rs | 544 ++++++++++++++++++ 4 files changed, 800 insertions(+) create mode 100644 rust/obs-source/src/media_admission.rs create mode 100644 rust/obs-source/tests/source/media_admission.rs diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 6cb0fc35ec..c656f26ad2 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -59,6 +59,7 @@ pub mod deinterlace_pacing; pub mod draw_plan; pub mod draw_technique; pub mod frame_copy; +pub mod media_admission; pub mod ptm_gate; pub mod render_route; pub mod size_route; diff --git a/rust/obs-source/src/media_admission.rs b/rust/obs-source/src/media_admission.rs new file mode 100644 index 0000000000..08fd870e32 --- /dev/null +++ b/rust/obs-source/src/media_admission.rs @@ -0,0 +1,254 @@ +//! Safe core of `libobs/obs-source-media-admission.c.h`: the media action +//! admission decisions of the `obs_source_media_*()` functions and +//! `process_media_actions()`. +//! +//! A media source (one with `OBS_SOURCE_CONTROLLABLE_MEDIA`) is controlled +//! through eleven public calls. Play/pause, restart, stop, next, previous +//! and set-time queue an action that the video thread runs later in +//! `process_media_actions()`; the duration, time and state getters call +//! the source straight away; started and ended emit a signal. These are +//! the decisions they ask for: +//! - [`admit`], [`admit_flags`] and [`admit_callback`]: whether a call is +//! accepted, one step at a time in the C's order. An invalid source is +//! rejected, then one without [`CONTROLLABLE_MEDIA`], then, for every +//! call but [`Call::Started`] and [`Call::Ended`], one without the call's +//! callback. A step that needs a value answers [`Admit::ReadFlags`] or +//! [`Admit::ReadCallback`], and `obs-source.c.h` reads that one value +//! then, so nothing is read before the step that needs it; +//! - [`time_fallback`] and [`state_fallback`]: what the getters return for +//! a rejected call, 0 and `OBS_MEDIA_STATE_NONE`; +//! - [`dispatch`]: the callback a queued action type calls, +//! [`Dispatch::Return`] for `MEDIA_ACTION_NONE` (the queue is empty) and +//! [`Dispatch::Skip`] for a type outside the enum; +//! - [`signal_reads_pause`] and [`signal`]: the signal emitted after the +//! callback, `action.pause` read only for a play/pause. +//! +//! `obs-source.c.h` keeps `data_valid()` and `obs_source_valid()` (they +//! log), every field read, the action queue and its mutex, the callbacks, +//! the signals and the source refs. Nothing here keeps state, takes a lock +//! or calls libobs. +//! +//! Characterized, not endorsed (`test_source_media_admission_steps`), and +//! kept: started and ended need no callback, so they signal for any +//! controllable source; a set-time emits no signal; a queued type outside +//! the enum is dropped silently and the loop takes the next action. +//! +//! Not ported yet: every function is `todo!()`, so the Tier 1 tests fail. + +#![deny( + clippy::arithmetic_side_effects, + clippy::indexing_slicing, + clippy::as_conversions, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unimplemented, + clippy::unreachable +)] + +use core::ffi::CStr; + +/// `OBS_SOURCE_CONTROLLABLE_MEDIA`, the output flag of a media source. +pub const CONTROLLABLE_MEDIA: u32 = 1 << 13; + +/// `OBS_MEDIA_STATE_NONE`, what `obs_source_media_get_state()` returns +/// for a rejected call. +pub const MEDIA_STATE_NONE: i32 = 0; + +/// `enum media_action_type` (`obs-internal.h`), the type of a queued +/// action, as the C passes it. +pub mod action { + /// `MEDIA_ACTION_NONE`: the queue is empty. + pub const NONE: i32 = 0; + /// `MEDIA_ACTION_PLAY_PAUSE`. + pub const PLAY_PAUSE: i32 = 1; + /// `MEDIA_ACTION_RESTART`. + pub const RESTART: i32 = 2; + /// `MEDIA_ACTION_STOP`. + pub const STOP: i32 = 3; + /// `MEDIA_ACTION_NEXT`. + pub const NEXT: i32 = 4; + /// `MEDIA_ACTION_PREVIOUS`. + pub const PREVIOUS: i32 = 5; + /// `MEDIA_ACTION_SET_TIME`. + pub const SET_TIME: i32 = 6; +} + +/// `enum obs_source_media_call`: the public `obs_source_media_*()` +/// function being admitted. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Call { + /// `obs_source_media_play_pause()`. + PlayPause, + /// `obs_source_media_restart()`. + Restart, + /// `obs_source_media_stop()`. + Stop, + /// `obs_source_media_next()`. + Next, + /// `obs_source_media_previous()`. + Previous, + /// `obs_source_media_get_duration()`. + GetDuration, + /// `obs_source_media_get_time()`. + GetTime, + /// `obs_source_media_set_time()`. + SetTime, + /// `obs_source_media_get_state()`. + GetState, + /// `obs_source_media_started()`. + Started, + /// `obs_source_media_ended()`. + Ended, +} + +impl Call { + /// Every call, in the C enum's order. + pub const ALL: [Self; 11] = [ + Self::PlayPause, + Self::Restart, + Self::Stop, + Self::Next, + Self::Previous, + Self::GetDuration, + Self::GetTime, + Self::SetTime, + Self::GetState, + Self::Started, + Self::Ended, + ]; + + /// The C enum's value. + pub fn value(self) -> i32 { + let _ = self; + todo!("Call::value") + } + + /// The call with the C enum's value `value`, `None` outside the enum. + pub fn from_value(value: i32) -> Option { + let _ = value; + todo!("Call::from_value") + } +} + +/// `enum obs_source_media_admit`: an admission answer, or the value to read +/// before it is known. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Admit { + /// `OBS_SOURCE_MEDIA_ADMIT_REJECT`: return (a getter returns its + /// fallback). + Reject, + /// `OBS_SOURCE_MEDIA_ADMIT_ACCEPT`: queue the action, call the getter + /// or emit the signal. + Accept, + /// `OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS`: read `source->info.output_flags`. + ReadFlags, + /// `OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK`: read the call's callback. + ReadCallback, +} + +impl Admit { + /// The C enum's value. + pub fn value(self) -> u32 { + let _ = self; + todo!("Admit::value") + } +} + +/// `enum obs_source_media_dispatch`: what `process_media_actions()` does +/// with an action it took off the queue. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Dispatch { + /// `OBS_SOURCE_MEDIA_DISPATCH_RETURN`: `MEDIA_ACTION_NONE`, return. + Return, + /// `OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE`: `media_play_pause(data, + /// action.pause)`. + PlayPause, + /// `OBS_SOURCE_MEDIA_DISPATCH_RESTART`: `media_restart(data)`. + Restart, + /// `OBS_SOURCE_MEDIA_DISPATCH_STOP`: `media_stop(data)`. + Stop, + /// `OBS_SOURCE_MEDIA_DISPATCH_NEXT`: `media_next(data)`. + Next, + /// `OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS`: `media_previous(data)`. + Previous, + /// `OBS_SOURCE_MEDIA_DISPATCH_SET_TIME`: `media_set_time(data, + /// action.ms)`. + SetTime, + /// `OBS_SOURCE_MEDIA_DISPATCH_SKIP`: a type outside the enum, nothing. + Skip, +} + +impl Dispatch { + /// Every dispatch, in the C enum's order. + pub const ALL: [Self; 8] = [ + Self::Return, + Self::PlayPause, + Self::Restart, + Self::Stop, + Self::Next, + Self::Previous, + Self::SetTime, + Self::Skip, + ]; + + /// The C enum's value. + pub fn value(self) -> i32 { + let _ = self; + todo!("Dispatch::value") + } + + /// The dispatch with the C enum's value `value`, `None` outside the + /// enum. + pub fn from_value(value: i32) -> Option { + let _ = value; + todo!("Dispatch::from_value") + } +} + +/// `obs_source_media_admit()`. +pub fn admit(valid: bool) -> Admit { + let _ = valid; + todo!("obs_source_media_admit") +} + +/// `obs_source_media_admit_flags()`; `call` is `None` outside the enum. +pub fn admit_flags(call: Option, output_flags: u32) -> Admit { + let _ = (call, output_flags); + todo!("obs_source_media_admit_flags") +} + +/// `obs_source_media_admit_callback()`. +pub fn admit_callback(has_callback: bool) -> Admit { + let _ = has_callback; + todo!("obs_source_media_admit_callback") +} + +/// `obs_source_media_time_fallback()`. +pub fn time_fallback() -> i64 { + todo!("obs_source_media_time_fallback") +} + +/// `obs_source_media_state_fallback()`. +pub fn state_fallback() -> i32 { + todo!("obs_source_media_state_fallback") +} + +/// `obs_source_media_dispatch()`. +pub fn dispatch(action_type: i32) -> Dispatch { + let _ = action_type; + todo!("obs_source_media_dispatch") +} + +/// `obs_source_media_signal_reads_pause()`; `dispatch` is `None` outside +/// the enum. +pub fn signal_reads_pause(dispatch: Option) -> bool { + let _ = dispatch; + todo!("obs_source_media_signal_reads_pause") +} + +/// `obs_source_media_signal()`; `dispatch` is `None` outside the enum. +pub fn signal(dispatch: Option, pause: bool) -> Option<&'static CStr> { + let _ = (dispatch, pause); + todo!("obs_source_media_signal") +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index dc220d3f28..7270dd24c3 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -20,6 +20,7 @@ mod draw_plan; mod draw_plan_parity; mod frame_copy; mod frame_copy_parity; +mod media_admission; mod ptm_gate; mod ptm_gate_parity; mod render_route; diff --git a/rust/obs-source/tests/source/media_admission.rs b/rust/obs-source/tests/source/media_admission.rs new file mode 100644 index 0000000000..6981b3fddf --- /dev/null +++ b/rust/obs-source/tests/source/media_admission.rs @@ -0,0 +1,544 @@ +//! Tier 1: `obs_source::media_admission`, the media action admission +//! decisions. +//! +//! The `steps_*` cases port `test/cmocka/test_source_media_admission_steps.c` +//! 1:1, under the same case names, in the same order, with the same inputs +//! and expectations. The C test's `enum_values` also checks the mirrors +//! against libobs's headers; that half is Tier 3's (the oracle compiles +//! them). +//! +//! The `edge_*` cases are new: every call value from -1000 to 1000 and the +//! ends of `i32` with every single output flag bit, against the rule +//! written out; every action type and dispatch value over the same range; +//! the steps in the callers' order with the values each one reads; a model +//! of `process_media_actions()` over random queues; and proptests of each +//! over full-range values. + +use std::ffi::CStr; + +use obs_source::media_admission::{ + Admit, CONTROLLABLE_MEDIA, Call, Dispatch, MEDIA_STATE_NONE, action, admit, admit_callback, + admit_flags, dispatch, signal, signal_reads_pause, state_fallback, time_fallback, +}; +use proptest::prelude::*; + +/// `OBS_SOURCE_VIDEO`, `OBS_SOURCE_AUDIO`, `OBS_SOURCE_ASYNC` and +/// `OBS_SOURCE_ASYNC_VIDEO` (`obs-source.h`). +const OBS_SOURCE_VIDEO: u32 = 1 << 0; +const OBS_SOURCE_AUDIO: u32 = 1 << 1; +const OBS_SOURCE_ASYNC: u32 = 1 << 2; +const OBS_SOURCE_ASYNC_VIDEO: u32 = OBS_SOURCE_ASYNC | OBS_SOURCE_VIDEO; + +/// The C test's `FLAGS`: none, the flag alone, every bit, every bit but +/// it, its neighbours alone, and the flag with others. +const FLAGS: [u32; 8] = [ + 0, + CONTROLLABLE_MEDIA, + u32::MAX, + !CONTROLLABLE_MEDIA, + CONTROLLABLE_MEDIA << 1, + CONTROLLABLE_MEDIA >> 1, + OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_ASYNC, + CONTROLLABLE_MEDIA | OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO, +]; + +/// Calls, action types and dispatches outside their enums, as the C +/// test's. +const OUTSIDE_CALLS: [i32; 6] = [-1, 11, 12, 99, i32::MIN, i32::MAX]; +const OUTSIDE_TYPES: [i32; 6] = [7, 8, -1, 100, i32::MIN, i32::MAX]; +const OUTSIDE_DISPATCHES: [i32; 6] = [8, 9, -1, 99, i32::MIN, i32::MAX]; + +/// The callers' rule, written out: the calls that need a callback. +fn needs_callback(call: Option) -> bool { + !matches!(call, Some(Call::Started | Call::Ended)) +} + +fn controllable(flags: u32) -> bool { + flags & (1 << 13) != 0 +} + +fn call(value: i32) -> Option { + Call::from_value(value) +} + +fn cstr(s: Option<&'static CStr>) -> Option<&'static str> { + s.map(|s| s.to_str().unwrap()) +} + +// --- enum values --------------------------------------------------------- + +#[test] +fn steps_enum_values() { + // the mirrors obs-source.c checks against libobs + assert_eq!(CONTROLLABLE_MEDIA, 1 << 13); + assert_eq!(MEDIA_STATE_NONE, 0); + assert_eq!(action::NONE, 0); + assert_eq!(action::PLAY_PAUSE, 1); + assert_eq!(action::RESTART, 2); + assert_eq!(action::STOP, 3); + assert_eq!(action::NEXT, 4); + assert_eq!(action::PREVIOUS, 5); + assert_eq!(action::SET_TIME, 6); + + let calls = [ + (Call::PlayPause, 0), + (Call::Restart, 1), + (Call::Stop, 2), + (Call::Next, 3), + (Call::Previous, 4), + (Call::GetDuration, 5), + (Call::GetTime, 6), + (Call::SetTime, 7), + (Call::GetState, 8), + (Call::Started, 9), + (Call::Ended, 10), + ]; + for (c, value) in calls { + assert_eq!(c.value(), value); + assert_eq!(Call::from_value(value), Some(c)); + } + assert_eq!(Call::ALL.map(Call::value), calls.map(|(_, v)| v)); + + assert_eq!(Admit::Reject.value(), 0); + assert_eq!(Admit::Accept.value(), 1); + assert_eq!(Admit::ReadFlags.value(), 2); + assert_eq!(Admit::ReadCallback.value(), 3); + + let dispatches = [ + (Dispatch::Return, 0), + (Dispatch::PlayPause, 1), + (Dispatch::Restart, 2), + (Dispatch::Stop, 3), + (Dispatch::Next, 4), + (Dispatch::Previous, 5), + (Dispatch::SetTime, 6), + (Dispatch::Skip, 7), + ]; + for (d, value) in dispatches { + assert_eq!(d.value(), value); + assert_eq!(Dispatch::from_value(value), Some(d)); + } + assert_eq!( + Dispatch::ALL.map(Dispatch::value), + dispatches.map(|(_, v)| v) + ); +} + +// --- admission ----------------------------------------------------------- + +#[test] +fn steps_admit_valid() { + assert_eq!(admit(false), Admit::Reject); + assert_eq!(admit(true), Admit::ReadFlags); +} + +#[test] +fn steps_admit_flags_every_call() { + for c in Call::ALL { + for flags in FLAGS { + let expected = if !controllable(flags) { + Admit::Reject + } else if needs_callback(Some(c)) { + Admit::ReadCallback + } else { + Admit::Accept + }; + assert_eq!(admit_flags(Some(c), flags), expected, "{c:?} {flags:#x}"); + } + } + + // every single bit: only OBS_SOURCE_CONTROLLABLE_MEDIA admits + for bit in 0..32 { + let flags = 1_u32 << bit; + let (cb, accept) = if bit == 13 { + (Admit::ReadCallback, Admit::Accept) + } else { + (Admit::Reject, Admit::Reject) + }; + assert_eq!(admit_flags(Some(Call::PlayPause), flags), cb); + assert_eq!(admit_flags(Some(Call::Started), flags), accept); + } +} + +#[test] +fn steps_admit_flags_outside_enum() { + for value in OUTSIDE_CALLS { + let c = call(value); + assert_eq!(c, None); + assert_eq!(admit_flags(c, CONTROLLABLE_MEDIA), Admit::ReadCallback); + assert_eq!(admit_flags(c, u32::MAX), Admit::ReadCallback); + assert_eq!(admit_flags(c, 0), Admit::Reject); + assert_eq!(admit_flags(c, !CONTROLLABLE_MEDIA), Admit::Reject); + } +} + +#[test] +fn steps_admit_callback() { + assert_eq!(admit_callback(true), Admit::Accept); + assert_eq!(admit_callback(false), Admit::Reject); +} + +/// The steps in the callers' order (`media_admit()` and the callback check +/// of `obs-source.c`) for one call: the answer and the values read. +fn admit_in_order( + c: Option, + valid: bool, + flags: u32, + has_callback: bool, +) -> (Admit, u32, u32) { + let (mut flag_reads, mut callback_reads) = (0, 0); + let mut step = admit(valid); + if step == Admit::ReadFlags { + flag_reads += 1; + step = admit_flags(c, flags); + } + if step == Admit::ReadCallback { + callback_reads += 1; + step = admit_callback(has_callback); + } + (step, flag_reads, callback_reads) +} + +#[test] +fn steps_admission_every_input() { + for c in Call::ALL { + for valid in [false, true] { + for flags in FLAGS { + for cb in [false, true] { + let (step, flag_reads, callback_reads) = + admit_in_order(Some(c), valid, flags, cb); + let accepted = valid && controllable(flags) && (!needs_callback(Some(c)) || cb); + assert_eq!( + step, + if accepted { + Admit::Accept + } else { + Admit::Reject + } + ); + assert_eq!(flag_reads, u32::from(valid)); + assert_eq!( + callback_reads, + u32::from(valid && controllable(flags) && needs_callback(Some(c))) + ); + } + } + } + } + + // characterized, not endorsed: started and ended need no callback + for c in [Call::Started, Call::Ended] { + assert_eq!( + admit_in_order(Some(c), true, CONTROLLABLE_MEDIA, false), + (Admit::Accept, 1, 0) + ); + } +} + +// --- fallbacks ----------------------------------------------------------- + +#[test] +fn steps_getter_fallbacks() { + assert_eq!(time_fallback(), 0); + assert_eq!(state_fallback(), MEDIA_STATE_NONE); +} + +// --- process_media_actions() --------------------------------------------- + +#[test] +fn steps_dispatch_every_type() { + assert_eq!(dispatch(action::NONE), Dispatch::Return); + assert_eq!(dispatch(action::PLAY_PAUSE), Dispatch::PlayPause); + assert_eq!(dispatch(action::RESTART), Dispatch::Restart); + assert_eq!(dispatch(action::STOP), Dispatch::Stop); + assert_eq!(dispatch(action::NEXT), Dispatch::Next); + assert_eq!(dispatch(action::PREVIOUS), Dispatch::Previous); + assert_eq!(dispatch(action::SET_TIME), Dispatch::SetTime); +} + +#[test] +fn steps_dispatch_outside_enum() { + // characterized, not endorsed: dropped, the next action is taken + for t in OUTSIDE_TYPES { + assert_eq!(dispatch(t), Dispatch::Skip); + } +} + +/// The C test's `SIGNALS`, by pause: false, true. +fn expected_signal(d: Dispatch) -> [Option<&'static str>; 2] { + match d { + Dispatch::PlayPause => [Some("media_play"), Some("media_pause")], + Dispatch::Restart => [Some("media_restart"); 2], + Dispatch::Stop => [Some("media_stopped"); 2], + Dispatch::Next => [Some("media_next"); 2], + Dispatch::Previous => [Some("media_previous"); 2], + // characterized, not endorsed: a set-time emits nothing + Dispatch::Return | Dispatch::SetTime | Dispatch::Skip => [None; 2], + } +} + +#[test] +fn steps_signal_every_dispatch() { + for d in Dispatch::ALL { + assert_eq!(signal_reads_pause(Some(d)), d == Dispatch::PlayPause); + let [play, pause] = expected_signal(d); + assert_eq!(cstr(signal(Some(d), false)), play, "{d:?}"); + assert_eq!(cstr(signal(Some(d), true)), pause, "{d:?}"); + } +} + +#[test] +fn steps_signal_outside_enum() { + for value in OUTSIDE_DISPATCHES { + let d = Dispatch::from_value(value); + assert_eq!(d, None); + assert!(!signal_reads_pause(d)); + assert_eq!(signal(d, false), None); + assert_eq!(signal(d, true), None); + } +} + +/// `process_media_actions()` written out with the port in its order: the +/// callback, then the signal, until the queue is empty or a +/// `MEDIA_ACTION_NONE` comes up. +fn run_queue(queue: &[(i32, bool)]) -> String { + let mut trace = Vec::new(); + let mut next = queue.iter(); + loop { + let (t, pause) = next.next().copied().unwrap_or((action::NONE, false)); + let d = dispatch(t); + let callback = match d { + Dispatch::Return => { + trace.push("return"); + return trace.join(" "); + } + Dispatch::PlayPause => Some("play_pause"), + Dispatch::Restart => Some("restart"), + Dispatch::Stop => Some("stop"), + Dispatch::Next => Some("next"), + Dispatch::Previous => Some("previous"), + Dispatch::SetTime => Some("set_time"), + Dispatch::Skip => None, + }; + trace.extend(callback); + trace.extend(cstr(signal(Some(d), signal_reads_pause(Some(d)) && pause))); + } +} + +#[test] +fn steps_process_every_action() { + let one = [ + ((action::PLAY_PAUSE, false), "play_pause media_play return"), + ((action::PLAY_PAUSE, true), "play_pause media_pause return"), + ((action::RESTART, false), "restart media_restart return"), + ((action::STOP, false), "stop media_stopped return"), + ((action::NEXT, false), "next media_next return"), + ((action::PREVIOUS, false), "previous media_previous return"), + ((action::SET_TIME, false), "set_time return"), + // the pause is not read for any other action + ((action::RESTART, true), "restart media_restart return"), + ((action::SET_TIME, true), "set_time return"), + // characterized, not endorsed: skipped, the loop goes on + ((7, true), "return"), + ((-1, false), "return"), + ((i32::MAX, false), "return"), + // a queued MEDIA_ACTION_NONE ends the loop like an empty queue + ((action::NONE, false), "return"), + ]; + for (a, trace) in one { + assert_eq!(run_queue(&[a]), trace, "{a:?}"); + } + + assert_eq!(run_queue(&[]), "return"); + + let mixed = [ + (action::STOP, false), + (99, true), + (action::PLAY_PAUSE, true), + (action::SET_TIME, false), + (action::NONE, false), + (action::NEXT, false), + ]; + assert_eq!( + run_queue(&mixed), + "stop media_stopped play_pause media_pause set_time return" + ); +} + +// --- edge cases ---------------------------------------------------------- + +/// Values around every enum and the ends of `i32`. +fn edge_values() -> impl Iterator { + (-1000..=1000).chain([ + i32::MIN, + i32::MIN + 1, + i32::MAX - 1, + i32::MAX, + 1 << 13, + -(1 << 13), + 0x100, + 0x1_0000, + ]) +} + +/// [`admit_flags`] written out. +fn model_admit_flags(c: Option, flags: u32) -> Admit { + if !controllable(flags) { + Admit::Reject + } else if needs_callback(c) { + Admit::ReadCallback + } else { + Admit::Accept + } +} + +#[test] +fn edge_call_values() { + for value in edge_values() { + let c = call(value); + assert_eq!(c.is_some(), (0..=10).contains(&value), "{value}"); + if let Some(c) = c { + assert_eq!(c.value(), value); + } + } +} + +#[test] +fn edge_admit_flags_every_bit() { + for value in edge_values() { + let c = call(value); + for bit in 0..32 { + let flags = 1_u32 << bit; + assert_eq!(admit_flags(c, flags), model_admit_flags(c, flags)); + assert_eq!(admit_flags(c, !flags), model_admit_flags(c, !flags)); + } + } +} + +#[test] +fn edge_admission_reads_in_order() { + for value in edge_values() { + let c = call(value); + for valid in [false, true] { + for flags in FLAGS { + for cb in [false, true] { + let (step, flag_reads, callback_reads) = admit_in_order(c, valid, flags, cb); + // never READ_* at the end: every step is answered + assert!(matches!(step, Admit::Accept | Admit::Reject)); + assert!(flag_reads <= u32::from(valid)); + assert!(callback_reads <= flag_reads); + let accepted = valid && controllable(flags) && (!needs_callback(c) || cb); + assert_eq!( + step == Admit::Accept, + accepted, + "{value} {valid} {flags:#x} {cb}" + ); + } + } + } + } +} + +/// [`dispatch`] written out from `enum media_action_type`. +fn model_dispatch(t: i32) -> Dispatch { + match t { + 0 => Dispatch::Return, + 1 => Dispatch::PlayPause, + 2 => Dispatch::Restart, + 3 => Dispatch::Stop, + 4 => Dispatch::Next, + 5 => Dispatch::Previous, + 6 => Dispatch::SetTime, + _ => Dispatch::Skip, + } +} + +#[test] +fn edge_dispatch_and_signal_values() { + for value in edge_values() { + assert_eq!(dispatch(value), model_dispatch(value), "{value}"); + + let d = Dispatch::from_value(value); + assert_eq!(d.is_some(), (0..=7).contains(&value), "{value}"); + if let Some(d) = d { + assert_eq!(d.value(), value); + } + assert_eq!(signal_reads_pause(d), d == Some(Dispatch::PlayPause)); + for pause in [false, true] { + let expected = d.and_then(|d| expected_signal(d)[usize::from(pause)]); + assert_eq!(cstr(signal(d, pause)), expected, "{value} {pause}"); + } + } +} + +#[test] +fn edge_signal_names_are_static() { + // the same pointer every time: the C returns string literals and the + // signal handler looks them up by name + for d in Dispatch::ALL { + for pause in [false, true] { + let a = signal(Some(d), pause).map(CStr::as_ptr); + let b = signal(Some(d), pause).map(CStr::as_ptr); + assert_eq!(a, b); + } + } +} + +/// `process_media_actions()` written out from the C, for the proptest. +fn model_queue(queue: &[(i32, bool)]) -> String { + let mut trace = Vec::new(); + for &(t, pause) in queue.iter().chain(std::iter::once(&(0, false))) { + let (callback, sig) = match t { + 0 => { + trace.push("return"); + return trace.join(" "); + } + 1 => ( + Some("play_pause"), + Some(if pause { "media_pause" } else { "media_play" }), + ), + 2 => (Some("restart"), Some("media_restart")), + 3 => (Some("stop"), Some("media_stopped")), + 4 => (Some("next"), Some("media_next")), + 5 => (Some("previous"), Some("media_previous")), + 6 => (Some("set_time"), None), + _ => (None, None), + }; + trace.extend(callback); + trace.extend(sig); + } + unreachable!("the queue ends in MEDIA_ACTION_NONE") +} + +fn any_type() -> impl Strategy { + prop_oneof![0..8_i32, -2..2_i32, any::()] +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(4000))] + + #[test] + fn edge_proptest_admission(value in prop_oneof![0..11_i32, any::()], valid: bool, + flags: u32, cb: bool) { + let c = call(value); + prop_assert_eq!(admit_flags(c, flags), model_admit_flags(c, flags)); + let (step, flag_reads, callback_reads) = admit_in_order(c, valid, flags, cb); + let accepted = valid && controllable(flags) && (!needs_callback(c) || cb); + prop_assert_eq!(step == Admit::Accept, accepted); + prop_assert_eq!(flag_reads, u32::from(valid)); + prop_assert_eq!(callback_reads, u32::from(valid && controllable(flags) && needs_callback(c))); + } + + #[test] + fn edge_proptest_dispatch(t in any_type(), pause: bool) { + let d = dispatch(t); + prop_assert_eq!(d, model_dispatch(t)); + prop_assert_eq!(signal_reads_pause(Some(d)), d == Dispatch::PlayPause); + prop_assert_eq!(cstr(signal(Some(d), pause)), expected_signal(d)[usize::from(pause)]); + } + + #[test] + fn edge_proptest_queue(queue in proptest::collection::vec((any_type(), any::()), 0..12)) { + prop_assert_eq!(run_queue(&queue), model_queue(&queue)); + } +} From a83936c305f8c151ccf883f46cba219000e1ea18 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:15:44 -0400 Subject: [PATCH 4/7] obs-source: Port the media action admission decisions Ports libobs/obs-source-media-admission.c.h, the media action admission decisions of obs-source.c, to the media_admission module of rust/obs-source. obs-source.c.h stays C: data_valid() and obs_source_valid() (they log), every field read, the action queue and its mutex, the callbacks, the signals and the source refs. The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/media_admission.rs): - admit(): ReadFlags for a valid source, else Reject; - admit_flags(): Reject without CONTROLLABLE_MEDIA (1 << 13), Accept for Call::Started and Call::Ended, else ReadCallback, a call outside the enum (None) included; - admit_callback(): Accept with the callback, else Reject; - time_fallback() 0 and state_fallback() MEDIA_STATE_NONE; - dispatch(): each enum media_action_type value to its Dispatch, Return for MEDIA_ACTION_NONE, Skip for anything else; - signal_reads_pause(): only for Dispatch::PlayPause; signal(): media_pause or media_play by the pause, media_restart, media_stopped, media_next, media_previous, None for the rest and outside the enum, as static &CStr names (the same pointer each time, as the C's literals); - Call, Admit and Dispatch with the C's numbers (value(), from_value()). The module denies clippy's arithmetic, indexing, as, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock; every function is a const fn over plain values. Shim (src/ffi/source_media_admission.rs): the eight functions keep the C signatures. The enums cross as int (obs-source.c.h checks enum media_action_type and enum obs_media_state; the header's own enums have no negative value, so an unsigned int one passes the same bits); a call or dispatch outside its enum maps to None and takes the C's path. The signal comes back as a static C string or NULL. No intentional differences: there is no pointer to check. C side: the file leaves libobs.core-source for its own group, libobs.ported-source-media-admission (LIBOBS_PORTED_SOURCES), whose PCH is the file's header alone (it mirrors the libobs values it needs), so the C test and the oracle compile it on its own. libobs.pch.h keeps the header for obs-source.c. The functions are not EXPORT, so the shims are hidden: rust-hidden.txt, the local: list of rust-exports.map and rust-unexports-macos.txt. libobs-rust already links the crate's ffi. The exported symbol sets are unchanged and equal: 1766 on the C backend, the hybrid and libobs-c-reference; the eight are local in all three, and the hybrid's come from the Rust archive (it has no object for the C file). ci/test_ported_sources.py checks the group on every host. test_source_media_admission_steps still compiles the C file into itself, unchanged. The new test_source_media_admission_steps_rust builds the same test source against libobs_rust-static (and libm except on MSVC): the test calls only the eight functions and includes their header and obs.h (for the values the header mirrors), so it takes libobs's include directories and links the archive alone. It passes 12 of 12 against the shims. The test_media_* tests (test_media_play_after_stop, test_media_restart_first_frame, test_media_restart_stale_frame, test_media_seek_keyframe, test_media_time and the rest), test_slideshow_empty, test_slideshow_manual_end, test_slideshow_size, test_stinger_media_duration and test_ffmpeg_restart_close see the swap through the hybrid: 24 of 24 on the hybrid and on libobs-c-reference, 23 of 23 on the C backend (no _rust variant there). Tier 1 source::media_admission passes 20/20. Refs #2239 --- ci/test_ported_sources.py | 1 + ...libobs-ported-source-media-admission.pch.h | 10 + libobs/build/libobs.core-source+.h.c | 1 - .../libobs.ported-source-media-admission+.h.c | 5 + libobs/build/source-sets.json | 1 + libobs/cmake/rust-exports.map | 10 + libobs/cmake/rust-hidden.txt | 12 ++ libobs/cmake/rust-unexports-macos.txt | 10 + libobs/obs-source-media-admission.c.h | 2 +- rust/obs-source/src/ffi/mod.rs | 1 + .../src/ffi/source_media_admission.rs | 88 ++++++++ rust/obs-source/src/media_admission.rs | 192 +++++++++++++----- .../test_source_media_admission_steps.cmake | 39 +++- 13 files changed, 313 insertions(+), 59 deletions(-) create mode 100644 libobs/build/libobs-ported-source-media-admission.pch.h create mode 100644 libobs/build/libobs.ported-source-media-admission+.h.c create mode 100644 rust/obs-source/src/ffi/source_media_admission.rs diff --git a/ci/test_ported_sources.py b/ci/test_ported_sources.py index 5c4f51446a..6fce0efb8b 100644 --- a/ci/test_ported_sources.py +++ b/ci/test_ported_sources.py @@ -48,6 +48,7 @@ "obs-source-draw-plan.c.h.o", "obs-source-frame-copy.c.h.o", "obs-source-load.c.h.o", + "obs-source-media-admission.c.h.o", "obs-source-ptm-gate.c.h.o", "obs-source-render-route.c.h.o", "obs-source-size.c.h.o", diff --git a/libobs/build/libobs-ported-source-media-admission.pch.h b/libobs/build/libobs-ported-source-media-admission.pch.h new file mode 100644 index 0000000000..4cf1977889 --- /dev/null +++ b/libobs/build/libobs-ported-source-media-admission.pch.h @@ -0,0 +1,10 @@ +/* Precompiled header (BUILD.md) for the libobs unity group + * libobs.ported-source-media-admission. obs-source-media-admission.c needs + * only its declarations (obs-source-media-admission.h, with stdbool.h, + * stddef.h and stdint.h, and the libobs values it mirrors), not the core, so + * the C oracle and the C test can compile it on its own. The implementation + * file includes this header and nothing else. */ + +#pragma once + +#include "libobs/obs-source-media-admission.h" diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index e1785c667a..c4cf0c47b3 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -7,7 +7,6 @@ #include "libobs/obs-scene-item-audio-actions.c.h" #include "libobs/obs-scene.c.h" #include "libobs/obs-source-deinterlace.c.h" -#include "libobs/obs-source-media-admission.c.h" #include "libobs/obs-source-transition.c.h" #include "libobs/obs-source.c.h" #include "libobs/obs-view.c.h" diff --git a/libobs/build/libobs.ported-source-media-admission+.h.c b/libobs/build/libobs.ported-source-media-admission+.h.c new file mode 100644 index 0000000000..b7c259c291 --- /dev/null +++ b/libobs/build/libobs.ported-source-media-admission+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): ported obs-source-media-admission.c. */ + +#include "libobs/build/libobs-ported-source-media-admission.pch.h" + +#include "libobs/obs-source-media-admission.c.h" diff --git a/libobs/build/source-sets.json b/libobs/build/source-sets.json index 86a44a1cc0..d4d5d9fb5f 100644 --- a/libobs/build/source-sets.json +++ b/libobs/build/source-sets.json @@ -200,6 +200,7 @@ "build/libobs.ported-source-draw-plan+.h.c", "build/libobs.ported-source-frame-copy+.h.c", "build/libobs.ported-source-load+.h.c", + "build/libobs.ported-source-media-admission+.h.c", "build/libobs.ported-source-profiler+.h.c", "build/libobs.ported-source-ptm-gate+.h.c", "build/libobs.ported-source-render-route+.h.c", diff --git a/libobs/cmake/rust-exports.map b/libobs/cmake/rust-exports.map index d375ef4ebb..dba3f51402 100644 --- a/libobs/cmake/rust-exports.map +++ b/libobs/cmake/rust-exports.map @@ -218,6 +218,16 @@ obs_source_frame_copy_full_range; obs_source_frame_copy_full_range2; obs_source_frame_copy_preload_changed; + /* obs-source-media-admission.c. obs-source.c calls them inside libobs. + * Not EXPORT. */ + obs_source_media_admit; + obs_source_media_admit_flags; + obs_source_media_admit_callback; + obs_source_media_time_fallback; + obs_source_media_state_fallback; + obs_source_media_dispatch; + obs_source_media_signal_reads_pause; + obs_source_media_signal; /* obs-source-ptm-gate.c. obs-source.c calls them inside libobs. Not * EXPORT. */ obs_source_ptm_gate_stop_time; diff --git a/libobs/cmake/rust-hidden.txt b/libobs/cmake/rust-hidden.txt index f0fc7115eb..1392aa4ac8 100644 --- a/libobs/cmake/rust-hidden.txt +++ b/libobs/cmake/rust-hidden.txt @@ -234,6 +234,18 @@ obs_source_frame_copy_cache_clean obs_source_frame_copy_full_range obs_source_frame_copy_full_range2 obs_source_frame_copy_preload_changed +# obs-source-media-admission.c: the obs_source_media_*() functions and +# process_media_actions() in obs-source.c call them inside libobs. Declared in +# obs-source-media-admission.h without EXPORT, so the shims stay hidden the +# same way. +obs_source_media_admit +obs_source_media_admit_flags +obs_source_media_admit_callback +obs_source_media_time_fallback +obs_source_media_state_fallback +obs_source_media_dispatch +obs_source_media_signal_reads_pause +obs_source_media_signal # obs-source-ptm-gate.c: source_muted() and get_source_volume() in # obs-source.c call them inside libobs. Declared in obs-source-ptm-gate.h # without EXPORT, so the shims stay hidden the same way. diff --git a/libobs/cmake/rust-unexports-macos.txt b/libobs/cmake/rust-unexports-macos.txt index 11dac28483..c8c5008fec 100644 --- a/libobs/cmake/rust-unexports-macos.txt +++ b/libobs/cmake/rust-unexports-macos.txt @@ -192,6 +192,16 @@ _obs_source_frame_copy_cache_clean _obs_source_frame_copy_full_range _obs_source_frame_copy_full_range2 _obs_source_frame_copy_preload_changed +# obs-source-media-admission.c: obs-source.c calls them inside libobs. Not +# EXPORT. +_obs_source_media_admit +_obs_source_media_admit_flags +_obs_source_media_admit_callback +_obs_source_media_time_fallback +_obs_source_media_state_fallback +_obs_source_media_dispatch +_obs_source_media_signal_reads_pause +_obs_source_media_signal # obs-source-ptm-gate.c: obs-source.c calls them inside libobs. Not EXPORT. _obs_source_ptm_gate_stop_time _obs_source_ptm_gate_held diff --git a/libobs/obs-source-media-admission.c.h b/libobs/obs-source-media-admission.c.h index 7ebc8135d5..b5960353aa 100644 --- a/libobs/obs-source-media-admission.c.h +++ b/libobs/obs-source-media-admission.c.h @@ -15,7 +15,7 @@ along with this program. If not, see . ******************************************************************************/ -#include "libobs/build/libobs.pch.h" +#include "libobs/build/libobs-ported-source-media-admission.pch.h" /* The media action admission decisions of obs-source.c, moved from the * obs_source_media_*() functions (the controllable and callback checks and diff --git a/rust/obs-source/src/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index 7e242e003b..69c5b0a9dc 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -11,6 +11,7 @@ pub mod source_deinterlace_pacing; pub mod source_draw_plan; pub mod source_draw_technique; pub mod source_frame_copy; +pub mod source_media_admission; pub mod source_ptm_gate; pub mod source_render_route; pub mod source_size; diff --git a/rust/obs-source/src/ffi/source_media_admission.rs b/rust/obs-source/src/ffi/source_media_admission.rs new file mode 100644 index 0000000000..d8f53abe29 --- /dev/null +++ b/rust/obs-source/src/ffi/source_media_admission.rs @@ -0,0 +1,88 @@ +//! C ABI for `libobs/obs-source-media-admission.c.h`, the media action +//! admission decisions, declared in `libobs/obs-source-media-admission.h` +//! without `EXPORT`. +//! +//! The `obs_source_media_*()` functions and `process_media_actions()` in +//! `obs-source.c.h` (still C) call `data_valid()` or `obs_source_valid()`, +//! read the source's output flags and callbacks when a step asks for them, +//! keep the action queue and its mutex, call the callbacks and emit the +//! signals. So `struct obs_source` is never mirrored, and these shims take +//! plain values, touch no memory, take no lock and call nothing in libobs. +//! All eight stay hidden (`rust-hidden.txt`). +//! +//! The enums cross as the C's `int` (`obs-source.c.h` checks +//! `enum media_action_type` and `enum obs_media_state`; the header's own +//! enums have no negative value, so an `unsigned int` one passes the same +//! bits), and a value outside an enum takes the path the C takes. The +//! signal names are static C strings, as the C's literals are. +//! +//! No intentional differences from C: every input is a value, so there is +//! no pointer to check. + +use std::os::raw::{c_char, c_int}; +use std::ptr; + +use crate::media_admission::{self as core, Call, Dispatch}; + +/// `enum obs_source_media_call`, `enum obs_source_media_admit` and +/// `enum obs_source_media_dispatch`, as the C passes and returns them. +#[allow(non_camel_case_types)] +pub type obs_source_media_enum = c_int; + +/// `enum obs_source_media_admit obs_source_media_admit(bool valid)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_admit(valid: bool) -> obs_source_media_enum { + core::admit(valid).value() +} + +/// `enum obs_source_media_admit obs_source_media_admit_flags(enum +/// obs_source_media_call call, uint32_t output_flags)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_admit_flags( + call: obs_source_media_enum, + output_flags: u32, +) -> obs_source_media_enum { + core::admit_flags(Call::from_value(call), output_flags).value() +} + +/// `enum obs_source_media_admit obs_source_media_admit_callback(bool +/// has_callback)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_admit_callback(has_callback: bool) -> obs_source_media_enum { + core::admit_callback(has_callback).value() +} + +/// `int64_t obs_source_media_time_fallback(void)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_time_fallback() -> i64 { + core::time_fallback() +} + +/// `int obs_source_media_state_fallback(void)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_state_fallback() -> c_int { + core::state_fallback() +} + +/// `enum obs_source_media_dispatch obs_source_media_dispatch(int type)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_dispatch(action_type: c_int) -> obs_source_media_enum { + core::dispatch(action_type).value() +} + +/// `bool obs_source_media_signal_reads_pause(enum obs_source_media_dispatch +/// dispatch)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_signal_reads_pause(dispatch: obs_source_media_enum) -> bool { + core::signal_reads_pause(Dispatch::from_value(dispatch)) +} + +/// `const char *obs_source_media_signal(enum obs_source_media_dispatch +/// dispatch, bool pause)`: a static name, or NULL. +#[unsafe(no_mangle)] +pub extern "C" fn obs_source_media_signal( + dispatch: obs_source_media_enum, + pause: bool, +) -> *const c_char { + core::signal(Dispatch::from_value(dispatch), pause).map_or(ptr::null(), |name| name.as_ptr()) +} diff --git a/rust/obs-source/src/media_admission.rs b/rust/obs-source/src/media_admission.rs index 08fd870e32..b983633cec 100644 --- a/rust/obs-source/src/media_admission.rs +++ b/rust/obs-source/src/media_admission.rs @@ -32,8 +32,6 @@ //! kept: started and ended need no callback, so they signal for any //! controllable source; a set-time emits no signal; a queued type outside //! the enum is dropped silently and the loop takes the next action. -//! -//! Not ported yet: every function is `todo!()`, so the Tier 1 tests fail. #![deny( clippy::arithmetic_side_effects, @@ -42,6 +40,7 @@ clippy::unwrap_used, clippy::expect_used, clippy::panic, + clippy::todo, clippy::unimplemented, clippy::unreachable )] @@ -119,15 +118,38 @@ impl Call { ]; /// The C enum's value. - pub fn value(self) -> i32 { - let _ = self; - todo!("Call::value") + pub const fn value(self) -> i32 { + match self { + Self::PlayPause => 0, + Self::Restart => 1, + Self::Stop => 2, + Self::Next => 3, + Self::Previous => 4, + Self::GetDuration => 5, + Self::GetTime => 6, + Self::SetTime => 7, + Self::GetState => 8, + Self::Started => 9, + Self::Ended => 10, + } } /// The call with the C enum's value `value`, `None` outside the enum. - pub fn from_value(value: i32) -> Option { - let _ = value; - todo!("Call::from_value") + pub const fn from_value(value: i32) -> Option { + Some(match value { + 0 => Self::PlayPause, + 1 => Self::Restart, + 2 => Self::Stop, + 3 => Self::Next, + 4 => Self::Previous, + 5 => Self::GetDuration, + 6 => Self::GetTime, + 7 => Self::SetTime, + 8 => Self::GetState, + 9 => Self::Started, + 10 => Self::Ended, + _ => return None, + }) } } @@ -149,9 +171,13 @@ pub enum Admit { impl Admit { /// The C enum's value. - pub fn value(self) -> u32 { - let _ = self; - todo!("Admit::value") + pub const fn value(self) -> i32 { + match self { + Self::Reject => 0, + Self::Accept => 1, + Self::ReadFlags => 2, + Self::ReadCallback => 3, + } } } @@ -193,62 +219,132 @@ impl Dispatch { ]; /// The C enum's value. - pub fn value(self) -> i32 { - let _ = self; - todo!("Dispatch::value") + pub const fn value(self) -> i32 { + match self { + Self::Return => 0, + Self::PlayPause => 1, + Self::Restart => 2, + Self::Stop => 3, + Self::Next => 4, + Self::Previous => 5, + Self::SetTime => 6, + Self::Skip => 7, + } } /// The dispatch with the C enum's value `value`, `None` outside the /// enum. - pub fn from_value(value: i32) -> Option { - let _ = value; - todo!("Dispatch::from_value") + pub const fn from_value(value: i32) -> Option { + Some(match value { + 0 => Self::Return, + 1 => Self::PlayPause, + 2 => Self::Restart, + 3 => Self::Stop, + 4 => Self::Next, + 5 => Self::Previous, + 6 => Self::SetTime, + 7 => Self::Skip, + _ => return None, + }) } } -/// `obs_source_media_admit()`. -pub fn admit(valid: bool) -> Admit { - let _ = valid; - todo!("obs_source_media_admit") +/// `obs_source_media_admit()`: the first step, [`Admit::ReadFlags`] for a +/// valid source (`data_valid()`, or `obs_source_valid()` for started and +/// ended), else [`Admit::Reject`]. +pub const fn admit(valid: bool) -> Admit { + if valid { + Admit::ReadFlags + } else { + Admit::Reject + } } -/// `obs_source_media_admit_flags()`; `call` is `None` outside the enum. -pub fn admit_flags(call: Option, output_flags: u32) -> Admit { - let _ = (call, output_flags); - todo!("obs_source_media_admit_flags") +/// `obs_source_media_admit_flags()`: the step after reading the output +/// flags. [`Admit::Reject`] without [`CONTROLLABLE_MEDIA`], +/// [`Admit::Accept`] for [`Call::Started`] and [`Call::Ended`], else +/// [`Admit::ReadCallback`], a call outside the enum (`None`) included. +pub const fn admit_flags(call: Option, output_flags: u32) -> Admit { + if output_flags & CONTROLLABLE_MEDIA == 0 { + return Admit::Reject; + } + + match call { + Some(Call::Started | Call::Ended) => Admit::Accept, + Some( + Call::PlayPause + | Call::Restart + | Call::Stop + | Call::Next + | Call::Previous + | Call::GetDuration + | Call::GetTime + | Call::SetTime + | Call::GetState, + ) + | None => Admit::ReadCallback, + } } -/// `obs_source_media_admit_callback()`. -pub fn admit_callback(has_callback: bool) -> Admit { - let _ = has_callback; - todo!("obs_source_media_admit_callback") +/// `obs_source_media_admit_callback()`: the step after reading the call's +/// callback, [`Admit::Accept`] when it is set, else [`Admit::Reject`]. +pub const fn admit_callback(has_callback: bool) -> Admit { + if has_callback { + Admit::Accept + } else { + Admit::Reject + } } -/// `obs_source_media_time_fallback()`. -pub fn time_fallback() -> i64 { - todo!("obs_source_media_time_fallback") +/// `obs_source_media_time_fallback()`: what `obs_source_media_get_duration()` +/// and `obs_source_media_get_time()` return for a rejected call, 0. +pub const fn time_fallback() -> i64 { + 0 } -/// `obs_source_media_state_fallback()`. -pub fn state_fallback() -> i32 { - todo!("obs_source_media_state_fallback") +/// `obs_source_media_state_fallback()`: what +/// `obs_source_media_get_state()` returns for a rejected call, +/// [`MEDIA_STATE_NONE`]. +pub const fn state_fallback() -> i32 { + MEDIA_STATE_NONE } -/// `obs_source_media_dispatch()`. -pub fn dispatch(action_type: i32) -> Dispatch { - let _ = action_type; - todo!("obs_source_media_dispatch") +/// `obs_source_media_dispatch()`: the callback a queued action of type +/// `action_type` calls, [`Dispatch::Return`] for [`action::NONE`] and +/// [`Dispatch::Skip`] for a type outside the enum. +pub const fn dispatch(action_type: i32) -> Dispatch { + match action_type { + action::NONE => Dispatch::Return, + action::PLAY_PAUSE => Dispatch::PlayPause, + action::RESTART => Dispatch::Restart, + action::STOP => Dispatch::Stop, + action::NEXT => Dispatch::Next, + action::PREVIOUS => Dispatch::Previous, + action::SET_TIME => Dispatch::SetTime, + _ => Dispatch::Skip, + } } -/// `obs_source_media_signal_reads_pause()`; `dispatch` is `None` outside -/// the enum. -pub fn signal_reads_pause(dispatch: Option) -> bool { - let _ = dispatch; - todo!("obs_source_media_signal_reads_pause") +/// `obs_source_media_signal_reads_pause()`: whether the signal reads +/// `action.pause`, only for [`Dispatch::PlayPause`] (the union holds the +/// time for a set-time). `None` is a value outside the enum. +pub const fn signal_reads_pause(dispatch: Option) -> bool { + matches!(dispatch, Some(Dispatch::PlayPause)) } -/// `obs_source_media_signal()`; `dispatch` is `None` outside the enum. -pub fn signal(dispatch: Option, pause: bool) -> Option<&'static CStr> { - let _ = (dispatch, pause); - todo!("obs_source_media_signal") +/// `obs_source_media_signal()`: the signal emitted after the callback, +/// `media_pause` or `media_play` by `pause`, `media_restart`, +/// `media_stopped`, `media_next` and `media_previous`; none for +/// [`Dispatch::SetTime`], [`Dispatch::Return`], [`Dispatch::Skip`] and a +/// value outside the enum (`None`). The names are static, as the C's +/// string literals. +pub const fn signal(dispatch: Option, pause: bool) -> Option<&'static CStr> { + match dispatch { + Some(Dispatch::PlayPause) => Some(if pause { c"media_pause" } else { c"media_play" }), + Some(Dispatch::Restart) => Some(c"media_restart"), + Some(Dispatch::Stop) => Some(c"media_stopped"), + Some(Dispatch::Next) => Some(c"media_next"), + Some(Dispatch::Previous) => Some(c"media_previous"), + Some(Dispatch::Return | Dispatch::SetTime | Dispatch::Skip) | None => None, + } } diff --git a/test/cmocka/tests.d/test_source_media_admission_steps.cmake b/test/cmocka/tests.d/test_source_media_admission_steps.cmake index 7df08e6571..8bdf7f5b31 100644 --- a/test/cmocka/tests.d/test_source_media_admission_steps.cmake +++ b/test/cmocka/tests.d/test_source_media_admission_steps.cmake @@ -1,12 +1,33 @@ # Characterization of the media action admission decisions of # libobs/obs-source.c (the obs_source_media_*() functions and -# process_media_actions()), moved to libobs/obs-source-media-admission.c -# before its Rust port: every call with every output flag set, valid or not -# and with or without its callback, in the callers' order with the values -# each step reads, the getters' fallbacks, the dispatch and signal of every -# queued action type in the enum and out, and a queue run through in order. -# Builds the moved file into itself. The functions are hidden in libobs, so -# this characterizes that C source; the test calls only them. -# test_media_play_after_stop, test_media_time, test_slideshow_manual_end and -# test_stinger_media_duration cover the callers through the real libobs. +# process_media_actions()), moved to libobs/obs-source-media-admission.c and +# ported to rust/obs-source (media_admission): every call with every output +# flag set, valid or not and with or without its callback, in the callers' +# order with the values each step reads, the getters' fallbacks, the dispatch +# and signal of every queued action type in the enum and out, and a queue run +# through in order. Builds the moved file into itself. The functions are +# hidden in libobs, so this characterizes that C source; the test calls only +# them. test_media_play_after_stop, test_media_time, test_slideshow_manual_end +# and test_stinger_media_duration cover the callers through the real libobs. # Target and test are declared in ../build/test-graph.json. + +# Exercise the unchanged characterization against the Rust shims. The test +# calls only the eight hidden functions, and includes their header and obs.h +# (for the libobs values the header mirrors; obs.h pulls SIMDe and +# obsconfig.h, hence libobs's include directories), so it links the archive +# alone: its obs-source member needs nothing from libobs or the other crates. +# Linking the archive directly avoids exporting private symbols just for a +# test. +if(TARGET libobs_rust-static) + add_executable(test_source_media_admission_steps_rust test_source_media_admission_steps.c) + target_include_directories( + test_source_media_admission_steps_rust + PRIVATE "${CMAKE_SOURCE_DIR}/libobs" $ ${CMOCKA_INCLUDE_DIR} + ) + target_link_libraries(test_source_media_admission_steps_rust PRIVATE libobs_rust-static ${CMOCKA_LIBRARIES}) + if(NOT MSVC) + target_link_libraries(test_source_media_admission_steps_rust PRIVATE m) + endif() + add_dependencies(cmocka-tests test_source_media_admission_steps_rust) + add_test(test_source_media_admission_steps_rust ${CMAKE_CURRENT_BINARY_DIR}/test_source_media_admission_steps_rust) +endif() From c0d6f7eccd28c39a708eb2fe451530683e1af434 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:36:48 -0400 Subject: [PATCH 5/7] obs-source: Check the media action admission port against the C Oracle (oracle/source_media_admission.c): the original obs-source-media-admission.c.h, unmodified, with its eight functions renamed to oracle_*, plus every value the port uses: the header's mirrors next to obs.h's OBS_SOURCE_CONTROLLABLE_MEDIA and OBS_MEDIA_STATE_NONE, the mirrored media_action_type values, the call, step and dispatch enums, and the sizes of the enums, int and bool. The renames also rename the two enum tags that share a function's name (enum obs_source_media_admit and enum obs_source_media_dispatch), so their sizes are taken under the oracle_ tag. The bool results are declared as u8 on the Rust side, the byte the C returns; the enums as c_int. Tier 3 (tests/source/media_admission_parity.rs, 8 tests). Every function takes and returns plain values, so each run compares the two results: the bools as bytes, the enums as values, the signal as the bytes of its name or both NULL. - the values and sizes against the C headers, and the fallbacks; - admission: the validity and callback steps; the flag step for every call value from -70000 to 70000, every 65521st int and the ends, with no flag, the flag alone, every bit and every bit but it; every call from -20 to 20 and the ends with each bit alone and every bit but it; - dispatch and signal: every action type, and every dispatch value with both pauses, over the same range; - the callers' order, one copy on each side: the steps of every call from -3 to 14 and the ends, both validities, 10 flag sets and both callbacks, with the values each step reads; process_media_actions() over every type from -3 to 10 and the ends, alone and in pairs, with both pauses; - proptests (20,000 cases each): admission over any call value, flags and inputs; dispatch and signal over any type and dispatch value; process_media_actions() over random queues of up to 11 actions. No input reaches an integer division or a 128-bit multiply on either side, so the MSVC x64 _udiv128 and INT_MIN / -1 faults cannot come up and no input is skipped there. Tier 1 and the parity module passed 10 runs in a row with fresh seeds (28/28 each). No regression file came up; the ones the todo!() stub and the mutants left were deleted. soldr cargo clippy --workspace --target x86_64-pc-windows-msvc --all-targets --locked -- -D warnings is clean. Mutation check (once, not committed): 28 mutants, Tier 1 (20 tests) and Tier 3 (8), failures per mutant. | Mutant | Tier 1 | Tier 3 | |---|---|---| | admit: valid inverted | 4 | 3 | | flags: the bit is 12 / the test inverted | 6 / 6 | 4 / 3 | | started needs a callback / ended needs one / get_state needs none | 5 / 5 / 5 | 3 / 3 / 3 | | a call outside the enum accepted | 4 | 3 | | callback test inverted | 4 | 3 | | time fallback 1 / state fallback 1 | 1 / 1 | 1 / 1 | | dispatch: stop as next / set-time skipped / outside the enum returns | 5 / 5 / 5 | 4 / 4 / 4 | | signal: play and pause swapped / media_stop / a set-time signal | 5 / 5 / 5 | 4 / 4 / 4 | | pause read for every dispatch | 3 | 2 | | Call::value next and previous swapped | 2 | 1 | | Dispatch::value skip 8 / Admit::value read steps swapped | 2 / 1 | 5 / 4 | | shim: call off by one / signal dispatch off by one / pause negated / reads_pause ignores the dispatch / admit() for the callback step | 0 / 0 / 0 / 0 / 0 | 3 / 4 / 4 / 2 / 3 | | Call::from_value started and ended swapped | 2 | 0 | | equivalent: the callback test as a match / NONE matched as 0 | 0 / 0 | 0 / 0 | 25 are killed by Tier 3. Of the other three, swapping started and ended in Call::from_value is equivalent at the C ABI (both are accepted without a callback), and Tier 1 kills it; the other two are rewrites. Tier 1 does not reach the shims; test_source_media_admission_steps_rust and Tier 3 do. No intentional differences: there is no pointer to check. Refs #2239 --- .../oracle/source_media_admission.c | 88 +++++ rust/obs-c-oracle/src/lib.rs | 1 + .../src/source_media_admission.rs | 78 ++++ rust/obs-source/tests/source/main.rs | 1 + .../tests/source/media_admission_parity.rs | 361 ++++++++++++++++++ 5 files changed, 529 insertions(+) create mode 100644 rust/obs-c-oracle/oracle/source_media_admission.c create mode 100644 rust/obs-c-oracle/src/source_media_admission.rs create mode 100644 rust/obs-source/tests/source/media_admission_parity.rs diff --git a/rust/obs-c-oracle/oracle/source_media_admission.c b/rust/obs-c-oracle/oracle/source_media_admission.c new file mode 100644 index 0000000000..9ce3b6dd29 --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_media_admission.c @@ -0,0 +1,88 @@ +/* Test-only oracle: the original libobs/obs-source-media-admission.c.h, + * unmodified, with its eight functions renamed to oracle_* so they can link + * next to the Rust shims. */ +#include +#include + +#include "obs.h" + +#define obs_source_media_admit oracle_obs_source_media_admit +#define obs_source_media_admit_flags oracle_obs_source_media_admit_flags +#define obs_source_media_admit_callback oracle_obs_source_media_admit_callback +#define obs_source_media_time_fallback oracle_obs_source_media_time_fallback +#define obs_source_media_state_fallback oracle_obs_source_media_state_fallback +#define obs_source_media_dispatch oracle_obs_source_media_dispatch +#define obs_source_media_signal_reads_pause oracle_obs_source_media_signal_reads_pause +#define obs_source_media_signal oracle_obs_source_media_signal + +#include "obs-source-media-admission.c.h" + +#undef obs_source_media_signal +#undef obs_source_media_signal_reads_pause +#undef obs_source_media_dispatch +#undef obs_source_media_state_fallback +#undef obs_source_media_time_fallback +#undef obs_source_media_admit_callback +#undef obs_source_media_admit_flags +#undef obs_source_media_admit + +/* The values and sizes the port relies on, in the order of + * rust/obs-c-oracle/src/source_media_admission.rs; INT64_MIN past the end. + * The libobs values the header mirrors come from obs.h (enum + * media_action_type is in obs-internal.h, which obs-source.c checks). The + * renames above also renamed the enum tags that share a function's name, + * enum obs_source_media_admit and enum obs_source_media_dispatch, so their + * sizes are taken under the oracle_ tag. */ +int64_t oracle_source_media_admission_value(size_t which); + +int64_t oracle_source_media_admission_value(size_t which) +{ + const int64_t values[] = { + /* the mirrors and the libobs values */ + OBS_SOURCE_MEDIA_CONTROLLABLE, + OBS_SOURCE_CONTROLLABLE_MEDIA, + OBS_SOURCE_MEDIA_STATE_NONE, + OBS_MEDIA_STATE_NONE, + OBS_SOURCE_MEDIA_ACTION_NONE, + OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE, + OBS_SOURCE_MEDIA_ACTION_RESTART, + OBS_SOURCE_MEDIA_ACTION_STOP, + OBS_SOURCE_MEDIA_ACTION_NEXT, + OBS_SOURCE_MEDIA_ACTION_PREVIOUS, + OBS_SOURCE_MEDIA_ACTION_SET_TIME, + /* enum obs_source_media_call */ + OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE, + OBS_SOURCE_MEDIA_CALL_RESTART, + OBS_SOURCE_MEDIA_CALL_STOP, + OBS_SOURCE_MEDIA_CALL_NEXT, + OBS_SOURCE_MEDIA_CALL_PREVIOUS, + OBS_SOURCE_MEDIA_CALL_GET_DURATION, + OBS_SOURCE_MEDIA_CALL_GET_TIME, + OBS_SOURCE_MEDIA_CALL_SET_TIME, + OBS_SOURCE_MEDIA_CALL_GET_STATE, + OBS_SOURCE_MEDIA_CALL_STARTED, + OBS_SOURCE_MEDIA_CALL_ENDED, + /* enum obs_source_media_admit */ + OBS_SOURCE_MEDIA_ADMIT_REJECT, + OBS_SOURCE_MEDIA_ADMIT_ACCEPT, + OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS, + OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK, + /* enum obs_source_media_dispatch */ + OBS_SOURCE_MEDIA_DISPATCH_RETURN, + OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE, + OBS_SOURCE_MEDIA_DISPATCH_RESTART, + OBS_SOURCE_MEDIA_DISPATCH_STOP, + OBS_SOURCE_MEDIA_DISPATCH_NEXT, + OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS, + OBS_SOURCE_MEDIA_DISPATCH_SET_TIME, + OBS_SOURCE_MEDIA_DISPATCH_SKIP, + /* sizes */ + sizeof(enum obs_source_media_call), + sizeof(enum oracle_obs_source_media_admit), + sizeof(enum oracle_obs_source_media_dispatch), + sizeof(enum obs_media_state), + sizeof(int), + sizeof(bool), + }; + return which < sizeof(values) / sizeof(values[0]) ? values[which] : INT64_MIN; +} diff --git a/rust/obs-c-oracle/src/lib.rs b/rust/obs-c-oracle/src/lib.rs index 27bfeb3a61..7257e1caf6 100644 --- a/rust/obs-c-oracle/src/lib.rs +++ b/rust/obs-c-oracle/src/lib.rs @@ -138,6 +138,7 @@ pub mod source_deinterlace_pacing; pub mod source_draw_plan; pub mod source_frame_copy; pub mod source_load; +pub mod source_media_admission; pub mod source_profiler; pub mod source_ptm_gate; pub mod source_render_route; diff --git a/rust/obs-c-oracle/src/source_media_admission.rs b/rust/obs-c-oracle/src/source_media_admission.rs new file mode 100644 index 0000000000..926e583d99 --- /dev/null +++ b/rust/obs-c-oracle/src/source_media_admission.rs @@ -0,0 +1,78 @@ +//! `oracle_*` build of `libobs/obs-source-media-admission.c.h` +//! (oracle/source_media_admission.c): the media action admission +//! decisions, renamed. The `bool` results are declared as `u8`, the byte +//! the C returns, so a parity test compares it without assuming it is 0 or +//! 1; the enums as [`c_int`], the width the C passes and returns them in. + +use std::os::raw::{c_char, c_int}; + +/// Index of each entry in `oracle_source_media_admission_value`, in the +/// C's order. +pub const VALUE_NAMES: [&str; 40] = [ + "OBS_SOURCE_MEDIA_CONTROLLABLE", + "OBS_SOURCE_CONTROLLABLE_MEDIA", + "OBS_SOURCE_MEDIA_STATE_NONE", + "OBS_MEDIA_STATE_NONE", + "OBS_SOURCE_MEDIA_ACTION_NONE", + "OBS_SOURCE_MEDIA_ACTION_PLAY_PAUSE", + "OBS_SOURCE_MEDIA_ACTION_RESTART", + "OBS_SOURCE_MEDIA_ACTION_STOP", + "OBS_SOURCE_MEDIA_ACTION_NEXT", + "OBS_SOURCE_MEDIA_ACTION_PREVIOUS", + "OBS_SOURCE_MEDIA_ACTION_SET_TIME", + "OBS_SOURCE_MEDIA_CALL_PLAY_PAUSE", + "OBS_SOURCE_MEDIA_CALL_RESTART", + "OBS_SOURCE_MEDIA_CALL_STOP", + "OBS_SOURCE_MEDIA_CALL_NEXT", + "OBS_SOURCE_MEDIA_CALL_PREVIOUS", + "OBS_SOURCE_MEDIA_CALL_GET_DURATION", + "OBS_SOURCE_MEDIA_CALL_GET_TIME", + "OBS_SOURCE_MEDIA_CALL_SET_TIME", + "OBS_SOURCE_MEDIA_CALL_GET_STATE", + "OBS_SOURCE_MEDIA_CALL_STARTED", + "OBS_SOURCE_MEDIA_CALL_ENDED", + "OBS_SOURCE_MEDIA_ADMIT_REJECT", + "OBS_SOURCE_MEDIA_ADMIT_ACCEPT", + "OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS", + "OBS_SOURCE_MEDIA_ADMIT_READ_CALLBACK", + "OBS_SOURCE_MEDIA_DISPATCH_RETURN", + "OBS_SOURCE_MEDIA_DISPATCH_PLAY_PAUSE", + "OBS_SOURCE_MEDIA_DISPATCH_RESTART", + "OBS_SOURCE_MEDIA_DISPATCH_STOP", + "OBS_SOURCE_MEDIA_DISPATCH_NEXT", + "OBS_SOURCE_MEDIA_DISPATCH_PREVIOUS", + "OBS_SOURCE_MEDIA_DISPATCH_SET_TIME", + "OBS_SOURCE_MEDIA_DISPATCH_SKIP", + "sizeof(enum obs_source_media_call)", + "sizeof(enum obs_source_media_admit)", + "sizeof(enum obs_source_media_dispatch)", + "sizeof(enum obs_media_state)", + "sizeof(int)", + "sizeof(bool)", +]; + +unsafe extern "C" { + /// `enum obs_source_media_admit obs_source_media_admit(bool valid)`. + pub fn oracle_obs_source_media_admit(valid: bool) -> c_int; + /// `enum obs_source_media_admit obs_source_media_admit_flags(enum + /// obs_source_media_call call, uint32_t output_flags)`. + pub fn oracle_obs_source_media_admit_flags(call: c_int, output_flags: u32) -> c_int; + /// `enum obs_source_media_admit obs_source_media_admit_callback(bool + /// has_callback)`. + pub fn oracle_obs_source_media_admit_callback(has_callback: bool) -> c_int; + /// `int64_t obs_source_media_time_fallback(void)`. + pub fn oracle_obs_source_media_time_fallback() -> i64; + /// `int obs_source_media_state_fallback(void)`. + pub fn oracle_obs_source_media_state_fallback() -> c_int; + /// `enum obs_source_media_dispatch obs_source_media_dispatch(int + /// type)`. + pub fn oracle_obs_source_media_dispatch(action_type: c_int) -> c_int; + /// `bool obs_source_media_signal_reads_pause(enum + /// obs_source_media_dispatch dispatch)`. + pub fn oracle_obs_source_media_signal_reads_pause(dispatch: c_int) -> u8; + /// `const char *obs_source_media_signal(enum obs_source_media_dispatch + /// dispatch, bool pause)`: a string literal, or NULL. + pub fn oracle_obs_source_media_signal(dispatch: c_int, pause: bool) -> *const c_char; + /// The entry named `VALUE_NAMES[which]`; `i64::MIN` out of range. + pub fn oracle_source_media_admission_value(which: usize) -> i64; +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 7270dd24c3..5184ca2632 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -21,6 +21,7 @@ mod draw_plan_parity; mod frame_copy; mod frame_copy_parity; mod media_admission; +mod media_admission_parity; mod ptm_gate; mod ptm_gate_parity; mod render_route; diff --git a/rust/obs-source/tests/source/media_admission_parity.rs b/rust/obs-source/tests/source/media_admission_parity.rs new file mode 100644 index 0000000000..d14d8a331c --- /dev/null +++ b/rust/obs-source/tests/source/media_admission_parity.rs @@ -0,0 +1,361 @@ +//! Tier 3: the `obs_source_media_*` admission shims against the original C +//! (`obs-c-oracle`, `oracle/source_media_admission.c`: the unmodified +//! `libobs/obs-source-media-admission.c.h` with its functions renamed). +//! +//! Every function takes and returns plain values, so a run compares the two +//! results: the C's `bool` as the byte it returns, the enums as their +//! values, the signal as the bytes of its name (or both NULL). +//! +//! Runs: +//! - the enum values, the mirrors of `OBS_SOURCE_CONTROLLABLE_MEDIA` and +//! `OBS_MEDIA_STATE_NONE` against obs.h, and the sizes, against the C +//! headers; the fallbacks; +//! - admission: the validity step; the flag step for every call value from +//! -70000 to 70000, every 65521st `i32` and the ends, with no flag, the +//! flag alone, every bit and every bit but it; every call value from -20 +//! to 20 and the ends with each of the 32 bits alone and every bit but +//! it; the callback step; +//! - dispatch and signal: every action type from -70000 to 70000, every +//! 65521st `i32` and the ends; every dispatch value over the same range +//! with both pauses; +//! - the callers' order, one copy on each side: the steps of each call +//! (both validities, 10 flag sets, both callbacks) with the values each +//! step reads, and `process_media_actions()` over every queued type from +//! -3 to 10 and the ends, alone and in pairs, with both pauses; +//! - proptests (20,000 cases each): admission over any call value, flags +//! and inputs; dispatch and signal over any type and dispatch value; the +//! callers' order over random queues of any type. +//! +//! No input reaches an integer division or a 128-bit multiply on either +//! side, so the MSVC x64 `_udiv128` and `INT_MIN / -1` faults cannot come +//! up and no input is skipped there. No intentional differences: there is +//! no pointer to check. + +use std::ffi::CStr; +use std::os::raw::{c_char, c_int}; + +use obs_c_oracle::source_media_admission as oracle; +use obs_source::ffi::source_media_admission as shim; +use obs_source::media_admission::{ + Admit, CONTROLLABLE_MEDIA, Call, Dispatch, MEDIA_STATE_NONE, action, +}; +use proptest::prelude::*; + +#[test] +fn values_match_the_c_headers() { + let mut rust: Vec = vec![ + CONTROLLABLE_MEDIA.into(), + CONTROLLABLE_MEDIA.into(), + MEDIA_STATE_NONE.into(), + MEDIA_STATE_NONE.into(), + action::NONE.into(), + action::PLAY_PAUSE.into(), + action::RESTART.into(), + action::STOP.into(), + action::NEXT.into(), + action::PREVIOUS.into(), + action::SET_TIME.into(), + ]; + rust.extend(Call::ALL.map(|c| i64::from(c.value()))); + rust.extend( + [ + Admit::Reject, + Admit::Accept, + Admit::ReadFlags, + Admit::ReadCallback, + ] + .map(|a| i64::from(a.value())), + ); + rust.extend(Dispatch::ALL.map(|d| i64::from(d.value()))); + let int = i64::try_from(std::mem::size_of::()).unwrap(); + rust.extend([int, int, int, int, int, 1]); + assert_eq!(rust.len(), oracle::VALUE_NAMES.len()); + + for (which, (name, value)) in oracle::VALUE_NAMES.iter().zip(rust).enumerate() { + // SAFETY: a pure lookup. + let c = unsafe { oracle::oracle_source_media_admission_value(which) }; + assert_eq!(value, c, "{name}"); + } + // SAFETY: a pure lookup, one past the end. + let past = unsafe { oracle::oracle_source_media_admission_value(oracle::VALUE_NAMES.len()) }; + assert_eq!(past, i64::MIN, "the list has as many values as names"); +} + +#[test] +fn fallbacks() { + // SAFETY: no arguments. + let (time, state) = unsafe { + ( + oracle::oracle_obs_source_media_time_fallback(), + oracle::oracle_obs_source_media_state_fallback(), + ) + }; + assert_eq!(shim::obs_source_media_time_fallback(), time); + assert_eq!(shim::obs_source_media_state_fallback(), state); +} + +// -------------------------------------------------------------------------- +// One call on each side + +fn check_admit(valid: bool) { + // SAFETY: plain values. + let c = unsafe { oracle::oracle_obs_source_media_admit(valid) }; + assert_eq!(shim::obs_source_media_admit(valid), c, "admit({valid})"); +} + +fn check_admit_flags(call: c_int, flags: u32) { + // SAFETY: plain values; the C takes any int for the enum. + let c = unsafe { oracle::oracle_obs_source_media_admit_flags(call, flags) }; + assert_eq!( + shim::obs_source_media_admit_flags(call, flags), + c, + "admit_flags({call}, {flags:#x})" + ); +} + +fn check_admit_callback(has_callback: bool) { + // SAFETY: plain values. + let c = unsafe { oracle::oracle_obs_source_media_admit_callback(has_callback) }; + assert_eq!( + shim::obs_source_media_admit_callback(has_callback), + c, + "admit_callback({has_callback})" + ); +} + +fn check_dispatch(action_type: c_int) { + // SAFETY: plain values. + let c = unsafe { oracle::oracle_obs_source_media_dispatch(action_type) }; + assert_eq!( + shim::obs_source_media_dispatch(action_type), + c, + "dispatch({action_type})" + ); +} + +/// The name a signal pointer points at, `None` for NULL. +fn name(ptr: *const c_char) -> Option> { + // SAFETY: both sides return NULL or a static NUL-terminated string. + (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_bytes().to_vec()) +} + +fn c_signal(dispatch: c_int, pause: bool) -> Option> { + // SAFETY: plain values; the result is NULL or a string literal. + name(unsafe { oracle::oracle_obs_source_media_signal(dispatch, pause) }) +} + +fn rs_signal(dispatch: c_int, pause: bool) -> Option> { + name(shim::obs_source_media_signal(dispatch, pause)) +} + +fn check_signal(dispatch: c_int) { + // SAFETY: plain values. + let c = unsafe { oracle::oracle_obs_source_media_signal_reads_pause(dispatch) }; + assert_eq!( + u8::from(shim::obs_source_media_signal_reads_pause(dispatch)), + c, + "signal_reads_pause({dispatch})" + ); + for pause in [false, true] { + assert_eq!( + rs_signal(dispatch, pause), + c_signal(dispatch, pause), + "signal({dispatch}, {pause})" + ); + } +} + +/// -70000 to 70000, every 65521st `i32` and the ends. +fn wide_values() -> impl Iterator { + (-70_000..=70_000) + .chain((i32::MIN..=i32::MAX).step_by(65_521)) + .chain([i32::MIN, i32::MIN + 1, i32::MAX - 1, i32::MAX]) +} + +const FLAG_SETS: [u32; 10] = [ + 0, + CONTROLLABLE_MEDIA, + u32::MAX, + !CONTROLLABLE_MEDIA, + CONTROLLABLE_MEDIA << 1, + CONTROLLABLE_MEDIA >> 1, + 0b111, + CONTROLLABLE_MEDIA | 0b111, + 0x8000_0000, + CONTROLLABLE_MEDIA | 0x8000_0000, +]; + +#[test] +fn admission_every_value() { + for valid in [false, true] { + check_admit(valid); + check_admit_callback(valid); + } + for call in wide_values() { + for flags in [0, CONTROLLABLE_MEDIA, u32::MAX, !CONTROLLABLE_MEDIA] { + check_admit_flags(call, flags); + } + } + for call in (-20..=20).chain([i32::MIN, i32::MAX]) { + for bit in 0..32 { + check_admit_flags(call, 1 << bit); + check_admit_flags(call, !(1 << bit)); + } + } +} + +#[test] +fn dispatch_and_signal_every_value() { + for value in wide_values() { + check_dispatch(value); + check_signal(value); + } +} + +// -------------------------------------------------------------------------- +// The callers' order, one copy on each side + +/// The admission steps of one call in `media_admit()` and the callback +/// check's order, with the values read, through the shims (`rs`) or the +/// oracle. +fn admit_in_order(rs: bool, call: c_int, valid: bool, flags: u32, has_callback: bool) -> String { + let admit = |v| { + if rs { + shim::obs_source_media_admit(v) + } else { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_source_media_admit(v) } + } + }; + let admit_flags = |c, f| { + if rs { + shim::obs_source_media_admit_flags(c, f) + } else { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_source_media_admit_flags(c, f) } + } + }; + let admit_callback = |cb| { + if rs { + shim::obs_source_media_admit_callback(cb) + } else { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_source_media_admit_callback(cb) } + } + }; + let read_flags = Admit::ReadFlags.value(); + let read_callback = Admit::ReadCallback.value(); + + let mut trace = Vec::new(); + let mut step = admit(valid); + if step == read_flags { + trace.push("flags".to_owned()); + step = admit_flags(call, flags); + } + if step == read_callback { + trace.push("callback".to_owned()); + step = admit_callback(has_callback); + } + trace.push(format!("= {step}")); + trace.join(" ") +} + +fn check_admit_in_order(call: c_int, valid: bool, flags: u32, has_callback: bool) { + assert_eq!( + admit_in_order(true, call, valid, flags, has_callback), + admit_in_order(false, call, valid, flags, has_callback), + "call {call} valid {valid} flags {flags:#x} callback {has_callback}" + ); +} + +/// `process_media_actions()` over a queue in its order, the callback, then +/// the signal, through the shims (`rs`) or the oracle. +fn run_queue(rs: bool, queue: &[(c_int, bool)]) -> String { + let dispatch = |t| { + if rs { + shim::obs_source_media_dispatch(t) + } else { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_source_media_dispatch(t) } + } + }; + let reads_pause = |d| { + if rs { + shim::obs_source_media_signal_reads_pause(d) + } else { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_source_media_signal_reads_pause(d) != 0 } + } + }; + let signal = |d, p| if rs { rs_signal(d, p) } else { c_signal(d, p) }; + + let mut trace = Vec::new(); + for &(t, pause) in queue.iter().chain(std::iter::once(&(action::NONE, false))) { + let d = dispatch(t); + trace.push(format!("dispatch {d}")); + if d == Dispatch::Return.value() { + return trace.join(" "); + } + if let Some(name) = signal(d, reads_pause(d) && pause) { + trace.push(String::from_utf8(name).unwrap()); + } + } + unreachable!("the queue ends in MEDIA_ACTION_NONE") +} + +fn check_queue(queue: &[(c_int, bool)]) { + assert_eq!(run_queue(true, queue), run_queue(false, queue), "{queue:?}"); +} + +#[test] +fn callers_order() { + for call in (-3..=14).chain([i32::MIN, i32::MAX]) { + for valid in [false, true] { + for flags in FLAG_SETS { + for cb in [false, true] { + check_admit_in_order(call, valid, flags, cb); + } + } + } + } + + let types: Vec = (-3..=10).chain([i32::MIN, i32::MAX]).collect(); + check_queue(&[]); + for &a in &types { + for pa in [false, true] { + check_queue(&[(a, pa)]); + for &b in &types { + for pb in [false, true] { + check_queue(&[(a, pa), (b, pb)]); + } + } + } + } +} + +fn any_type() -> impl Strategy { + prop_oneof![0..8_i32, -2..12_i32, any::()] +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(20_000))] + + #[test] + fn proptest_admission(call in prop_oneof![0..11_i32, any::()], valid: bool, + flags in prop_oneof![any::(), Just(CONTROLLABLE_MEDIA)], + cb: bool) { + check_admit_flags(call, flags); + check_admit_in_order(call, valid, flags, cb); + } + + #[test] + fn proptest_dispatch_and_signal(t in any_type(), d in any_type()) { + check_dispatch(t); + check_signal(d); + } + + #[test] + fn proptest_queue(queue in proptest::collection::vec((any_type(), any::()), 0..12)) { + check_queue(&queue); + } +} From 638d1dcb5c7db298f0e6a6ab7970190485f74250 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:41:45 -0400 Subject: [PATCH 6/7] docs: Record the media action admission port The rust/README.md crate table now lists libobs/obs-source-media-admission.c.h among the rust/obs-source units, and its port table has a row for it: the eight functions and what they decide, the READ_ steps that keep each field read where it was, the mirrored libobs values and their checks, what stays C (data_valid() and obs_source_valid(), every field read, the action queue and its mutex, the callbacks before their signals, the signals and the refs), the enums as int and the static signal names, what is kept and characterized, no intentional differences, the _rust variant of the characterization, the real-libobs tests and what Tier 3 compares. The crate's description and lib.rs say what it holds. docs/rust-port/naming.md already maps libobs/obs-source*.c.h to rust/obs-source. A port with no change in behaviour adds no docs/features.md line. port_comparison gets its own bench file, benches/port_comparison/source_media_admission.rs, in the sorted modules! list: 1024 calls through the admission steps in the callers' order (every call, both validities, flag sets with and without OBS_SOURCE_CONTROLLABLE_MEDIA, both callbacks) and 1024 queued actions through the dispatch and the signal (every type and a few outside the enum, both pauses), folded into checksums both sides must match. Neither side allocates, and the module passes the bench's per-module allocation check. On x86_64 Linux (GCC, not pinned, load average 28 to 36; median, two runs): admission 7.0 and 8.7 us Rust, 3.4 and 6.0 us C per 1024 calls; process_actions 20.7 and 19.6 us Rust, 12.0 and 19.5 us C. Under 8 ns more a call, for calls a user or a client makes by hand. soldr cargo test -p obs-c-oracle --locked --bench port_comparison passes. Fixes #2239 --- rust/README.md | 3 +- rust/obs-c-oracle/benches/port_comparison.rs | 3 + .../port_comparison/source_media_admission.rs | 165 ++++++++++++++++++ rust/obs-source/Cargo.toml | 2 +- rust/obs-source/src/lib.rs | 6 +- 5 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 rust/obs-c-oracle/benches/port_comparison/source_media_admission.rs diff --git a/rust/README.md b/rust/README.md index f22219ed27..0e4f2b9ef0 100644 --- a/rust/README.md +++ b/rust/README.md @@ -22,7 +22,7 @@ are in [docs/rust-port/naming.md](../docs/rust-port/naming.md#repository-layout- | `obs-missing-files/` | Port of `libobs/obs-missing-files.c.h` | | `obs-output/` | Ports of `libobs/obs-output-delay.c.h` (the stream delay), `libobs/obs-output-interleave.c.h` (the encoded packet interleaver), `libobs/obs-output-caption-text.c.h` (the caption text wrap) , `libobs/obs-output-protocols.c.h` (the output protocol-list match), `libobs/obs-encoder-roi.c.h` (the encoder region of interest checks and scaling), `libobs/obs-output-video-checks.c.h` (the output video size, conversion and capture checks), `libobs/obs-encoder-size.c.h` (the encoder size and info choices) and `libobs/obs-service-getters.c.h` (the service capability, connect-info, settings, properties and identity functions, and its lifecycle, references and activation) | | `obs-scene/` | Ports of the units extracted from `libobs/obs-scene.c`: `libobs/obs-scene-bounds.c.h`, `libobs/obs-scene-blend.c.h`, `libobs/obs-scene-coords.c.h`, `libobs/obs-scene-group-transform.c.h`, `libobs/obs-scene-audio-actions.c.h` (the core of the scene item visibility audio ramp), `libobs/obs-scene-extent.c.h` (the content extent of a scene or group), `libobs/obs-scene-crop.c.h` (the scene item crop arithmetic), `libobs/obs-scene-render-plan.c.h` (the per-item render decisions of `render_item` and `render_item_texture`), and `libobs/obs-scene-item-names.c.h` (the scene item save/load names and coordinate keys), and `libobs/obs-scene-audio-window.c.h` (the audio window decisions of `scene_audio_render`) | -| `obs-source/` | Ports of the units extracted from `libobs/obs-source.c`, `libobs/obs-source-deinterlace.c` and `libobs/obs-source-transition.c`: so far `libobs/obs-source-async-pacing.c.h` (the async video frame pacing of `get_closest_frame()`), `libobs/obs-source-audio-input.c.h` (the audio input steps of `process_audio()` and `reset_resampler()`), `libobs/obs-source-audio-render.c.h` (the audio render mix plan of `obs_source_audio_render()`, `custom_audio_render()` and `process_audio_source_tick()`), `libobs/obs-source-audio-timing.c.h` (the audio timestamp placement of `source_output_audio_data()`), `libobs/obs-source-color-space.c.h` (the colour space query routing of `obs_source_get_color_space()`), `libobs/obs-source-conversion-plan.c.h` (the async video GPU conversion plan), `libobs/obs-source-deinterlace-draw.c.h` (the deinterlace draw decisions), `libobs/obs-source-deinterlace-pacing.c.h` (the 2x deinterlace frame pacing), `libobs/obs-source-draw-plan.c.h` (the source draw decisions of `rotate_async_video()`, `obs_source_render_async_video()` and `source_render()`), `libobs/obs-source-frame-copy.c.h` (the async frame copy plan and cache decisions), `libobs/obs-source-ptm-gate.c.h` (the push-to-mute and push-to-talk gate of `source_muted()`), `libobs/obs-source-render-route.c.h` (the source and filter render routing), `libobs/obs-source-size.c.h` (the size query routing of `obs_source_get_width()` and `obs_source_get_height()`), `libobs/obs-source-transition-clock.c.h` (the transition clock and fit of `libobs/obs-source-transition.c.h`), `libobs/obs-source-transition-render.c.h` (the transition render and audio steps of `libobs/obs-source-transition.c.h`) and `libobs/obs-source-volume.c.h` (the volume snap of `get_source_volume()` and the apply decisions of `apply_audio_volume()`) | +| `obs-source/` | Ports of the units extracted from `libobs/obs-source.c`, `libobs/obs-source-deinterlace.c` and `libobs/obs-source-transition.c`: so far `libobs/obs-source-async-pacing.c.h` (the async video frame pacing of `get_closest_frame()`), `libobs/obs-source-audio-input.c.h` (the audio input steps of `process_audio()` and `reset_resampler()`), `libobs/obs-source-audio-render.c.h` (the audio render mix plan of `obs_source_audio_render()`, `custom_audio_render()` and `process_audio_source_tick()`), `libobs/obs-source-audio-timing.c.h` (the audio timestamp placement of `source_output_audio_data()`), `libobs/obs-source-color-space.c.h` (the colour space query routing of `obs_source_get_color_space()`), `libobs/obs-source-conversion-plan.c.h` (the async video GPU conversion plan), `libobs/obs-source-deinterlace-draw.c.h` (the deinterlace draw decisions), `libobs/obs-source-deinterlace-pacing.c.h` (the 2x deinterlace frame pacing), `libobs/obs-source-draw-plan.c.h` (the source draw decisions of `rotate_async_video()`, `obs_source_render_async_video()` and `source_render()`), `libobs/obs-source-media-admission.c.h` (the media action admission decisions of the `obs_source_media_*()` functions and `process_media_actions()`), `libobs/obs-source-frame-copy.c.h` (the async frame copy plan and cache decisions), `libobs/obs-source-ptm-gate.c.h` (the push-to-mute and push-to-talk gate of `source_muted()`), `libobs/obs-source-render-route.c.h` (the source and filter render routing), `libobs/obs-source-size.c.h` (the size query routing of `obs_source_get_width()` and `obs_source_get_height()`), `libobs/obs-source-transition-clock.c.h` (the transition clock and fit of `libobs/obs-source-transition.c.h`), `libobs/obs-source-transition-render.c.h` (the transition render and audio steps of `libobs/obs-source-transition.c.h`) and `libobs/obs-source-volume.c.h` (the volume snap of `get_source_volume()` and the apply decisions of `apply_audio_volume()`) | | `obs-audio-monitoring/` | Ports of `libobs/audio-monitoring/*` (so far `pulse/pulseaudio-stream-flags.c.h` and `pulse/pulseaudio-monitor-format.c.h`) | | `obs-audio-controls/` | Port of `libobs/obs-audio-controls.c.h` | | `obs-core/` | Ports of the units extracted from `libobs/obs.c.h`, `libobs/obs-module.c.h` and `libobs/obs-audio.c.h`: so far `libobs/obs-video-plan.c.h` (the video output plan), `libobs/obs-context-names.c.h` (the context names), `libobs/obs-source-load.c.h` (the source load migration and value rules), `libobs/obs-module-paths.c.h` (the module search paths), `libobs/obs-module-names.c.h` (module names and files), `libobs/obs-module-locale.c.h` (the module locale files), `libobs/obs-module-source-rules.c.h` (the source registration rules), `libobs/obs-module-type-rules.c.h` (the output, encoder and service registration rules), `libobs/obs-audio-mix.c.h` (the audio tick arithmetic); of `libobs/util/source-profiler.c.h` (per-source tick and render timing), which reads core state; of `libobs/obs-view-api.c.h` (views); and of `libobs/obs-video-copy-plan.c.h` (the output frame copy plan and scale effect choice, from `libobs/obs-video.c.h`); and of `libobs/obs-video-output-step.c.h` (the per-frame video output step decisions, from `libobs/obs-video.c.h`) | @@ -169,6 +169,7 @@ and compares their exported symbols. `OBS_LIBOBS_BACKEND=C` is temporary rollbac | `libobs/obs-source-deinterlace-pacing.c.h` | `obs-source::deinterlace_pacing` | Swapped in hybrid `libobs` (group `libobs.ported-source-deinterlace-pacing`). The frame pacing of double-rate deinterlacing (Yadif 2x, Linear 2x, Discard 2x), from `deinterlace_get_closest_frames()` and `ready_deinterlace_frames()`, as six functions on plain integers: `obs_source_deinterlace_pacing_hold()` (an unbuffered source keeps its frame while the frame's end is ahead of the clock by less than `TS_JUMP_THRESHOLD`), `obs_source_deinterlace_pacing_wait_for_next()` and `_waiting_frame_ts()` (the "don't skip ahead" guard of an unbuffered source with two frames queued), `obs_source_deinterlace_pacing_half_duration()` (half the time from the frame before; with no usable frame before, that is none, a timestamp going backwards, or a gap past twice `TS_JUMP_THRESHOLD`, the half duration before when it is sane, else half the canvas interval, #1965), `obs_source_deinterlace_pacing_buffered_offset()` (a buffered source's offset from the source clock, #395) and `obs_source_deinterlace_pacing_reanchor()` (an unbuffered source's offset, kept unless the frame comes early or misses its tick and its first field, #395). They are declared in `obs-source-deinterlace-pacing.h` without `EXPORT`, so the shims stay hidden. `obs-source-deinterlace.c.h` keeps the `async_unbuffered` and `deinterlace_offset` tests before the hold and the guard, the field and `obs->video` reads and the stores in their order, the `async_frames` queue, the buffered walk, `first_frame()`, the textures and the render. Every sum and difference wraps as the C's `uint64_t` does, and the re-anchor's lateness is `cast_signed()` of the wrapped difference, the C's `(int64_t)`. The crate still depends on no other crate. Kept, characterized, not endorsed: a timestamp going backwards wraps the guard's end and the waiting timestamp; the offsets wrap when the frame's clock is ahead of the canvas, and a lateness of 2^63 or more counts as early; at 29.97 and 59.94 frames a second into a slightly faster canvas the offset re-anchors on every frame. No intentional differences. `test_deinterlace_pacing_steps` compiles the C into itself, and `test_deinterlace_pacing_steps_rust` runs the same test source against `libobs_rust-static`; `test_deinterlace_2x_field_order` sees the swap through the real libobs. Tier 3 compares the result bytes of every function over the special values and full-range proptests, and sequences of 25, 29.97, 50 and 59.94 frames a second into 30 and 60 fps, buffered and unbuffered, through a model of the caller (the queue, the buffered walk and the stores), every call and the state after every tick; `first_frame_cadences` runs the first frame of a new source and the first after a pause at those rates and checks its fields and that every later state is the one of before #1965. | | `libobs/obs-source-draw-plan.c.h` | `obs-source::draw_plan` | Swapped in hybrid `libobs` (group `libobs.ported-source-draw-plan`). The source draw decisions of `rotate_async_video()`, `obs_source_render_async_video()` and `source_render()`, as eight functions on plain values: `obs_source_draw_plan_rotation_x()` and `_y()` (the translate that moves a rotated async frame back into its box: height or width for 270 and 90, both for 180, nothing for any other angle; the rotation is in 0-359 since #2136), `obs_source_draw_plan_async_linear_srgb()` (the graphics flag, or an SDR frame into anything but `GS_CS_SRGB`, or an HDR frame tonemapped into SDR), `obs_source_draw_plan_async_nonlinear_alpha()` (an SDR frame drawn linear whose alpha is not linear), `obs_source_draw_plan_technique()` (the technique for each pair of source and current colour spaces, with or without non-linear alpha; `source_render()`'s conversion uses the same table without it), `obs_source_draw_plan_reads_white_level()` and `_multiplier()` (into or out of scRGB, the level over 80 or 80 over the level, `obs_get_video_sdr_white_level()` read only then, the same for both callers) and `obs_source_draw_plan_convert()` (whether `source_render()` draws through `color_space_texrender`: the two spaces in different classes, SDR, 709_EXTENDED and scRGB). The techniques are `enum obs_source_draw_technique` (`obs-source-draw-technique.h`, `obs-source::draw_technique`), shared with the deinterlace draw decisions; C maps them to names. They are declared in `obs-source-draw-plan.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `gs_*` call in its order and under its conditions (the decisions are separate calls, not one plan, so neither `gs_get_linear_srgb()` nor the white level read is hoisted), `convert_video_space()`, `obs_get_video_sdr_white_level()`, `gs_get_format_from_space()`, the texrenders and the technique names. Colour spaces cross as `int` and the rotation as `long` (`c_long`), so values outside the enum or 0-359 take the C's paths. The multiplier is one `f32` division, the C's, bit for bit (NaN payloads and infinities included), and the size converts to `f32` as `(float)uint32_t` does. Kept, characterized, not endorsed: a white level of 0 gives a multiplier of 0 into scRGB and +inf out of it (-0 gives -inf, a NaN stays a NaN); a rotation outside 0-359 is not moved; an SDR frame into a current space outside the enum is drawn linear with non-linear alpha, with `Draw`. No intentional differences. `test_source_draw_plan_steps` compiles the C into itself, and `test_source_draw_plan_steps_rust` runs the same test source against `libobs_rust-static`; `test_async_rotation_normalize`, `test_filter_color_space`, `test_source_color_space_steps`, `test_color_correction_16f`, `test_pipewire_cursor_hdr` and `test_texture_render` see the swap through the real libobs. Tier 3 compares the result bytes of every function: rotations around 0-359, a stride over all of `c_long` and past 32 bits, sizes around 2^24 and `u32::MAX`, every pair of 649 spaces with every flag, every pair of 12 spaces at 26 special white levels, both callers' decisions in their order, and proptests over any rotation, size, space and `f32` white level bit pattern. | | `libobs/obs-source-frame-copy.c.h` | `obs-source::frame_copy` | Swapped in hybrid `libobs` (group `libobs.ported-source-frame-copy`). The async frame copy plan and cache decisions of `obs-source.c`, as six functions on plain values: `obs_source_frame_copy_plan()` (`copy_frame_data()`, `copy_frame_data_plane()` and `copy_frame_data_line()`: the colour range only when the frame is not full range, 065379b; then per format each plane's rows, `(height + 1) / 2` for 4:2:0 chroma, 8440a53; one copy of line size x rows in `size_t` when the two line sizes are equal, else rows of the smaller line size; no plane for P216, P416 and values outside the enum), `obs_source_frame_copy_cache_step()` (`cache_video()`'s queue limit at `MAX_ASYNC_FRAMES`, 7f7901b, which clears the cache and refuses the frame, then `async_texture_changed()`'s reset on a new size or convert type), `obs_source_frame_copy_cache_clean()` (one entry of `clean_cache()`: an unused entry counts one more call and is dropped at `MAX_UNUSED_FRAME_DURATION`, 3a90be3, 0815d5c), `obs_source_frame_copy_full_range()` and `_full_range2()` (a frame given to `obs_source_output_video()`, `obs_source_preload_video()` or `obs_source_set_video_frame()` that is not YUV is full range, 8d125dc; their `*2()` variants are full range when `resolve_video_range()` gives `VIDEO_RANGE_FULL`) and `obs_source_frame_copy_preload_changed()` (`preload_frame_changed()`). They are declared in `obs-source-frame-copy.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `memcpy()` (it runs the plan, each row at `y * line size` in `uint32_t`), the metadata copy, `obs_source_frame_create()` and `_destroy()`, the `async_cache` and `async_frames` darrays and the walk that picks the first unused entry (with #2048's `prev_frame` reset, #2009), `async_mutex`, the refcount atomics, and `get_convert_type()` (it passes the two convert types). Everything crosses by value, as `#[repr(C)]` mirrors of the header's structs: no pointer crosses. The formats and ranges cross as `int`, so values outside the enums take the C's paths. The arithmetic is the C's, wrap for wrap: `(height + 1) / 2` in `u32` and the one copy's size as a `usize` product. Kept, characterized, not endorsed: P216 and P416 copy no plane ("Unimplemented"); `UINT32_MAX` rows have 0 chroma rows; an unused count past 5 is never dropped (unreachable); the `*2()` rule keeps an explicit `VIDEO_RANGE_PARTIAL` on an RGB frame, which the first rule would make full range. Intentional difference, unreachable: `clean_cache()`'s `++unused_count` overflows a `long` at `LONG_MAX`, which is undefined in C; the port wraps. No entry gets past 5. `test_source_frame_copy_steps` compiles the C into itself, and `test_source_frame_copy_steps_rust` runs the same test source against `libobs_rust-static`; `test_video_frame`, the media restart tests, the v4l2 and PipeWire camera tests, `test_async_rotation_normalize` and the deinterlace tests see the swap through the real libobs. Tier 3 compares every field of every result over every C format value against every pattern of the four planes' line sizes (equal, smaller, larger, 0, or a destination of 0) at the `u32` height edges (2,280,000 plans), real frame line sizes, the queue limit over every length up to 64 with each key field changed alone, every count from -1000 to 1000 and the `c_long` ends but `LONG_MAX`, the range rules over formats -300 to 300 and every range from -10 to 10 with the `i32` ends, every preload combination around the edges, and proptests over each. | +| `libobs/obs-source-media-admission.c.h` | `obs-source::media_admission` | Swapped in hybrid `libobs` (group `libobs.ported-source-media-admission`). The media action admission decisions of the eleven `obs_source_media_*()` functions and `process_media_actions()` (obs-websocket reaches them through `TriggerMediaInputAction` and `SetMediaInputCursor`), as eight functions on plain values: `obs_source_media_admit()`, `_admit_flags()` and `_admit_callback()` (whether a call is accepted, one step at a time in the C's order: an invalid source is rejected, then one without `OBS_SOURCE_CONTROLLABLE_MEDIA`, then, for every call but `_started()` and `_ended()`, one without the call's callback; a step that needs a value answers `READ_FLAGS` or `READ_CALLBACK` and `obs-source.c.h` reads it then, so the flags are read only for a valid source and a callback only for a controllable one), `obs_source_media_time_fallback()` and `_state_fallback()` (what a rejected getter returns, 0 and `OBS_MEDIA_STATE_NONE`), `obs_source_media_dispatch()` (each queued `enum media_action_type` to its callback, return for `MEDIA_ACTION_NONE`, skip for a type outside the enum) and `obs_source_media_signal_reads_pause()` and `_signal()` (the signal after the callback: `media_play` or `media_pause` by `action.pause`, read only for a play/pause, `media_restart`, `media_stopped`, `media_next`, `media_previous`, none for a set-time). They are declared in `obs-source-media-admission.h` without `EXPORT`, so the shims stay hidden; the header mirrors `OBS_SOURCE_CONTROLLABLE_MEDIA`, `OBS_MEDIA_STATE_NONE` and `enum media_action_type` as defines, which `obs-source.c.h` checks, so the file and its PCH need no libobs header. `obs-source.c.h` keeps `data_valid()` and `obs_source_valid()` (they log), every field read, the action queue and its mutex, the callbacks (each before its signal, `action.pause` and `action.ms` read where they were), the signals and the source refs. The enums cross as `int`, so values outside them take the C's paths; the signal names are static C strings. Kept, characterized, not endorsed: `_started()` and `_ended()` need no callback, so they signal for any controllable source (and with no data: they check `obs_source_valid()`); a set-time emits no signal; a queued type outside the enum is dropped silently and the loop takes the next action, and a queued `MEDIA_ACTION_NONE` stops it with actions still queued. No intentional differences. `test_source_media_admission_steps` compiles the C into itself, and `test_source_media_admission_steps_rust` runs the same test source against `libobs_rust-static`; the `test_media_*` tests, `test_slideshow_*`, `test_stinger_media_duration` and `test_ffmpeg_restart_close` see the swap through the real libobs. Tier 3 compares the oracle and the shims: the enum values and the mirrors against obs.h, the flag step for every call value from -70000 to 70000 and a stride over all of `int` with each output flag bit, every action type and dispatch value over the same range with both pauses (the signal by its name), the admission steps and `process_media_actions()` in their order, one copy on each side, and proptests over any call, flags, type and queue. | | `libobs/obs-source-ptm-gate.c.h` | `obs-source::ptm_gate` | Swapped in hybrid `libobs` (group `libobs.ported-source-ptm-gate`). The push-to-mute and push-to-talk gate of `source_muted()`, which gives every audio capture callback its muted flag, as four functions on plain values: `obs_source_ptm_gate_stop_time()` (#2058's `push_to_stop_time()`: while a gate's key is held, the moment it stops holding once let go, `os_time` plus the delay in milliseconds, saturated at `UINT64_MAX` where the product or the sum would wrap, #2051; `get_source_volume()` stores its stop times through it too), `obs_source_ptm_gate_held()` (a key let go holds strictly before its stop time), and `obs_source_ptm_gate_mutes()` and `obs_source_ptm_gate_talk_mutes()` (push-to-mute mutes while enabled and active, push-to-talk while enabled and not active). They are declared in `obs-source-ptm-gate.h` without `EXPORT`, so the shims stay hidden. `source_muted()` and `get_source_volume()` stay C with every read and write of the source's fields in the same order: a stop time is stored only while its gate is enabled and its key pressed (the mix thread stores the same two fields), each pressed flag is read again for its active flag (the hotkey thread writes `user_push_to_*_pressed` without atomics), a stop time is read only when its key is not pressed, and `enabled`, `user_muted` and the enabled flags only where the C's short-circuits reached them. `get_source_volume()` goes through the same four for its stop times, holds and gates (#2158), with the mix's pressed flags and `muted`. No pointer crosses. The core's stop time is `os_time.saturating_add(delay_ms.saturating_mul(NS_PER_MS))`, the same as the C's two checks. Kept, characterized, not endorsed: a saturated stop time does not hold at `os_time` `UINT64_MAX` itself; a stop time stored before a gate was turned off still holds when it is turned back on; while held, an earlier packet moves the stop time back; the mix and the capture callbacks share the stop times, so either one's store holds the other open. No intentional differences. `test_source_ptm_gate_steps` compiles the C into itself, and `test_source_ptm_gate_steps_rust` runs the same test source against `libobs_rust-static`; `test_source_audio_ranges` (the keys pressed through the hotkey router, the stop time read back after a packet, the saturation edges) sees the swap through the real libobs. Tier 3 compares the oracle, the shims and the core: the constant, the gates over their four inputs, the stop time and the hold over every pair of 46 special values and full-range proptests, and `source_muted()` copied onto a stand-in source over every combination of its six flags with stop times around the clock and saturated, and a full-range proptest, the result and both stored stop times. | | `libobs/obs-source-render-route.c.h` | `obs-source::render_route` | Swapped in hybrid `libobs` (group `libobs.ported-source-render-route`). The source and filter render routing of `source_render_video()`, `obs_source_main_render()`, `can_bypass()`, `obs_source_process_filter_begin_with_color_space()`, `obs_source_process_filter_tech_end()` and `obs_source_skip_video_filter()`, as 23 functions on plain values: `obs_source_render_route_filter()` (the target and parent check, no target first, #2177), the "no video", async update and inactive checks of `source_render_video()` with a `_reads_` function for each value the old short circuits read on one side only, the draw as a route over `enum obs_source_render_route_draw` (`_draw()`, `_skip()` and `_filter_render()` start it, `_draw_next()` takes the one value a `READ_` step asks for and returns the next step or the draw: default render, filters, main render, filter target, deinterlace or async video), `obs_source_main_render()`'s custom draw, sRGB-aware and default-effect rules, `can_bypass()` (`_bypass_reads_space()`, then `_bypass()`; the SRGB and space rules of #1493's filter colour space class), the zero size skip, the texrender format check, and the tech end's linear sRGB flag, technique name (`"Draw"` for NULL) and bypass or texture. They are declared in `obs-source-render-route.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `gs_*` call and texrender, the refs, the render calls, `get_base_width()` and `get_base_height()` (it passes the sizes), the debug markers and every field read in its order and under its conditions; that is why the decisions are many small calls and not one plan per function. Types, the direct render choice, colour spaces and formats cross as `int`; `obs-source.c.h` checks the four enums are `int`-sized. A draw step outside the enum comes back unchanged. Kept, characterized, not endorsed: `ASYNC` without `VIDEO` is no video; a direct render choice outside the enum is not direct; a size of 2^31 or more is negative in the C's `int` and does not skip. One pointer crosses: the technique name, returned as given or as a static `"Draw"`, never read. No other intentional differences. `test_source_render_route_steps` compiles the C into itself, and `test_source_render_route_steps_rust` runs the same test source against `libobs_rust-static`; `test_filter_color_space`, `test_filter_skip_removed`, `test_scroll_filter_wide_source`, `test_color_correction_16f`, `test_darken_transparent`, `test_scene_rotated_scale_filter`, `test_slideshow_size` and `test_texture_render` see the swap through the real libobs. Tier 3 compares the result bytes of every function over every boolean, sweeps of types, choices, spaces, formats and sizes over all of `i32`, every 16-bit flag pattern, 17 million bypass inputs, every draw step value, and each caller's decisions in its order (19.9 million filters, 166,400 sources), plus full-range proptests. | | `libobs/obs-source-size.c.h` | `obs-source::size_route` | Swapped in hybrid `libobs` (group `libobs.ported-source-size`). The size query routing of `obs_source_get_width()` and `obs_source_get_height()`, as two functions: `obs_source_size_route()` (where `get_base_width()` and `get_base_height()` take a source's size from: a transition reports `transition_actual_cx`/`cy` while enabled and 0 otherwise, 6839ff7; a source with data and a size callback asks it, f1aa71b, a filter only while enabled, f04ef23; a filter without one asks its target; an active async source reports its frame, `async_width` and `async_height` swapped unless `async_rotation % 180 == 0`, b9d6675, and 0 before its first frame, 506e30d; anything else reports 0) and `obs_source_size_entry()` (where `obs_source_get_width()` starts: a filter at itself, ed8998e; any other source at its first filter if it has filters, 3510e69, else at itself). A filter is a source with a filter parent, 8a1486d, not one of the filter type. They are declared in `obs-source-size.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps `data_valid()`, `filter_mutex` (a filter takes no lock; any other source holds its `filter_mutex` while it reads `filters.num`, asks the start and reads the first filter), the recursion into the target and the first filter, the `get_width` and `get_height` callbacks and the field each route reads. It reads `info.type`, `context.data != NULL`, the axis's callback `!= NULL`, `filter_parent != NULL`, `enabled`, `async_active` and the `long` `async_rotation` into `struct obs_source_size_node` (passed by value, mirrored); one route serves both axes. No source pointer crosses. The rotation is `c_long` (64 bits on Linux and macOS, 32 on Windows) and the swap is `wrapping_rem(180) != 0`, the C's `%` for every value. `obs-source.c.h` checks that the header's filter and transition types match `obs-source.h` and that `enum obs_source_type` is `int`-sized. Kept, characterized, not endorsed: a filter with no parent (detached) asks its callback even while disabled, and without one reports its async frame or 0 instead of asking a target; a source with a callback but no data reports its async frame or 0. No intentional differences. `test_source_size_route_steps` compiles the C into itself, and `test_source_size_route_steps_rust` runs the same test source against `libobs_rust-static`; `test_async_rotation_normalize` (#2136), `test_slideshow_size`, `test_filter_color_space`, `test_scene_item_crop`, `test_scene_rotated_scale_filter` and the transition and scene size tests see the swap through the real libobs. Tier 3 compares the node's layout and values, the route over every combination of the five flags with eight types and 46 rotations, every rotation from -100,000 to 100,000, the entry, and proptests over any node with any `c_long` rotation; a second oracle builds the unchanged C with a 32-bit `long`, as MSVC does, and is compared over the same rows and any `i32` rotation. | diff --git a/rust/obs-c-oracle/benches/port_comparison.rs b/rust/obs-c-oracle/benches/port_comparison.rs index 7c9c822846..3760372e0d 100644 --- a/rust/obs-c-oracle/benches/port_comparison.rs +++ b/rust/obs-c-oracle/benches/port_comparison.rs @@ -64,6 +64,8 @@ mod source_draw_plan; mod source_frame_copy; #[path = "port_comparison/source_load.rs"] mod source_load; +#[path = "port_comparison/source_media_admission.rs"] +mod source_media_admission; #[path = "port_comparison/source_profiler.rs"] mod source_profiler; #[path = "port_comparison/source_ptm_gate.rs"] @@ -171,6 +173,7 @@ fn comparisons(criterion: &mut Criterion) { source_draw_plan, source_frame_copy, source_load, + source_media_admission, source_profiler, source_ptm_gate, source_render_route, diff --git a/rust/obs-c-oracle/benches/port_comparison/source_media_admission.rs b/rust/obs-c-oracle/benches/port_comparison/source_media_admission.rs new file mode 100644 index 0000000000..d110c8b9b8 --- /dev/null +++ b/rust/obs-c-oracle/benches/port_comparison/source_media_admission.rs @@ -0,0 +1,165 @@ +//! obs-source: the media action admission decisions +//! (`libobs/obs-source-media-admission.c.h`), which every +//! `obs_source_media_*()` call runs (obs-websocket's +//! `TriggerMediaInputAction` and `SetMediaInputCursor`, the frontend's media +//! controls, hotkeys) and `process_media_actions()` runs for every queued +//! action on the video thread. Each measurement folds its results into a +//! checksum that both sides must match: +//! - `admission`: 1024 calls through the steps in the callers' order (the +//! validity step, the flags only for a valid source, the callback only +//! for a controllable one that has one to check) over every call, both +//! validities, flag sets with and without OBS_SOURCE_CONTROLLABLE_MEDIA +//! and both callbacks; +//! - `process_actions`: 1024 queued actions through the dispatch and the +//! signal (read the pause only for a play/pause), every action type and a +//! few outside the enum, both pauses; the signal name's first byte goes +//! into the checksum. +//! +//! Neither side allocates while measuring. +//! +//! Measured when it was added (x86_64 Linux, GCC, not pinned to a core, +//! load average 28 to 36; median per 1024, two runs): admission 7.0 and +//! 8.7 us Rust, 3.4 and 6.0 us C; process_actions 20.7 and 19.6 us Rust, +//! 12.0 and 19.5 us C. Under 8 ns more a call either way, for calls a user +//! or a client makes by hand. + +use std::hint::black_box; +use std::os::raw::{c_char, c_int}; + +use criterion::{Criterion, Throughput}; +use obs_c_oracle::source_media_admission as c; +use obs_source::ffi::source_media_admission as rs; + +const COUNT: usize = 1024; + +/// `OBS_SOURCE_MEDIA_ADMIT_READ_FLAGS`, `_READ_CALLBACK` and `_ACCEPT`. +const READ_FLAGS: c_int = 2; +const READ_CALLBACK: c_int = 3; +const ACCEPT: c_int = 1; +/// `OBS_SOURCE_MEDIA_DISPATCH_RETURN`. +const RETURN: c_int = 0; + +struct Side { + admit: fn(bool) -> c_int, + admit_flags: fn(c_int, u32) -> c_int, + admit_callback: fn(bool) -> c_int, + dispatch: fn(c_int) -> c_int, + reads_pause: fn(c_int) -> bool, + signal: fn(c_int, bool) -> *const c_char, +} + +const RUST: Side = Side { + admit: |v| rs::obs_source_media_admit(v), + admit_flags: |call, f| rs::obs_source_media_admit_flags(call, f), + admit_callback: |cb| rs::obs_source_media_admit_callback(cb), + dispatch: |t| rs::obs_source_media_dispatch(t), + reads_pause: |d| rs::obs_source_media_signal_reads_pause(d), + signal: |d, p| rs::obs_source_media_signal(d, p), +}; + +const C: Side = Side { + // SAFETY: plain values; the C touches no memory. + admit: |v| unsafe { c::oracle_obs_source_media_admit(v) }, + // SAFETY: as above; the C takes any int for the enum. + admit_flags: |call, f| unsafe { c::oracle_obs_source_media_admit_flags(call, f) }, + // SAFETY: as above. + admit_callback: |cb| unsafe { c::oracle_obs_source_media_admit_callback(cb) }, + // SAFETY: as above. + dispatch: |t| unsafe { c::oracle_obs_source_media_dispatch(t) }, + // SAFETY: as above. + reads_pause: |d| unsafe { c::oracle_obs_source_media_signal_reads_pause(d) != 0 }, + // SAFETY: as above; the result is NULL or a string literal. + signal: |d, p| unsafe { c::oracle_obs_source_media_signal(d, p) }, +}; + +const FLAGS: [u32; 6] = [1 << 13, (1 << 13) | 0b111, 0b111, 0, u32::MAX, !(1 << 13)]; + +/// Per call: the call, whether the source is valid, its flags and whether +/// it has the callback. +fn calls() -> Vec<(c_int, bool, u32, bool)> { + (0..COUNT) + .map(|i| { + let call = c_int::try_from(i % 11).unwrap(); + (call, i % 13 != 0, FLAGS[(i / 11) % FLAGS.len()], i % 5 != 0) + }) + .collect() +} + +fn run_admission(side: &Side, calls: &[(c_int, bool, u32, bool)]) -> u64 { + let mut sum = 0_u64; + for &(call, valid, flags, cb) in calls { + let mut step = (side.admit)(black_box(valid)); + if step == READ_FLAGS { + step = (side.admit_flags)(call, black_box(flags)); + } + if step == READ_CALLBACK { + step = (side.admit_callback)(black_box(cb)); + } + sum = sum + .wrapping_mul(31) + .wrapping_add(u64::from(step == ACCEPT) + 1); + } + sum +} + +const TYPES: [c_int; 10] = [1, 2, 3, 4, 5, 6, 1, 7, -1, 100]; + +/// Per queued action: its type and pause. +fn actions() -> Vec<(c_int, bool)> { + (0..COUNT) + .map(|i| (TYPES[i % TYPES.len()], i % 3 == 0)) + .collect() +} + +fn run_actions(side: &Side, actions: &[(c_int, bool)]) -> u64 { + let mut sum = 0_u64; + for &(t, pause) in actions { + let d = (side.dispatch)(black_box(t)); + if d == RETURN { + continue; + } + let signal = (side.signal)(d, (side.reads_pause)(d) && black_box(pause)); + let first = if signal.is_null() { + 0 + } else { + // SAFETY: a static NUL-terminated name, at least one byte. + u64::from(unsafe { signal.cast::().read() }) + }; + sum = sum + .wrapping_mul(31) + .wrapping_add(u64::try_from(d).unwrap()) + .wrapping_add(first); + } + sum +} + +pub(crate) fn benchmarks(criterion: &mut Criterion) { + let calls = calls(); + let actions = actions(); + assert_eq!( + run_admission(&RUST, &calls), + run_admission(&C, &calls), + "benchmark fixture differs: admission" + ); + assert_eq!( + run_actions(&RUST, &actions), + run_actions(&C, &actions), + "benchmark fixture differs: process_actions" + ); + + let mut group = criterion.benchmark_group("source_media_admission/admission"); + group.throughput(Throughput::Elements(COUNT as u64)); + group.bench_function("rust", |b| { + b.iter(|| black_box(run_admission(&RUST, &calls))) + }); + group.bench_function("c", |b| b.iter(|| black_box(run_admission(&C, &calls)))); + group.finish(); + + let mut group = criterion.benchmark_group("source_media_admission/process_actions"); + group.throughput(Throughput::Elements(COUNT as u64)); + group.bench_function("rust", |b| { + b.iter(|| black_box(run_actions(&RUST, &actions))) + }); + group.bench_function("c", |b| b.iter(|| black_box(run_actions(&C, &actions)))); + group.finish(); +} diff --git a/rust/obs-source/Cargo.toml b/rust/obs-source/Cargo.toml index 8ba8a586af..6a988c19e6 100644 --- a/rust/obs-source/Cargo.toml +++ b/rust/obs-source/Cargo.toml @@ -2,7 +2,7 @@ autotests = false name = "obs-source" version = "0.1.0" -description = "Rust ports of libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-render.c.h (the transition render and audio steps) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions)" +description = "Rust ports of libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-render.c.h (the transition render and audio steps) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions)" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index c656f26ad2..c31596cf34 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -24,6 +24,10 @@ //! `libobs/obs-source-frame-copy.c.h`, the async frame copy plan and cache //! decisions of `copy_frame_data()`, `cache_video()`, `clean_cache()` and the //! `obs_source_output_video()` families; +//! `libobs/obs-source-media-admission.c.h`, the media action admission +//! decisions of the `obs_source_media_*()` functions and +//! `process_media_actions()` (whether a call is accepted, the getters' +//! fallbacks, and each queued action's callback and signal); //! `libobs/obs-source-ptm-gate.c.h`, the //! push-to-mute and push-to-talk gate of `source_muted()`; //! `libobs/obs-source-render-route.c.h`, the source and filter render @@ -40,7 +44,7 @@ //! The safe cores are [`async_pacing`], [`audio_input`], //! [`audio_render_plan`], [`audio_timing`], //! [`color_space`], [`conversion_plan`], [`deinterlace_draw`], -//! [`deinterlace_pacing`], [`draw_plan`], [`frame_copy`], [`ptm_gate`], [`render_route`], [`size_route`], +//! [`deinterlace_pacing`], [`draw_plan`], [`frame_copy`], [`media_admission`], [`ptm_gate`], [`render_route`], [`size_route`], //! [`transition_clock`], [`transition_render`] and [`volume_apply`]; [`draw_technique`] holds the //! technique and colour space values [`deinterlace_draw`] and [`draw_plan`] //! share. The C From 4c723d143cd3858ec370e780b7ef9c36f0163907 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 19:33:12 -0400 Subject: [PATCH 7/7] docs: Sort the media admission entry in the obs-source crate row The rust/README.md obs-source/ row lists its units by file name, so libobs/obs-source-media-admission.c.h goes after libobs/obs-source-frame-copy.c.h, before libobs/obs-source-ptm-gate.c.h. Fixes #2239 --- rust/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/README.md b/rust/README.md index 0e4f2b9ef0..b106248061 100644 --- a/rust/README.md +++ b/rust/README.md @@ -22,7 +22,7 @@ are in [docs/rust-port/naming.md](../docs/rust-port/naming.md#repository-layout- | `obs-missing-files/` | Port of `libobs/obs-missing-files.c.h` | | `obs-output/` | Ports of `libobs/obs-output-delay.c.h` (the stream delay), `libobs/obs-output-interleave.c.h` (the encoded packet interleaver), `libobs/obs-output-caption-text.c.h` (the caption text wrap) , `libobs/obs-output-protocols.c.h` (the output protocol-list match), `libobs/obs-encoder-roi.c.h` (the encoder region of interest checks and scaling), `libobs/obs-output-video-checks.c.h` (the output video size, conversion and capture checks), `libobs/obs-encoder-size.c.h` (the encoder size and info choices) and `libobs/obs-service-getters.c.h` (the service capability, connect-info, settings, properties and identity functions, and its lifecycle, references and activation) | | `obs-scene/` | Ports of the units extracted from `libobs/obs-scene.c`: `libobs/obs-scene-bounds.c.h`, `libobs/obs-scene-blend.c.h`, `libobs/obs-scene-coords.c.h`, `libobs/obs-scene-group-transform.c.h`, `libobs/obs-scene-audio-actions.c.h` (the core of the scene item visibility audio ramp), `libobs/obs-scene-extent.c.h` (the content extent of a scene or group), `libobs/obs-scene-crop.c.h` (the scene item crop arithmetic), `libobs/obs-scene-render-plan.c.h` (the per-item render decisions of `render_item` and `render_item_texture`), and `libobs/obs-scene-item-names.c.h` (the scene item save/load names and coordinate keys), and `libobs/obs-scene-audio-window.c.h` (the audio window decisions of `scene_audio_render`) | -| `obs-source/` | Ports of the units extracted from `libobs/obs-source.c`, `libobs/obs-source-deinterlace.c` and `libobs/obs-source-transition.c`: so far `libobs/obs-source-async-pacing.c.h` (the async video frame pacing of `get_closest_frame()`), `libobs/obs-source-audio-input.c.h` (the audio input steps of `process_audio()` and `reset_resampler()`), `libobs/obs-source-audio-render.c.h` (the audio render mix plan of `obs_source_audio_render()`, `custom_audio_render()` and `process_audio_source_tick()`), `libobs/obs-source-audio-timing.c.h` (the audio timestamp placement of `source_output_audio_data()`), `libobs/obs-source-color-space.c.h` (the colour space query routing of `obs_source_get_color_space()`), `libobs/obs-source-conversion-plan.c.h` (the async video GPU conversion plan), `libobs/obs-source-deinterlace-draw.c.h` (the deinterlace draw decisions), `libobs/obs-source-deinterlace-pacing.c.h` (the 2x deinterlace frame pacing), `libobs/obs-source-draw-plan.c.h` (the source draw decisions of `rotate_async_video()`, `obs_source_render_async_video()` and `source_render()`), `libobs/obs-source-media-admission.c.h` (the media action admission decisions of the `obs_source_media_*()` functions and `process_media_actions()`), `libobs/obs-source-frame-copy.c.h` (the async frame copy plan and cache decisions), `libobs/obs-source-ptm-gate.c.h` (the push-to-mute and push-to-talk gate of `source_muted()`), `libobs/obs-source-render-route.c.h` (the source and filter render routing), `libobs/obs-source-size.c.h` (the size query routing of `obs_source_get_width()` and `obs_source_get_height()`), `libobs/obs-source-transition-clock.c.h` (the transition clock and fit of `libobs/obs-source-transition.c.h`), `libobs/obs-source-transition-render.c.h` (the transition render and audio steps of `libobs/obs-source-transition.c.h`) and `libobs/obs-source-volume.c.h` (the volume snap of `get_source_volume()` and the apply decisions of `apply_audio_volume()`) | +| `obs-source/` | Ports of the units extracted from `libobs/obs-source.c`, `libobs/obs-source-deinterlace.c` and `libobs/obs-source-transition.c`: so far `libobs/obs-source-async-pacing.c.h` (the async video frame pacing of `get_closest_frame()`), `libobs/obs-source-audio-input.c.h` (the audio input steps of `process_audio()` and `reset_resampler()`), `libobs/obs-source-audio-render.c.h` (the audio render mix plan of `obs_source_audio_render()`, `custom_audio_render()` and `process_audio_source_tick()`), `libobs/obs-source-audio-timing.c.h` (the audio timestamp placement of `source_output_audio_data()`), `libobs/obs-source-color-space.c.h` (the colour space query routing of `obs_source_get_color_space()`), `libobs/obs-source-conversion-plan.c.h` (the async video GPU conversion plan), `libobs/obs-source-deinterlace-draw.c.h` (the deinterlace draw decisions), `libobs/obs-source-deinterlace-pacing.c.h` (the 2x deinterlace frame pacing), `libobs/obs-source-draw-plan.c.h` (the source draw decisions of `rotate_async_video()`, `obs_source_render_async_video()` and `source_render()`), `libobs/obs-source-frame-copy.c.h` (the async frame copy plan and cache decisions), `libobs/obs-source-media-admission.c.h` (the media action admission decisions of the `obs_source_media_*()` functions and `process_media_actions()`), `libobs/obs-source-ptm-gate.c.h` (the push-to-mute and push-to-talk gate of `source_muted()`), `libobs/obs-source-render-route.c.h` (the source and filter render routing), `libobs/obs-source-size.c.h` (the size query routing of `obs_source_get_width()` and `obs_source_get_height()`), `libobs/obs-source-transition-clock.c.h` (the transition clock and fit of `libobs/obs-source-transition.c.h`), `libobs/obs-source-transition-render.c.h` (the transition render and audio steps of `libobs/obs-source-transition.c.h`) and `libobs/obs-source-volume.c.h` (the volume snap of `get_source_volume()` and the apply decisions of `apply_audio_volume()`) | | `obs-audio-monitoring/` | Ports of `libobs/audio-monitoring/*` (so far `pulse/pulseaudio-stream-flags.c.h` and `pulse/pulseaudio-monitor-format.c.h`) | | `obs-audio-controls/` | Port of `libobs/obs-audio-controls.c.h` | | `obs-core/` | Ports of the units extracted from `libobs/obs.c.h`, `libobs/obs-module.c.h` and `libobs/obs-audio.c.h`: so far `libobs/obs-video-plan.c.h` (the video output plan), `libobs/obs-context-names.c.h` (the context names), `libobs/obs-source-load.c.h` (the source load migration and value rules), `libobs/obs-module-paths.c.h` (the module search paths), `libobs/obs-module-names.c.h` (module names and files), `libobs/obs-module-locale.c.h` (the module locale files), `libobs/obs-module-source-rules.c.h` (the source registration rules), `libobs/obs-module-type-rules.c.h` (the output, encoder and service registration rules), `libobs/obs-audio-mix.c.h` (the audio tick arithmetic); of `libobs/util/source-profiler.c.h` (per-source tick and render timing), which reads core state; of `libobs/obs-view-api.c.h` (views); and of `libobs/obs-video-copy-plan.c.h` (the output frame copy plan and scale effect choice, from `libobs/obs-video.c.h`); and of `libobs/obs-video-output-step.c.h` (the per-frame video output step decisions, from `libobs/obs-video.c.h`) |