From 8f33e5279ee3a6b77ecd35e0e7d20f320808baa8 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:39:22 -0400 Subject: [PATCH 1/6] libobs: Move the canvas texture draw and display clear decisions into obs-canvas-draw.c Behaviour-neutral extraction before the Rust port. The decisions of obs_render_canvas_texture_internal() (obs.c) and render_display_begin() (obs-display.c) move to libobs/obs-canvas-draw.c.h, as eight functions on plain values declared in the new libobs/obs-canvas-draw.h without EXPORT (hidden, as -fvisibility=hidden keeps them): - obs_canvas_draw_skip(has_mix, texture_rendered): the early return, for a canvas with no mix or a mix that has not rendered its texture. obs.c passes video && video->texture_rendered, so the field is still read only when there is a mix; - obs_canvas_draw_technique(source_space, current_space): Draw, DrawTonemap for GS_CS_709_EXTENDED into SDR, DrawMultiply into GS_CS_709_SCRGB, as enum obs_source_draw_technique (obs-source-draw-technique.h), which the source draw decisions already use; obs.c maps it to the name with obs_source_draw_technique_name(); - obs_canvas_draw_reads_white_level(current_space) and obs_canvas_draw_multiplier(sdr_white_level): whether to read obs_get_video_sdr_white_level() (GS_CS_709_SCRGB only), and the white level / 80.0f; - obs_display_clear_reads_space(always_srgb) and obs_display_clear_linear(current_space): the clear colour is sRGB when the host always clears in sRGB, else linear only into GS_CS_SRGB; - obs_display_clear_flags(use_clear_workaround): depth and stencil, and colour without the workaround; - obs_display_clear_draws_solid(use_clear_workaround): whether the solid effect draws the clear colour. obs.c.h and obs-display.c.h keep every gs_* call in its order and under its conditions, the effect and param lookups, the blend state, the swapchain, the resize, the viewport, the solid effect, and the two queries: obs_get_video_sdr_white_level() is still called only into GS_CS_709_SCRGB, and gs_get_color_space() for the clear colour only when obs_host_display_clear_color_always_srgb(), asked first, says no. That is why each is split into a "reads" question and the answer from the value. Checked in a scratch harness (not committed) that compiles origin/master's obs_render_canvas_texture_internal() and render_display_begin() verbatim, and the moved ones with obs-canvas-draw.c.h, as two translation units over shared stubs. The stubs log every gs_* call, the white level, the host query, the colour space queries and vec4_from_rgba() and _srgb() with their arguments (floats as bits, pointers by identity), and the mix and display fields after each run. The two logs are byte-identical under GCC and clang at -O0 and -O2 over 2,050,400 runs each (about 14.5 million logged calls), and under GCC with ASan and UBSan over 450,400. The inputs cover, for the canvas, no mix and both texture_rendered values, every pair of the four colour spaces and five values outside the enum (INT_MIN and INT_MAX included), white levels of 80, 300, 0, -0, NaN, the infinities, a denormal and FLT_MAX, and random bit patterns; for the display, equal and changed sizes, both update_color_space values, present ready or not, both host answers, every space, five background colours and both workaround values, plus a million random runs of each. 17 of 18 planted changes fail it; the one that survives is equivalent (the skip ignoring has_mix, since obs.c passes texture_rendered false without a mix). GS_CLEAR_COLOR, GS_CLEAR_DEPTH and GS_CLEAR_STENCIL are copied into the header as OBS_DISPLAY_CLEAR_*, so it needs only stdbool.h, stdint.h and obs-source-draw-technique.h; obs-display.c.h checks them with _Static_assert. The new file joins libobs.core with libobs.pch.h, which includes the new header; source-sets.json lists it. The exported symbol set is unchanged (1766); the eight functions are local. git log -L on both functions shows upstream history (jpark37's colour space and display clear work, PatTheMav's switch and Apple Silicon clear colour fixes) plus the fork's host interfaces (#1051), which turned the Apple ifdef into obs_host_display_clear_color_always_srgb(). That call stays where it is. Refs #2240. --- libobs/build/libobs.core+.h.c | 1 + libobs/build/libobs.pch.h | 3 ++ libobs/build/source-sets.json | 1 + libobs/obs-canvas-draw.c.h | 85 +++++++++++++++++++++++++++++++ libobs/obs-canvas-draw.h | 95 +++++++++++++++++++++++++++++++++++ libobs/obs-display.c.h | 15 +++--- libobs/obs.c.h | 19 ++----- 7 files changed, 198 insertions(+), 21 deletions(-) create mode 100644 libobs/obs-canvas-draw.c.h create mode 100644 libobs/obs-canvas-draw.h diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index b4247f4e34..faace0f594 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -2,6 +2,7 @@ #include "libobs/build/libobs.pch.h" +#include "libobs/obs-canvas-draw.c.h" #include "libobs/obs-hotkey.c.h" #include "libobs/obs-module.c.h" #include "libobs/obs.c.h" diff --git a/libobs/build/libobs.pch.h b/libobs/build/libobs.pch.h index 925837df88..0ba152ce51 100644 --- a/libobs/build/libobs.pch.h +++ b/libobs/build/libobs.pch.h @@ -4,6 +4,9 @@ #pragma once +/* obs-canvas-draw.c */ +#include "obs-canvas-draw.h" + /* obs-hotkey.c */ #include diff --git a/libobs/build/source-sets.json b/libobs/build/source-sets.json index 4dc5fbf3e3..2e0e17622a 100644 --- a/libobs/build/source-sets.json +++ b/libobs/build/source-sets.json @@ -4,6 +4,7 @@ "obs-audio-mix.h", "obs-av1.h", "obs-avc.h", + "obs-canvas-draw.h", "obs-config.h", "obs-core-modules-loader.h", "obs-data.h", diff --git a/libobs/obs-canvas-draw.c.h b/libobs/obs-canvas-draw.c.h new file mode 100644 index 0000000000..cbb503e3da --- /dev/null +++ b/libobs/obs-canvas-draw.c.h @@ -0,0 +1,85 @@ +/****************************************************************************** + 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" + +/* obs_render_canvas_texture_internal()'s early return. */ +bool obs_canvas_draw_skip(bool has_mix, bool texture_rendered) +{ + return !has_mix || !texture_rendered; +} + +/* obs_render_canvas_texture_internal()'s technique switch. */ +enum obs_source_draw_technique obs_canvas_draw_technique(int source_space, int current_space) +{ + enum obs_source_draw_technique technique = OBS_SOURCE_DRAW_TECH_DRAW; + + switch (current_space) { + case GS_CS_SRGB: + case GS_CS_SRGB_16F: + if (source_space == GS_CS_709_EXTENDED) + technique = OBS_SOURCE_DRAW_TECH_DRAW_TONEMAP; + break; + case GS_CS_709_SCRGB: + technique = OBS_SOURCE_DRAW_TECH_DRAW_MULTIPLY; + break; + case GS_CS_709_EXTENDED: + break; + } + + return technique; +} + +/* The multiplier switch: only GS_CS_709_SCRGB reads the white level. */ +bool obs_canvas_draw_reads_white_level(int current_space) +{ + switch (current_space) { + case GS_CS_709_SCRGB: + return true; + } + + return false; +} + +float obs_canvas_draw_multiplier(float sdr_white_level) +{ + return sdr_white_level / 80.f; +} + +/* render_display_begin()'s clear colour: the host first, then the space. */ +bool obs_display_clear_reads_space(bool always_srgb) +{ + return !always_srgb; +} + +bool obs_display_clear_linear(int current_space) +{ + return current_space == GS_CS_SRGB; +} + +uint32_t obs_display_clear_flags(bool use_clear_workaround) +{ + uint32_t clear_flags = OBS_DISPLAY_CLEAR_DEPTH | OBS_DISPLAY_CLEAR_STENCIL; + if (!use_clear_workaround) + clear_flags |= OBS_DISPLAY_CLEAR_COLOR; + return clear_flags; +} + +bool obs_display_clear_draws_solid(bool use_clear_workaround) +{ + return use_clear_workaround; +} diff --git a/libobs/obs-canvas-draw.h b/libobs/obs-canvas-draw.h new file mode 100644 index 0000000000..ca1781d867 --- /dev/null +++ b/libobs/obs-canvas-draw.h @@ -0,0 +1,95 @@ +/****************************************************************************** + 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 "obs-source-draw-technique.h" + +/* The canvas texture draw and display clear decisions, on plain values + * (obs-canvas-draw.c): + * - obs_render_canvas_texture_internal() (obs.c): whether a canvas draws at + * all, and the technique and multiplier for each pair of source and + * current colour spaces; + * - render_display_begin() (obs-display.c): how the background colour + * converts to the clear colour, the clear flags, and whether the solid + * colour workaround draws. + * + * obs.c and obs-display.c keep every gs_* call in its order and under the + * same conditions, the effect and param lookups, the blend state, + * obs_get_video_sdr_white_level(), obs_host_display_clear_color_always_srgb(), + * the swapchain, the resize and the viewport: they pass their results in and + * act on what comes back. obs_get_video_sdr_white_level() is called only when + * obs_canvas_draw_reads_white_level() says so, and gs_get_color_space() for + * the clear colour only when obs_display_clear_reads_space() says so, as + * before. None of these functions takes a lock, calls into libobs or keeps + * state. + * + * Colour spaces are enum gs_color_space values, passed as int. A value + * outside the enum takes the paths it took before. The techniques are enum + * obs_source_draw_technique (obs-source-draw-technique.h), which the source + * draw decisions share; these return Draw, DrawMultiply and DrawTonemap only. + * + * Hidden in libobs: not EXPORT. */ + +/* GS_CLEAR_COLOR, GS_CLEAR_DEPTH and GS_CLEAR_STENCIL (graphics/graphics.h), + * copied so this header needs no graphics headers; obs-display.c checks them. */ +#define OBS_DISPLAY_CLEAR_COLOR (1 << 0) +#define OBS_DISPLAY_CLEAR_DEPTH (1 << 1) +#define OBS_DISPLAY_CLEAR_STENCIL (1 << 2) + +/* Whether obs_render_canvas_texture_internal() returns before drawing: the + * canvas has no mix (has_mix false), or its mix has not rendered its texture. + * obs.c reads texture_rendered only when there is a mix, and passes false + * otherwise. */ +bool obs_canvas_draw_skip(bool has_mix, bool texture_rendered); + +/* The technique the canvas texture draws with: + * - DrawTonemap for a GS_CS_709_EXTENDED source into SDR (GS_CS_SRGB, + * GS_CS_SRGB_16F); + * - DrawMultiply into GS_CS_709_SCRGB, from any source; + * - Draw for any other pair, a space outside the enum included. */ +enum obs_source_draw_technique obs_canvas_draw_technique(int source_space, int current_space); + +/* Whether obs_render_canvas_texture_internal() reads + * obs_get_video_sdr_white_level(): into GS_CS_709_SCRGB only. */ +bool obs_canvas_draw_reads_white_level(int current_space); + +/* The multiplier into GS_CS_709_SCRGB: sdr_white_level / 80.0f. One float + * division, so a white level of 0 gives 0 and a NaN stays a NaN. Any other + * current space keeps 1.0f, which obs.c sets without asking. */ +float obs_canvas_draw_multiplier(float sdr_white_level); + +/* Whether render_display_begin() asks gs_get_color_space() for the clear + * colour: only when the host does not always clear in sRGB + * (obs_host_display_clear_color_always_srgb(), asked first). */ +bool obs_display_clear_reads_space(bool always_srgb); + +/* Whether the background colour converts to a linear clear colour + * (vec4_from_rgba()) rather than sRGB (vec4_from_rgba_srgb()): only into + * GS_CS_SRGB. */ +bool obs_display_clear_linear(int current_space); + +/* The flags render_display_begin() clears with: depth and stencil always, + * colour too without the clear workaround. */ +uint32_t obs_display_clear_flags(bool use_clear_workaround); + +/* Whether render_display_begin() draws the clear colour with the solid + * effect after the viewport: only with the clear workaround. */ +bool obs_display_clear_draws_solid(bool use_clear_workaround); diff --git a/libobs/obs-display.c.h b/libobs/obs-display.c.h index bb2a3d0a6d..9aa77b0c3f 100644 --- a/libobs/obs-display.c.h +++ b/libobs/obs-display.c.h @@ -160,6 +160,11 @@ void obs_display_remove_draw_callback(obs_display_t *display, void (*draw)(void pthread_mutex_unlock(&display->draw_callbacks_mutex); } +/* The clear flags obs-canvas-draw.h copies. */ +_Static_assert(OBS_DISPLAY_CLEAR_COLOR == GS_CLEAR_COLOR, "GS_CLEAR_COLOR"); +_Static_assert(OBS_DISPLAY_CLEAR_DEPTH == GS_CLEAR_DEPTH, "GS_CLEAR_DEPTH"); +_Static_assert(OBS_DISPLAY_CLEAR_STENCIL == GS_CLEAR_STENCIL, "GS_CLEAR_STENCIL"); + static inline bool render_display_begin(struct obs_display *display, uint32_t cx, uint32_t cy, bool update_color_space) { struct vec4 clear_color; @@ -187,9 +192,9 @@ static inline bool render_display_begin(struct obs_display *display, uint32_t cx * render pass that returns the clear color for every fragment, the color becomes subject to automatic sRGB * gamma encoding if the render target uses an sRGB color format. */ - if (obs_host_display_clear_color_always_srgb()) + if (!obs_display_clear_reads_space(obs_host_display_clear_color_always_srgb())) vec4_from_rgba_srgb(&clear_color, display->background_color); - else if (gs_get_color_space() == GS_CS_SRGB) + else if (obs_display_clear_linear(gs_get_color_space())) vec4_from_rgba(&clear_color, display->background_color); else vec4_from_rgba_srgb(&clear_color, display->background_color); @@ -197,9 +202,7 @@ static inline bool render_display_begin(struct obs_display *display, uint32_t cx const bool use_clear_workaround = display->use_clear_workaround; - uint32_t clear_flags = GS_CLEAR_DEPTH | GS_CLEAR_STENCIL; - if (!use_clear_workaround) - clear_flags |= GS_CLEAR_COLOR; + const uint32_t clear_flags = obs_display_clear_flags(use_clear_workaround); gs_clear(clear_flags, &clear_color, 1.0f, 0); gs_enable_depth_test(false); @@ -209,7 +212,7 @@ static inline bool render_display_begin(struct obs_display *display, uint32_t cx gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); gs_set_viewport(0, 0, cx, cy); - if (use_clear_workaround) { + if (obs_display_clear_draws_solid(use_clear_workaround)) { gs_effect_t *const solid_effect = obs->video.solid_effect; gs_effect_set_vec4(gs_effect_get_param_by_name(solid_effect, "color"), &clear_color); while (gs_effect_loop(solid_effect, "Solid")) diff --git a/libobs/obs.c.h b/libobs/obs.c.h index c67ef16df4..f996b37221 100644 --- a/libobs/obs.c.h +++ b/libobs/obs.c.h @@ -2221,26 +2221,15 @@ static void obs_render_canvas_texture_internal(obs_canvas_t *canvas, enum gs_ble gs_eparam_t *param; video = canvas->mix; - if (!video || !video->texture_rendered) + if (obs_canvas_draw_skip(video != NULL, video && video->texture_rendered)) return; const enum gs_color_space source_space = video->render_space; const enum gs_color_space current_space = gs_get_color_space(); - const char *tech_name = "Draw"; + const char *tech_name = obs_source_draw_technique_name(obs_canvas_draw_technique(source_space, current_space)); float multiplier = 1.f; - switch (current_space) { - case GS_CS_SRGB: - case GS_CS_SRGB_16F: - if (source_space == GS_CS_709_EXTENDED) - tech_name = "DrawTonemap"; - break; - case GS_CS_709_SCRGB: - tech_name = "DrawMultiply"; - multiplier = obs_get_video_sdr_white_level() / 80.f; - break; - case GS_CS_709_EXTENDED: - break; - } + if (obs_canvas_draw_reads_white_level(current_space)) + multiplier = obs_canvas_draw_multiplier(obs_get_video_sdr_white_level()); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); From 5ff9bc557daa4c861a06b3f065082c4430e7418a Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:44:22 -0400 Subject: [PATCH 2/6] test: Characterize the canvas texture draw and display clear decisions test_canvas_draw_steps compiles libobs/obs-canvas-draw.c.h into itself and calls the eight functions through their header (they are hidden in libobs). 12 cases pin the current C: - the constants: the three technique values, the copied clear flags against GS_CLEAR_*, and the technique names; - obs_render_canvas_texture_internal(): both early returns (no mix, texture not rendered), and no mix with a rendered flag, which obs.c never passes (characterized, not endorsed); the technique for every pair of the four colour spaces, and spaces outside the enum (-1, 4, 99, INT_MIN, INT_MAX) on either side; the white level read into scRGB only; the multiplier at SDR white levels of 80, 300 and 0, and for any float (-0, negative, the infinities, NaN, a denormal, FLT_MAX, and every multiple of 80 up to 80 * 2^16); and the name and multiplier obs.c ends up with for every pair and level; - render_display_begin(): whether the space is read for both host answers, the linear clear colour into GS_CS_SRGB only, the conversion for every combination of host answer and space, and the clear flags and solid colour workaround for both workaround values. It is in the test graph in name order, built with ASan and UBSan, with libm except on MSVC like the other step tests, so it runs on every platform without a display. tests.d/test_canvas_draw_steps.cmake says what it covers. Passes 12/12 on the C backend. No test drives the two callers through a real graphics device; the canvas tests (test_canvas_flags, test_scene_private_canvas, test_canvas_destroy_scene_refs, test_shutdown_canvas_weak_ref) cover the canvases and their mixes through the real libobs. Refs #2240. --- test/cmocka/build/test-graph.json | 29 ++ test/cmocka/test_canvas_draw_steps.c | 328 ++++++++++++++++++ .../tests.d/test_canvas_draw_steps.cmake | 14 + 3 files changed, 371 insertions(+) create mode 100644 test/cmocka/test_canvas_draw_steps.c create mode 100644 test/cmocka/tests.d/test_canvas_draw_steps.cmake diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index a85fa3cf93..ec481790b6 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -446,6 +446,29 @@ ], "requires": "OS_LINUX" }, + "test_canvas_draw_steps": { + "sources": [ + "test/cmocka/test_canvas_draw_steps.c", + "libobs/obs-canvas-draw.c.h" + ], + "includes": [ + "libobs", + "deps/libcaption" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + { + "name": "m", + "requires": { + "not": "MSVC" + } + }, + "OBS::native-test-cmocka" + ], + "sanitizers": "address,undefined" + }, "test_canvas_flags": { "sources": [ "test/cmocka/test_canvas_flags.c" @@ -3854,6 +3877,12 @@ ] ] }, + "test_canvas_draw_steps": { + "target": "test_canvas_draw_steps", + "command": [ + "${target}" + ] + }, "test_canvas_flags": { "target": "test_canvas_flags", "command": [ diff --git a/test/cmocka/test_canvas_draw_steps.c b/test/cmocka/test_canvas_draw_steps.c new file mode 100644 index 0000000000..7836b432c4 --- /dev/null +++ b/test/cmocka/test_canvas_draw_steps.c @@ -0,0 +1,328 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "obs.h" +#include "obs-canvas-draw.h" + +/* + * Characterization of the canvas texture draw and display clear decisions, + * moved to libobs/obs-canvas-draw.c before their Rust port: + * - obs_render_canvas_texture_internal() (obs.c): obs_canvas_draw_skip(), + * the early return; obs_canvas_draw_technique(), the technique for each + * pair of source and current colour spaces; + * obs_canvas_draw_reads_white_level() and obs_canvas_draw_multiplier(), + * when the SDR white level is read and the multiplier it gives; + * - render_display_begin() (obs-display.c): + * obs_display_clear_reads_space() and obs_display_clear_linear(), how the + * background colour converts to the clear colour (87698b1e0 for the + * always-sRGB hosts); obs_display_clear_flags() and + * obs_display_clear_draws_solid(), the clear and the solid colour + * workaround (f88300a61, 37389ff24). + * 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. No test drives the two callers through + * a real graphics device; test_canvas_flags, test_scene_private_canvas, + * test_canvas_destroy_scene_refs and test_shutdown_canvas_weak_ref cover the + * canvases and their mixes through the real libobs. + */ + +/* colour spaces outside enum gs_color_space */ +static const int OUTSIDE_SPACES[] = {-1, 4, 99, INT_MIN, INT_MAX}; +#define OUTSIDE_SPACE_COUNT (sizeof(OUTSIDE_SPACES) / sizeof(OUTSIDE_SPACES[0])) + +static const int SPACES[] = {GS_CS_SRGB, GS_CS_SRGB_16F, GS_CS_709_EXTENDED, GS_CS_709_SCRGB}; +#define SPACE_COUNT (sizeof(SPACES) / sizeof(SPACES[0])) + +/* SDR white levels: OBS's default, a common one, and 0 */ +static const float WHITES[] = {80.0f, 300.0f, 0.0f}; +#define WHITE_COUNT (sizeof(WHITES) / sizeof(WHITES[0])) + +static uint32_t float_bits(float f) +{ + uint32_t u; + memcpy(&u, &f, sizeof(u)); + return u; +} + +static float bits_float(uint32_t u) +{ + float f; + memcpy(&f, &u, sizeof(f)); + return f; +} + +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_bits(float actual, uint32_t expected, const char *what, int line) +{ + if (float_bits(actual) != expected) { + fprintf(stderr, "line %d: %s is %a (0x%08" PRIx32 "), expected %a (0x%08" PRIx32 ")\n", line, what, + (double)actual, float_bits(actual), (double)bits_float(expected), expected); + 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_BITS(actual, expected) check_bits((actual), (expected), #actual, __LINE__) + +#define D OBS_SOURCE_DRAW_TECH_DRAW +#define M OBS_SOURCE_DRAW_TECH_DRAW_MULTIPLY +#define T OBS_SOURCE_DRAW_TECH_DRAW_TONEMAP + +/* --- constants --------------------------------------------------------- */ + +/* The Rust port returns these numbers and flags. */ +static void constants(void **state) +{ + (void)state; + CHECK_INT(OBS_SOURCE_DRAW_TECH_DRAW, 0); + CHECK_INT(OBS_SOURCE_DRAW_TECH_DRAW_MULTIPLY, 1); + CHECK_INT(OBS_SOURCE_DRAW_TECH_DRAW_TONEMAP, 2); + CHECK_INT(sizeof(enum obs_source_draw_technique), sizeof(int)); + CHECK_INT(sizeof(enum gs_color_space), sizeof(int)); + CHECK_INT(OBS_DISPLAY_CLEAR_COLOR, GS_CLEAR_COLOR); + CHECK_INT(OBS_DISPLAY_CLEAR_DEPTH, GS_CLEAR_DEPTH); + CHECK_INT(OBS_DISPLAY_CLEAR_STENCIL, GS_CLEAR_STENCIL); + CHECK_INT(OBS_DISPLAY_CLEAR_COLOR, 1); + CHECK_INT(OBS_DISPLAY_CLEAR_DEPTH, 2); + CHECK_INT(OBS_DISPLAY_CLEAR_STENCIL, 4); + assert_string_equal(obs_source_draw_technique_name(D), "Draw"); + assert_string_equal(obs_source_draw_technique_name(M), "DrawMultiply"); + assert_string_equal(obs_source_draw_technique_name(T), "DrawTonemap"); +} + +/* --- canvas: the early return ------------------------------------------ */ + +/* A canvas draws only when it has a mix that rendered its texture: both + * early returns (no mix, texture not rendered) skip. obs.c passes + * texture_rendered false without a mix. Characterized, not endorsed: no mix + * with texture_rendered true, which obs.c never passes, also skips. */ +static void skip_every_input(void **state) +{ + (void)state; + CHECK_BOOL(obs_canvas_draw_skip(false, false), true); + CHECK_BOOL(obs_canvas_draw_skip(false, true), true); + CHECK_BOOL(obs_canvas_draw_skip(true, false), true); + CHECK_BOOL(obs_canvas_draw_skip(true, true), false); +} + +/* --- canvas: technique ------------------------------------------------- */ + +/* [source][current]: a 709_EXTENDED canvas is tonemapped into SDR; anything + * into scRGB is multiplied; everything else draws as is (an SDR canvas into + * 709_EXTENDED, scRGB into SDR included: characterized, not endorsed, the + * mix renders only SDR and 709_EXTENDED). */ +static const enum obs_source_draw_technique TECHNIQUE[4][4] = { + {D, D, D, M}, + {D, D, D, M}, + {T, T, D, M}, + {D, D, D, M}, +}; + +static void technique_space_pairs(void **state) +{ + (void)state; + for (size_t s = 0; s < SPACE_COUNT; s++) { + for (size_t c = 0; c < SPACE_COUNT; c++) { + CHECK_INT(obs_canvas_draw_technique(SPACES[s], SPACES[c]), TECHNIQUE[s][c]); + } + } +} + +/* A current space outside the enum draws as is, from any source. A source + * outside the enum takes the current space's row: Draw into SDR and + * 709_EXTENDED, DrawMultiply into scRGB. */ +static void technique_outside_enum(void **state) +{ + (void)state; + for (size_t o = 0; o < OUTSIDE_SPACE_COUNT; o++) { + for (size_t s = 0; s < SPACE_COUNT; s++) + CHECK_INT(obs_canvas_draw_technique(SPACES[s], OUTSIDE_SPACES[o]), D); + for (size_t p = 0; p < OUTSIDE_SPACE_COUNT; p++) + CHECK_INT(obs_canvas_draw_technique(OUTSIDE_SPACES[p], OUTSIDE_SPACES[o]), D); + CHECK_INT(obs_canvas_draw_technique(OUTSIDE_SPACES[o], GS_CS_SRGB), D); + CHECK_INT(obs_canvas_draw_technique(OUTSIDE_SPACES[o], GS_CS_SRGB_16F), D); + CHECK_INT(obs_canvas_draw_technique(OUTSIDE_SPACES[o], GS_CS_709_EXTENDED), D); + CHECK_INT(obs_canvas_draw_technique(OUTSIDE_SPACES[o], GS_CS_709_SCRGB), M); + } +} + +/* --- canvas: white level and multiplier -------------------------------- */ + +/* Only a draw into scRGB reads the white level; a space outside the enum + * does not. */ +static void reads_white_level_spaces(void **state) +{ + (void)state; + CHECK_BOOL(obs_canvas_draw_reads_white_level(GS_CS_SRGB), false); + CHECK_BOOL(obs_canvas_draw_reads_white_level(GS_CS_SRGB_16F), false); + CHECK_BOOL(obs_canvas_draw_reads_white_level(GS_CS_709_EXTENDED), false); + CHECK_BOOL(obs_canvas_draw_reads_white_level(GS_CS_709_SCRGB), true); + for (size_t o = 0; o < OUTSIDE_SPACE_COUNT; o++) + CHECK_BOOL(obs_canvas_draw_reads_white_level(OUTSIDE_SPACES[o]), false); +} + +/* The multiplier is the white level over scRGB's 80 nits: 1 at OBS's + * default, 3.75 at 300, 0 at 0. */ +static void multiplier_white_levels(void **state) +{ + (void)state; + CHECK_BITS(obs_canvas_draw_multiplier(80.0f), 0x3f800000); /* 1 */ + CHECK_BITS(obs_canvas_draw_multiplier(300.0f), 0x40700000); /* 3.75 */ + CHECK_BITS(obs_canvas_draw_multiplier(0.0f), 0x00000000); + CHECK_BITS(obs_canvas_draw_multiplier(203.0f), float_bits(203.0f / 80.0f)); + CHECK_BITS(obs_canvas_draw_multiplier(10000.0f), 0x42fa0000); /* 125 */ +} + +/* One float division, whatever the level (obs_set_video_levels() takes any + * float). Characterized, not endorsed: -0 stays -0, a negative level gives a + * negative multiplier, the infinities stay infinite, a NaN stays a NaN, and + * a denormal underflows to 0. */ +static void multiplier_any_level(void **state) +{ + (void)state; + CHECK_BITS(obs_canvas_draw_multiplier(-0.0f), 0x80000000); + CHECK_BITS(obs_canvas_draw_multiplier(-80.0f), 0xbf800000); + CHECK_BITS(obs_canvas_draw_multiplier(INFINITY), 0x7f800000); + CHECK_BITS(obs_canvas_draw_multiplier(-INFINITY), 0xff800000); + CHECK_BITS(obs_canvas_draw_multiplier(1e-45f), 0x00000000); + CHECK_BITS(obs_canvas_draw_multiplier(FLT_MAX), float_bits(FLT_MAX / 80.0f)); + CHECK_BOOL(isnan(obs_canvas_draw_multiplier(NAN)), true); + /* every multiple of 80 up to 80 * 2^16 divides exactly */ + for (uint32_t k = 0; k <= 65536; k++) + CHECK_BITS(obs_canvas_draw_multiplier(80.0f * (float)k), float_bits((float)k)); +} + +/* The whole of obs_render_canvas_texture_internal()'s decision, as obs.c + * asks it: the technique name it loops over, and the multiplier it sets + * (1 unless the white level is read). */ +static void canvas_plan_every_input(void **state) +{ + (void)state; + static const char *const NAMES[4][4] = { + {"Draw", "Draw", "Draw", "DrawMultiply"}, + {"Draw", "Draw", "Draw", "DrawMultiply"}, + {"DrawTonemap", "DrawTonemap", "Draw", "DrawMultiply"}, + {"Draw", "Draw", "Draw", "DrawMultiply"}, + }; + static const uint32_t MULTIPLIERS[WHITE_COUNT] = {0x3f800000, 0x40700000, 0x00000000}; + + for (size_t s = 0; s < SPACE_COUNT; s++) { + for (size_t c = 0; c < SPACE_COUNT; c++) { + for (size_t w = 0; w < WHITE_COUNT; w++) { + const char *name = + obs_source_draw_technique_name(obs_canvas_draw_technique(SPACES[s], SPACES[c])); + float multiplier = 1.f; + if (obs_canvas_draw_reads_white_level(SPACES[c])) + multiplier = obs_canvas_draw_multiplier(WHITES[w]); + + assert_string_equal(name, NAMES[s][c]); + CHECK_BITS(multiplier, SPACES[c] == GS_CS_709_SCRGB ? MULTIPLIERS[w] : 0x3f800000); + } + } + } +} + +/* --- display: clear colour --------------------------------------------- */ + +/* The space is read only when the host does not always clear in sRGB. */ +static void clear_reads_space_every_input(void **state) +{ + (void)state; + CHECK_BOOL(obs_display_clear_reads_space(false), true); + CHECK_BOOL(obs_display_clear_reads_space(true), false); +} + +/* The background colour stays linear only into GS_CS_SRGB; GS_CS_SRGB_16F, + * HDR and a space outside the enum convert it to sRGB. */ +static void clear_linear_spaces(void **state) +{ + (void)state; + CHECK_BOOL(obs_display_clear_linear(GS_CS_SRGB), true); + CHECK_BOOL(obs_display_clear_linear(GS_CS_SRGB_16F), false); + CHECK_BOOL(obs_display_clear_linear(GS_CS_709_EXTENDED), false); + CHECK_BOOL(obs_display_clear_linear(GS_CS_709_SCRGB), false); + for (size_t o = 0; o < OUTSIDE_SPACE_COUNT; o++) + CHECK_BOOL(obs_display_clear_linear(OUTSIDE_SPACES[o]), false); +} + +/* As render_display_begin() asks it: a host that always clears in sRGB + * converts to sRGB in every space (Metal and OpenGL on Apple Silicon, + * 87698b1e0); otherwise linear into GS_CS_SRGB only. */ +static void clear_colour_every_input(void **state) +{ + (void)state; + for (int always = 0; always < 2; always++) { + for (size_t c = 0; c < SPACE_COUNT + OUTSIDE_SPACE_COUNT; c++) { + const int space = c < SPACE_COUNT ? SPACES[c] : OUTSIDE_SPACES[c - SPACE_COUNT]; + const bool linear = obs_display_clear_reads_space(always) && obs_display_clear_linear(space); + CHECK_BOOL(linear, !always && space == GS_CS_SRGB); + } + } +} + +/* --- display: clear flags and the workaround ---------------------------- */ + +/* Depth and stencil are always cleared; colour only without the clear + * workaround, which draws the colour with the solid effect instead. */ +static void clear_every_input(void **state) +{ + (void)state; + CHECK_INT(obs_display_clear_flags(false), GS_CLEAR_COLOR | GS_CLEAR_DEPTH | GS_CLEAR_STENCIL); + CHECK_INT(obs_display_clear_flags(true), GS_CLEAR_DEPTH | GS_CLEAR_STENCIL); + CHECK_BOOL(obs_display_clear_draws_solid(false), false); + CHECK_BOOL(obs_display_clear_draws_solid(true), true); + for (int workaround = 0; workaround < 2; workaround++) { + const uint32_t flags = obs_display_clear_flags(workaround); + /* the colour is either cleared or drawn, never both or neither */ + CHECK_BOOL(((flags & GS_CLEAR_COLOR) != 0) != obs_display_clear_draws_solid(workaround), true); + } +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(constants), + cmocka_unit_test(skip_every_input), + cmocka_unit_test(technique_space_pairs), + cmocka_unit_test(technique_outside_enum), + cmocka_unit_test(reads_white_level_spaces), + cmocka_unit_test(multiplier_white_levels), + cmocka_unit_test(multiplier_any_level), + cmocka_unit_test(canvas_plan_every_input), + cmocka_unit_test(clear_reads_space_every_input), + cmocka_unit_test(clear_linear_spaces), + cmocka_unit_test(clear_colour_every_input), + cmocka_unit_test(clear_every_input), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/tests.d/test_canvas_draw_steps.cmake b/test/cmocka/tests.d/test_canvas_draw_steps.cmake new file mode 100644 index 0000000000..e1900e8be5 --- /dev/null +++ b/test/cmocka/tests.d/test_canvas_draw_steps.cmake @@ -0,0 +1,14 @@ +# Characterization of the canvas texture draw and display clear decisions of +# libobs/obs.c (obs_render_canvas_texture_internal()) and libobs/obs-display.c +# (render_display_begin()), moved to libobs/obs-canvas-draw.c before their port +# to rust/obs-core (canvas_draw): the early return with and without a mix and a +# rendered texture, the technique for every pair of colour spaces and spaces +# outside the enum, the white level read and the multiplier at SDR white levels +# of 80, 300 and 0 and any float, the clear colour conversion for both host +# answers and every space, and the clear flags and solid colour workaround. +# Builds the moved file on its own: no display and no libobs core, so it runs on +# every platform. The functions are hidden in libobs, so this characterizes that +# C source; the test calls only them and obs_source_draw_technique_name(). +# test_canvas_flags, test_scene_private_canvas, test_canvas_destroy_scene_refs +# and test_shutdown_canvas_weak_ref cover the canvases through the real libobs. +# Target and test are declared in ../build/test-graph.json. From c621c3fe0e5c80418a3e545efff96d61abc00976 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:47:48 -0400 Subject: [PATCH 3/6] obs-core: Add Tier 1 tests for the canvas draw port The safe API of obs_core::canvas_draw, with todo!() bodies: the colour space constants (GS_CS_*), the clear flags (CLEAR_COLOR, CLEAR_DEPTH, CLEAR_STENCIL), SCRGB_WHITE, Technique (Draw, DrawMultiply, DrawTonemap, with the C's values and names), and skip(), technique(), reads_white_level(), multiplier(), clear_reads_space(), clear_linear(), clear_flags() and clear_draws_solid(). Colour spaces are c_int, as the C passes enum gs_color_space. Technique mirrors only the three values of enum obs_source_draw_technique that these decisions return: obs-core cannot depend on obs-source, whose draw_technique module (#2206) has all six, with the same numbers and names. tests/obs_core/canvas_draw.rs ports test_canvas_draw_steps.c 1:1: its 12 cases as steps_*, under the same names, in the same order, with the same values, the "characterized, not endorsed" ones included. Three new edge_* proptests (4096 cases each) check the technique, the white level read and the linear clear colour over any int space against the C's switch written out, the multiplier over every f32 white level taken as a bit pattern (#1951) against one division by 80, and the skip, clear flags and workaround over every flag. soldr cargo test -p obs-data --test obs-tests-core -- canvas_draw fails 14 of 15 with "not yet implemented"; steps_constants, which reads only the constants and the enum, passes. Refs #2240. --- rust/obs-core/src/canvas_draw.rs | 159 +++++++++++ rust/obs-core/src/lib.rs | 1 + rust/obs-core/tests/obs_core/canvas_draw.rs | 296 ++++++++++++++++++++ rust/obs-core/tests/obs_core/main.rs | 1 + 4 files changed, 457 insertions(+) create mode 100644 rust/obs-core/src/canvas_draw.rs create mode 100644 rust/obs-core/tests/obs_core/canvas_draw.rs diff --git a/rust/obs-core/src/canvas_draw.rs b/rust/obs-core/src/canvas_draw.rs new file mode 100644 index 0000000000..1280a0858c --- /dev/null +++ b/rust/obs-core/src/canvas_draw.rs @@ -0,0 +1,159 @@ +//! Safe core of `libobs/obs-canvas-draw.c.h`: the canvas texture draw +//! decisions of `obs_render_canvas_texture_internal()` (`obs.c`) and the +//! display clear decisions of `render_display_begin()` (`obs-display.c`). +//! +//! `obs.c` and `obs-display.c` keep every `gs_*` call in its order and under +//! its conditions, the effect and param lookups, the blend state, the +//! swapchain, the resize, the viewport and the solid effect, and they make +//! the two queries: `obs_get_video_sdr_white_level()` and +//! `obs_host_display_clear_color_always_srgb()`. They pass the values here +//! and do what the answer says. These keep no state, take no lock and touch +//! no texture. +//! +//! - [`skip`]: whether a canvas draws at all (it needs a mix that rendered +//! its texture). +//! - [`technique`], [`reads_white_level`] and [`multiplier`]: the technique +//! of `default.effect` the canvas texture draws with, whether the SDR white +//! level is read, and the multiplier it gives. +//! - [`clear_reads_space`] and [`clear_linear`]: whether the background +//! colour converts to a linear or an sRGB clear colour. +//! - [`clear_flags`] and [`clear_draws_solid`]: what `gs_clear()` clears, and +//! whether the solid colour workaround draws the colour instead. +//! +//! The C asks the white level only into scRGB, and the colour space for the +//! clear colour only when the host does not always clear in sRGB, so each is +//! a "reads" question and an answer from the value, called where the C +//! decided. +//! +//! [`Technique`] mirrors the three values of `enum +//! obs_source_draw_technique` (`libobs/obs-source-draw-technique.h`) these +//! decisions return, with the C's numbers and names: the same values as +//! `obs_source::draw_technique::Technique` (#2206), which obs-core cannot +//! depend on. The colour spaces are `enum gs_color_space`, taken as the C's +//! `int`; a value outside the enum takes the path it took in the C. +//! +//! No intentional differences from the C. + +use core::ffi::c_int; + +/// `GS_CS_SRGB` (`enum gs_color_space`, `graphics/graphics.h`): SDR. +pub const GS_CS_SRGB: c_int = 0; +/// `GS_CS_SRGB_16F`: high-precision SDR. +pub const GS_CS_SRGB_16F: c_int = 1; +/// `GS_CS_709_EXTENDED`: the canvas, Mac EDR (HDR). +pub const GS_CS_709_EXTENDED: c_int = 2; +/// `GS_CS_709_SCRGB`: 1.0 = 80 nits, Windows and Linux HDR. +pub const GS_CS_709_SCRGB: c_int = 3; + +/// `GS_CLEAR_COLOR` (`OBS_DISPLAY_CLEAR_COLOR`). +pub const CLEAR_COLOR: u32 = 1 << 0; +/// `GS_CLEAR_DEPTH` (`OBS_DISPLAY_CLEAR_DEPTH`). +pub const CLEAR_DEPTH: u32 = 1 << 1; +/// `GS_CLEAR_STENCIL` (`OBS_DISPLAY_CLEAR_STENCIL`). +pub const CLEAR_STENCIL: u32 = 1 << 2; + +/// The nits of 1.0 in scRGB: the multiplier is the white level over it. +pub const SCRGB_WHITE: f32 = 80.0; + +/// The technique of `default.effect` the canvas texture draws with: the +/// values of `enum obs_source_draw_technique` that +/// `obs_canvas_draw_technique()` returns, with the C's discriminants. C maps +/// them to the name (`obs_source_draw_technique_name()`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Technique { + /// `"Draw"`. + Draw = 0, + /// `"DrawMultiply"`: into scRGB. + DrawMultiply = 1, + /// `"DrawTonemap"`: a 709 extended canvas into SDR. + DrawTonemap = 2, +} + +impl Technique { + /// The C's enum value. + #[must_use] + pub const fn value(self) -> u32 { + match self { + Technique::Draw => 0, + Technique::DrawMultiply => 1, + Technique::DrawTonemap => 2, + } + } + + /// The technique's name in `default.effect`, as + /// `obs_source_draw_technique_name()` maps it. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Technique::Draw => "Draw", + Technique::DrawMultiply => "DrawMultiply", + Technique::DrawTonemap => "DrawTonemap", + } + } +} + +/// `obs_canvas_draw_skip()`: whether `obs_render_canvas_texture_internal()` +/// returns before drawing, for a canvas with no mix or a mix whose texture +/// is not rendered. +#[must_use] +pub fn skip(has_mix: bool, texture_rendered: bool) -> bool { + let _ = (has_mix, texture_rendered); + todo!() +} + +/// `obs_canvas_draw_technique()`: `DrawTonemap` for a +/// [`GS_CS_709_EXTENDED`] canvas into SDR, `DrawMultiply` into +/// [`GS_CS_709_SCRGB`], `Draw` otherwise. +#[must_use] +pub fn technique(source_space: c_int, current_space: c_int) -> Technique { + let _ = (source_space, current_space); + todo!() +} + +/// `obs_canvas_draw_reads_white_level()`: whether the white level is read, +/// into [`GS_CS_709_SCRGB`] only. +#[must_use] +pub fn reads_white_level(current_space: c_int) -> bool { + let _ = current_space; + todo!() +} + +/// `obs_canvas_draw_multiplier()`: the white level over [`SCRGB_WHITE`], one +/// `f32` division. +#[must_use] +pub fn multiplier(sdr_white_level: f32) -> f32 { + let _ = sdr_white_level; + todo!() +} + +/// `obs_display_clear_reads_space()`: whether the colour space is read for +/// the clear colour, only when the host does not always clear in sRGB. +#[must_use] +pub fn clear_reads_space(always_srgb: bool) -> bool { + let _ = always_srgb; + todo!() +} + +/// `obs_display_clear_linear()`: whether the clear colour stays linear +/// (`vec4_from_rgba()`), into [`GS_CS_SRGB`] only. +#[must_use] +pub fn clear_linear(current_space: c_int) -> bool { + let _ = current_space; + todo!() +} + +/// `obs_display_clear_flags()`: depth and stencil, and colour without the +/// clear workaround. +#[must_use] +pub fn clear_flags(use_clear_workaround: bool) -> u32 { + let _ = use_clear_workaround; + todo!() +} + +/// `obs_display_clear_draws_solid()`: whether the solid effect draws the +/// clear colour, with the clear workaround only. +#[must_use] +pub fn clear_draws_solid(use_clear_workaround: bool) -> bool { + let _ = use_clear_workaround; + todo!() +} diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index c4fe99a88f..b2a4a7422d 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -26,6 +26,7 @@ #![deny(unsafe_code)] pub mod audio_mix; +pub mod canvas_draw; pub mod context_names; pub mod module_locale; pub mod module_names; diff --git a/rust/obs-core/tests/obs_core/canvas_draw.rs b/rust/obs-core/tests/obs_core/canvas_draw.rs new file mode 100644 index 0000000000..4f12ef8c2d --- /dev/null +++ b/rust/obs-core/tests/obs_core/canvas_draw.rs @@ -0,0 +1,296 @@ +//! Tier 1: `obs_core::canvas_draw`, the canvas texture draw and display +//! clear decisions. +//! +//! The `steps_*` cases port `test/cmocka/test_canvas_draw_steps.c` 1:1: its +//! 12 cases under the same names, in the same order, with the same values +//! and expectations, the "characterized, not endorsed" ones included. The C +//! calls the hidden `obs_canvas_draw_*` and `obs_display_clear_*` +//! functions; here the safe core is called directly, and the C's technique +//! names are [`Technique::name`]. +//! +//! The `edge_*` cases are new: proptests over every colour space `int` and +//! every `f32` white level (taken as bit patterns, so NaNs, infinities and +//! denormals come up) against models written from the C's switch and +//! expressions. + +use core::ffi::c_int; + +use obs_core::canvas_draw::{ + CLEAR_COLOR, CLEAR_DEPTH, CLEAR_STENCIL, GS_CS_709_EXTENDED, GS_CS_709_SCRGB, GS_CS_SRGB, + GS_CS_SRGB_16F, SCRGB_WHITE, Technique, clear_draws_solid, clear_flags, clear_linear, + clear_reads_space, multiplier, reads_white_level, skip, technique, +}; +use proptest::prelude::*; + +/// Colour spaces outside `enum gs_color_space`. +const OUTSIDE_SPACES: [c_int; 5] = [-1, 4, 99, c_int::MIN, c_int::MAX]; + +const SPACES: [c_int; 4] = [ + GS_CS_SRGB, + GS_CS_SRGB_16F, + GS_CS_709_EXTENDED, + GS_CS_709_SCRGB, +]; + +/// SDR white levels: OBS's default, a common one, and 0. +const WHITES: [f32; 3] = [80.0, 300.0, 0.0]; + +const D: Technique = Technique::Draw; +const M: Technique = Technique::DrawMultiply; +const T: Technique = Technique::DrawTonemap; + +fn check_bits(what: &str, got: f32, want: u32) { + assert_eq!( + got.to_bits(), + want, + "{what}: {got} ({:#010x}), expected {} ({want:#010x})", + got.to_bits(), + f32::from_bits(want) + ); +} + +// --------------------------------------------------------------------------- +// constants + +#[test] +fn steps_constants() { + assert_eq!(Technique::Draw.value(), 0); + assert_eq!(Technique::DrawMultiply.value(), 1); + assert_eq!(Technique::DrawTonemap.value(), 2); + assert_eq!( + size_of::(), + 1, + "the safe enum; the shim returns the C's int" + ); + assert_eq!(CLEAR_COLOR, 1); + assert_eq!(CLEAR_DEPTH, 2); + assert_eq!(CLEAR_STENCIL, 4); + assert_eq!(D.name(), "Draw"); + assert_eq!(M.name(), "DrawMultiply"); + assert_eq!(T.name(), "DrawTonemap"); + check_bits("SCRGB_WHITE", SCRGB_WHITE, 0x42a0_0000); +} + +// --------------------------------------------------------------------------- +// canvas: the early return + +/// Both early returns skip; no mix with a rendered flag, which obs.c never +/// passes, also skips (characterized, not endorsed). +#[test] +fn steps_skip_every_input() { + assert!(skip(false, false)); + assert!(skip(false, true)); + assert!(skip(true, false)); + assert!(!skip(true, true)); +} + +// --------------------------------------------------------------------------- +// canvas: technique + +/// `[source][current]`. +const TECHNIQUE: [[Technique; 4]; 4] = [[D, D, D, M], [D, D, D, M], [T, T, D, M], [D, D, D, M]]; + +#[test] +fn steps_technique_space_pairs() { + for (s, row) in SPACES.iter().zip(TECHNIQUE) { + for (c, want) in SPACES.iter().zip(row) { + assert_eq!(technique(*s, *c), want, "source {s} current {c}"); + } + } +} + +#[test] +fn steps_technique_outside_enum() { + for o in OUTSIDE_SPACES { + for s in SPACES { + assert_eq!(technique(s, o), D, "source {s} current {o}"); + } + for p in OUTSIDE_SPACES { + assert_eq!(technique(p, o), D, "source {p} current {o}"); + } + assert_eq!(technique(o, GS_CS_SRGB), D); + assert_eq!(technique(o, GS_CS_SRGB_16F), D); + assert_eq!(technique(o, GS_CS_709_EXTENDED), D); + assert_eq!(technique(o, GS_CS_709_SCRGB), M); + } +} + +// --------------------------------------------------------------------------- +// canvas: white level and multiplier + +#[test] +fn steps_reads_white_level_spaces() { + assert!(!reads_white_level(GS_CS_SRGB)); + assert!(!reads_white_level(GS_CS_SRGB_16F)); + assert!(!reads_white_level(GS_CS_709_EXTENDED)); + assert!(reads_white_level(GS_CS_709_SCRGB)); + for o in OUTSIDE_SPACES { + assert!(!reads_white_level(o), "{o}"); + } +} + +#[test] +fn steps_multiplier_white_levels() { + check_bits("80", multiplier(80.0), 0x3f80_0000); + check_bits("300", multiplier(300.0), 0x4070_0000); + check_bits("0", multiplier(0.0), 0x0000_0000); + check_bits("203", multiplier(203.0), (203.0_f32 / 80.0).to_bits()); + check_bits("10000", multiplier(10000.0), 0x42fa_0000); +} + +/// Characterized, not endorsed: -0 stays -0, a negative level gives a +/// negative multiplier, the infinities stay infinite, a NaN stays a NaN, and +/// a denormal underflows to 0. +#[test] +fn steps_multiplier_any_level() { + check_bits("-0", multiplier(-0.0), 0x8000_0000); + check_bits("-80", multiplier(-80.0), 0xbf80_0000); + check_bits("inf", multiplier(f32::INFINITY), 0x7f80_0000); + check_bits("-inf", multiplier(f32::NEG_INFINITY), 0xff80_0000); + check_bits("1e-45", multiplier(1e-45), 0x0000_0000); + check_bits("FLT_MAX", multiplier(f32::MAX), (f32::MAX / 80.0).to_bits()); + assert!(multiplier(f32::NAN).is_nan()); + // every multiple of 80 up to 80 * 2^16 divides exactly + let mut k = 0.0_f32; + while k <= 65536.0 { + check_bits("80 k", multiplier(80.0 * k), k.to_bits()); + k += 1.0; + } +} + +#[test] +fn steps_canvas_plan_every_input() { + const NAMES: [[&str; 4]; 4] = [ + ["Draw", "Draw", "Draw", "DrawMultiply"], + ["Draw", "Draw", "Draw", "DrawMultiply"], + ["DrawTonemap", "DrawTonemap", "Draw", "DrawMultiply"], + ["Draw", "Draw", "Draw", "DrawMultiply"], + ]; + const MULTIPLIERS: [u32; 3] = [0x3f80_0000, 0x4070_0000, 0x0000_0000]; + + for (s, names) in SPACES.iter().zip(NAMES) { + for (c, want_name) in SPACES.iter().zip(names) { + for (w, want_multiplier) in WHITES.iter().zip(MULTIPLIERS) { + let name = technique(*s, *c).name(); + let mut got = 1.0_f32; + if reads_white_level(*c) { + got = multiplier(*w); + } + assert_eq!(name, want_name, "source {s} current {c}"); + let want = if *c == GS_CS_709_SCRGB { + want_multiplier + } else { + 0x3f80_0000 + }; + check_bits("multiplier", got, want); + } + } + } +} + +// --------------------------------------------------------------------------- +// display: clear colour + +#[test] +fn steps_clear_reads_space_every_input() { + assert!(clear_reads_space(false)); + assert!(!clear_reads_space(true)); +} + +#[test] +fn steps_clear_linear_spaces() { + assert!(clear_linear(GS_CS_SRGB)); + assert!(!clear_linear(GS_CS_SRGB_16F)); + assert!(!clear_linear(GS_CS_709_EXTENDED)); + assert!(!clear_linear(GS_CS_709_SCRGB)); + for o in OUTSIDE_SPACES { + assert!(!clear_linear(o), "{o}"); + } +} + +#[test] +fn steps_clear_colour_every_input() { + for always in [false, true] { + for space in SPACES.into_iter().chain(OUTSIDE_SPACES) { + let linear = clear_reads_space(always) && clear_linear(space); + assert_eq!( + linear, + !always && space == GS_CS_SRGB, + "always {always} space {space}" + ); + } + } +} + +// --------------------------------------------------------------------------- +// display: clear flags and the workaround + +#[test] +fn steps_clear_every_input() { + assert_eq!( + clear_flags(false), + CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL + ); + assert_eq!(clear_flags(true), CLEAR_DEPTH | CLEAR_STENCIL); + assert!(!clear_draws_solid(false)); + assert!(clear_draws_solid(true)); + for workaround in [false, true] { + let flags = clear_flags(workaround); + assert_ne!( + flags & CLEAR_COLOR != 0, + clear_draws_solid(workaround), + "{workaround}" + ); + } +} + +// --------------------------------------------------------------------------- +// edge cases (new) + +/// `obs_canvas_draw_technique()`'s switch, written out. +fn model_technique(source: c_int, current: c_int) -> Technique { + match current { + GS_CS_SRGB | GS_CS_SRGB_16F if source == GS_CS_709_EXTENDED => T, + GS_CS_709_SCRGB => M, + _ => D, + } +} + +/// A colour space: mostly in or next to the enum, sometimes any `int`. +fn space() -> impl Strategy { + prop_oneof![3 => -2..6_i32, 1 => any::()] +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(4096))] + + #[test] + fn edge_technique_any_space(source in space(), current in space()) { + prop_assert_eq!(technique(source, current), model_technique(source, current)); + prop_assert_eq!(reads_white_level(current), current == GS_CS_709_SCRGB); + prop_assert_eq!(clear_linear(current), current == GS_CS_SRGB); + } + + /// Every white level as a bit pattern (#1951: no wide `Range`): + /// one division by 80, bit for bit, NaN for NaN. + #[test] + fn edge_multiplier_any_bits(bits in any::()) { + let level = f32::from_bits(bits); + let got = multiplier(level); + let want = level / 80.0; + if want.is_nan() { + prop_assert!(got.is_nan()); + } else { + prop_assert_eq!(got.to_bits(), want.to_bits()); + } + } + + #[test] + fn edge_skip_and_clear_any_flags(has_mix: bool, rendered: bool, always: bool, workaround: bool) { + prop_assert_eq!(skip(has_mix, rendered), !has_mix || !rendered); + prop_assert_eq!(clear_reads_space(always), !always); + let colour = if workaround { 0 } else { CLEAR_COLOR }; + prop_assert_eq!(clear_flags(workaround), CLEAR_DEPTH | CLEAR_STENCIL | colour); + prop_assert_eq!(clear_draws_solid(workaround), workaround); + } +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 26e57767a7..155f35ec7d 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -3,6 +3,7 @@ mod audio_mix; mod audio_mix_parity; +mod canvas_draw; mod context_names; mod context_names_parity; mod module_locale; From 1d75d3bd5134fde60eadb1b44a23a9a76de2eca6 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 17:57:34 -0400 Subject: [PATCH 4/6] obs-core: Port the canvas texture draw and display clear decisions Ports libobs/obs-canvas-draw.c.h, the canvas texture draw decisions of obs.c and the display clear decisions of obs-display.c, to the canvas_draw module of rust/obs-core. obs.c.h and obs-display.c.h stay C around it: every gs_* call in its order and under its conditions, the effect and param lookups, the blend state, the swapchain, the resize, the viewport, the solid effect, obs_get_video_sdr_white_level() and obs_host_display_clear_color_always_srgb() (they pass the values in). The hybrid libobs drops the C file and links the Rust shims in its place. Safe core (src/canvas_draw.rs): - skip(): no mix, or a texture not rendered; - technique(): DrawTonemap for GS_CS_709_EXTENDED into GS_CS_SRGB or GS_CS_SRGB_16F, DrawMultiply into GS_CS_709_SCRGB, else Draw (a space outside the enum included); - reads_white_level(): into GS_CS_709_SCRGB only; multiplier(): the white level over SCRGB_WHITE (80), one f32 division as in the C; - clear_reads_space(): not when the host always clears in sRGB; clear_linear(): into GS_CS_SRGB only; - clear_flags(): CLEAR_DEPTH | CLEAR_STENCIL, with CLEAR_COLOR without the clear workaround; clear_draws_solid(): with the workaround. The module denies clippy's arithmetic, indexing, as-conversion, unwrap, expect, panic, todo, unimplemented and unreachable lints, keeps no state and takes no lock. No intentional differences from the C. Technique mirrors the three values of enum obs_source_draw_technique these decisions return, with the C's numbers and names; obs-core cannot depend on obs-source, whose draw_technique (#2206) has all six. Shims (src/ffi/canvas_draw.rs): the eight functions keep the C signatures. No canvas, mix or display is mirrored: only colour spaces as c_int, flags as bool, the white level as f32, the clear flags as u32 and the technique as the enum's u32, as the obs-source shims return it. C side: the file leaves libobs.core for its own group, libobs.ported-canvas-draw (LIBOBS_PORTED_SOURCES), whose PCH is obs.h (for the gs_color_space values) and obs-canvas-draw.h; libobs.pch.h keeps the header for obs.c and obs-display.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. ci/test_ported_sources.py checks the group on every host. The exported symbol set is 1766 on the C, hybrid and c-ref builds, the same set on all three, with the eight functions local. test_canvas_draw_steps still compiles the C file into itself, unchanged. It has no _rust variant: linking it against libobs_rust-static was tried and fails with 399 undefined references (108 symbols), because the shims' archive member (an obs_core codegen unit) also holds the other obs-core ports, which need libobs and obs-util's platform code, as for test_video_output_step_steps (#2181). The Tier 3 parity tests compare the shims with this C instead. Tier 1 obs_core::canvas_draw passes 15/15. Refs #2240. --- ci/test_ported_sources.py | 1 + libobs/build/libobs-ported-canvas-draw.pch.h | 11 +++ libobs/build/libobs.core+.h.c | 1 - libobs/build/libobs.ported-canvas-draw+.h.c | 6 ++ libobs/build/source-sets.json | 1 + libobs/cmake/rust-exports.map | 10 +++ libobs/cmake/rust-hidden.txt | 11 +++ libobs/cmake/rust-unexports-macos.txt | 10 +++ libobs/obs-canvas-draw.c.h | 8 +- rust/obs-core/src/canvas_draw.rs | 49 ++++++++---- rust/obs-core/src/ffi/canvas_draw.rs | 79 ++++++++++++++++++++ rust/obs-core/src/ffi/mod.rs | 1 + 12 files changed, 170 insertions(+), 18 deletions(-) create mode 100644 libobs/build/libobs-ported-canvas-draw.pch.h create mode 100644 libobs/build/libobs.ported-canvas-draw+.h.c create mode 100644 rust/obs-core/src/ffi/canvas_draw.rs diff --git a/ci/test_ported_sources.py b/ci/test_ported_sources.py index 5c4f51446a..4840b3d689 100644 --- a/ci/test_ported_sources.py +++ b/ci/test_ported_sources.py @@ -18,6 +18,7 @@ PORTED_ON_EVERY_HOST = ( "graphics/graphics-sprite.c.h.o", "obs-audio-mix.c.h.o", + "obs-canvas-draw.c.h.o", "obs-context-names.c.h.o", "obs-encoder-roi.c.h.o", "obs-encoder-size.c.h.o", diff --git a/libobs/build/libobs-ported-canvas-draw.pch.h b/libobs/build/libobs-ported-canvas-draw.pch.h new file mode 100644 index 0000000000..fc533d8f64 --- /dev/null +++ b/libobs/build/libobs-ported-canvas-draw.pch.h @@ -0,0 +1,11 @@ +/* Precompiled header (BUILD.md) for the libobs unity group + * libobs.ported-canvas-draw. obs-canvas-draw.c needs its declarations + * (obs-canvas-draw.h, which brings obs-source-draw-technique.h) and the + * gs_color_space enum (obs.h), so the C oracle and the C test can compile it + * on their own. The implementation file includes this header and nothing + * else. */ + +#pragma once + +#include "obs.h" +#include "obs-canvas-draw.h" diff --git a/libobs/build/libobs.core+.h.c b/libobs/build/libobs.core+.h.c index faace0f594..b4247f4e34 100644 --- a/libobs/build/libobs.core+.h.c +++ b/libobs/build/libobs.core+.h.c @@ -2,7 +2,6 @@ #include "libobs/build/libobs.pch.h" -#include "libobs/obs-canvas-draw.c.h" #include "libobs/obs-hotkey.c.h" #include "libobs/obs-module.c.h" #include "libobs/obs.c.h" diff --git a/libobs/build/libobs.ported-canvas-draw+.h.c b/libobs/build/libobs.ported-canvas-draw+.h.c new file mode 100644 index 0000000000..54354c40d7 --- /dev/null +++ b/libobs/build/libobs.ported-canvas-draw+.h.c @@ -0,0 +1,6 @@ +/* Unity group (BUILD.md): ported canvas texture draw and display clear + * decisions. */ + +#include "libobs/build/libobs-ported-canvas-draw.pch.h" + +#include "libobs/obs-canvas-draw.c.h" diff --git a/libobs/build/source-sets.json b/libobs/build/source-sets.json index 2e0e17622a..790f563c8b 100644 --- a/libobs/build/source-sets.json +++ b/libobs/build/source-sets.json @@ -152,6 +152,7 @@ "build/libobs.ported-audio-controls+.h.c", "build/libobs.ported-audio-mix+.h.c", "build/libobs.ported-callback+.h.c", + "build/libobs.ported-canvas-draw+.h.c", "build/libobs.ported-context-names+.h.c", "build/libobs.ported-data+.h.c", "build/libobs.ported-effect-lifecycle+.h.c", diff --git a/libobs/cmake/rust-exports.map b/libobs/cmake/rust-exports.map index d375ef4ebb..013121597d 100644 --- a/libobs/cmake/rust-exports.map +++ b/libobs/cmake/rust-exports.map @@ -425,6 +425,16 @@ obs_video_step_ring; obs_video_step_download; obs_video_step_output; + /* obs-canvas-draw.c. obs.c and obs-display.c call them inside libobs. + * Not EXPORT. */ + obs_canvas_draw_multiplier; + obs_canvas_draw_reads_white_level; + obs_canvas_draw_skip; + obs_canvas_draw_technique; + obs_display_clear_draws_solid; + obs_display_clear_flags; + obs_display_clear_linear; + obs_display_clear_reads_space; /* util/source-profiler.c. obs.c, obs-video.c and obs-source.c call the * frame hooks inside libobs. Declared in obs-internal.h, not EXPORT. */ source_profiler_reset_video; diff --git a/libobs/cmake/rust-hidden.txt b/libobs/cmake/rust-hidden.txt index f0fc7115eb..f19d25a390 100644 --- a/libobs/cmake/rust-hidden.txt +++ b/libobs/cmake/rust-hidden.txt @@ -478,6 +478,17 @@ obs_video_step_render obs_video_step_ring obs_video_step_download obs_video_step_output +# obs-canvas-draw.c: obs_render_canvas_texture_internal() in obs.c and +# render_display_begin() in obs-display.c call them inside libobs. Declared in +# obs-canvas-draw.h without EXPORT, so the shims stay hidden the same way. +obs_canvas_draw_multiplier +obs_canvas_draw_reads_white_level +obs_canvas_draw_skip +obs_canvas_draw_technique +obs_display_clear_draws_solid +obs_display_clear_flags +obs_display_clear_linear +obs_display_clear_reads_space # util/source-profiler.c: obs.c, obs-video.c and obs-source.c call the frame # hooks inside libobs. Declared in obs-internal.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..0d7954163c 100644 --- a/libobs/cmake/rust-unexports-macos.txt +++ b/libobs/cmake/rust-unexports-macos.txt @@ -387,6 +387,16 @@ _obs_video_step_render _obs_video_step_ring _obs_video_step_download _obs_video_step_output +# obs-canvas-draw.c: obs.c and obs-display.c call them inside libobs. Not +# EXPORT. +_obs_canvas_draw_multiplier +_obs_canvas_draw_reads_white_level +_obs_canvas_draw_skip +_obs_canvas_draw_technique +_obs_display_clear_draws_solid +_obs_display_clear_flags +_obs_display_clear_linear +_obs_display_clear_reads_space # util/source-profiler.c: the frame hooks libobs calls inside itself. Not # EXPORT. _source_profiler_reset_video diff --git a/libobs/obs-canvas-draw.c.h b/libobs/obs-canvas-draw.c.h index cbb503e3da..4150bdfe6c 100644 --- a/libobs/obs-canvas-draw.c.h +++ b/libobs/obs-canvas-draw.c.h @@ -15,7 +15,13 @@ along with this program. If not, see . ******************************************************************************/ -#include "libobs/build/libobs.pch.h" +#include "libobs/build/libobs-ported-canvas-draw.pch.h" + +/* The canvas texture draw and display clear decisions, moved from + * obs_render_canvas_texture_internal() in obs.c and render_display_begin() in + * obs-display.c: only colour spaces, flags and the white level, no texture, + * effect or display. obs.c and obs-display.c make the calls they decide on. + * Ported to rust/obs-core (canvas_draw): the hybrid libobs drops this file. */ /* obs_render_canvas_texture_internal()'s early return. */ bool obs_canvas_draw_skip(bool has_mix, bool texture_rendered) diff --git a/rust/obs-core/src/canvas_draw.rs b/rust/obs-core/src/canvas_draw.rs index 1280a0858c..3d0551bba6 100644 --- a/rust/obs-core/src/canvas_draw.rs +++ b/rust/obs-core/src/canvas_draw.rs @@ -32,8 +32,24 @@ //! depend on. The colour spaces are `enum gs_color_space`, taken as the C's //! `int`; a value outside the enum takes the path it took in the C. //! +//! No input comes from outside OBS (the spaces come from the graphics +//! subsystem and the mix, the white level from `obs_set_video_levels()`, the +//! flags from libobs and the host), but nothing here can panic on any input. +//! //! No intentional differences from the C. +#![deny( + clippy::arithmetic_side_effects, + clippy::indexing_slicing, + clippy::as_conversions, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::todo, + clippy::unimplemented, + clippy::unreachable +)] + use core::ffi::c_int; /// `GS_CS_SRGB` (`enum gs_color_space`, `graphics/graphics.h`): SDR. @@ -97,8 +113,7 @@ impl Technique { /// is not rendered. #[must_use] pub fn skip(has_mix: bool, texture_rendered: bool) -> bool { - let _ = (has_mix, texture_rendered); - todo!() + !has_mix || !texture_rendered } /// `obs_canvas_draw_technique()`: `DrawTonemap` for a @@ -106,54 +121,56 @@ pub fn skip(has_mix: bool, texture_rendered: bool) -> bool { /// [`GS_CS_709_SCRGB`], `Draw` otherwise. #[must_use] pub fn technique(source_space: c_int, current_space: c_int) -> Technique { - let _ = (source_space, current_space); - todo!() + match current_space { + GS_CS_SRGB | GS_CS_SRGB_16F if source_space == GS_CS_709_EXTENDED => Technique::DrawTonemap, + GS_CS_709_SCRGB => Technique::DrawMultiply, + _ => Technique::Draw, + } } /// `obs_canvas_draw_reads_white_level()`: whether the white level is read, /// into [`GS_CS_709_SCRGB`] only. #[must_use] pub fn reads_white_level(current_space: c_int) -> bool { - let _ = current_space; - todo!() + current_space == GS_CS_709_SCRGB } /// `obs_canvas_draw_multiplier()`: the white level over [`SCRGB_WHITE`], one /// `f32` division. #[must_use] pub fn multiplier(sdr_white_level: f32) -> f32 { - let _ = sdr_white_level; - todo!() + sdr_white_level / SCRGB_WHITE } /// `obs_display_clear_reads_space()`: whether the colour space is read for /// the clear colour, only when the host does not always clear in sRGB. #[must_use] pub fn clear_reads_space(always_srgb: bool) -> bool { - let _ = always_srgb; - todo!() + !always_srgb } /// `obs_display_clear_linear()`: whether the clear colour stays linear /// (`vec4_from_rgba()`), into [`GS_CS_SRGB`] only. #[must_use] pub fn clear_linear(current_space: c_int) -> bool { - let _ = current_space; - todo!() + current_space == GS_CS_SRGB } /// `obs_display_clear_flags()`: depth and stencil, and colour without the /// clear workaround. #[must_use] pub fn clear_flags(use_clear_workaround: bool) -> u32 { - let _ = use_clear_workaround; - todo!() + let flags = CLEAR_DEPTH | CLEAR_STENCIL; + if use_clear_workaround { + flags + } else { + flags | CLEAR_COLOR + } } /// `obs_display_clear_draws_solid()`: whether the solid effect draws the /// clear colour, with the clear workaround only. #[must_use] pub fn clear_draws_solid(use_clear_workaround: bool) -> bool { - let _ = use_clear_workaround; - todo!() + use_clear_workaround } diff --git a/rust/obs-core/src/ffi/canvas_draw.rs b/rust/obs-core/src/ffi/canvas_draw.rs new file mode 100644 index 0000000000..cf71b008bb --- /dev/null +++ b/rust/obs-core/src/ffi/canvas_draw.rs @@ -0,0 +1,79 @@ +//! C ABI for `libobs/obs-canvas-draw.c.h`, the canvas texture draw and +//! display clear decisions, declared in `libobs/obs-canvas-draw.h` without +//! `EXPORT`. +//! +//! `obs_render_canvas_texture_internal()` in `obs.c.h` and +//! `render_display_begin()` in `obs-display.c.h` (still C) make every `gs_*` +//! call in its order, read the mix's fields, the colour spaces, the white +//! level and the host's answer, pass the values in and act on what comes +//! back. So no canvas, mix or display is 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 technique comes back as `enum obs_source_draw_technique` +//! (`libobs/obs-source-draw-technique.h`), whose values run from 0 to 5, so +//! the C's enum type is `unsigned int` or `int` and every value fits both; it +//! crosses as `u32`, as the obs-source shims return it. +//! +//! No intentional differences from C: every input is a value, so there is +//! no pointer to check. + +use core::ffi::c_int; + +use crate::canvas_draw as draw; + +/// `enum obs_source_draw_technique`. +#[allow(non_camel_case_types)] +pub type obs_source_draw_technique = u32; + +/// `bool obs_canvas_draw_skip(bool has_mix, bool texture_rendered)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_canvas_draw_skip(has_mix: bool, texture_rendered: bool) -> bool { + draw::skip(has_mix, texture_rendered) +} + +/// `enum obs_source_draw_technique obs_canvas_draw_technique(int +/// source_space, int current_space)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_canvas_draw_technique( + source_space: c_int, + current_space: c_int, +) -> obs_source_draw_technique { + draw::technique(source_space, current_space).value() +} + +/// `bool obs_canvas_draw_reads_white_level(int current_space)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_canvas_draw_reads_white_level(current_space: c_int) -> bool { + draw::reads_white_level(current_space) +} + +/// `float obs_canvas_draw_multiplier(float sdr_white_level)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_canvas_draw_multiplier(sdr_white_level: f32) -> f32 { + draw::multiplier(sdr_white_level) +} + +/// `bool obs_display_clear_reads_space(bool always_srgb)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_display_clear_reads_space(always_srgb: bool) -> bool { + draw::clear_reads_space(always_srgb) +} + +/// `bool obs_display_clear_linear(int current_space)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_display_clear_linear(current_space: c_int) -> bool { + draw::clear_linear(current_space) +} + +/// `uint32_t obs_display_clear_flags(bool use_clear_workaround)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_display_clear_flags(use_clear_workaround: bool) -> u32 { + draw::clear_flags(use_clear_workaround) +} + +/// `bool obs_display_clear_draws_solid(bool use_clear_workaround)`. +#[unsafe(no_mangle)] +pub extern "C" fn obs_display_clear_draws_solid(use_clear_workaround: bool) -> bool { + draw::clear_draws_solid(use_clear_workaround) +} diff --git a/rust/obs-core/src/ffi/mod.rs b/rust/obs-core/src/ffi/mod.rs index c96329bf79..b4e8ca4ff0 100644 --- a/rust/obs-core/src/ffi/mod.rs +++ b/rust/obs-core/src/ffi/mod.rs @@ -1,6 +1,7 @@ //! C ABI shims, one module per C file. pub mod audio_mix; +pub mod canvas_draw; pub mod context_names; pub mod module_locale; pub mod module_names; From 8c25d85b26dcc08db3d687a19eba07cc2d64ca1e Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:13:20 -0400 Subject: [PATCH 5/6] obs-core: Check the canvas draw port against the C rust/obs-c-oracle/oracle/canvas_draw.c compiles the unchanged libobs/obs-canvas-draw.c.h with its eight functions renamed oracle_*, plus the enum values, the clear flags (the header's copies and graphics.h's) and the type sizes, and obs_source_draw_technique_name(). tests/obs_core/canvas_draw_parity.rs (7 tests) runs the shim, the C and the safe core on every input and compares the results exactly: the C's bool as the byte it returns, the technique as its value, the clear flags as the uint32_t, the multiplier as its bits (a NaN's payload included). - the 19 values and sizes against the C headers, and the technique names; - exhaustive: every flag of the skip, the clear colour, the clear flags and the workaround; the technique, the white level read and the linear clear colour for every pair of 649 spaces (-320 to 320 and four near each end of int); the multiplier for 131,072 bit patterns covering every sign, exponent and NaN class, every multiple of 80 to 80 * 2^16 and 24 special levels; - both callers' decisions in their order (the skip, the technique name, the white level read and the multiplier only when it is read; the host answer, the space only when it is read, the flags and the workaround), for every flag, the spaces -3 to 6 and the int ends, and the special levels; - proptests (20,000 cases each) over any space, any white level bit pattern (#1951: no float range) and every flag, decision by decision and both callers at once. No input reaches an integer division or a 128-bit multiply on either side (the one division is the f32 multiplier, which cannot trap), so nothing is skipped on MSVC x64. No intentional differences. The parity module passed 10 runs in a row with fresh seeds. test_canvas_draw_steps passed 12/12 under ASan and UBSan. The committed regression files hold the seeds proptest saved while mutants failed; all pass on the port. Mutation check (the mutants are not committed): 28 mutants, 19 in the core and 9 in the shims, each run against Tier 1 (15 tests) and Tier 3 (7). 27 fail. The one that survives is equivalent: the shim passing has_mix and texture_rendered swapped, and !a || !b is symmetric. Tier 1 does not reach the shims; Tier 3 kills every other shim mutant. Each mutant and the tests that fail on it: 1. core, skip: || becomes && T1: edge_skip_and_clear_any_flags, steps_skip_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 2. core, skip ignores has_mix T1: edge_skip_and_clear_any_flags, steps_skip_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 3. core, technique: GS_CS_SRGB_16F loses the tonemap T1: edge_technique_any_space, steps_canvas_plan_every_input, steps_technique_space_pairs T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 4. core, technique: tonemaps a scRGB source, not 709 extended T1: edge_technique_any_space, steps_canvas_plan_every_input, steps_technique_space_pairs T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 5. core, technique: Draw into scRGB T1: edge_technique_any_space, steps_canvas_plan_every_input, steps_technique_outside_enum, steps_technique_space_pairs T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 6. core, technique: DrawTonemap into 709 extended T1: edge_technique_any_space, steps_canvas_plan_every_input, steps_technique_outside_enum, steps_technique_space_pairs T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 7. core, reads_white_level: >= scRGB T1: edge_technique_any_space, steps_reads_white_level_spaces T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 8. core, multiplier: / 81 T1: edge_multiplier_any_bits, steps_canvas_plan_every_input, steps_multiplier_any_level, steps_multiplier_white_levels T3: callers_every_input, every_white_level_class, proptest_callers, proptest_decisions 9. core, multiplier: * (1 / 80) T1: edge_multiplier_any_bits, steps_multiplier_white_levels T3: callers_every_input, every_white_level_class, proptest_callers, proptest_decisions 10. core, multiplier: NaN becomes 0 T1: edge_multiplier_any_bits, steps_multiplier_any_level T3: callers_every_input, every_white_level_class, proptest_callers, proptest_decisions 11. core, clear_reads_space: not negated T1: edge_skip_and_clear_any_flags, steps_clear_colour_every_input, steps_clear_reads_space_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 12. core, clear_linear: <= GS_CS_SRGB_16F T1: edge_technique_any_space, steps_clear_colour_every_input, steps_clear_linear_spaces T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 13. core, clear_linear: also below 0 T1: edge_technique_any_space, steps_clear_colour_every_input, steps_clear_linear_spaces T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 14. core, clear_flags: no stencil T1: edge_skip_and_clear_any_flags, steps_clear_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 15. core, clear_flags: colour with the workaround T1: edge_skip_and_clear_any_flags, steps_clear_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 16. core, clear_draws_solid: negated T1: edge_skip_and_clear_any_flags, steps_clear_every_input T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 17. core, Technique::value: DrawTonemap 3 T1: steps_constants T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions, values_match_the_c_headers 18. core, Technique::name: DrawTonemap renamed T1: steps_canvas_plan_every_input, steps_constants T3: values_match_the_c_headers 19. core, CLEAR_STENCIL: 1 << 3 T1: steps_constants T3: callers_every_input, every_flag, proptest_callers, proptest_decisions, values_match_the_c_headers 20. shim, skip: arguments swapped: SURVIVES (equivalent) T1: none T3: none 21. shim, skip: texture_rendered always true T1: none T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 22. shim, technique: spaces swapped T1: none T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 23. shim, reads_white_level: always scRGB T1: none T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 24. shim, multiplier: level negated T1: none T3: callers_every_input, every_white_level_class, proptest_callers, proptest_decisions 25. shim, clear_reads_space: always false T1: none T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 26. shim, clear_linear: negated T1: none T3: callers_every_input, every_space_pair, proptest_callers, proptest_decisions 27. shim, clear_flags: workaround negated T1: none T3: callers_every_input, every_flag, proptest_callers, proptest_decisions 28. shim, clear_draws_solid: calls clear_reads_space T1: none T3: callers_every_input, every_flag, proptest_callers, proptest_decisions Refs #2240. --- rust/obs-c-oracle/oracle/canvas_draw.c | 67 +++ rust/obs-c-oracle/src/canvas_draw.rs | 54 +++ rust/obs-c-oracle/src/lib.rs | 1 + .../tests/obs_core/canvas_draw_parity.rs | 435 ++++++++++++++++++ rust/obs-core/tests/obs_core/main.rs | 1 + .../proptest-regressions/canvas_draw.txt | 13 + .../canvas_draw_parity.txt | 20 + 7 files changed, 591 insertions(+) create mode 100644 rust/obs-c-oracle/oracle/canvas_draw.c create mode 100644 rust/obs-c-oracle/src/canvas_draw.rs create mode 100644 rust/obs-core/tests/obs_core/canvas_draw_parity.rs create mode 100644 rust/obs-core/tests/proptest-regressions/canvas_draw.txt create mode 100644 rust/obs-core/tests/proptest-regressions/canvas_draw_parity.txt diff --git a/rust/obs-c-oracle/oracle/canvas_draw.c b/rust/obs-c-oracle/oracle/canvas_draw.c new file mode 100644 index 0000000000..b1fa1ae13c --- /dev/null +++ b/rust/obs-c-oracle/oracle/canvas_draw.c @@ -0,0 +1,67 @@ +/* Test-only oracle: the original libobs/obs-canvas-draw.c.h, unmodified, + * with its eight functions renamed to oracle_* so they can link next to the + * Rust shims. */ +#include +#include + +#define obs_canvas_draw_skip oracle_obs_canvas_draw_skip +#define obs_canvas_draw_technique oracle_obs_canvas_draw_technique +#define obs_canvas_draw_reads_white_level oracle_obs_canvas_draw_reads_white_level +#define obs_canvas_draw_multiplier oracle_obs_canvas_draw_multiplier +#define obs_display_clear_reads_space oracle_obs_display_clear_reads_space +#define obs_display_clear_linear oracle_obs_display_clear_linear +#define obs_display_clear_flags oracle_obs_display_clear_flags +#define obs_display_clear_draws_solid oracle_obs_display_clear_draws_solid + +#include "obs-canvas-draw.c.h" + +#undef obs_display_clear_draws_solid +#undef obs_display_clear_flags +#undef obs_display_clear_linear +#undef obs_display_clear_reads_space +#undef obs_canvas_draw_multiplier +#undef obs_canvas_draw_reads_white_level +#undef obs_canvas_draw_technique +#undef obs_canvas_draw_skip + +/* The technique's name as obs.c maps it, for a value the port returns. */ +const char *oracle_canvas_draw_technique_name(int technique); + +const char *oracle_canvas_draw_technique_name(int technique) +{ + return obs_source_draw_technique_name((enum obs_source_draw_technique)technique); +} + +/* The enum values, flags and sizes the port relies on, in the order of + * rust/obs-c-oracle/src/canvas_draw.rs; INT64_MIN past the end. */ +int64_t oracle_canvas_draw_value(size_t which); + +int64_t oracle_canvas_draw_value(size_t which) +{ + const int64_t values[] = { + /* enum gs_color_space */ + GS_CS_SRGB, + GS_CS_SRGB_16F, + GS_CS_709_EXTENDED, + GS_CS_709_SCRGB, + /* enum obs_source_draw_technique */ + OBS_SOURCE_DRAW_TECH_DRAW, + OBS_SOURCE_DRAW_TECH_DRAW_MULTIPLY, + OBS_SOURCE_DRAW_TECH_DRAW_TONEMAP, + /* the clear flags, copied and from graphics.h */ + OBS_DISPLAY_CLEAR_COLOR, + OBS_DISPLAY_CLEAR_DEPTH, + OBS_DISPLAY_CLEAR_STENCIL, + GS_CLEAR_COLOR, + GS_CLEAR_DEPTH, + GS_CLEAR_STENCIL, + /* sizes */ + sizeof(enum gs_color_space), + sizeof(enum obs_source_draw_technique), + sizeof(int), + sizeof(bool), + sizeof(float), + sizeof(uint32_t), + }; + return which < sizeof(values) / sizeof(values[0]) ? values[which] : INT64_MIN; +} diff --git a/rust/obs-c-oracle/src/canvas_draw.rs b/rust/obs-c-oracle/src/canvas_draw.rs new file mode 100644 index 0000000000..aab3d1d87e --- /dev/null +++ b/rust/obs-c-oracle/src/canvas_draw.rs @@ -0,0 +1,54 @@ +//! `oracle_*` build of `libobs/obs-canvas-draw.c.h` (oracle/canvas_draw.c): +//! the canvas texture draw and display clear 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 technique as `u32`, its +//! value. + +use std::os::raw::{c_char, c_int}; + +/// Index of each entry in `oracle_canvas_draw_value`, in the C's order. +pub const VALUE_NAMES: [&str; 19] = [ + "GS_CS_SRGB", + "GS_CS_SRGB_16F", + "GS_CS_709_EXTENDED", + "GS_CS_709_SCRGB", + "OBS_SOURCE_DRAW_TECH_DRAW", + "OBS_SOURCE_DRAW_TECH_DRAW_MULTIPLY", + "OBS_SOURCE_DRAW_TECH_DRAW_TONEMAP", + "OBS_DISPLAY_CLEAR_COLOR", + "OBS_DISPLAY_CLEAR_DEPTH", + "OBS_DISPLAY_CLEAR_STENCIL", + "GS_CLEAR_COLOR", + "GS_CLEAR_DEPTH", + "GS_CLEAR_STENCIL", + "sizeof(enum gs_color_space)", + "sizeof(enum obs_source_draw_technique)", + "sizeof(int)", + "sizeof(bool)", + "sizeof(float)", + "sizeof(uint32_t)", +]; + +unsafe extern "C" { + /// `bool obs_canvas_draw_skip(bool has_mix, bool texture_rendered)`. + pub fn oracle_obs_canvas_draw_skip(has_mix: bool, texture_rendered: bool) -> u8; + /// `enum obs_source_draw_technique obs_canvas_draw_technique(int + /// source_space, int current_space)`. + pub fn oracle_obs_canvas_draw_technique(source_space: c_int, current_space: c_int) -> u32; + /// `bool obs_canvas_draw_reads_white_level(int current_space)`. + pub fn oracle_obs_canvas_draw_reads_white_level(current_space: c_int) -> u8; + /// `float obs_canvas_draw_multiplier(float sdr_white_level)`. + pub fn oracle_obs_canvas_draw_multiplier(sdr_white_level: f32) -> f32; + /// `bool obs_display_clear_reads_space(bool always_srgb)`. + pub fn oracle_obs_display_clear_reads_space(always_srgb: bool) -> u8; + /// `bool obs_display_clear_linear(int current_space)`. + pub fn oracle_obs_display_clear_linear(current_space: c_int) -> u8; + /// `uint32_t obs_display_clear_flags(bool use_clear_workaround)`. + pub fn oracle_obs_display_clear_flags(use_clear_workaround: bool) -> u32; + /// `bool obs_display_clear_draws_solid(bool use_clear_workaround)`. + pub fn oracle_obs_display_clear_draws_solid(use_clear_workaround: bool) -> u8; + /// `obs_source_draw_technique_name()` for a technique value. + pub fn oracle_canvas_draw_technique_name(technique: c_int) -> *const c_char; + /// The entry named `VALUE_NAMES[which]`; `i64::MIN` out of range. + pub fn oracle_canvas_draw_value(which: usize) -> i64; +} diff --git a/rust/obs-c-oracle/src/lib.rs b/rust/obs-c-oracle/src/lib.rs index 27bfeb3a61..ce9de0ecb7 100644 --- a/rust/obs-c-oracle/src/lib.rs +++ b/rust/obs-c-oracle/src/lib.rs @@ -41,6 +41,7 @@ pub mod bitstream; pub mod bmem; pub mod buffered_file_serializer; pub mod calldata; +pub mod canvas_draw; pub mod cf_tokenizer; pub mod config_file; pub mod context_names; diff --git a/rust/obs-core/tests/obs_core/canvas_draw_parity.rs b/rust/obs-core/tests/obs_core/canvas_draw_parity.rs new file mode 100644 index 0000000000..8a011e6cf5 --- /dev/null +++ b/rust/obs-core/tests/obs_core/canvas_draw_parity.rs @@ -0,0 +1,435 @@ +//! Tier 3: the `obs_canvas_draw_*` and `obs_display_clear_*` shims against +//! the original C (`obs-c-oracle`, `oracle/canvas_draw.c`: the unmodified +//! `libobs/obs-canvas-draw.c.h` with its functions renamed), and the safe +//! core against both. +//! +//! Every function takes and returns plain values, so a run compares the +//! bytes of the results: the C's `bool` as the byte it returns, the +//! technique as its value, the clear flags as the `uint32_t`, the +//! multiplier as its bits (a NaN's payload included). +//! +//! Runs: +//! - the enum values, the clear flags (copied and from `graphics.h`) and the +//! type sizes against the C headers, and the technique names; +//! - exhaustive: every flag of the skip, the clear colour, the clear flags +//! and the workaround; the technique, the white level read and the linear +//! clear colour for every pair of 649 spaces (-320 to 320 and four near +//! each end of `i32`); the multiplier for every `f32` whose top 16 bits +//! vary (65,536 patterns, each sign, exponent and NaN class), every +//! multiple of 80 to 80 * 2^16, and 24 special levels; +//! - the decisions of `obs_render_canvas_texture_internal()` and +//! `render_display_begin()` in their order (the skip, the technique name, +//! the white level read and the multiplier only when it is read; the host +//! answer, the space only when it is read, the clear flags and the +//! workaround), one copy on each side; +//! - proptests (20,000 cases each): every decision over any space and any +//! white level bit pattern (#1951: never a float range), and both callers' +//! decisions over all of it at once. +//! +//! No input reaches an integer division or a 128-bit multiply on either +//! side (the only division is the `f32` multiplier, which cannot trap), so +//! no input is skipped on MSVC x64. No intentional differences: there is no +//! pointer to check. + +use std::ffi::CStr; +use std::os::raw::c_int; + +use obs_c_oracle::canvas_draw as oracle; +use obs_core::canvas_draw::{ + self as core_draw, CLEAR_COLOR, CLEAR_DEPTH, CLEAR_STENCIL, GS_CS_709_EXTENDED, + GS_CS_709_SCRGB, GS_CS_SRGB, GS_CS_SRGB_16F, Technique, +}; +use obs_core::ffi::canvas_draw as shim; +use proptest::prelude::*; + +const TECHNIQUES: [Technique; 3] = [ + Technique::Draw, + Technique::DrawMultiply, + Technique::DrawTonemap, +]; + +#[test] +fn values_match_the_c_headers() { + let rust: [i64; 19] = [ + GS_CS_SRGB.into(), + GS_CS_SRGB_16F.into(), + GS_CS_709_EXTENDED.into(), + GS_CS_709_SCRGB.into(), + TECHNIQUES[0].value().into(), + TECHNIQUES[1].value().into(), + TECHNIQUES[2].value().into(), + CLEAR_COLOR.into(), + CLEAR_DEPTH.into(), + CLEAR_STENCIL.into(), + CLEAR_COLOR.into(), + CLEAR_DEPTH.into(), + CLEAR_STENCIL.into(), + 4, + 4, + 4, + 1, + 4, + 4, + ]; + for (which, (name, value)) in oracle::VALUE_NAMES.iter().zip(rust).enumerate() { + // SAFETY: a pure lookup. + let c = unsafe { oracle::oracle_canvas_draw_value(which) }; + assert_eq!(value, c, "{name}"); + } + // SAFETY: a pure lookup, one past the end. + let past = unsafe { oracle::oracle_canvas_draw_value(oracle::VALUE_NAMES.len()) }; + assert_eq!(past, i64::MIN, "the list has as many values as names"); + // The names C maps each value the port returns to are the port's. + for technique in TECHNIQUES { + let value = c_int::try_from(technique.value()).unwrap(); + // SAFETY: returns a static string for any value. + let name = unsafe { CStr::from_ptr(oracle::oracle_canvas_draw_technique_name(value)) }; + assert_eq!(name.to_str().unwrap(), technique.name()); + } +} + +// -------------------------------------------------------------------------- +// One call on each side + +fn c_skip(has_mix: bool, rendered: bool) -> u8 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_canvas_draw_skip(has_mix, rendered) } +} + +fn c_technique(s: c_int, c: c_int) -> u32 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_canvas_draw_technique(s, c) } +} + +fn c_reads_white_level(c: c_int) -> u8 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_canvas_draw_reads_white_level(c) } +} + +fn c_multiplier(level: f32) -> u32 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_canvas_draw_multiplier(level) }.to_bits() +} + +fn c_reads_space(always: bool) -> u8 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_display_clear_reads_space(always) } +} + +fn c_linear(c: c_int) -> u8 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_display_clear_linear(c) } +} + +fn c_flags(workaround: bool) -> u32 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_display_clear_flags(workaround) } +} + +fn c_solid(workaround: bool) -> u8 { + // SAFETY: plain values. + unsafe { oracle::oracle_obs_display_clear_draws_solid(workaround) } +} + +fn check_flags(has_mix: bool, rendered: bool, always: bool, workaround: bool) { + let what = format!("mix {has_mix} rendered {rendered} always {always} workaround {workaround}"); + assert_eq!( + u8::from(shim::obs_canvas_draw_skip(has_mix, rendered)), + c_skip(has_mix, rendered), + "{what}" + ); + assert_eq!( + core_draw::skip(has_mix, rendered), + c_skip(has_mix, rendered) != 0, + "{what}" + ); + assert_eq!( + u8::from(shim::obs_display_clear_reads_space(always)), + c_reads_space(always), + "{what}" + ); + assert_eq!( + core_draw::clear_reads_space(always), + c_reads_space(always) != 0, + "{what}" + ); + assert_eq!( + shim::obs_display_clear_flags(workaround), + c_flags(workaround), + "{what}" + ); + assert_eq!( + core_draw::clear_flags(workaround), + c_flags(workaround), + "{what}" + ); + assert_eq!( + u8::from(shim::obs_display_clear_draws_solid(workaround)), + c_solid(workaround), + "{what}" + ); + assert_eq!( + core_draw::clear_draws_solid(workaround), + c_solid(workaround) != 0, + "{what}" + ); +} + +fn check_spaces(s: c_int, c: c_int) { + assert_eq!( + shim::obs_canvas_draw_technique(s, c), + c_technique(s, c), + "technique {s} {c}" + ); + assert_eq!( + core_draw::technique(s, c).value(), + c_technique(s, c), + "core technique {s} {c}" + ); + assert_eq!( + u8::from(shim::obs_canvas_draw_reads_white_level(c)), + c_reads_white_level(c), + "reads {c}" + ); + assert_eq!( + core_draw::reads_white_level(c), + c_reads_white_level(c) != 0, + "core reads {c}" + ); + assert_eq!( + u8::from(shim::obs_display_clear_linear(c)), + c_linear(c), + "linear {c}" + ); + assert_eq!( + core_draw::clear_linear(c), + c_linear(c) != 0, + "core linear {c}" + ); +} + +fn check_multiplier(level: f32) { + let c = c_multiplier(level); + assert_eq!( + shim::obs_canvas_draw_multiplier(level).to_bits(), + c, + "multiplier {level} ({:#010x})", + level.to_bits() + ); + assert_eq!( + core_draw::multiplier(level).to_bits(), + c, + "core multiplier {level} ({:#010x})", + level.to_bits() + ); +} + +/// `obs_render_canvas_texture_internal()`'s decisions in its order, as +/// (drawn, technique name, white level read, multiplier bits); one side's +/// functions are passed in. +struct Canvas { + skip: fn(bool, bool) -> bool, + technique: fn(c_int, c_int) -> u32, + reads: fn(c_int) -> bool, + multiplier: fn(f32) -> u32, +} + +fn canvas_plan( + side: &Canvas, + has_mix: bool, + rendered: bool, + s: c_int, + c: c_int, + level: f32, +) -> Option<(String, bool, u32)> { + if (side.skip)(has_mix, rendered) { + return None; + } + let value = c_int::try_from((side.technique)(s, c)).unwrap(); + // SAFETY: returns a static string for any value. + let name = unsafe { CStr::from_ptr(oracle::oracle_canvas_draw_technique_name(value)) }; + let reads = (side.reads)(c); + let multiplier = if reads { + (side.multiplier)(level) + } else { + 1.0_f32.to_bits() + }; + Some((name.to_str().unwrap().to_owned(), reads, multiplier)) +} + +/// `render_display_begin()`'s decisions in its order, as (space read, +/// linear, clear flags, solid draw). +fn display_plan_c(always: bool, c: c_int, workaround: bool) -> (bool, bool, u32, bool) { + let reads = c_reads_space(always) != 0; + let linear = reads && c_linear(c) != 0; + (reads, linear, c_flags(workaround), c_solid(workaround) != 0) +} + +fn display_plan_rs(always: bool, c: c_int, workaround: bool) -> (bool, bool, u32, bool) { + let reads = shim::obs_display_clear_reads_space(always); + let linear = reads && shim::obs_display_clear_linear(c); + ( + reads, + linear, + shim::obs_display_clear_flags(workaround), + shim::obs_display_clear_draws_solid(workaround), + ) +} + +const C_SIDE: Canvas = Canvas { + skip: |m, r| c_skip(m, r) != 0, + technique: c_technique, + reads: |c| c_reads_white_level(c) != 0, + multiplier: c_multiplier, +}; + +const RS_SIDE: Canvas = Canvas { + skip: |m, r| shim::obs_canvas_draw_skip(m, r), + technique: |s, c| shim::obs_canvas_draw_technique(s, c), + reads: |c| shim::obs_canvas_draw_reads_white_level(c), + multiplier: |l| shim::obs_canvas_draw_multiplier(l).to_bits(), +}; + +fn check_callers( + has_mix: bool, + rendered: bool, + s: c_int, + c: c_int, + level: f32, + always: bool, + workaround: bool, +) { + assert_eq!( + canvas_plan(&RS_SIDE, has_mix, rendered, s, c, level), + canvas_plan(&C_SIDE, has_mix, rendered, s, c, level), + "canvas mix {has_mix} rendered {rendered} {s} {c} {level}" + ); + assert_eq!( + display_plan_rs(always, c, workaround), + display_plan_c(always, c, workaround), + "display always {always} {c} workaround {workaround}" + ); +} + +// -------------------------------------------------------------------------- +// Exhaustive + +/// -320 to 320 and four near each end of `i32`. +fn spaces() -> Vec { + let mut spaces: Vec = (-320..=320).collect(); + spaces.extend([c_int::MIN, c_int::MIN + 1, c_int::MAX - 1, c_int::MAX]); + spaces.extend([ + c_int::MIN + 2, + c_int::MIN + 3, + c_int::MAX - 3, + c_int::MAX - 2, + ]); + spaces +} + +const SPECIAL_LEVELS: [f32; 24] = [ + 0.0, + -0.0, + 1.0, + -1.0, + 80.0, + -80.0, + 100.0, + 203.0, + 300.0, + 1000.0, + 10000.0, + f32::MIN_POSITIVE, + 1e-45, + -1e-45, + f32::MAX, + f32::MIN, + f32::EPSILON, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + -f32::NAN, + 0.1, + 79.999_99, + 80.000_01, +]; + +#[test] +fn every_flag() { + for bits in 0..16_u8 { + check_flags(bits & 1 != 0, bits & 2 != 0, bits & 4 != 0, bits & 8 != 0); + } +} + +#[test] +fn every_space_pair() { + let spaces = spaces(); + for &s in &spaces { + for &c in &spaces { + check_spaces(s, c); + } + } +} + +#[test] +fn every_white_level_class() { + for high in 0..=u16::MAX { + let bits = u32::from(high) << 16 | 0x5a5a; + check_multiplier(f32::from_bits(bits)); + check_multiplier(f32::from_bits(u32::from(high) << 16)); + } + let mut k = 0.0_f32; + while k <= 65536.0 { + check_multiplier(80.0 * k); + k += 1.0; + } + for level in SPECIAL_LEVELS { + check_multiplier(level); + } +} + +#[test] +fn callers_every_input() { + let spaces: Vec = (-3..=6).chain([c_int::MIN, c_int::MAX]).collect(); + for bits in 0..16_u8 { + for &s in &spaces { + for &c in &spaces { + for level in SPECIAL_LEVELS { + check_callers( + bits & 1 != 0, + bits & 2 != 0, + s, + c, + level, + bits & 4 != 0, + bits & 8 != 0, + ); + } + } + } + } +} + +// -------------------------------------------------------------------------- +// Proptests + +/// A colour space: mostly in or next to the enum, sometimes any `int`. +fn space() -> impl Strategy { + prop_oneof![3 => -2..6_i32, 1 => any::()] +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(20_000))] + + #[test] + fn proptest_decisions(s in space(), c in space(), bits in any::(), flags in 0..16_u8) { + check_spaces(s, c); + check_multiplier(f32::from_bits(bits)); + check_flags(flags & 1 != 0, flags & 2 != 0, flags & 4 != 0, flags & 8 != 0); + } + + #[test] + fn proptest_callers(s in space(), c in space(), bits in any::(), flags in 0..16_u8) { + check_callers(flags & 1 != 0, flags & 2 != 0, s, c, f32::from_bits(bits), flags & 4 != 0, flags & 8 != 0); + } +} diff --git a/rust/obs-core/tests/obs_core/main.rs b/rust/obs-core/tests/obs_core/main.rs index 155f35ec7d..89220e0ed5 100644 --- a/rust/obs-core/tests/obs_core/main.rs +++ b/rust/obs-core/tests/obs_core/main.rs @@ -4,6 +4,7 @@ mod audio_mix; mod audio_mix_parity; mod canvas_draw; +mod canvas_draw_parity; mod context_names; mod context_names_parity; mod module_locale; diff --git a/rust/obs-core/tests/proptest-regressions/canvas_draw.txt b/rust/obs-core/tests/proptest-regressions/canvas_draw.txt new file mode 100644 index 0000000000..047687686e --- /dev/null +++ b/rust/obs-core/tests/proptest-regressions/canvas_draw.txt @@ -0,0 +1,13 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 44fb44a5048beff73bdd7aa8b0c40c9ed5c6657a94c720b412d9dd958b61d5cd # shrinks to has_mix = false, rendered = true, always = false, workaround = false +cc a4136cd1d91df84c84297abbaa0482ed65345976b681d6e74ec1f4dc90a9e90b # shrinks to source = 2, current = 1 +cc f5b0bd68f8d1544ac03587b33457c7cb7d7b1ca82dc13c9fe39840288c9efd03 # shrinks to source = 0, current = 3 +cc 2fd02168c60385e22dc6797358847a876edfa2c41e9364ee9d031026a43a26f7 # shrinks to source = 0, current = 2 +cc c41393004d410566067a8b92281111e7915e28df0f462519fc6149b0f1f9ccbb # shrinks to bits = 136322018 +cc faa0f5ba1453b0ceae5cca474e62c9dc59579e4c0390368fb5fa9ee28127ac32 # shrinks to bits = 2139095041 +cc d269f9144a0316ecc9b4afeee44c2a4001d85ad6595b88e33e704f935ce607c2 # shrinks to source = 0, current = -1 diff --git a/rust/obs-core/tests/proptest-regressions/canvas_draw_parity.txt b/rust/obs-core/tests/proptest-regressions/canvas_draw_parity.txt new file mode 100644 index 0000000000..48ec2c09b1 --- /dev/null +++ b/rust/obs-core/tests/proptest-regressions/canvas_draw_parity.txt @@ -0,0 +1,20 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc e05d337ff79e21b2edc93dfe43730fefbcfb7a619c0730c9027aa4b225415876 # shrinks to s = 0, c = 0, bits = 0, flags = 1 +cc 33816f6bd07a4450c2e90ad7df010cbffcf82c4a4f5779d59ed100d8c5ab08f2 # shrinks to s = 0, c = 0, bits = 0, flags = 1 +cc 4489b1cc093701c60b47de46eb0a78f20bc9c0aff29443d11e89590997f5c909 # shrinks to s = 2, c = 1, bits = 0, flags = 0 +cc 2b3b774240383ea4b7ae2ced9986dd3b270caa27f2c1ec74e1b3f7f748a02429 # shrinks to s = 2, c = 1, bits = 0, flags = 3 +cc 2ed9c43425df5e0396ee3874e4af782a83ae848a5fd4db5e096f6d528472566b # shrinks to s = 0, c = 3, bits = 0, flags = 0 +cc f18c6e1f2935f3f85fc5510ee3a22e033859e38f78db89b134bafa1c262fea61 # shrinks to s = 0, c = 3, bits = 0, flags = 3 +cc 893a05a6b304c6da22613b21a7ea53940e71410e727bf95f7dcf61918c43ae97 # shrinks to s = 0, c = 2, bits = 0, flags = 0 +cc aafea503a1b3629008f8c457067d7d96e6ad86900c7c87cd1d5b902ff465a8a2 # shrinks to s = 0, c = 2, bits = 0, flags = 3 +cc 22cabad396670d3bbd486421cfb3391172ebb65cbd04960bdd636802772ceb43 # shrinks to s = 0, c = 4, bits = 0, flags = 3 +cc e99b41b3d6a9b11faf637aac3fe8ffc8a28b98a5b1a7830dac05a72f2d2c8708 # shrinks to s = 0, c = 3, bits = 289374447, flags = 3 +cc 67c225c8141ab89db465aadcb959267d86db4862185f949b60c0f52a14d18fb2 # shrinks to s = 0, c = 0, bits = 2139095041, flags = 0 +cc 113cd52ad3530e11f00574bf37be348d515d63586e266f13292aeca689130f9a # shrinks to s = 0, c = 3, bits = 2139095041, flags = 3 +cc 64991d04c6f7985964c1ef6543ec9fed60e7973b43e4a3daa8564bdb23dcf9f7 # shrinks to s = 0, c = -1, bits = 0, flags = 0 +cc 503a6dc14f7828944ee1af776df7d536bc25a6eb6b1babea37c8ace53b7fc797 # shrinks to s = 0, c = -1, bits = 0, flags = 0 From 798c5aa413ba272fa017839a93980477bd1621b2 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sat, 24 Oct 2026 18:19:53 -0400 Subject: [PATCH 6/6] docs: Record the canvas draw port - rust/README.md: the obs-core crate row names libobs/obs-canvas-draw.c.h, and a row for the file says what is swapped in the hybrid, what obs.c.h and obs-display.c.h keep, why the white level and the clear colour's space are each split into a "reads" question and an answer, why Technique mirrors only three values, why there is no _rust variant, and what Tier 3 covers; - rust/obs-core: the crate description and the lib.rs docs list the module; - docs/rust-port/naming.md: obs-canvas-draw.c.h, extracted from obs.c.h and obs-display.c.h, maps to rust/obs-core; - rust/obs-c-oracle/benches/port_comparison/canvas_draw.rs: canvas_draw/canvas_texture and canvas_draw/display_begin, each caller's decisions in their order over 1024 calls on each side, folded into a checksum both must match. It allocates nothing, so the per-module allocation check holds. It joins the sorted modules![] list. port_comparison (x86_64 Linux, GCC, not pinned, load average 29 to 35; median of two runs): canvas_texture 10.4 and 8.7 us Rust, 5.6 and 13.4 us C; display_begin 7.8 and 8.8 us Rust, 5.8 and 13.4 us C, per 1024 calls: about 5 to 13 ns a call either way, within the noise of this host. No docs/features.md line: the port changes no behaviour. Fixes #2240. --- docs/rust-port/naming.md | 2 +- rust/README.md | 3 +- rust/obs-c-oracle/benches/port_comparison.rs | 3 + .../benches/port_comparison/canvas_draw.rs | 170 ++++++++++++++++++ rust/obs-core/Cargo.toml | 2 +- rust/obs-core/src/lib.rs | 12 +- 6 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 rust/obs-c-oracle/benches/port_comparison/canvas_draw.rs diff --git a/docs/rust-port/naming.md b/docs/rust-port/naming.md index 3b66199070..b8892a0376 100644 --- a/docs/rust-port/naming.md +++ b/docs/rust-port/naming.md @@ -61,7 +61,7 @@ One name per thing, so releases, crates and tags can't be confused (#320). | `libobs/obs-source*.c.h` | `rust/obs-source` | | `libobs/audio-monitoring/` | `rust/obs-audio-monitoring` | | `libobs/obs-audio-controls.c.h` | `rust/obs-audio-controls` | -| `libobs/obs.c.h` and the units extracted from it (`obs-video-plan.c.h`, `obs-context-names.c.h`, `obs-source-load.c.h`), and those extracted from `libobs/obs-module.c.h` (`obs-module-paths.c.h`, `obs-module-names.c.h`, `obs-module-locale.c.h`, `obs-module-source-rules.c.h`, `obs-module-type-rules.c.h`), `libobs/obs-view-api.c.h`, and `obs-video-copy-plan.c.h` and `obs-video-output-step.c.h`, extracted from `libobs/obs-video.c.h` | `rust/obs-core` | +| `libobs/obs.c.h` and the units extracted from it (`obs-video-plan.c.h`, `obs-context-names.c.h`, `obs-source-load.c.h`), and those extracted from `libobs/obs-module.c.h` (`obs-module-paths.c.h`, `obs-module-names.c.h`, `obs-module-locale.c.h`, `obs-module-source-rules.c.h`, `obs-module-type-rules.c.h`), `libobs/obs-view-api.c.h`, and `obs-video-copy-plan.c.h` and `obs-video-output-step.c.h`, extracted from `libobs/obs-video.c.h`, and `obs-canvas-draw.c.h`, extracted from `libobs/obs.c.h` and `libobs/obs-display.c.h` | `rust/obs-core` | | `plugins/obs-nvenc/` (CUDA/NVENC loader) | `rust/obs-nvenc`, linked through `rust/obs-nvenc-plugin` | | GPU acceleration status (frontend, #846) | `rust/obs-gpu-status`, linked through `rust/obs-gpu-status-frontend` | | all libobs ports, as one C ABI drop-in | `rust/libobs-rust` | diff --git a/rust/README.md b/rust/README.md index f22219ed27..5ee2c7fc24 100644 --- a/rust/README.md +++ b/rust/README.md @@ -25,7 +25,7 @@ are in [docs/rust-port/naming.md](../docs/rust-port/naming.md#repository-layout- | `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-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`) | +| `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`); and of `libobs/obs-canvas-draw.c.h` (the canvas texture draw and display clear decisions, from `libobs/obs.c.h` and `libobs/obs-display.c.h`) | | `obs-nvenc/`, `obs-nvenc-plugin/` | Port of the `plugins/obs-nvenc` CUDA/NVENC loader, and the staticlib that plugin links | | `obs-gpu-status/`, `obs-gpu-status-frontend/` | GPU acceleration status (#846), and the staticlib the frontend links | | `obs-c-oracle/` | Test-only: original C sources compiled with `oracle_` symbols for layout and differential tests | @@ -197,6 +197,7 @@ and compares their exported symbols. `OBS_LIBOBS_BACKEND=C` is temporary rollbac | `libobs/obs-video-plan.c.h` | `obs-core::video_plan` | Swapped in hybrid `libobs` (group `libobs.ported-video-plan`). The video output plan: `obs_video_size_valid`, `obs_video_align_output_size`, `obs_video_output_size_valid` (with the check after the alignment of #1734), `obs_video_scale_type_name` and `obs_video_output_plan`, declared in `obs-internal.h` without `EXPORT`, are hidden; `obs_reset_video()` and the mix setup in `obs.c.h` (still C) call them and create the textures and surfaces from the plan. The plan is returned by value as the `#[repr(C)]` `struct obs_video_output_plan` (layout test against the C), and its technique names are `'static` `c"..."` strings, which `obs-video.c` keeps and looks up in `format_conversion.effect` by name. The `gs_color_format`, `gs_color_space` and `obs_scale_type` values are Rust constants (`video_format` and `video_colorspace` are `obs-media-io`'s), compared against the headers by the parity test; a value outside its enum takes the C's `default:` branch. The texel sizes are the C's `1.f / (float)size`, bit for bit, infinite for a zero size as in C. The sizes come from profiles, obs-websocket and scripts, so the core cannot panic, index out of bounds or overflow for any input. Intentional difference: a null pointer to `obs_video_align_output_size` is skipped (C dereferences it). Tier 3 compares every format and color space value, inside and outside the enums, at the characterization's sizes and the extremes, and random sizes, field by field and floats bit for bit. `test_video_output_plan` compiles the C into itself, so Tier 3 compares the swap; `test_video_output_formats` runs it through `obs_reset_video()` and real frames. | | `libobs/obs-video-copy-plan.c.h` | `obs-core::video_copy_plan` | Swapped in hybrid `libobs` (group `libobs.ported-video-copy-plan`). Five pure functions on plain values, declared in `obs-video-copy-plan.h` without `EXPORT` and hidden: `obs_video_gpu_copy_plan` (the copies of `set_gpu_converted_data()`: per format, each plane's row size, rows and strides, one copy of `row * rows` when the row size equals both line sizes, the packed NV12 / P010 UV plane continuing input plane 0), `obs_video_rgbx_copy_plan` (`copy_rgbx_frame()`: one copy of `linesize * height` when the line sizes match, else rows of `width * 4`), `obs_video_scale_resolution_close` (`resolution_close()`), `obs_video_scale_effect_choice` (`get_scale_effect()` with `get_scale_effect_internal()`: default when close, else bilinear low resolution under half on both axes, else the scale type's, with the bicubic-else-default fallback over a mask of the effects that loaded) and `obs_video_mix_reuse_match` (one comparison of `can_reuse_mix_texture()`). `obs-video.c.h` keeps every `memcpy()` (it runs the plan), the frame lock and unlock, `video_output_get_info()` (only when the target is not close, as before), the effect pointers (it maps the returned enum to `obs->video`'s) and the walk of the mix list; #581's unblended `draw_mix_texture()` is unchanged. The plan, the scale input and the reuse keys cross as `#[repr(C)]` structs whose layout Tier 3 checks; a mix's view crosses as a number. The arithmetic is the C's wrap for wrap: `u32` row sizes (`width * 2` and `* 4` wrap, "characterized, not endorsed") and `usize` products for the `size_t` sizes. Intentional difference, MSVC only and unreachable: `resolution_close()` subtracts in `long`; the port answers as `i64` does, which equals a 32-bit `long` for every size below 2^31 (checked for every size `obs_video_size_valid()` allows), where the C would overflow above it. `test_video_copy_plan_steps` compiles the C into itself; it has no `_rust` variant, because the shims' archive member also holds the context names, module locale and source rules, the audio mix and the source profiler, which need libobs (404 undefined references). `test_video_output_formats`, `test_scaled_mix_alpha`, `test_encoding_lag_rescale` and `test_video_output_plan` see the swap through the hybrid libobs. Tier 3 compares every result exactly over every C format value against every pattern of the six line sizes (row size, off it, or 0) at the `u32` edges (1,530,900 frames), every scale type, loaded mask, close and low resolution edge, the reuse match with each field flipped, and proptests over full-range sizes and line sizes. | | `libobs/obs-video-output-step.c.h` | `obs-core::video_output_step` | Swapped in hybrid `libobs` (group `libobs.ported-video-output-step`). Ten pure functions on plain values, declared in `obs-video-output-step.h` without `EXPORT` and hidden: `obs_video_step_activation` (`update_active_state()`: a counter above 0 is active; the base, raw and GPU frame data clears for each that was not active and is now, and the new was flags), `obs_video_step_stage` (`stage_output_texture()`: copy surface 0 from the output texture without GPU conversion, `channel_count` surfaces from the convert textures once converted, else nothing), `obs_video_step_queue`, `_queue_copy_uv` and `_queue_count` (`queue_frame()`: a duplicate when no frame is free or a repeat finds one queued, else a copy for raw output or a repeat, else a swap; the separate UV copy unless the host's NV12 planes share a texture; the count left), `obs_video_step_render_targets` and `obs_video_step_render` (`render_video()`: outputs for raw or GPU, from the encode textures for GPU; then convert, encode, stage), and `obs_video_step_ring`, `_download` and `_output` (`output_frame()`: the texture before and after `cur_texture`, wrapping at exactly `NUM_TEXTURES`; download and output for raw output). `obs-video.c.h` keeps every `gs_*` call in its order and under its conditions, the deques (and the `deque_data()` NULL check when texture-based encoding stops), `os_sem_post()`, the texture-frame host calls, `obs_host_nv12_planes_share_texture()` and `obs_host_gpu_encode_surfaces()` (it passes their answers, asked where they were), `download_frame()`'s maps, the mix list and its mutex, and both atomic loads (it passes the loaded `long`s). The decisions are split where the C asked a host or read a field between them, so no call moves. The six structs cross as `#[repr(C)]` mirrors whose layout Tier 3 checks; the queue action as its C value. Intentional difference, unreachable: where the C's `int` arithmetic overflows (undefined: `--count` at `INT_MIN`, the ring's prev of `INT_MIN` and next of `INT_MAX`), the port wraps. `test_video_output_step_steps` compiles the C into itself; it has no `_rust` variant, for the reason `test_video_copy_plan_steps` has none (the shims' archive member needs libobs). `test_video_output_formats`, `test_raw_output_video_reset`, `test_encoding_lag_rescale`, `test_scaled_mix_alpha`, `test_video_output_plan` and the texture encoder tests see the swap through the hybrid libobs. Tier 3 compares every result exactly over every flag, the counters at the `long` and `int` edges, channel counts and queue sizes at the `size_t` edges, counts and ring values over every `int` from -200,000 to 200,000 and the ends, and proptests over full-range values. | +| `libobs/obs-canvas-draw.c.h` | `obs-core::canvas_draw` | Swapped in hybrid `libobs` (group `libobs.ported-canvas-draw`). Eight pure functions on plain values, declared in `obs-canvas-draw.h` without `EXPORT` and hidden: `obs_canvas_draw_skip` (`obs_render_canvas_texture_internal()`: no mix, or a texture not rendered), `obs_canvas_draw_technique` (`DrawTonemap` for a `GS_CS_709_EXTENDED` canvas into SDR, `DrawMultiply` into `GS_CS_709_SCRGB`, else `Draw`, as `enum obs_source_draw_technique`, which the source draw decisions share; obs-core mirrors only these three values, since it cannot depend on obs-source), `obs_canvas_draw_reads_white_level` and `obs_canvas_draw_multiplier` (the white level is read into scRGB only; the white level over 80), `obs_display_clear_reads_space` and `obs_display_clear_linear` (`render_display_begin()`: the clear colour is sRGB when the host always clears in sRGB, else linear into `GS_CS_SRGB` only), and `obs_display_clear_flags` and `obs_display_clear_draws_solid` (depth and stencil, and colour without the clear workaround, which draws the colour with the solid effect instead). `obs.c.h` and `obs-display.c.h` keep every `gs_*` call in its order and under its conditions, the effect and param lookups, the blend state, the swapchain, the resize, the viewport, the solid effect, `obs_get_video_sdr_white_level()` and `obs_host_display_clear_color_always_srgb()` (they pass the values in). The white level and the clear colour's space are each a "reads" question and an answer, so neither query moves out of its branch. No intentional differences. `test_canvas_draw_steps` compiles the C into itself; it has no `_rust` variant, for the reason `test_video_copy_plan_steps` has none (the shims' archive member needs libobs). No test drives the callers through a real graphics device; the canvas tests (`test_canvas_flags`, `test_scene_private_canvas`, `test_canvas_destroy_scene_refs`, `test_shutdown_canvas_weak_ref`) run against the hybrid libobs. Tier 3 compares every result exactly over every flag, every pair of 649 colour spaces, 131,072 white level bit patterns and every multiple of 80 to 80 * 2^16, both callers' decisions in their order, and proptests over any space and any white level bit pattern. | | `libobs/obs-view-api.c.h` | `obs-core::view` | Swapped in hybrid `libobs` (group `libobs.ported-view`). Views (#1933): `obs_view_create`, `_destroy`, `_get_source`, `_set_source`, `_render`, `_add`, `_add2`, `_remove` and `_enum_video_info` are exported; `obs_view_init` and `obs_view_free`, which `obs-canvas.c` calls on the view embedded in each canvas (declared in `obs-internal.h` without `EXPORT`), are hidden. `struct obs_view` stays C in `obs-view.c.h`, embedded in `struct obs_canvas`: the C file and the shims reach its mutex, channels and type, a source's `removed` flag and the `obs->video.mixes` list only through hidden one-step accessors there (`obs_view_lock`, `obs_view_channel`, `obs_view_source_removed`, `obs_view_mix_add`, `obs_view_mix_view`, ...); the sources through the `obs_source_*` calls the C makes. The safe core runs over a `Host` trait in the C's order: `set_source` takes the new reference and swaps it under the lock, then activates the new source and deactivates and releases the old one; `render` drops removed sources and renders the others under the lock. Kept, characterized, not endorsed: `obs_view_render` releases a removed source without deactivating it, so it stays showing; `obs_view_enum_video_info` does not check the view, so NULL enumerates the mixes whose view was removed. Intentional differences: no assert on the channel (an out-of-range channel returns, as release libobs does); a NULL `enum_proc` with a matching mix panics (the C calls through it). Tier 2: `test_view`. Tier 3 runs fixed and random operation sequences through the C (oracle built with `NDEBUG`) and the shims over shared traced stand-ins, comparing the trace, results, every channel and the mixes after each step, plus `obs_view_init`/`obs_view_free` on a raw struct. | ## obs-studio-rust diff --git a/rust/obs-c-oracle/benches/port_comparison.rs b/rust/obs-c-oracle/benches/port_comparison.rs index 7c9c822846..a461a9dbbc 100644 --- a/rust/obs-c-oracle/benches/port_comparison.rs +++ b/rust/obs-c-oracle/benches/port_comparison.rs @@ -8,6 +8,8 @@ use std::{fmt::Debug, hint::black_box}; mod audio; #[path = "port_comparison/callback.rs"] mod callback; +#[path = "port_comparison/canvas_draw.rs"] +mod canvas_draw; #[path = "port_comparison/codecs.rs"] mod codecs; #[path = "port_comparison/conversions.rs"] @@ -143,6 +145,7 @@ fn comparisons(criterion: &mut Criterion) { modules![ audio, callback, + canvas_draw, codecs, conversions, core_units, diff --git a/rust/obs-c-oracle/benches/port_comparison/canvas_draw.rs b/rust/obs-c-oracle/benches/port_comparison/canvas_draw.rs new file mode 100644 index 0000000000..c35d92ad91 --- /dev/null +++ b/rust/obs-c-oracle/benches/port_comparison/canvas_draw.rs @@ -0,0 +1,170 @@ +//! obs-core: the canvas texture draw and display clear decisions +//! (`libobs/obs-canvas-draw.c.h`), which `obs_render_canvas_texture_internal()` +//! runs once a frame for each canvas drawn into a display, and +//! `render_display_begin()` once a frame for each display. Each measurement +//! runs 1024 calls that reach every branch, and folds the results into a +//! checksum that both sides must match: +//! - `canvas_texture`: the decisions of one canvas draw in its order (the +//! skip, the technique, the white level read and the multiplier only when +//! it is read), over both skip flags, every pair of colour spaces and +//! white levels of 80 to 480 nits; +//! - `display_begin`: the clear colour (the host's answer, then the space +//! only when it is read), the clear flags and the workaround, over both +//! host answers, every colour space and both workaround values. +//! +//! Neither side allocates, so the module leaves no allocation live. +//! +//! Measured when it was added (x86_64 Linux, GCC, not pinned to a core, a +//! machine at a load average of 29 to 35; median per 1024 calls, two runs): +//! canvas_texture 10.4 and 8.7 us Rust, 5.6 and 13.4 us C; display_begin +//! 7.8 and 8.8 us Rust, 5.8 and 13.4 us C. About 5 to 13 ns a call either +//! way, within the noise of that host. + +use std::hint::black_box; +use std::os::raw::c_int; + +use criterion::{Criterion, Throughput}; +use obs_c_oracle::canvas_draw as c; +use obs_core::ffi::canvas_draw as rs; + +const CALLS: usize = 1024; + +/// A small deterministic generator, so both sides see the same calls. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + self.0 >> 11 + } +} + +fn small(r: u64, n: u64) -> c_int { + c_int::try_from(r % n).unwrap() +} + +#[derive(Clone, Copy)] +struct Draw { + has_mix: bool, + rendered: bool, + source_space: c_int, + current_space: c_int, + white: f32, + always_srgb: bool, + workaround: bool, +} + +fn draws() -> Vec { + let mut rng = Lcg(2240); + (0..CALLS) + .map(|_| { + let r = rng.next(); + Draw { + // mostly drawn, as a live canvas is + has_mix: !(r & 15).is_multiple_of(16), + rendered: !((r >> 20) & 7).is_multiple_of(8), + source_space: small(r >> 4, 4), + current_space: small(r >> 8, 4), + white: [80.0, 203.0, 300.0, 480.0][usize::try_from((r >> 12) % 4).unwrap()], + always_srgb: (r >> 14).is_multiple_of(2), + workaround: (r >> 15).is_multiple_of(2), + } + }) + .collect() +} + +struct Side { + skip: fn(bool, bool) -> u8, + technique: fn(c_int, c_int) -> u32, + reads_white_level: fn(c_int) -> u8, + multiplier: fn(f32) -> f32, + reads_space: fn(bool) -> u8, + linear: fn(c_int) -> u8, + flags: fn(bool) -> u32, + draws_solid: fn(bool) -> u8, +} + +const RUST: Side = Side { + skip: |m, t| u8::from(rs::obs_canvas_draw_skip(m, t)), + technique: |s, c| rs::obs_canvas_draw_technique(s, c), + reads_white_level: |c| u8::from(rs::obs_canvas_draw_reads_white_level(c)), + multiplier: |w| rs::obs_canvas_draw_multiplier(w), + reads_space: |a| u8::from(rs::obs_display_clear_reads_space(a)), + linear: |c| u8::from(rs::obs_display_clear_linear(c)), + flags: |w| rs::obs_display_clear_flags(w), + draws_solid: |w| u8::from(rs::obs_display_clear_draws_solid(w)), +}; + +// SAFETY (each): the oracle functions take and return plain values. +const C: Side = Side { + skip: |m, t| unsafe { c::oracle_obs_canvas_draw_skip(m, t) }, + technique: |s, cs| unsafe { c::oracle_obs_canvas_draw_technique(s, cs) }, + reads_white_level: |cs| unsafe { c::oracle_obs_canvas_draw_reads_white_level(cs) }, + multiplier: |w| unsafe { c::oracle_obs_canvas_draw_multiplier(w) }, + reads_space: |a| unsafe { c::oracle_obs_display_clear_reads_space(a) }, + linear: |cs| unsafe { c::oracle_obs_display_clear_linear(cs) }, + flags: |w| unsafe { c::oracle_obs_display_clear_flags(w) }, + draws_solid: |w| unsafe { c::oracle_obs_display_clear_draws_solid(w) }, +}; + +fn fold(sum: u64, value: u64) -> u64 { + sum.wrapping_mul(31).wrapping_add(value) +} + +fn canvas_texture(side: &Side, draws: &[Draw]) -> u64 { + let mut sum = 0u64; + for d in draws { + let d = black_box(*d); + let skip = (side.skip)(d.has_mix, d.has_mix && d.rendered); + sum = fold(sum, u64::from(skip)); + if skip != 0 { + continue; + } + let technique = (side.technique)(d.source_space, d.current_space); + let multiplier = if (side.reads_white_level)(d.current_space) != 0 { + (side.multiplier)(d.white) + } else { + 1.0 + }; + sum = fold(sum, u64::from(technique)); + sum = fold(sum, u64::from(multiplier.to_bits())); + } + sum +} + +fn display_begin(side: &Side, draws: &[Draw]) -> u64 { + let mut sum = 0u64; + for d in draws { + let d = black_box(*d); + let linear = (side.reads_space)(d.always_srgb) != 0 && (side.linear)(d.current_space) != 0; + sum = fold(sum, u64::from(linear)); + sum = fold(sum, u64::from((side.flags)(d.workaround))); + sum = fold(sum, u64::from((side.draws_solid)(d.workaround))); + } + sum +} + +pub(crate) fn benchmarks(criterion: &mut Criterion) { + let draws = draws(); + for (name, run) in [ + ( + "canvas_texture", + canvas_texture as fn(&Side, &[Draw]) -> u64, + ), + ("display_begin", display_begin), + ] { + assert_eq!( + run(&RUST, &draws), + run(&C, &draws), + "benchmark fixture differs: {name}" + ); + let mut group = criterion.benchmark_group(format!("canvas_draw/{name}")); + group.throughput(Throughput::Elements(CALLS as u64)); + group.bench_function("rust", |b| b.iter(|| black_box(run(&RUST, &draws)))); + group.bench_function("c", |b| b.iter(|| black_box(run(&C, &draws)))); + group.finish(); + } +} diff --git a/rust/obs-core/Cargo.toml b/rust/obs-core/Cargo.toml index 2bbc1573a2..cf678b4a52 100644 --- a/rust/obs-core/Cargo.toml +++ b/rust/obs-core/Cargo.toml @@ -2,7 +2,7 @@ autotests = false name = "obs-core" version = "0.1.0" -description = "Rust ports of the units extracted from the libobs core: libobs/obs-video-plan.c.h, libobs/obs-context-names.c.h, libobs/obs-module-paths.c.h, libobs/obs-module-names.c.h, libobs/obs-module-locale.c.h, libobs/obs-module-source-rules.c.h, libobs/obs-module-type-rules.c.h, libobs/obs-audio-mix.c.h, libobs/util/source-profiler.c.h, libobs/obs-view-api.c.h, libobs/obs-video-copy-plan.c.h, libobs/obs-source-load.c.h, libobs/obs-video-output-step.c.h" +description = "Rust ports of the units extracted from the libobs core: libobs/obs-video-plan.c.h, libobs/obs-context-names.c.h, libobs/obs-module-paths.c.h, libobs/obs-module-names.c.h, libobs/obs-module-locale.c.h, libobs/obs-module-source-rules.c.h, libobs/obs-module-type-rules.c.h, libobs/obs-audio-mix.c.h, libobs/util/source-profiler.c.h, libobs/obs-view-api.c.h, libobs/obs-video-copy-plan.c.h, libobs/obs-source-load.c.h, libobs/obs-video-output-step.c.h, libobs/obs-canvas-draw.c.h" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/rust/obs-core/src/lib.rs b/rust/obs-core/src/lib.rs index b2a4a7422d..3bcf1812e2 100644 --- a/rust/obs-core/src/lib.rs +++ b/rust/obs-core/src/lib.rs @@ -11,17 +11,21 @@ //! and `libobs/obs-video-output-step.c.h` (from `obs-video.c.h`), the output //! frame copy plan and scale effect choice, and the per-frame video output //! step decisions; and `libobs/obs-source-load.c.h` (from `obs.c.h`), the -//! source load migration and value rules. +//! source load migration and value rules; and `libobs/obs-canvas-draw.c.h` +//! (from `obs.c.h` and `obs-display.c.h`), the canvas texture draw and +//! display clear decisions. //! //! The safe cores are [`video_plan`], [`context_names`], [`module_paths`], //! [`module_names`], [`module_locale`], [`module_source_rules`], //! [`module_type_rules`], [`audio_mix`], [`source_profiler`], [`view`], -//! [`video_copy_plan`], [`video_output_step`] and [`source_load`]. +//! [`video_copy_plan`], [`video_output_step`], [`source_load`] and +//! [`canvas_draw`]. //! [`video_plan`] sizes the conversion textures; [`video_output_step`] //! decides, each frame, what is rendered, converted, staged, queued for the //! GPU encoders and downloaded; [`video_copy_plan`] plans the copies of a -//! downloaded frame into each output frame. The C ABI shims live in -//! [`ffi`]. +//! downloaded frame into each output frame; [`canvas_draw`] picks the +//! technique a canvas texture draws into a display with, and how the display +//! is cleared. The C ABI shims live in [`ffi`]. #![deny(unsafe_code)]