diff --git a/Cargo.toml b/Cargo.toml index d415462374..64adb6bd9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -93,8 +93,12 @@ codegen-units = 256 # Standalone source-step fixtures must not pull module lookup's core-global # adapter merely because release codegen groups unrelated source FFI modules. # Keep the source modules separate, matching the other standalone consumers. +# obs-source has more than 256 modules, so at 256 rustc merges small ones: the +# source_render port (#5976) put obs_source_get_private_settings in the +# push-to-enable signal's member, and every standalone source fixture then +# failed to link obs_source_private_settings_fields. 1024 leaves headroom. [profile.release.package.obs-source] -codegen-units = 256 +codegen-units = 1024 # Output module lookup also reaches the core global. Keep unrelated standalone # Rust-static output/encoder consumers in separate optimized archive members. diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index a15d0ffd88..fa029a39b7 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -78,6 +78,7 @@ #include "libobs/obs-source-boolean-query-fields.c.h" #include "libobs/obs-source-canvas-getter-fields.c.h" #include "libobs/obs-source-caption-callback-fields.c.h" +#include "libobs/obs-source-convert-render-fields.c.h" #include "libobs/obs-source-copy-filters-fields.c.h" #include "libobs/obs-source-default-flags-fields.c.h" #include "libobs/obs-source-default-render-fields.c.h" diff --git a/libobs/build/libobs.ported-source-convert-render+.h.c b/libobs/build/libobs.ported-source-convert-render+.h.c new file mode 100644 index 0000000000..daa80348f9 --- /dev/null +++ b/libobs/build/libobs.ported-source-convert-render+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original source_render and its hidden wrapper for C reference. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-convert-render.c.h" diff --git a/libobs/build/ported-source-sets/source-convert-render.json b/libobs/build/ported-source-sets/source-convert-render.json new file mode 100644 index 0000000000..7721eb226e --- /dev/null +++ b/libobs/build/ported-source-sets/source-convert-render.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-convert-render+.h.c" + ] +} diff --git a/libobs/cmake/rust-hidden.d/obs-source-source_convert_render.txt b/libobs/cmake/rust-hidden.d/obs-source-source_convert_render.txt new file mode 100644 index 0000000000..bb6930e62c --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-source-source_convert_render.txt @@ -0,0 +1,5 @@ +# obs-source-convert-render.c.h (#5976): source_render(), the draw behind +# obs_source_default_render() and obs_source_main_render(), through its +# wrapper. Declared in obs-source.c.h without EXPORT, so the shim stays +# hidden. +obs_source_default_render_source_render diff --git a/libobs/obs-source-convert-render-fields.c.h b/libobs/obs-source-convert-render-fields.c.h new file mode 100644 index 0000000000..8c1f6067d8 --- /dev/null +++ b/libobs/obs-source-convert-render-fields.c.h @@ -0,0 +1,249 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters of the Rust source_render() (its hidden wrapper + * obs_source_default_render_source_render(), declared in obs-source.c.h, no + * EXPORT; obs-source::ffi::source_convert_render, #5976), each one access of + * obs-source-convert-render.c.h: the profiler's begin and end, + * context.data, the current and the source's colour spaces, the format of a + * space, the SDR white level, color_space_texrender (read and written) and + * its format, destroy, create, reset, begin, end and texture, the base size, + * blending, the clear, the ortho, the source's video_render, the default + * effect, the technique and param lookups, the framebuffer sRGB flag, the + * texture and float sets, the blend stack, the technique and pass calls and + * the sprite. The caller passes a live source and runs in the graphics + * context the render holds. */ + +/* The values the Rust core passes as numbers. */ +_Static_assert(GS_BLEND_ONE == 1, "GS_BLEND_ONE"); +_Static_assert(GS_BLEND_INVSRCALPHA == 5, "GS_BLEND_INVSRCALPHA"); +_Static_assert(GS_ZS_NONE == 0, "GS_ZS_NONE"); +_Static_assert(GS_CLEAR_COLOR == 1, "GS_CLEAR_COLOR"); +_Static_assert(sizeof(enum gs_blend_type) == sizeof(int), "enum gs_blend_type is passed as int"); +_Static_assert(sizeof(enum gs_zstencil_format) == sizeof(int), "enum gs_zstencil_format is passed as int"); +_Static_assert(sizeof(enum gs_color_format) == sizeof(int), "enum gs_color_format is passed as int"); +_Static_assert(sizeof(enum gs_color_space) == sizeof(int), "enum gs_color_space is passed as int"); +_Static_assert(sizeof(enum obs_source_draw_technique) == sizeof(int), "the technique is passed as int"); + +uint64_t obs_source_convert_render_begin(gs_timer_t **timer); +uint64_t obs_source_convert_render_begin(gs_timer_t **timer) +{ + return source_profiler_source_render_begin(timer); +} + +void obs_source_convert_render_end(obs_source_t *source, uint64_t start, gs_timer_t *timer); +void obs_source_convert_render_end(obs_source_t *source, uint64_t start, gs_timer_t *timer) +{ + source_profiler_source_render_end(source, start, timer); +} + +void *obs_source_convert_render_data(const obs_source_t *source); +void *obs_source_convert_render_data(const obs_source_t *source) +{ + return source->context.data; +} + +int obs_source_convert_render_color_space(void); +int obs_source_convert_render_color_space(void) +{ + return (int)gs_get_color_space(); +} + +int obs_source_convert_render_source_space(obs_source_t *source, int current); +int obs_source_convert_render_source_space(obs_source_t *source, int current) +{ + const enum gs_color_space current_space = (enum gs_color_space)current; + return (int)obs_source_get_color_space(source, 1, ¤t_space); +} + +int obs_source_convert_render_format(int space); +int obs_source_convert_render_format(int space) +{ + return (int)gs_get_format_from_space((enum gs_color_space)space); +} + +float obs_source_convert_render_sdr_white_level(void); +float obs_source_convert_render_sdr_white_level(void) +{ + return obs_get_video_sdr_white_level(); +} + +gs_texrender_t *obs_source_convert_render_texrender(const obs_source_t *source); +gs_texrender_t *obs_source_convert_render_texrender(const obs_source_t *source) +{ + return source->color_space_texrender; +} + +void obs_source_convert_render_set_texrender(obs_source_t *source, gs_texrender_t *texrender); +void obs_source_convert_render_set_texrender(obs_source_t *source, gs_texrender_t *texrender) +{ + source->color_space_texrender = texrender; +} + +int obs_source_convert_render_texrender_format(const gs_texrender_t *texrender); +int obs_source_convert_render_texrender_format(const gs_texrender_t *texrender) +{ + return (int)gs_texrender_get_format(texrender); +} + +void obs_source_convert_render_texrender_destroy(gs_texrender_t *texrender); +void obs_source_convert_render_texrender_destroy(gs_texrender_t *texrender) +{ + gs_texrender_destroy(texrender); +} + +gs_texrender_t *obs_source_convert_render_texrender_create(int format, int zsformat); +gs_texrender_t *obs_source_convert_render_texrender_create(int format, int zsformat) +{ + return gs_texrender_create((enum gs_color_format)format, (enum gs_zstencil_format)zsformat); +} + +void obs_source_convert_render_texrender_reset(gs_texrender_t *texrender); +void obs_source_convert_render_texrender_reset(gs_texrender_t *texrender) +{ + gs_texrender_reset(texrender); +} + +uint32_t obs_source_convert_render_width(obs_source_t *source); +uint32_t obs_source_convert_render_width(obs_source_t *source) +{ + return obs_source_base_width(source); +} + +uint32_t obs_source_convert_render_height(obs_source_t *source); +uint32_t obs_source_convert_render_height(obs_source_t *source) +{ + return obs_source_base_height(source); +} + +bool obs_source_convert_render_texrender_begin(gs_texrender_t *texrender, uint32_t cx, uint32_t cy, int space); +bool obs_source_convert_render_texrender_begin(gs_texrender_t *texrender, uint32_t cx, uint32_t cy, int space) +{ + return gs_texrender_begin_with_color_space(texrender, cx, cy, (enum gs_color_space)space); +} + +void obs_source_convert_render_enable_blending(bool enable); +void obs_source_convert_render_enable_blending(bool enable) +{ + gs_enable_blending(enable); +} + +void obs_source_convert_render_clear(uint32_t flags, const struct vec4 *color, float depth, uint8_t stencil); +void obs_source_convert_render_clear(uint32_t flags, const struct vec4 *color, float depth, uint8_t stencil) +{ + gs_clear(flags, color, depth, stencil); +} + +void obs_source_convert_render_ortho(float left, float right, float top, float bottom, float znear, float zfar); +void obs_source_convert_render_ortho(float left, float right, float top, float bottom, float znear, float zfar) +{ + gs_ortho(left, right, top, bottom, znear, zfar); +} + +void obs_source_convert_render_video_render(obs_source_t *source, void *data, gs_effect_t *effect); +void obs_source_convert_render_video_render(obs_source_t *source, void *data, gs_effect_t *effect) +{ + source->info.video_render(data, effect); +} + +void obs_source_convert_render_texrender_end(gs_texrender_t *texrender); +void obs_source_convert_render_texrender_end(gs_texrender_t *texrender) +{ + gs_texrender_end(texrender); +} + +gs_effect_t *obs_source_convert_render_default_effect(void); +gs_effect_t *obs_source_convert_render_default_effect(void) +{ + return obs->video.default_effect; +} + +gs_technique_t *obs_source_convert_render_technique(gs_effect_t *effect, int technique); +gs_technique_t *obs_source_convert_render_technique(gs_effect_t *effect, int technique) +{ + return gs_effect_get_technique(effect, + obs_source_draw_technique_name((enum obs_source_draw_technique)technique)); +} + +bool obs_source_convert_render_framebuffer_srgb(void); +bool obs_source_convert_render_framebuffer_srgb(void) +{ + return gs_framebuffer_srgb_enabled(); +} + +void obs_source_convert_render_enable_framebuffer_srgb(bool enable); +void obs_source_convert_render_enable_framebuffer_srgb(bool enable) +{ + gs_enable_framebuffer_srgb(enable); +} + +gs_texture_t *obs_source_convert_render_texrender_texture(const gs_texrender_t *texrender); +gs_texture_t *obs_source_convert_render_texrender_texture(const gs_texrender_t *texrender) +{ + return gs_texrender_get_texture(texrender); +} + +gs_eparam_t *obs_source_convert_render_param(gs_effect_t *effect, const char *name); +gs_eparam_t *obs_source_convert_render_param(gs_effect_t *effect, const char *name) +{ + return gs_effect_get_param_by_name(effect, name); +} + +void obs_source_convert_render_set_texture_srgb(gs_eparam_t *param, gs_texture_t *tex); +void obs_source_convert_render_set_texture_srgb(gs_eparam_t *param, gs_texture_t *tex) +{ + gs_effect_set_texture_srgb(param, tex); +} + +void obs_source_convert_render_set_float(gs_eparam_t *param, float value); +void obs_source_convert_render_set_float(gs_eparam_t *param, float value) +{ + gs_effect_set_float(param, value); +} + +void obs_source_convert_render_blend_push(void); +void obs_source_convert_render_blend_push(void) +{ + gs_blend_state_push(); +} + +void obs_source_convert_render_blend_function(int src, int dest); +void obs_source_convert_render_blend_function(int src, int dest) +{ + gs_blend_function((enum gs_blend_type)src, (enum gs_blend_type)dest); +} + +size_t obs_source_convert_render_technique_begin(gs_technique_t *tech); +size_t obs_source_convert_render_technique_begin(gs_technique_t *tech) +{ + return gs_technique_begin(tech); +} + +void obs_source_convert_render_begin_pass(gs_technique_t *tech, size_t pass); +void obs_source_convert_render_begin_pass(gs_technique_t *tech, size_t pass) +{ + gs_technique_begin_pass(tech, pass); +} + +void obs_source_convert_render_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, uint32_t height); +void obs_source_convert_render_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, uint32_t height) +{ + gs_draw_sprite(tex, flip, width, height); +} + +void obs_source_convert_render_end_pass(gs_technique_t *tech); +void obs_source_convert_render_end_pass(gs_technique_t *tech) +{ + gs_technique_end_pass(tech); +} + +void obs_source_convert_render_technique_end(gs_technique_t *tech); +void obs_source_convert_render_technique_end(gs_technique_t *tech) +{ + gs_technique_end(tech); +} + +void obs_source_convert_render_blend_pop(void); +void obs_source_convert_render_blend_pop(void) +{ + gs_blend_state_pop(); +} diff --git a/libobs/obs-source-convert-render.c.h b/libobs/obs-source-convert-render.c.h new file mode 100644 index 0000000000..7daf8024a2 --- /dev/null +++ b/libobs/obs-source-convert-render.c.h @@ -0,0 +1,98 @@ +#include "libobs/build/libobs.pch.h" + +/* source_render(), the draw behind obs_source_default_render() and + * obs_source_main_render(): the source's own video_render, drawn straight or, + * when its colour space differs from the target's, through + * color_space_texrender and the default effect. Moved verbatim out of + * obs-source.c.h with its hidden wrapper + * obs_source_default_render_source_render() (no EXPORT) (#5976). Every + * decision is in obs-source-draw-plan.c; this keeps the profiler bracket, the + * source's fields, the texrender cache and the graphics calls. */ + +static void source_render(obs_source_t *source, gs_effect_t *effect) +{ + gs_timer_t *timer = NULL; + const uint64_t start = source_profiler_source_render_begin(&timer); + + void *const data = source->context.data; + const enum gs_color_space current_space = gs_get_color_space(); + const enum gs_color_space source_space = obs_source_get_color_space(source, 1, ¤t_space); + + enum gs_color_format format = gs_get_format_from_space(source_space); + const bool convert = obs_source_draw_plan_convert((int)source_space, (int)current_space); + const char *convert_tech = obs_source_draw_technique_name( + obs_source_draw_plan_technique((int)source_space, (int)current_space, false)); + const float multiplier = obs_source_draw_plan_reads_white_level((int)source_space, (int)current_space) + ? obs_source_draw_plan_multiplier((int)source_space, (int)current_space, + obs_get_video_sdr_white_level()) + : 1.0f; + + if (convert) { + if (source->color_space_texrender) { + if (gs_texrender_get_format(source->color_space_texrender) != format) { + gs_texrender_destroy(source->color_space_texrender); + source->color_space_texrender = NULL; + } + } + + if (!source->color_space_texrender) { + source->color_space_texrender = gs_texrender_create(format, GS_ZS_NONE); + } + + gs_texrender_reset(source->color_space_texrender); + const uint32_t cx = obs_source_base_width(source); + const uint32_t cy = obs_source_base_height(source); + if (gs_texrender_begin_with_color_space(source->color_space_texrender, cx, cy, source_space)) { + gs_enable_blending(false); + + struct vec4 clear_color; + vec4_zero(&clear_color); + gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); + + source->info.video_render(data, effect); + + gs_enable_blending(true); + + gs_texrender_end(source->color_space_texrender); + + gs_effect_t *default_effect = obs->video.default_effect; + gs_technique_t *tech = gs_effect_get_technique(default_effect, convert_tech); + + const bool previous = gs_framebuffer_srgb_enabled(); + gs_enable_framebuffer_srgb(true); + + gs_texture_t *const tex = gs_texrender_get_texture(source->color_space_texrender); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(default_effect, "image"), tex); + gs_effect_set_float(gs_effect_get_param_by_name(default_effect, "multiplier"), multiplier); + + gs_blend_state_push(); + gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); + + const size_t passes = gs_technique_begin(tech); + for (size_t i = 0; i < passes; i++) { + gs_technique_begin_pass(tech, i); + gs_draw_sprite(tex, 0, 0, 0); + gs_technique_end_pass(tech); + } + gs_technique_end(tech); + + gs_blend_state_pop(); + + gs_enable_framebuffer_srgb(previous); + } + } else { + source->info.video_render(data, effect); + } + source_profiler_source_render_end(source, start, timer); +} + +/* The static draw obs_source_default_render() makes + * (obs-source-default-render.c.h, and its fields adapter + * obs-source-default-render-fields.c.h for the Rust port). Hidden: no + * EXPORT. */ +void obs_source_default_render_source_render(obs_source_t *source, gs_effect_t *effect); +void obs_source_default_render_source_render(obs_source_t *source, gs_effect_t *effect) +{ + source_render(source, effect); +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index 557f485c01..3011948c05 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -556,93 +556,11 @@ _Static_assert(OBS_SOURCE_SIZE_TYPE_FILTER == OBS_SOURCE_TYPE_FILTER, "OBS_SOURC _Static_assert(OBS_SOURCE_SIZE_TYPE_TRANSITION == OBS_SOURCE_TYPE_TRANSITION, "OBS_SOURCE_TYPE_TRANSITION"); _Static_assert(sizeof(enum obs_source_type) == sizeof(int), "enum obs_source_type is passed as int"); -static void source_render(obs_source_t *source, gs_effect_t *effect) -{ - gs_timer_t *timer = NULL; - const uint64_t start = source_profiler_source_render_begin(&timer); - - void *const data = source->context.data; - const enum gs_color_space current_space = gs_get_color_space(); - const enum gs_color_space source_space = obs_source_get_color_space(source, 1, ¤t_space); - - enum gs_color_format format = gs_get_format_from_space(source_space); - const bool convert = obs_source_draw_plan_convert((int)source_space, (int)current_space); - const char *convert_tech = obs_source_draw_technique_name( - obs_source_draw_plan_technique((int)source_space, (int)current_space, false)); - const float multiplier = obs_source_draw_plan_reads_white_level((int)source_space, (int)current_space) - ? obs_source_draw_plan_multiplier((int)source_space, (int)current_space, - obs_get_video_sdr_white_level()) - : 1.0f; - - if (convert) { - if (source->color_space_texrender) { - if (gs_texrender_get_format(source->color_space_texrender) != format) { - gs_texrender_destroy(source->color_space_texrender); - source->color_space_texrender = NULL; - } - } - - if (!source->color_space_texrender) { - source->color_space_texrender = gs_texrender_create(format, GS_ZS_NONE); - } - - gs_texrender_reset(source->color_space_texrender); - const uint32_t cx = obs_source_base_width(source); - const uint32_t cy = obs_source_base_height(source); - if (gs_texrender_begin_with_color_space(source->color_space_texrender, cx, cy, source_space)) { - gs_enable_blending(false); - - struct vec4 clear_color; - vec4_zero(&clear_color); - gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); - gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); - - source->info.video_render(data, effect); - - gs_enable_blending(true); - - gs_texrender_end(source->color_space_texrender); - - gs_effect_t *default_effect = obs->video.default_effect; - gs_technique_t *tech = gs_effect_get_technique(default_effect, convert_tech); - - const bool previous = gs_framebuffer_srgb_enabled(); - gs_enable_framebuffer_srgb(true); - - gs_texture_t *const tex = gs_texrender_get_texture(source->color_space_texrender); - gs_effect_set_texture_srgb(gs_effect_get_param_by_name(default_effect, "image"), tex); - gs_effect_set_float(gs_effect_get_param_by_name(default_effect, "multiplier"), multiplier); - - gs_blend_state_push(); - gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - - const size_t passes = gs_technique_begin(tech); - for (size_t i = 0; i < passes; i++) { - gs_technique_begin_pass(tech, i); - gs_draw_sprite(tex, 0, 0, 0); - gs_technique_end_pass(tech); - } - gs_technique_end(tech); - - gs_blend_state_pop(); - - gs_enable_framebuffer_srgb(previous); - } - } else { - source->info.video_render(data, effect); - } - source_profiler_source_render_end(source, start, timer); -} - -/* The static draw obs_source_default_render() makes - * (obs-source-default-render.c.h, and its fields adapter - * obs-source-default-render-fields.c.h for the Rust port). Hidden: no - * EXPORT. */ +/* source_render(), the draw behind obs_source_default_render() and + * obs_source_main_render(), and its hidden wrapper + * obs_source_default_render_source_render() (no EXPORT) are in + * obs-source-convert-render.c.h (#5976). */ void obs_source_default_render_source_render(obs_source_t *source, gs_effect_t *effect); -void obs_source_default_render_source_render(obs_source_t *source, gs_effect_t *effect) -{ - source_render(source, effect); -} _Static_assert(sizeof(enum obs_source_type) == sizeof(int), "enum obs_source_type is passed as int"); _Static_assert(sizeof(enum obs_allow_direct_render) == sizeof(int), "enum obs_allow_direct_render is passed as int"); diff --git a/rust/README.md b/rust/README.md index dc92d8b92e..cfab97d4df 100644 --- a/rust/README.md +++ b/rust/README.md @@ -462,6 +462,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-source-color-space.c.h` | `obs-source::color_space` | Swapped in hybrid `libobs` (group `libobs.ported-source-color-space`). The colour space query routing of `obs_source_get_color_space()`, as two functions: `obs_source_color_space_route()` (which source answers: a non-filter without video asks its filter parent; a filter without video asks its target, #1493; a source without data, or disabled, asks its target; an async source picks; anything else asks its callback, in that order) and `obs_source_color_space_pick()` (the async pick: the first preferred space equal to the frame's space, else the last one, else the frame's space). They are declared in `obs-source-color-space.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps `data_valid()`, reads `info.type`, `info.output_flags`, `context.data != NULL`, `enabled`, `filter_parent != NULL` and `filter_target != NULL` into `struct obs_source_color_space_node` (passed by value, mirrored), and keeps the recursion into the parent or target, `convert_video_space()` of the async frame (it passes the frame's space) and the `video_get_color_space` callback. No source pointer crosses. Colour spaces cross as `int`; `obs-source.c.h` checks that `enum gs_color_space` and `enum obs_source_type` are `int`-sized and that the header's filter type and flags match `obs-source.h`. Only `OBS_SOURCE_TYPE_FILTER` is a filter and only the VIDEO and ASYNC bits count. Kept, characterized, not endorsed: a filter flagged async picks unless the earlier rules send it to its target; with no data and nowhere to go the route is the callback or the pick (`data_valid()` keeps libobs from getting there); a value outside the enum in the preferred list is compared and returned as it is. Intentional difference: a null preferred list with a count above 0 is read as empty (the C reads through the null pointer; libobs passes `NULL` only with a count of 0). `test_source_color_space_steps` compiles the C into itself, and `test_source_color_space_steps_rust` runs the same test source against `libobs_rust-static`; `test_filter_color_space` (the HDR Tone Mapping chains of #1493) sees the swap through the real libobs. Tier 3 compares the route over every row of the characterization with eight types and sixteen sets of other flags, a proptest over any node, the pick over every list of 0 to 5 values from -1..=4 and a proptest over lists of 0 to 8 arbitrary `i32` values. | | `libobs/obs-source-configurable.c.h` | `obs-source::configurable` | #5117: `obs_source_configurable()` answers true only for a source with live data and either property callback, never calling either one or consulting the type registry; a NULL source logs its `LOG_DEBUG` line and answers false, a source without data answers false silently. Safe Rust core; the shim reads the existing `obs_source_properties_instance_fields()` adapter after rejecting NULL, so no new layout adapter or link support. The original C (with its `data_valid` macro) moves to the reference-only group `libobs.ported-source-configurable`. The unchanged C characterization runs against hybrid and reference libraries; Tier 3 runs the original C and the Rust export over every flag combination with noise-filled sources whose type id is never registered. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-conversion-plan.c.h` | `obs-source::conversion_plan` | Swapped in hybrid `libobs` (group `libobs.ported-source-conversion-plan`). The async video GPU conversion plan of `obs-source.c`, as one function: `obs_source_conversion_plan_fill()` takes the frame's format, range, transfer and size and fills `struct obs_source_conversion_plan` (mirrored): the convert type (`get_convert_type()`), the channel count and each plane's width, height and texture format (the nineteen `set_*_sizes()` of `init_gpu_conversion()`; the RGB limited plane takes `convert_video_format()`'s format, RGBA16F for PQ and HLG), the technique of `format_conversion.effect` (`select_conversion_technique()`) and the linear flag (`need_linear_output()`). It is declared in `obs-source-conversion-plan.h` without `EXPORT`, so the shim stays hidden. `obs-source.c.h` keeps `set_async_texture_size()` (the change check, the textures and texrenders, the graphics context), `upload_raw_frame()`, `update_async_texrender()` and its shader parameters, the `convert_video_format()` inline of `obs-internal.h` for its other callers, and the two asserts for a frame that needs no conversion; `get_convert_type()`, `select_conversion_technique()` and `need_linear_output()` keep their signatures and read the plan, and `init_gpu_conversion()` copies it into `async_convert_width`, `async_convert_height` and `async_texture_formats` for the plan's planes, then `async_channel_count`. The format and transfer cross as `int`, so values outside the enums take the C's `default:` paths (no conversion, no technique); the transfer is the frame's `uint8_t`, so it counts modulo 256. The technique crosses as a pointer to a `c"..."` literal of the core (a `&'static CStr`), or null: nothing is allocated. Kept, characterized, not endorsed: the sizes wrap in `u32` as the C's do near `UINT32_MAX` (`(width + 1) / 2` is 0 at `UINT32_MAX`, `width * 3` wraps from 0x55555556, `(width + 5) / 6 * 4` is 0 from `UINT32_MAX - 4`); the port uses `wrapping_*` for each. Intentional difference: a null plan is left alone (the C writes through it; libobs passes a plan on its stack). `test_async_conversion_plan` compiles the C into itself and pins the whole table (every format and two values outside the enum, both ranges, every transfer, 4 and 258, at 14 sizes up to `UINT32_MAX`, from tables generated from the moved C), and `test_async_conversion_plan_rust` runs the same test source against `libobs_rust-static`; `test_media_restart_first_frame`, `test_deinterlace_2x_field_order` and `test_pipewire_camera_nv12` see the swap through the real libobs. Tier 3 compares every field, the technique as a string, over format x range x transfer exhaustively (47 formats, 270 transfers, 22 widths and heights: 1.1 million plans), every pair of 22 sizes for the in-enum formats, and a proptest over any `u32` size and any `i32` format and transfer. | +| `libobs/obs-source-convert-render.c.h` | `obs-source::convert_render`, shim in `obs-source::ffi::source_convert_render` | #5976: swapped in hybrid `libobs` (group `libobs.ported-source-convert-render`). `source_render()`, the draw behind `obs_source_default_render()` and `obs_source_main_render()`, now the hidden Rust export of its wrapper `obs_source_default_render_source_render()` (declared in `obs-source.c.h` without `EXPORT`, hidden through `rust-hidden.d`). Inside the profiler bracket: `context.data`, the current colour space, the source's colour space asked with it as the one preferred space, and the format of the source's space; then `obs-source::draw_plan` (convert or not, the technique, and the multiplier, with the SDR white level read only into or out of scRGB, else 1). A source in the target's class (SDR, extended linear, scRGB, or a space outside the enum) is drawn straight with its own `video_render(data, effect)`. Any other pair: `color_space_texrender` read for the check, again for the format and again for `gs_texrender_destroy()` when its format is not the source's (then cleared), created with `GS_ZS_NONE` when there is none, read again for the reset, the base width and height, read again for `gs_texrender_begin_with_color_space()` in the source's space; only when that begins: blending off, cleared to zero, the ortho of the base size, `info.video_render` read and called, blending on, read again for the end; then `obs->video.default_effect` and its technique, the framebuffer sRGB flag turned on (restored after), the texture of the texrender read again set as sRGB on `image`, the multiplier on `multiplier`, the blend state pushed with `GS_BLEND_ONE`/`GS_BLEND_INVSRCALPHA`, one sprite per pass, the blend state popped. Safe core over a `Host` trait; the profiler, the fields, the colour space query, the base size and every graphics call stay C in `obs-source-convert-render-fields.c.h` (live group `libobs.core-source`, no `EXPORT`). The new `test_source_convert_render` (Linux with OpenGL; rendered on the test thread in the graphics context) runs against hybrid and reference libraries: 5 cases of a source drawn straight in its own class, extended linear and scRGB drawn through the texrender into sRGB (the box's tonemapped pixels read back, nothing outside, the framebuffer flag restored), the texrender kept while the format matches and made again when it changes, a plain source converted with the default effect, and a source of size 0 not drawn. Tier 3 runs the original C (with the oracle's original draw decisions) and the Rust export on real-layout sources through shared stand-ins of the profiler, the colour spaces, the format, the white level, every texrender call, the base size, blending, the clear, the ortho, `video_render`, the default effect, the lookups, the framebuffer flag, the sets, the blend stack and the technique, pass and sprite calls, with clobbers that repoint `context.data` from the profiler and the colour space query, repoint or clear `color_space_texrender` from the colour space query, the format query, the reset, `video_render` and the end, and swap `info.video_render` when blending goes off, over a grid of spaces, held texrenders, sizes, effects, passes, failures and clobbers, and a proptest; it compares the log (floats as bits, with the blend depth and the texrender, technique, pass, profiler and blending state), the fields, the texrenders destroyed and created, the graphics state left and every other byte, checks that every clobber reaches the C, and rejects twelve mutants. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-copy-filters.c.h` | `obs-source::copy_filters`, shims in `obs-source::ffi::source_copy_filters` | #5792: swapped in hybrid `libobs` (group `libobs.ported-source-copy-filters`). `obs_source_copy_filters()`, `obs_source_copy_single_filter()`, and `duplicate_filters()` as the hidden `obs_source_duplicate_filters()` that `obs_source_duplicate()` calls. A NULL destination, source or filter logs one `LOG_DEBUG` line (the destination first) and does nothing. The filter copy takes a reference to each of the source's filters under its `filter_mutex` (the count read before each entry, a filter whose reference fails skipped), then after the unlock copies them from the last to the first: a free name (`get_new_filter_name()`), the enabled state, `obs_source_duplicate()` (private as the destination is, or as `obs_source_duplicate()` says), the copy's enabled state, the name freed, `obs_source_filter_add()`, the copy and the reference released; a failed duplicate goes through the same calls as NULL. The single copy checks `filter_compatible()` first and copies once, always private, with no lock and no reference on the filter. Safe core over a `FilterCopy` trait; the shims reject NULL before calling the adapters of `obs-source-copy-filters-fields.c.h` (live group `libobs.core-source`, no `EXPORT`). `get_new_filter_name()` (with its lookup) and `filter_compatible()` stay in `obs-source.c.h` (hidden, declared in `obs-internal.h`). The new `test_source_copy_filters` runs against hybrid and reference libraries through the real core; `test_filter_clipboard` and the scene and source duplicate tests run the callers. Tier 3 runs the original C and the Rust exports on noise-filled real-header sources with recording stand-ins for every libobs call they make, over every count up to 7, private flag, argument pair and pattern of failing references, disabled, incompatible and failing duplicates, and a proptest, comparing every call in order with its arguments and lock state, every fixture byte, the lock and the log line; it rejects two mutants. | None. | | `libobs/obs-source-default-render.c.h` | `obs-source::default_render`, shim in `obs-source::ffi::source_default_render` | #5893: `obs_source_default_render()` swapped in hybrid `libobs` (group `libobs.ported-source-default-render`). A source without data (its create failed, or it is being destroyed) draws nothing and begins no technique. Otherwise the core's default effect is read, its `"Draw"` technique looked up and begun once; for each pass the pass begins, the source renders with the effect (`source_render()`, static in `obs-source.c.h`, through its hidden wrapper) and the pass ends; then the technique ends, also with no passes. No NULL check on the source, as in the C. Safe Rust core over a `DefaultRender` trait; the data check, the effect, every `gs_*` call and the render stay behind `obs-source-default-render-fields.c.h` (live group `libobs.core-source`, no `EXPORT`). The new `test_source_default_render` (Linux with OpenGL) draws a source on the graphics thread against hybrid and reference libraries: drawn once, with the default effect and its `"Draw"` technique current and ended after; a source without data is not drawn and no technique is begun. Tier 3 runs the original C and the Rust export on a noise-filled real-header source and a private core with recording stand-ins for every call, over every data, effect and technique state, pass counts 0 to 5 and a proptest, comparing every call in order with its arguments and every byte of the source and core; it rejects five mutants. No intentional differences; Tier 4 does not apply. | None. | | `libobs/obs-source-defaults.c.h` | `obs-source::defaults` | #5640: `obs_get_source_defaults()` and its unused hidden twin `obs_source_settings()` look the type up with the Rust `get_source_info()`; an unknown ID returns NULL and creates nothing, a known one returns a new caller-owned `obs_data_t` filled by `get_defaults2(type_data, settings)`, else `get_defaults(settings)`, else left empty. Safe Rust core; the shim reads the callbacks through the properties getter's existing `obs_source_properties_info_fields()` adapter. Unchanged C characterization (`test_source_defaults`, `test_source_info_lookup`) and original-C differential coverage over the real registry adapter. No intentional differences; Tier 4 does not apply. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 9e93b00687..9613492ae0 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -69,6 +69,8 @@ mod canonical_source_audio_volume_apply_swap_is_registered; mod canonical_source_canvas_getter_swap_is_registered; #[path = "native/registration/canonical_source_configurable_swap_is_registered.rs"] mod canonical_source_configurable_swap_is_registered; +#[path = "native/registration/canonical_source_convert_render_swap_is_registered.rs"] +mod canonical_source_convert_render_swap_is_registered; #[path = "native/registration/canonical_source_copy_filters_swap_is_registered.rs"] mod canonical_source_copy_filters_swap_is_registered; #[path = "native/registration/canonical_source_default_render_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_convert_render_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_convert_render_swap_is_registered.rs new file mode 100644 index 0000000000..8472a42b1c --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_convert_render_swap_is_registered.rs @@ -0,0 +1,71 @@ +use super::*; + +#[test] +fn canonical_source_convert_render_swap_is_registered() { + use obs_build::validation::graph::{Graph, Source}; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut graph = Graph::load(&root.join("test/cmocka/build/test-graph.json")).unwrap(); + let name = "test_source_convert_render"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + // The test compiles no copy of the draw: obs_source_video_render() of + // the real libobs reaches the hidden symbol (Rust in hybrid, the + // original C in the reference) in the graphics context. The render + // needs the OpenGL core, so only Linux selects it. + let selected = graph + .select(&[("OS_LINUX".into(), true), ("HAVE_OBS_OPENGL".into(), true)].into()) + .unwrap(); + assert!( + matches!(selected.targets[name].sources.as_slice(), [Source::Path(path)] + if path == "test/cmocka/test_source_convert_render.c") + ); + assert!(selected.targets[name].definitions.is_empty()); + assert_eq!(selected.tests[name].target, name); + for os in ["OS_MACOS", "OS_WINDOWS"] { + let facts = [ + (os.into(), true), + ("OS_LINUX".into(), false), + ("HAVE_OBS_OPENGL".into(), true), + ]; + let selected = graph.select(&facts.into()).unwrap(); + assert!(selected.targets.is_empty(), "{os}"); + } + let ported = + fs::read_to_string(root.join("libobs/build/ported-source-sets/source-convert-render.json")) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-convert-render+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-convert-render+.h.c")) + .unwrap(); + assert!(group.contains("#include \"libobs/obs-source-convert-render.c.h\"")); + let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core-source+.h.c")).unwrap(); + assert!(!hybrid.contains("#include \"libobs/obs-source-convert-render.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source-convert-render-fields.c.h\"")); + // obs-source.c.h keeps no copy of the draw. + let source = fs::read_to_string(root.join("libobs/obs-source.c.h")).unwrap(); + for step in [ + "static void source_render(obs_source_t *source, gs_effect_t *effect)\n{", + "obs_source_default_render_source_render(obs_source_t *source, gs_effect_t *effect)\n{", + ] { + assert!(!source.contains(step), "{step}"); + } + let hidden = fs::read_to_string( + root.join("libobs/cmake/rust-hidden.d/obs-source-source_convert_render.txt"), + ) + .unwrap(); + let steps = ["obs_source_default_render_source_render"]; + assert_eq!( + hidden + .lines() + .filter(|line| !line.starts_with('#')) + .collect::>(), + steps + ); + // Hidden, not exported: it has no EXPORT. + for entry in fs::read_dir(root.join("libobs/cmake/rust-exports.d")).unwrap() { + let text = fs::read_to_string(entry.unwrap().path()).unwrap(); + for step in steps { + assert!(!text.lines().any(|line| line == step), "{step}"); + } + } +} diff --git a/rust/obs-c-oracle/oracle.d/source-convert-render.list b/rust/obs-c-oracle/oracle.d/source-convert-render.list new file mode 100644 index 0000000000..dc20feb6a2 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-convert-render.list @@ -0,0 +1 @@ +source-convert-render.inc|libobs/obs-source-convert-render.c.h|auto diff --git a/rust/obs-c-oracle/oracle/source_convert_render.c b/rust/obs-c-oracle/oracle/source_convert_render.c new file mode 100644 index 0000000000..bf3c743e6a --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_convert_render.c @@ -0,0 +1,736 @@ +/* Tier 3: the unchanged extracted source_render() and its hidden wrapper + * (libobs/obs-source-convert-render.c.h), the wrapper renamed + * oracle_obs_source_default_render_source_render, against the Rust export, + * over the real source layout. The draw decisions it asks are the oracle's + * original C (source_draw_plan.c). + * + * The production adapters the Rust export calls + * (libobs/obs-source-convert-render-fields.c.h) are compiled here under + * their real names, the one definition of each in the test binaries. Both + * they and the original go through the same stand-ins: the profiler's begin + * and end, the current colour space, the source's colour space, the format + * of a space, the SDR white level, the texrender's format, destroy, create, + * reset, begin, end and texture, the base size, blending, the clear, the + * ortho, the source's video_render, the default effect (obs->video), the + * technique and param lookups, the framebuffer sRGB flag, the texture and + * float sets, the blend stack, the technique and pass calls and the sprite + * log one event each, with the blend depth and the texrender, technique, + * pass and profiler state at that moment. With the clobber bits set the + * stand-ins also rewrite context.data, color_space_texrender and + * info.video_render as they go, so a field read in another place than the + * C's shows. The log is per thread. + * + * Each side of a case (0 the C, 1 the Rust) has its own source, data, + * effects, techniques, params, textures, texrenders and timer, so the two + * can be compared by token and byte for byte afterwards. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include "libobs/build/libobs.pch.h" + +#define CR_DATA 3 +#define CR_TEXRENDERS 4 +/* the texrender gs_texrender_create() gives */ +#define CR_CREATED 3 +#define CR_TECHS 7 +#define CR_PARAMS 3 +#define CR_EVENTS 64 +/* the token of a pointer that is none of the side's */ +#define CR_FOREIGN 99 + +enum cr_kind { + CR_BEGIN = 1, + CR_END, + CR_COLOR_SPACE, + CR_SOURCE_SPACE, + CR_FORMAT, + CR_WHITE, + CR_TR_FORMAT, + CR_TR_DESTROY, + CR_TR_CREATE, + CR_TR_RESET, + CR_WIDTH, + CR_HEIGHT, + CR_TR_BEGIN, + CR_BLENDING, + CR_CLEAR, + CR_ORTHO, + CR_RENDER, + CR_TR_END, + CR_TECHNIQUE, + CR_FB_GET, + CR_FB_SET, + CR_TR_TEXTURE, + CR_PARAM, + CR_SET_TEXTURE_SRGB, + CR_SET_FLOAT, + CR_BLEND_PUSH, + CR_BLEND_FUNCTION, + CR_TECH_BEGIN, + CR_PASS_BEGIN, + CR_DRAW, + CR_PASS_END, + CR_TECH_END, + CR_BLEND_POP, + CR_RENDER_B, + CR_ORTHO_Z, + CR_CLEAR_B, +}; + +struct oracle_cr_event { + uint32_t kind; + int32_t blend; + /* bit 0: in a technique, bit 1: in a pass, bit 2: profiling, bit 3: in + * the texrender, bit 4: blending off */ + int32_t state; + int32_t pad; + int64_t a; + int64_t b; + int64_t c; + int64_t d; +}; + +struct oracle_cr_log { + uint32_t events; + struct oracle_cr_event event[CR_EVENTS]; +}; + +/* A case: the source's fields and the graphics state. A token of -1 is + * NULL. Mirrored by the parity test. */ +struct oracle_cr_spec { + uint64_t start; + float white; + int32_t current_space; + int32_t source_space; + uint32_t width; + uint32_t height; + /* the texrender the source holds, and the format of each (0 to 2) */ + int32_t texrender; + int32_t formats[CR_TEXRENDERS]; + /* the data the source holds */ + int32_t data; + /* the effect the caller passes: 0 the side's, -1 NULL */ + int32_t effect; + uint32_t passes; + /* bit 0: the profiler's begin points context.data at data 1; bit 1: + * gs_get_color_space() points it at data 2; bit 2: the texrender's + * format query points color_space_texrender at texrender 1; bit 3: + * gs_texrender_reset() points it at texrender 2; bit 4: video_render + * points it at texrender 0; bit 5: gs_enable_blending(false) swaps + * info.video_render for the second stand-in; bit 6: gs_texrender_end() + * points it at texrender 1; bit 7: obs_source_get_color_space() clears + * it */ + uint32_t clobber; + /* bit i < 6: the technique of value i is not found; bit 6: no "image"; + * bit 7: no "multiplier" */ + uint32_t missing; + bool timer; + bool create_fails; + bool begin_fails; + bool no_texture; + bool no_default_effect; + bool fb_srgb; +}; + +struct cr_object { + uint32_t id; +}; + +struct cr_side { + struct obs_source *source; + struct cr_object data[CR_DATA]; + struct cr_object effect; + struct cr_object default_effect; + struct cr_object techs[CR_TECHS]; + struct cr_object params[CR_PARAMS]; + struct cr_object textures[CR_TEXRENDERS]; + struct cr_object texrenders[CR_TEXRENDERS]; + struct cr_object timer; + int32_t formats[CR_TEXRENDERS]; + uint32_t destroyed; +}; + +static THREAD_LOCAL struct cr_side cr_sides[2]; +static THREAD_LOCAL struct oracle_cr_spec cr_spec; +static THREAD_LOCAL struct oracle_cr_log cr_log; +static THREAD_LOCAL struct cr_side *cr_watched; +static THREAD_LOCAL struct obs_core *cr_core; +static THREAD_LOCAL bool cr_fb_srgb; +static THREAD_LOCAL int32_t cr_blend; +static THREAD_LOCAL int32_t cr_state; + +static void cr_record(uint32_t kind, int64_t a, int64_t b, int64_t c, int64_t d) +{ + if (cr_log.events >= CR_EVENTS) + return; + struct oracle_cr_event *e = &cr_log.event[cr_log.events++]; + e->kind = kind; + e->blend = cr_blend; + e->state = cr_state; + e->a = a; + e->b = b; + e->c = c; + e->d = d; +} + +static int64_t cr_bits(float value) +{ + uint32_t bits; + memcpy(&bits, &value, sizeof(bits)); + return (int64_t)bits; +} + +/* The index of `p` in a table of the watched side, -1 for NULL. */ +static int32_t cr_token(const void *p, const struct cr_object *table, size_t n) +{ + if (!p) + return -1; + if (!cr_watched) + return CR_FOREIGN; + const struct cr_object *o = p; + if (o >= table && o < table + n) + return (int32_t)(o - table); + return CR_FOREIGN; +} + +#define CR_TOKEN(p, field, n) (cr_watched ? cr_token((p), cr_watched->field, (n)) : ((p) ? CR_FOREIGN : -1)) + +static int32_t cr_texrender_token(const void *p) +{ + return CR_TOKEN(p, texrenders, CR_TEXRENDERS); +} + +static void *cr_texrender_ptr(int32_t token) +{ + if (!cr_watched || token < 0 || token >= CR_TEXRENDERS) + return NULL; + return &cr_watched->texrenders[token]; +} + +static void *cr_data_ptr(int32_t token) +{ + if (!cr_watched || token < 0 || token >= CR_DATA) + return NULL; + return &cr_watched->data[token]; +} + +static uint64_t cr_begin(gs_timer_t **timer) +{ + cr_record(CR_BEGIN, timer && *timer == NULL ? 1 : 0, 0, 0, 0); + cr_state |= 4; + if (timer) + *timer = cr_spec.timer && cr_watched ? (gs_timer_t *)&cr_watched->timer : NULL; + if ((cr_spec.clobber & 1) && cr_watched) + cr_watched->source->context.data = cr_data_ptr(1); + return cr_spec.start; +} + +static void cr_end(obs_source_t *source, uint64_t start, gs_timer_t *timer) +{ + cr_state &= ~4; + cr_record(CR_END, cr_watched && source == cr_watched->source ? 1 : 0, (int64_t)start, + cr_watched ? cr_token(timer, &cr_watched->timer, 1) : -1, 0); +} + +static enum gs_color_space cr_color_space(void) +{ + cr_record(CR_COLOR_SPACE, 0, 0, 0, 0); + if ((cr_spec.clobber & 2) && cr_watched) + cr_watched->source->context.data = cr_data_ptr(2); + return (enum gs_color_space)cr_spec.current_space; +} + +static enum gs_color_space cr_source_space(obs_source_t *source, size_t count, + const enum gs_color_space *preferred_spaces) +{ + cr_record(CR_SOURCE_SPACE, cr_watched && source == cr_watched->source ? 1 : 0, (int64_t)count, + preferred_spaces ? (int64_t)preferred_spaces[0] : -1, 0); + if ((cr_spec.clobber & 128) && cr_watched) + cr_watched->source->color_space_texrender = NULL; + return (enum gs_color_space)cr_spec.source_space; +} + +static enum gs_color_format cr_format(enum gs_color_space space) +{ + cr_record(CR_FORMAT, (int64_t)space, 0, 0, 0); + /* the side's formats 0 to 2, by space */ + return (enum gs_color_format)((int)space & 3); +} + +static float cr_white(void) +{ + cr_record(CR_WHITE, 0, 0, 0, 0); + return cr_spec.white; +} + +static enum gs_color_format cr_tr_format(const gs_texrender_t *texrender) +{ + const int32_t token = cr_texrender_token(texrender); + cr_record(CR_TR_FORMAT, token, 0, 0, 0); + if ((cr_spec.clobber & 4) && cr_watched) + cr_watched->source->color_space_texrender = cr_texrender_ptr(1); + if (token < 0 || token >= CR_TEXRENDERS || !cr_watched) + return GS_UNKNOWN; + return (enum gs_color_format)cr_watched->formats[token]; +} + +static void cr_tr_destroy(gs_texrender_t *texrender) +{ + const int32_t token = cr_texrender_token(texrender); + cr_record(CR_TR_DESTROY, token, 0, 0, 0); + if (cr_watched && token >= 0 && token < CR_TEXRENDERS) + cr_watched->destroyed |= 1u << token; +} + +static gs_texrender_t *cr_tr_create(enum gs_color_format format, enum gs_zstencil_format zsformat) +{ + cr_record(CR_TR_CREATE, (int64_t)format, (int64_t)zsformat, 0, 0); + if (cr_spec.create_fails || !cr_watched) + return NULL; + cr_watched->formats[CR_CREATED] = (int32_t)format; + cr_watched->destroyed &= ~(1u << CR_CREATED); + return cr_texrender_ptr(CR_CREATED); +} + +static void cr_tr_reset(gs_texrender_t *texrender) +{ + cr_record(CR_TR_RESET, cr_texrender_token(texrender), 0, 0, 0); + if ((cr_spec.clobber & 8) && cr_watched) + cr_watched->source->color_space_texrender = cr_texrender_ptr(2); +} + +static uint32_t cr_width(const obs_source_t *source) +{ + cr_record(CR_WIDTH, cr_watched && source == cr_watched->source ? 1 : 0, 0, 0, 0); + return cr_spec.width; +} + +static uint32_t cr_height(const obs_source_t *source) +{ + cr_record(CR_HEIGHT, cr_watched && source == cr_watched->source ? 1 : 0, 0, 0, 0); + return cr_spec.height; +} + +static bool cr_tr_begin(gs_texrender_t *texrender, uint32_t cx, uint32_t cy, enum gs_color_space space) +{ + cr_record(CR_TR_BEGIN, cr_texrender_token(texrender), (int64_t)cx, (int64_t)cy, (int64_t)space); + const bool ok = texrender && cx && cy && !cr_spec.begin_fails; + if (ok) + cr_state |= 8; + return ok; +} + +void cr_render_b(void *data, gs_effect_t *effect); + +static void cr_blending(bool enable) +{ + cr_record(CR_BLENDING, enable, 0, 0, 0); + if (enable) + cr_state &= ~16; + else + cr_state |= 16; + if (!enable && (cr_spec.clobber & 32) && cr_watched) + cr_watched->source->info.video_render = cr_render_b; +} + +static void cr_clear(uint32_t flags, const struct vec4 *color, float depth, uint8_t stencil) +{ + cr_record(CR_CLEAR, (int64_t)flags, color ? cr_bits(color->x) : -1, color ? cr_bits(color->y) : -1, + color ? cr_bits(color->z) : -1); + cr_record(CR_CLEAR_B, color ? cr_bits(color->w) : -1, cr_bits(depth), (int64_t)stencil, 0); +} + +static void cr_ortho(float left, float right, float top, float bottom, float znear, float zfar) +{ + cr_record(CR_ORTHO, cr_bits(left), cr_bits(right), cr_bits(top), cr_bits(bottom)); + cr_record(CR_ORTHO_Z, cr_bits(znear), cr_bits(zfar), 0, 0); +} + +static int32_t cr_effect_token(const void *effect) +{ + if (!effect) + return -1; + if (!cr_watched) + return CR_FOREIGN; + if (effect == &cr_watched->effect) + return 0; + if (effect == &cr_watched->default_effect) + return 1; + return CR_FOREIGN; +} + +static void cr_render_common(uint32_t kind, void *data, gs_effect_t *effect) +{ + cr_record(kind, CR_TOKEN(data, data, CR_DATA), cr_effect_token(effect), 0, 0); + if ((cr_spec.clobber & 16) && cr_watched) + cr_watched->source->color_space_texrender = cr_texrender_ptr(0); +} + +static void cr_render(void *data, gs_effect_t *effect) +{ + cr_render_common(CR_RENDER, data, effect); +} + +void cr_render_b(void *data, gs_effect_t *effect) +{ + cr_render_common(CR_RENDER_B, data, effect); +} + +static void cr_tr_end(gs_texrender_t *texrender) +{ + cr_state &= ~8; + cr_record(CR_TR_END, cr_texrender_token(texrender), 0, 0, 0); + if ((cr_spec.clobber & 64) && cr_watched) + cr_watched->source->color_space_texrender = cr_texrender_ptr(1); +} + +static const char *const cr_tech_names[CR_TECHS - 1] = { + "Draw", + "DrawMultiply", + "DrawTonemap", + "DrawMultiplyTonemap", + "DrawNonlinearAlpha", + "DrawNonlinearAlphaMultiply", +}; + +static gs_technique_t *cr_get_technique(const gs_effect_t *effect, const char *name) +{ + int32_t index = CR_TECHS - 1; + for (int32_t i = 0; i < CR_TECHS - 1; i++) { + if (name && strcmp(name, cr_tech_names[i]) == 0) + index = i; + } + cr_record(CR_TECHNIQUE, cr_effect_token(effect), index, 0, 0); + if (!effect || !cr_watched || (index < 6 && (cr_spec.missing & (1u << index)))) + return NULL; + return (gs_technique_t *)&cr_watched->techs[index]; +} + +static int32_t cr_tech_token(const gs_technique_t *tech) +{ + return CR_TOKEN(tech, techs, CR_TECHS); +} + +static bool cr_fb_get(void) +{ + cr_record(CR_FB_GET, cr_fb_srgb, 0, 0, 0); + return cr_fb_srgb; +} + +static void cr_fb_set(bool enable) +{ + cr_record(CR_FB_SET, enable, 0, 0, 0); + cr_fb_srgb = enable; +} + +static gs_texture_t *cr_tr_texture(const gs_texrender_t *texrender) +{ + const int32_t token = cr_texrender_token(texrender); + cr_record(CR_TR_TEXTURE, token, 0, 0, 0); + if (cr_spec.no_texture || !cr_watched || token < 0 || token >= CR_TEXRENDERS) + return NULL; + return (gs_texture_t *)&cr_watched->textures[token]; +} + +static int32_t cr_tex_token(const void *tex) +{ + return CR_TOKEN(tex, textures, CR_TEXRENDERS); +} + +static gs_eparam_t *cr_get_param(const gs_effect_t *effect, const char *name) +{ + int32_t index = 2; + if (name && strcmp(name, "image") == 0) + index = 0; + else if (name && strcmp(name, "multiplier") == 0) + index = 1; + cr_record(CR_PARAM, cr_effect_token(effect), index, 0, 0); + if (!effect || !cr_watched || (index == 0 && (cr_spec.missing & 64)) || (index == 1 && (cr_spec.missing & 128))) + return NULL; + return (gs_eparam_t *)&cr_watched->params[index]; +} + +static int32_t cr_param_token(const gs_eparam_t *param) +{ + return CR_TOKEN(param, params, CR_PARAMS); +} + +static void cr_set_texture_srgb(gs_eparam_t *param, gs_texture_t *tex) +{ + cr_record(CR_SET_TEXTURE_SRGB, cr_param_token(param), cr_tex_token(tex), 0, 0); +} + +static void cr_set_float(gs_eparam_t *param, float value) +{ + cr_record(CR_SET_FLOAT, cr_param_token(param), cr_bits(value), 0, 0); +} + +static void cr_blend_push(void) +{ + cr_blend++; + cr_record(CR_BLEND_PUSH, 0, 0, 0, 0); +} + +static void cr_blend_function(enum gs_blend_type src, enum gs_blend_type dest) +{ + cr_record(CR_BLEND_FUNCTION, (int64_t)src, (int64_t)dest, 0, 0); +} + +static size_t cr_tech_begin(gs_technique_t *tech) +{ + cr_record(CR_TECH_BEGIN, cr_tech_token(tech), 0, 0, 0); + if (!tech) + return 0; + cr_state |= 1; + return cr_spec.passes; +} + +static bool cr_pass_begin(gs_technique_t *tech, size_t pass) +{ + cr_record(CR_PASS_BEGIN, cr_tech_token(tech), (int64_t)pass, 0, 0); + cr_state |= 2; + return true; +} + +static void cr_draw(gs_texture_t *tex, uint32_t flip, uint32_t width, uint32_t height) +{ + cr_record(CR_DRAW, cr_tex_token(tex), (int64_t)flip, (int64_t)width, (int64_t)height); +} + +static void cr_pass_end(gs_technique_t *tech) +{ + cr_state &= ~2; + cr_record(CR_PASS_END, cr_tech_token(tech), 0, 0, 0); +} + +static void cr_tech_end(gs_technique_t *tech) +{ + cr_state &= ~1; + cr_record(CR_TECH_END, cr_tech_token(tech), 0, 0, 0); +} + +static void cr_blend_pop(void) +{ + cr_blend--; + cr_record(CR_BLEND_POP, 0, 0, 0, 0); +} + +#define obs cr_core +#define source_profiler_source_render_begin cr_begin +#define source_profiler_source_render_end cr_end +#define gs_get_color_space cr_color_space +#define obs_source_get_color_space cr_source_space +#define gs_get_format_from_space cr_format +#define obs_get_video_sdr_white_level cr_white +#define gs_texrender_get_format cr_tr_format +#define gs_texrender_destroy cr_tr_destroy +#define gs_texrender_create cr_tr_create +#define gs_texrender_reset cr_tr_reset +#define obs_source_base_width cr_width +#define obs_source_base_height cr_height +#define gs_texrender_begin_with_color_space cr_tr_begin +#define gs_enable_blending cr_blending +#define gs_clear cr_clear +#define gs_ortho cr_ortho +#define gs_texrender_end cr_tr_end +#define gs_effect_get_technique cr_get_technique +#define gs_framebuffer_srgb_enabled cr_fb_get +#define gs_enable_framebuffer_srgb cr_fb_set +#define gs_texrender_get_texture cr_tr_texture +#define gs_effect_get_param_by_name cr_get_param +#define gs_effect_set_texture_srgb cr_set_texture_srgb +#define gs_effect_set_float cr_set_float +#define gs_blend_state_push cr_blend_push +#define gs_blend_function cr_blend_function +#define gs_technique_begin cr_tech_begin +#define gs_technique_begin_pass cr_pass_begin +#define gs_draw_sprite cr_draw +#define gs_technique_end_pass cr_pass_end +#define gs_technique_end cr_tech_end +#define gs_blend_state_pop cr_blend_pop + +#define obs_source_default_render_source_render oracle_obs_source_default_render_source_render +#define obs_source_draw_plan_convert oracle_obs_source_draw_plan_convert +#define obs_source_draw_plan_technique oracle_obs_source_draw_plan_technique +#define obs_source_draw_plan_reads_white_level oracle_obs_source_draw_plan_reads_white_level +#define obs_source_draw_plan_multiplier oracle_obs_source_draw_plan_multiplier + +bool oracle_obs_source_draw_plan_convert(int source_space, int current_space); +enum obs_source_draw_technique oracle_obs_source_draw_plan_technique(int source_space, int current_space, + bool nonlinear_alpha); +bool oracle_obs_source_draw_plan_reads_white_level(int source_space, int current_space); +float oracle_obs_source_draw_plan_multiplier(int source_space, int current_space, float sdr_white_level); + +#include "source-convert-render.inc" + +#undef obs_source_draw_plan_multiplier +#undef obs_source_draw_plan_reads_white_level +#undef obs_source_draw_plan_technique +#undef obs_source_draw_plan_convert +#undef obs_source_default_render_source_render + +#include "source-convert-render-fields.inc" + +#undef gs_blend_state_pop +#undef gs_technique_end +#undef gs_technique_end_pass +#undef gs_draw_sprite +#undef gs_technique_begin_pass +#undef gs_technique_begin +#undef gs_blend_function +#undef gs_blend_state_push +#undef gs_effect_set_float +#undef gs_effect_set_texture_srgb +#undef gs_effect_get_param_by_name +#undef gs_texrender_get_texture +#undef gs_enable_framebuffer_srgb +#undef gs_framebuffer_srgb_enabled +#undef gs_effect_get_technique +#undef gs_texrender_end +#undef gs_ortho +#undef gs_clear +#undef gs_enable_blending +#undef gs_texrender_begin_with_color_space +#undef obs_source_base_height +#undef obs_source_base_width +#undef gs_texrender_reset +#undef gs_texrender_create +#undef gs_texrender_destroy +#undef gs_texrender_get_format +#undef obs_get_video_sdr_white_level +#undef gs_get_format_from_space +#undef obs_source_get_color_space +#undef gs_get_color_space +#undef source_profiler_source_render_end +#undef source_profiler_source_render_begin +#undef obs + +/* ------------------------------------------------------------------------ */ +/* the fixtures */ + +/* Side `side`'s source, set to `spec` (which also becomes the stand-ins' + * script). */ +struct obs_source *oracle_cr_new(const struct oracle_cr_spec *spec, int side); +struct obs_source *oracle_cr_new(const struct oracle_cr_spec *spec, int side) +{ + struct cr_side *s = &cr_sides[side ? 1 : 0]; + struct obs_source *source = bzalloc(sizeof(struct obs_source)); + + cr_spec = *spec; + s->source = source; + s->destroyed = 0; + for (int i = 0; i < CR_TEXRENDERS; i++) + s->formats[i] = spec->formats[i]; + struct cr_side *watched = cr_watched; + cr_watched = s; + source->context.data = cr_data_ptr(spec->data); + source->color_space_texrender = cr_texrender_ptr(spec->texrender); + cr_watched = watched; + source->info.video_render = cr_render; + return source; +} + +void oracle_cr_free(int side); +void oracle_cr_free(int side) +{ + struct cr_side *s = &cr_sides[side ? 1 : 0]; + if (!s->source) + return; + if (cr_watched == s) + cr_watched = NULL; + bfree(s->source); + s->source = NULL; +} + +/* Watch side `side` on this thread, clear the log and set the graphics + * state and obs->video.default_effect to the spec's. */ +void oracle_cr_watch(int side); +void oracle_cr_watch(int side) +{ + cr_watched = &cr_sides[side ? 1 : 0]; + if (!cr_core) + cr_core = bzalloc(sizeof(struct obs_core)); + cr_core->video.default_effect = cr_spec.no_default_effect ? NULL : (gs_effect_t *)&cr_watched->default_effect; + cr_fb_srgb = cr_spec.fb_srgb; + cr_blend = 0; + cr_state = 0; + memset(&cr_log, 0, sizeof(cr_log)); +} + +void oracle_cr_log(struct oracle_cr_log *out); +void oracle_cr_log(struct oracle_cr_log *out) +{ + *out = cr_log; +} + +/* The caller's effect of the watched side, NULL for -1. */ +void *oracle_cr_effect(void); +void *oracle_cr_effect(void) +{ + if (!cr_watched || cr_spec.effect < 0) + return NULL; + return &cr_watched->effect; +} + +/* What a side's source holds and the graphics state it left. */ +struct oracle_cr_result { + int32_t texrender; + int32_t data; + int32_t blend; + int32_t state; + uint32_t destroyed; + int32_t created_format; + bool fb_srgb; + /* 0: the first stand-in, 1: the second, 2: another */ + uint8_t render; +}; + +void oracle_cr_result(int side, struct oracle_cr_result *out); +void oracle_cr_result(int side, struct oracle_cr_result *out) +{ + struct cr_side *s = &cr_sides[side ? 1 : 0]; + const struct obs_source *source = s->source; + struct cr_side *watched = cr_watched; + + memset(out, 0, sizeof(*out)); + cr_watched = s; + out->texrender = cr_texrender_token(source->color_space_texrender); + out->data = CR_TOKEN(source->context.data, data, CR_DATA); + cr_watched = watched; + out->blend = cr_blend; + out->state = cr_state; + out->destroyed = s->destroyed; + out->created_format = s->formats[CR_CREATED]; + out->fb_srgb = cr_fb_srgb; + out->render = source->info.video_render == cr_render ? 0 : source->info.video_render == cr_render_b ? 1 : 2; +} + +/* Whether the two sides' sources are byte for byte the same outside their + * own tables: the data, texrender and video_render pointers are taken from + * side 0 (the parity test compares them by token). */ +bool oracle_cr_same(void); +bool oracle_cr_same(void) +{ + struct obs_source *x = bmemdup(cr_sides[0].source, sizeof(struct obs_source)); + struct obs_source *y = bmemdup(cr_sides[1].source, sizeof(struct obs_source)); + y->context.data = x->context.data; + y->color_space_texrender = x->color_space_texrender; + y->info.video_render = x->info.video_render; + bool same = memcmp(x, y, sizeof(*x)) == 0; + bfree(x); + bfree(y); + return same; +} + +size_t oracle_cr_events(void); +size_t oracle_cr_events(void) +{ + return CR_EVENTS; +} + +/* The original, as the C reference runs it, on side 0. */ +void oracle_cr_run(void *effect); +void oracle_cr_run(void *effect) +{ + oracle_obs_source_default_render_source_render(cr_sides[0].source, effect); +} diff --git a/rust/obs-source/src/convert_render.rs b/rust/obs-source/src/convert_render.rs new file mode 100644 index 0000000000..904d2b1374 --- /dev/null +++ b/rust/obs-source/src/convert_render.rs @@ -0,0 +1,263 @@ +//! Safe core of `libobs/obs-source-convert-render.c.h`: `source_render()`, +//! the draw behind `obs_source_default_render()` and +//! `obs_source_main_render()`, reached through its hidden wrapper +//! `obs_source_default_render_source_render()` (no `EXPORT`). +//! +//! [`source_render`], inside the profiler bracket: `context.data`, the +//! current colour space, the source's colour space asked with it as the one +//! preferred space, and the source's format from that space; then the +//! decisions of [`crate::draw_plan`] (convert or not, the technique, and the +//! multiplier, with the SDR white level read only when +//! [`crate::draw_plan::reads_white_level`] says so, else 1). +//! +//! - No conversion: the source's `video_render(data, effect)`, nothing else. +//! - Conversion: `color_space_texrender` destroyed and cleared when its +//! format is not the source's, created ([`GS_ZS_NONE`]) when there is +//! none, reset, and begun at the source's base size in the source's space. +//! Only when that begin succeeds: blending off, the target cleared to zero +//! ([`GS_CLEAR_COLOR`]), the ortho of the base size, `video_render`, +//! blending on, the texrender ended; then the default effect's technique, +//! the framebuffer sRGB flag turned on (restored after), the texrender's +//! texture set as sRGB on `image`, the multiplier set on `multiplier`, the +//! blend state pushed with [`GS_BLEND_ONE`] / [`GS_BLEND_INVSRCALPHA`], +//! one sprite per pass of the technique, and the blend state popped. +//! +//! Like the C, `color_space_texrender` is read again for every call that +//! takes it (the check, the format, the destroy, the reset, the begin, the +//! end and the texture), and `info.video_render` is read when it is called. Every +//! decision is [`crate::draw_plan`]; the fields, the profiler, the colour +//! space query, the base size and every graphics call stay C, reached +//! through the [`Host`] trait one access at a time. +//! +//! No intentional differences from 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 crate::draw_plan::{self, Technique}; + +/// `GS_BLEND_ONE`. +pub const GS_BLEND_ONE: i32 = 1; +/// `GS_BLEND_INVSRCALPHA`. +pub const GS_BLEND_INVSRCALPHA: i32 = 5; +/// `GS_ZS_NONE`. +pub const GS_ZS_NONE: i32 = 0; +/// `GS_CLEAR_COLOR`. +pub const GS_CLEAR_COLOR: u32 = 1 << 0; + +/// The default effect's params the draw sets. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Param { + /// `"image"`. + Image, + /// `"multiplier"`. + Multiplier, +} + +impl Param { + /// The param's name in `default.effect`. + pub const fn name(self) -> &'static core::ffi::CStr { + match self { + Param::Image => c"image", + Param::Multiplier => c"multiplier", + } + } +} + +/// The source's fields, the profiler, the colour space query, the base +/// size and the graphics calls the draw makes, in the C's terms. +pub trait Host { + /// A live, non-null source. + type Source: Copy; + /// `context.data`, NULL included. + type Data: Copy; + /// A `gs_effect_t *`, NULL included. + type Effect: Copy; + /// A `gs_technique_t *` as the lookup gives it, NULL included. + type Technique: Copy; + /// A `gs_eparam_t *` as the lookup gives it, NULL included. + type Param: Copy; + /// A `gs_texture_t *` as the texrender gives it, NULL included. + type Texture: Copy; + /// A non-null `gs_texrender_t *`. + type Texrender: Copy; + /// The `gs_timer_t *` the profiler's begin left. + type Timer: Copy; + + /// `gs_timer_t *timer = NULL;` and + /// `source_profiler_source_render_begin(&timer)`: the start and the + /// timer. + fn render_begin(&self) -> (u64, Self::Timer); + /// `source_profiler_source_render_end(source, start, timer)`. + fn render_end(&self, source: Self::Source, start: u64, timer: Self::Timer); + /// `source->context.data`. + fn data(&self, source: Self::Source) -> Self::Data; + /// `gs_get_color_space()`, as `int`. + fn color_space(&self) -> i32; + /// `obs_source_get_color_space(source, 1, ¤t)`, as `int`. + fn source_color_space(&self, source: Self::Source, current: i32) -> i32; + /// `gs_get_format_from_space(space)`, as `int`. + fn format_from_space(&self, space: i32) -> i32; + /// `obs_get_video_sdr_white_level()`. + fn sdr_white_level(&self) -> f32; + /// `source->color_space_texrender`; `None` is NULL. + fn texrender(&self, source: Self::Source) -> Option; + /// `source->color_space_texrender = texrender`. + fn set_texrender(&self, source: Self::Source, texrender: Option); + /// `gs_texrender_get_format(texrender)`, as `int`, NULL included. + fn texrender_format(&self, texrender: Option) -> i32; + /// `gs_texrender_destroy(texrender)`, NULL included. + fn texrender_destroy(&self, texrender: Option); + /// `gs_texrender_create(format, zsformat)`; `None` is NULL. + fn texrender_create(&self, format: i32, zsformat: i32) -> Option; + /// `gs_texrender_reset(texrender)`, NULL included. + fn texrender_reset(&self, texrender: Option); + /// `obs_source_base_width(source)`. + fn base_width(&self, source: Self::Source) -> u32; + /// `obs_source_base_height(source)`. + fn base_height(&self, source: Self::Source) -> u32; + /// `gs_texrender_begin_with_color_space(texrender, cx, cy, space)`, + /// NULL included. + fn texrender_begin( + &self, + texrender: Option, + cx: u32, + cy: u32, + space: i32, + ) -> bool; + /// `gs_enable_blending(enable)`. + fn enable_blending(&self, enable: bool); + /// `gs_clear(flags, &color, depth, stencil)`. + fn clear(&self, flags: u32, color: [f32; 4], depth: f32, stencil: u8); + /// `gs_ortho(left, right, top, bottom, znear, zfar)`. + fn ortho(&self, left: f32, right: f32, top: f32, bottom: f32, znear: f32, zfar: f32); + /// `source->info.video_render(data, effect)`, the field read here. + fn video_render(&self, source: Self::Source, data: Self::Data, effect: Self::Effect); + /// `gs_texrender_end(texrender)`, NULL included. + fn texrender_end(&self, texrender: Option); + /// `obs->video.default_effect`. + fn default_effect(&self) -> Self::Effect; + /// `gs_effect_get_technique(effect, + /// obs_source_draw_technique_name(technique))`. + fn technique(&self, effect: Self::Effect, technique: Technique) -> Self::Technique; + /// `gs_framebuffer_srgb_enabled()`. + fn framebuffer_srgb_enabled(&self) -> bool; + /// `gs_enable_framebuffer_srgb(enable)`. + fn enable_framebuffer_srgb(&self, enable: bool); + /// `gs_texrender_get_texture(texrender)`, NULL included. + fn texrender_texture(&self, texrender: Option) -> Self::Texture; + /// `gs_effect_get_param_by_name(effect, param.name())`. + fn param(&self, effect: Self::Effect, param: Param) -> Self::Param; + /// `gs_effect_set_texture_srgb(param, tex)`. + fn set_texture_srgb(&self, param: Self::Param, tex: Self::Texture); + /// `gs_effect_set_float(param, value)`. + fn set_float(&self, param: Self::Param, value: f32); + /// `gs_blend_state_push()`. + fn blend_state_push(&self); + /// `gs_blend_function(src, dest)`, each a `gs_blend_type`. + fn blend_function(&self, src: i32, dest: i32); + /// `gs_technique_begin(tech)`: the pass count. + fn technique_begin(&self, tech: Self::Technique) -> usize; + /// `gs_technique_begin_pass(tech, pass)` (the result is not looked + /// at). + fn technique_begin_pass(&self, tech: Self::Technique, pass: usize); + /// `gs_draw_sprite(tex, flip, width, height)`. + fn draw_sprite(&self, tex: Self::Texture, flip: u32, width: u32, height: u32); + /// `gs_technique_end_pass(tech)`. + fn technique_end_pass(&self, tech: Self::Technique); + /// `gs_technique_end(tech)`. + fn technique_end(&self, tech: Self::Technique); + /// `gs_blend_state_pop()`. + fn blend_state_pop(&self); +} + +/// `(float)size`: the nearest `f32`, as the C's conversion of a +/// `uint32_t`. +#[allow(clippy::as_conversions)] +pub fn size_f32(size: u32) -> f32 { + size as f32 +} + +/// `source_render(source, effect)`. +pub fn source_render(host: &H, source: H::Source, effect: H::Effect) { + let (start, timer) = host.render_begin(); + + let data = host.data(source); + let current_space = host.color_space(); + let source_space = host.source_color_space(source, current_space); + + let format = host.format_from_space(source_space); + let convert = draw_plan::convert(source_space, current_space); + let technique = draw_plan::technique(source_space, current_space, false); + let multiplier = if draw_plan::reads_white_level(source_space, current_space) { + draw_plan::multiplier(source_space, current_space, host.sdr_white_level()) + } else { + 1.0 + }; + + if convert { + if host.texrender(source).is_some() + && host.texrender_format(host.texrender(source)) != format + { + host.texrender_destroy(host.texrender(source)); + host.set_texrender(source, None); + } + + if host.texrender(source).is_none() { + host.set_texrender(source, host.texrender_create(format, GS_ZS_NONE)); + } + + host.texrender_reset(host.texrender(source)); + let cx = host.base_width(source); + let cy = host.base_height(source); + if host.texrender_begin(host.texrender(source), cx, cy, source_space) { + host.enable_blending(false); + + host.clear(GS_CLEAR_COLOR, [0.0; 4], 0.0, 0); + host.ortho(0.0, size_f32(cx), 0.0, size_f32(cy), -100.0, 100.0); + + host.video_render(source, data, effect); + + host.enable_blending(true); + + host.texrender_end(host.texrender(source)); + + let default_effect = host.default_effect(); + let tech = host.technique(default_effect, technique); + + let previous = host.framebuffer_srgb_enabled(); + host.enable_framebuffer_srgb(true); + + let tex = host.texrender_texture(host.texrender(source)); + host.set_texture_srgb(host.param(default_effect, Param::Image), tex); + host.set_float(host.param(default_effect, Param::Multiplier), multiplier); + + host.blend_state_push(); + host.blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); + + let passes = host.technique_begin(tech); + for pass in 0..passes { + host.technique_begin_pass(tech, pass); + host.draw_sprite(tex, 0, 0, 0); + host.technique_end_pass(tech); + } + host.technique_end(tech); + + host.blend_state_pop(); + + host.enable_framebuffer_srgb(previous); + } + } else { + host.video_render(source, data, effect); + } + host.render_end(source, start, timer); +} diff --git a/rust/obs-source/src/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index d62f46445b..09c18eb171 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -37,6 +37,7 @@ pub mod source_caption_callbacks; pub mod source_color_space; pub mod source_configurable; pub mod source_conversion_plan; +pub mod source_convert_render; pub mod source_copy_filters; pub mod source_default_flags; pub mod source_default_render; diff --git a/rust/obs-source/src/ffi/source_convert_render.rs b/rust/obs-source/src/ffi/source_convert_render.rs new file mode 100644 index 0000000000..19a9652a9f --- /dev/null +++ b/rust/obs-source/src/ffi/source_convert_render.rs @@ -0,0 +1,313 @@ +//! C ABI for `libobs/obs-source-convert-render.c.h`: `source_render()`, +//! the draw behind `obs_source_default_render()` and +//! `obs_source_main_render()`, through its hidden wrapper +//! `obs_source_default_render_source_render()`. `obs-source.c.h` declares +//! it without `EXPORT`, so the shim stays hidden (`rust-hidden.d`). +//! +//! Runs the safe core ([`crate::convert_render`]) over the C-owned source: +//! the profiler, the fields, the colour space query, the base size and +//! every graphics call are one access each through the adapters of +//! `obs-source-convert-render-fields.c.h`. Like the C, nothing checks the +//! source: the render passes a live one, inside the graphics context. The +//! data, effect, technique, param, texture, texrender and timer pointers +//! cross as they are. +//! +//! No intentional differences from C. + +use core::ffi::{CStr, c_char, c_int, c_void}; +use core::ptr::{self, NonNull}; + +use crate::convert_render::{self, Host, Param}; +use crate::draw_plan::Technique; + +unsafe extern "C" { + fn obs_source_convert_render_begin(timer: *mut *mut c_void) -> u64; + fn obs_source_convert_render_end(source: *mut c_void, start: u64, timer: *mut c_void); + fn obs_source_convert_render_data(source: *const c_void) -> *mut c_void; + fn obs_source_convert_render_color_space() -> c_int; + fn obs_source_convert_render_source_space(source: *mut c_void, current: c_int) -> c_int; + fn obs_source_convert_render_format(space: c_int) -> c_int; + fn obs_source_convert_render_sdr_white_level() -> f32; + fn obs_source_convert_render_texrender(source: *const c_void) -> *mut c_void; + fn obs_source_convert_render_set_texrender(source: *mut c_void, texrender: *mut c_void); + fn obs_source_convert_render_texrender_format(texrender: *const c_void) -> c_int; + fn obs_source_convert_render_texrender_destroy(texrender: *mut c_void); + fn obs_source_convert_render_texrender_create(format: c_int, zsformat: c_int) -> *mut c_void; + fn obs_source_convert_render_texrender_reset(texrender: *mut c_void); + fn obs_source_convert_render_width(source: *mut c_void) -> u32; + fn obs_source_convert_render_height(source: *mut c_void) -> u32; + fn obs_source_convert_render_texrender_begin( + texrender: *mut c_void, + cx: u32, + cy: u32, + space: c_int, + ) -> bool; + fn obs_source_convert_render_enable_blending(enable: bool); + fn obs_source_convert_render_clear(flags: u32, color: *const [f32; 4], depth: f32, stencil: u8); + fn obs_source_convert_render_ortho( + left: f32, + right: f32, + top: f32, + bottom: f32, + znear: f32, + zfar: f32, + ); + fn obs_source_convert_render_video_render( + source: *mut c_void, + data: *mut c_void, + effect: *mut c_void, + ); + fn obs_source_convert_render_texrender_end(texrender: *mut c_void); + fn obs_source_convert_render_default_effect() -> *mut c_void; + fn obs_source_convert_render_technique(effect: *mut c_void, technique: c_int) -> *mut c_void; + fn obs_source_convert_render_framebuffer_srgb() -> bool; + fn obs_source_convert_render_enable_framebuffer_srgb(enable: bool); + fn obs_source_convert_render_texrender_texture(texrender: *const c_void) -> *mut c_void; + fn obs_source_convert_render_param(effect: *mut c_void, name: *const c_char) -> *mut c_void; + fn obs_source_convert_render_set_texture_srgb(param: *mut c_void, tex: *mut c_void); + fn obs_source_convert_render_set_float(param: *mut c_void, value: f32); + fn obs_source_convert_render_blend_push(); + fn obs_source_convert_render_blend_function(src: c_int, dest: c_int); + fn obs_source_convert_render_technique_begin(tech: *mut c_void) -> usize; + fn obs_source_convert_render_begin_pass(tech: *mut c_void, pass: usize); + fn obs_source_convert_render_draw_sprite(tex: *mut c_void, flip: u32, width: u32, height: u32); + fn obs_source_convert_render_end_pass(tech: *mut c_void); + fn obs_source_convert_render_technique_end(tech: *mut c_void); + fn obs_source_convert_render_blend_pop(); +} + +/// The caller's live source. +#[derive(Clone, Copy)] +struct Source(*mut c_void); + +/// `context.data`, NULL included. +#[derive(Clone, Copy)] +struct Data(*mut c_void); + +/// `gs_effect_t *`, NULL included. +#[derive(Clone, Copy)] +struct Effect(*mut c_void); + +/// `gs_technique_t *`, NULL included. +#[derive(Clone, Copy)] +struct Tech(*mut c_void); + +/// `gs_eparam_t *`, NULL included. +#[derive(Clone, Copy)] +struct EffectParam(*mut c_void); + +/// `gs_texture_t *`, NULL included. +#[derive(Clone, Copy)] +struct Texture(*mut c_void); + +/// A non-null `gs_texrender_t *`. +#[derive(Clone, Copy)] +struct Texrender(NonNull); + +/// The `gs_timer_t *` the profiler's begin left, NULL included. +#[derive(Clone, Copy)] +struct Timer(*mut c_void); + +/// `enum obs_source_draw_technique` as the C's `int` (0 to 5). +fn technique_value(technique: Technique) -> c_int { + c_int::try_from(technique.value()).unwrap_or_default() +} + +/// The texrender as the C passes it, NULL for `None`. +fn texrender_ptr(texrender: Option) -> *mut c_void { + texrender.map_or(ptr::null_mut(), |t| t.0.as_ptr()) +} + +/// The live libobs source the caller hands over. +struct Libobs; + +// SAFETY (every method): `source` is the caller's live, non-null source, +// rendered in the graphics context; the data, effect, technique, param, +// texture, texrender and timer are the ones the caller and the adapters +// gave, as the core passes them back. +impl Host for Libobs { + type Source = Source; + type Data = Data; + type Effect = Effect; + type Technique = Tech; + type Param = EffectParam; + type Texture = Texture; + type Texrender = Texrender; + type Timer = Timer; + fn render_begin(&self) -> (u64, Timer) { + let mut timer = ptr::null_mut(); + // SAFETY: a valid slot for the timer, NULL as the C starts it. + let start = unsafe { obs_source_convert_render_begin(&mut timer) }; + (start, Timer(timer)) + } + fn render_end(&self, source: Source, start: u64, timer: Timer) { + // SAFETY: a live source and the begin's start and timer. + unsafe { obs_source_convert_render_end(source.0, start, timer.0) } + } + fn data(&self, source: Source) -> Data { + // SAFETY: a live source. + Data(unsafe { obs_source_convert_render_data(source.0) }) + } + fn color_space(&self) -> i32 { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_color_space() } + } + fn source_color_space(&self, source: Source, current: i32) -> i32 { + // SAFETY: a live source. + unsafe { obs_source_convert_render_source_space(source.0, current) } + } + fn format_from_space(&self, space: i32) -> i32 { + // SAFETY: a plain value lookup. + unsafe { obs_source_convert_render_format(space) } + } + fn sdr_white_level(&self) -> f32 { + // SAFETY: libobs is up while a source renders. + unsafe { obs_source_convert_render_sdr_white_level() } + } + fn texrender(&self, source: Source) -> Option { + // SAFETY: a live source. + NonNull::new(unsafe { obs_source_convert_render_texrender(source.0) }).map(Texrender) + } + fn set_texrender(&self, source: Source, texrender: Option) { + // SAFETY: a live source; the texrender is NULL or one the adapters + // made. + unsafe { obs_source_convert_render_set_texrender(source.0, texrender_ptr(texrender)) } + } + fn texrender_format(&self, texrender: Option) -> i32 { + // SAFETY: the source's texrender or NULL (checked there), in the + // graphics context. + unsafe { obs_source_convert_render_texrender_format(texrender_ptr(texrender)) } + } + fn texrender_destroy(&self, texrender: Option) { + // SAFETY: the source's texrender or NULL (checked there), cleared + // from the source next. + unsafe { obs_source_convert_render_texrender_destroy(texrender_ptr(texrender)) } + } + fn texrender_create(&self, format: i32, zsformat: i32) -> Option { + // SAFETY: in the graphics context. + NonNull::new(unsafe { obs_source_convert_render_texrender_create(format, zsformat) }) + .map(Texrender) + } + fn texrender_reset(&self, texrender: Option) { + // SAFETY: the source's texrender or NULL (checked there). + unsafe { obs_source_convert_render_texrender_reset(texrender_ptr(texrender)) } + } + fn base_width(&self, source: Source) -> u32 { + // SAFETY: a live source. + unsafe { obs_source_convert_render_width(source.0) } + } + fn base_height(&self, source: Source) -> u32 { + // SAFETY: a live source. + unsafe { obs_source_convert_render_height(source.0) } + } + fn texrender_begin(&self, texrender: Option, cx: u32, cy: u32, space: i32) -> bool { + // SAFETY: the source's texrender or NULL (checked there), in the + // graphics context. + unsafe { + obs_source_convert_render_texrender_begin(texrender_ptr(texrender), cx, cy, space) + } + } + fn enable_blending(&self, enable: bool) { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_enable_blending(enable) } + } + fn clear(&self, flags: u32, color: [f32; 4], depth: f32, stencil: u8) { + // SAFETY: in the graphics context; `color` is a `struct vec4`'s + // four floats, live for the call. + unsafe { obs_source_convert_render_clear(flags, &color, depth, stencil) } + } + fn ortho(&self, left: f32, right: f32, top: f32, bottom: f32, znear: f32, zfar: f32) { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_ortho(left, right, top, bottom, znear, zfar) } + } + fn video_render(&self, source: Source, data: Data, effect: Effect) { + // SAFETY: a live source with a video_render (the caller's route + // checked it), its data and the caller's effect. + unsafe { obs_source_convert_render_video_render(source.0, data.0, effect.0) } + } + fn texrender_end(&self, texrender: Option) { + // SAFETY: the source's texrender or NULL (checked there). + unsafe { obs_source_convert_render_texrender_end(texrender_ptr(texrender)) } + } + fn default_effect(&self) -> Effect { + // SAFETY: libobs is up while a source renders. + Effect(unsafe { obs_source_convert_render_default_effect() }) + } + fn technique(&self, effect: Effect, technique: Technique) -> Tech { + // SAFETY: the default effect, in the graphics context. + Tech(unsafe { obs_source_convert_render_technique(effect.0, technique_value(technique)) }) + } + fn framebuffer_srgb_enabled(&self) -> bool { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_framebuffer_srgb() } + } + fn enable_framebuffer_srgb(&self, enable: bool) { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_enable_framebuffer_srgb(enable) } + } + fn texrender_texture(&self, texrender: Option) -> Texture { + // SAFETY: the source's texrender or NULL (checked there). + Texture(unsafe { obs_source_convert_render_texrender_texture(texrender_ptr(texrender)) }) + } + fn param(&self, effect: Effect, param: Param) -> EffectParam { + let name: &CStr = param.name(); + // SAFETY: the default effect and a NUL-terminated name. + EffectParam(unsafe { obs_source_convert_render_param(effect.0, name.as_ptr()) }) + } + fn set_texture_srgb(&self, param: EffectParam, tex: Texture) { + // SAFETY: the param the lookup gave and the texrender's texture, + // each NULL included (checked there). + unsafe { obs_source_convert_render_set_texture_srgb(param.0, tex.0) } + } + fn set_float(&self, param: EffectParam, value: f32) { + // SAFETY: the param the lookup gave, NULL included (checked there). + unsafe { obs_source_convert_render_set_float(param.0, value) } + } + fn blend_state_push(&self) { + // SAFETY: in the graphics context. + unsafe { obs_source_convert_render_blend_push() } + } + fn blend_function(&self, src: i32, dest: i32) { + // SAFETY: in the graphics context; two gs_blend_type values. + unsafe { obs_source_convert_render_blend_function(src, dest) } + } + fn technique_begin(&self, tech: Tech) -> usize { + // SAFETY: the technique the lookup gave, NULL included (checked + // there). + unsafe { obs_source_convert_render_technique_begin(tech.0) } + } + fn technique_begin_pass(&self, tech: Tech, pass: usize) { + // SAFETY: the technique the core began. + unsafe { obs_source_convert_render_begin_pass(tech.0, pass) } + } + fn draw_sprite(&self, tex: Texture, flip: u32, width: u32, height: u32) { + // SAFETY: the texrender's texture, inside the technique's pass. + unsafe { obs_source_convert_render_draw_sprite(tex.0, flip, width, height) } + } + fn technique_end_pass(&self, tech: Tech) { + // SAFETY: the technique whose pass the core began. + unsafe { obs_source_convert_render_end_pass(tech.0) } + } + fn technique_end(&self, tech: Tech) { + // SAFETY: the technique the core began. + unsafe { obs_source_convert_render_technique_end(tech.0) } + } + fn blend_state_pop(&self) { + // SAFETY: in the graphics context, after the core's push. + unsafe { obs_source_convert_render_blend_pop() } + } +} + +/// `obs_source_default_render_source_render(source, effect)`: the hidden +/// wrapper of `source_render()`. +/// +/// # Safety +/// `source` is a live source with a `video_render`, rendered in the +/// graphics context; `effect` is NULL or a live effect. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_default_render_source_render( + source: *mut c_void, + effect: *mut c_void, +) { + convert_render::source_render(&Libobs, Source(source), Effect(effect)); +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index f94e4f270c..298dbea8d0 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -274,6 +274,10 @@ //! `source_render_video()`, `source_draw_route()` and `get_type_format()` //! (the validity check, the reference, the fields, the skip, the updates //! and the draws stay in a C fields adapter); +//! `libobs/obs-source-convert-render.c.h`, `source_render()`, the draw +//! behind `obs_source_default_render()` and `obs_source_main_render()`, +//! through its hidden wrapper (the profiler, the fields, the texrender cache +//! and the graphics calls stay in a C fields adapter); //! `libobs/obs-source-video-render-draws.c.h`, its two draws //! `obs_source_render_filters()` and `obs_source_main_render()`, through //! their hidden wrappers (the lock, the fields, the references and the @@ -299,7 +303,7 @@ //! [`audio_input_path`], //! [`audio_output`], [`audio_place`], //! [`audio_render_plan`], [`audio_render_steps`], [`audio_timing`], [`audio_volume_apply`], -//! [`color_space`], [`conversion_plan`], [`deinterlace`], [`deinterlace_draw`], +//! [`color_space`], [`conversion_plan`], [`convert_render`], [`deinterlace`], [`deinterlace_draw`], //! [`deinterlace_pacing`], [`deinterlace_select`], [`draw_plan`], [`source_draw`], [`filter_backup`], [`frame_copy`], [`media_admission`], [`monitoring`], [`muted_volume`], [`own_clock_drift`] (new code with no C original, #4182), [`ptm_gate`], [`render_route`], [`set_name`], [`size_route`], [`source_duplicate`], [`source_filter_chain`], //! [`transition_access`], [`transition_audio`], [`transition_clock`], [`transition_load`], [`transition_render`], //! [`transition_sample_time`], [`transition_settings`], [`transition_size`], @@ -354,6 +358,7 @@ pub mod caption_callbacks; pub mod color_space; pub mod configurable; pub mod conversion_plan; +pub mod convert_render; pub mod copy_filters; pub mod default_flags; pub mod default_render; diff --git a/rust/obs-source/tests/source/convert_render.rs b/rust/obs-source/tests/source/convert_render.rs new file mode 100644 index 0000000000..e6ddc27525 --- /dev/null +++ b/rust/obs-source/tests/source/convert_render.rs @@ -0,0 +1,784 @@ +//! Tier 1: `obs_source::convert_render` over a recording model of a source +//! and the graphics state: the profiler bracket, `context.data`, the current +//! and the source's colour spaces, the format, the SDR white level, +//! `color_space_texrender` and its format, destroy, create, reset, begin, +//! end and texture, the base size, blending, the clear and the ortho, the +//! source's `video_render`, the default effect, the technique and params, +//! the framebuffer sRGB flag, the blend stack, the passes and the sprites, +//! one access at a time, mirroring the `test_source_convert_render` cases: +//! drawn straight, through a new, a kept and a remade texrender, a begin +//! that fails, and into and out of scRGB. The model fails a test on a pop +//! or end without its push or begin, and on a sprite outside a pass. +use obs_source::convert_render::{ + GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, GS_CLEAR_COLOR, GS_ZS_NONE, Host, Param, size_f32, + source_render, +}; +use obs_source::draw_plan::{ + GS_CS_709_EXTENDED, GS_CS_709_SCRGB, GS_CS_SRGB, GS_CS_SRGB_16F, Technique, +}; +use std::cell::RefCell; + +/// The tokens: the source's data, the caller's effect, the default effect, +/// the technique, the params, the texrenders and their textures, the timer. +const DATA: u32 = 5; +const EFFECT: u32 = 10; +const DEFAULT_EFFECT: u32 = 11; +const TECH: u32 = 20; +const IMAGE: u32 = 30; +const MULTIPLIER: u32 = 31; +const TR: u32 = 50; +const NEW_TR: u32 = 51; +const OTHER_TR: u32 = 52; +const TIMER: u32 = 60; +const START_NS: u64 = 123_456; +/// The formats the model gives: `GS_RGBA` for SDR, `GS_RGBA16F` otherwise. +const GS_RGBA: i32 = 3; +const GS_RGBA16F: i32 = 10; + +#[derive(Debug, Clone, Copy, PartialEq)] +enum Event { + Begin, + End(u64, u32), + Data, + ColorSpace, + SourceColorSpace(i32), + Format(i32), + WhiteLevel, + Texrender, + SetTexrender(Option), + TexrenderFormat(Option), + Destroy(Option), + Create(i32, i32), + Reset(Option), + Width, + Height, + TexrenderBegin(Option, u32, u32, i32), + Blending(bool), + Clear(u32, [f32; 4], f32, u8), + Ortho(f32, f32, f32, f32, f32, f32), + VideoRender(u32, u32), + TexrenderEnd(Option), + DefaultEffect, + Technique(u32, Technique), + FbSrgb, + EnableFbSrgb(bool), + TexrenderTexture(Option), + Param(u32, Param), + SetTextureSrgb(u32, u32), + SetFloat(u32, f32), + BlendPush, + BlendFunction(i32, i32), + TechBegin(u32), + PassBegin(u32, usize), + Draw(u32, u32, u32, u32), + PassEnd(u32), + TechEnd(u32), + BlendPop, +} + +struct State { + current_space: i32, + source_space: i32, + white: f32, + texrender: Option, + texrender_formats: Vec<(u32, i32)>, + created: Option, + width: u32, + height: u32, + begin_ok: bool, + passes: usize, + fb_srgb: bool, + blending: bool, + blend_depth: i32, + in_texrender: bool, + in_tech: bool, + in_pass: bool, + profiling: bool, + /// What the source's `video_render` does to `color_space_texrender`. + render_sets_texrender: Option>, + /// What `gs_texrender_get_format()` does to `color_space_texrender`. + format_sets_texrender: Option>, + events: Vec, +} + +struct Model { + s: RefCell, +} + +impl Model { + /// An sRGB source of 4 x 3 into an sRGB target, no texrender yet, a + /// texrender begin that succeeds, a technique of one pass. + fn new() -> Self { + Model { + s: RefCell::new(State { + current_space: GS_CS_SRGB, + source_space: GS_CS_SRGB, + white: 300.0, + texrender: None, + texrender_formats: vec![(TR, GS_RGBA), (OTHER_TR, GS_RGBA16F)], + created: Some(NEW_TR), + width: 4, + height: 3, + begin_ok: true, + passes: 1, + fb_srgb: false, + blending: true, + blend_depth: 0, + in_texrender: false, + in_tech: false, + in_pass: false, + profiling: false, + render_sets_texrender: None, + format_sets_texrender: None, + events: Vec::new(), + }), + } + } + fn with(self, f: impl FnOnce(&mut State)) -> Self { + f(&mut self.s.borrow_mut()); + self + } + fn push(&self, event: Event) { + self.s.borrow_mut().events.push(event); + } + fn events(&self) -> Vec { + std::mem::take(&mut self.s.borrow_mut().events) + } + fn run(&self, effect: u32) -> Vec { + source_render(self, 1, effect); + let s = self.s.borrow(); + assert!(!s.profiling, "the profiler is left open"); + assert!(!s.in_texrender && !s.in_tech && !s.in_pass, "left begun"); + assert_eq!(s.blend_depth, 0, "the blend stack is unbalanced"); + assert!(s.blending, "blending is left off"); + drop(s); + self.events() + } +} + +fn format_of(space: i32) -> i32 { + if space == GS_CS_709_EXTENDED || space == GS_CS_709_SCRGB || space == GS_CS_SRGB_16F { + GS_RGBA16F + } else { + GS_RGBA + } +} + +impl Host for Model { + type Source = u32; + type Data = u32; + type Effect = u32; + type Technique = u32; + type Param = u32; + type Texture = u32; + type Texrender = u32; + type Timer = u32; + + fn render_begin(&self) -> (u64, u32) { + self.push(Event::Begin); + let mut s = self.s.borrow_mut(); + assert!(!s.profiling); + s.profiling = true; + (START_NS, TIMER) + } + fn render_end(&self, source: u32, start: u64, timer: u32) { + assert_eq!(source, 1); + self.push(Event::End(start, timer)); + let mut s = self.s.borrow_mut(); + assert!(s.profiling, "end without begin"); + s.profiling = false; + } + fn data(&self, _: u32) -> u32 { + self.push(Event::Data); + DATA + } + fn color_space(&self) -> i32 { + self.push(Event::ColorSpace); + self.s.borrow().current_space + } + fn source_color_space(&self, _: u32, current: i32) -> i32 { + self.push(Event::SourceColorSpace(current)); + self.s.borrow().source_space + } + fn format_from_space(&self, space: i32) -> i32 { + self.push(Event::Format(space)); + format_of(space) + } + fn sdr_white_level(&self) -> f32 { + self.push(Event::WhiteLevel); + self.s.borrow().white + } + fn texrender(&self, _: u32) -> Option { + self.push(Event::Texrender); + self.s.borrow().texrender + } + fn set_texrender(&self, _: u32, texrender: Option) { + self.push(Event::SetTexrender(texrender)); + self.s.borrow_mut().texrender = texrender; + } + fn texrender_format(&self, texrender: Option) -> i32 { + self.push(Event::TexrenderFormat(texrender)); + let mut s = self.s.borrow_mut(); + if let Some(swapped) = s.format_sets_texrender { + s.texrender = swapped; + } + s.texrender_formats + .iter() + .find(|(t, _)| Some(*t) == texrender) + .map_or(0, |(_, f)| *f) + } + fn texrender_destroy(&self, texrender: Option) { + self.push(Event::Destroy(texrender)); + } + fn texrender_create(&self, format: i32, zsformat: i32) -> Option { + self.push(Event::Create(format, zsformat)); + let mut s = self.s.borrow_mut(); + if let Some(t) = s.created { + s.texrender_formats.push((t, format)); + } + s.created + } + fn texrender_reset(&self, texrender: Option) { + self.push(Event::Reset(texrender)); + } + fn base_width(&self, _: u32) -> u32 { + self.push(Event::Width); + self.s.borrow().width + } + fn base_height(&self, _: u32) -> u32 { + self.push(Event::Height); + self.s.borrow().height + } + fn texrender_begin(&self, texrender: Option, cx: u32, cy: u32, space: i32) -> bool { + self.push(Event::TexrenderBegin(texrender, cx, cy, space)); + let mut s = self.s.borrow_mut(); + let ok = texrender.is_some() && cx != 0 && cy != 0 && s.begin_ok; + s.in_texrender = ok; + ok + } + fn enable_blending(&self, enable: bool) { + self.push(Event::Blending(enable)); + self.s.borrow_mut().blending = enable; + } + fn clear(&self, flags: u32, color: [f32; 4], depth: f32, stencil: u8) { + self.push(Event::Clear(flags, color, depth, stencil)); + } + fn ortho(&self, left: f32, right: f32, top: f32, bottom: f32, znear: f32, zfar: f32) { + self.push(Event::Ortho(left, right, top, bottom, znear, zfar)); + } + fn video_render(&self, _: u32, data: u32, effect: u32) { + self.push(Event::VideoRender(data, effect)); + let mut s = self.s.borrow_mut(); + if let Some(texrender) = s.render_sets_texrender { + s.texrender = texrender; + } + } + fn texrender_end(&self, texrender: Option) { + self.push(Event::TexrenderEnd(texrender)); + let mut s = self.s.borrow_mut(); + assert!(s.in_texrender, "texrender end without begin"); + s.in_texrender = false; + } + fn default_effect(&self) -> u32 { + self.push(Event::DefaultEffect); + DEFAULT_EFFECT + } + fn technique(&self, effect: u32, technique: Technique) -> u32 { + self.push(Event::Technique(effect, technique)); + TECH + } + fn framebuffer_srgb_enabled(&self) -> bool { + self.push(Event::FbSrgb); + self.s.borrow().fb_srgb + } + fn enable_framebuffer_srgb(&self, enable: bool) { + self.push(Event::EnableFbSrgb(enable)); + self.s.borrow_mut().fb_srgb = enable; + } + fn texrender_texture(&self, texrender: Option) -> u32 { + self.push(Event::TexrenderTexture(texrender)); + texrender.map_or(0, |t| t + 100) + } + fn param(&self, effect: u32, param: Param) -> u32 { + self.push(Event::Param(effect, param)); + match param { + Param::Image => IMAGE, + Param::Multiplier => MULTIPLIER, + } + } + fn set_texture_srgb(&self, param: u32, tex: u32) { + self.push(Event::SetTextureSrgb(param, tex)); + } + fn set_float(&self, param: u32, value: f32) { + self.push(Event::SetFloat(param, value)); + } + fn blend_state_push(&self) { + self.push(Event::BlendPush); + self.s.borrow_mut().blend_depth += 1; + } + fn blend_function(&self, src: i32, dest: i32) { + self.push(Event::BlendFunction(src, dest)); + } + fn technique_begin(&self, tech: u32) -> usize { + self.push(Event::TechBegin(tech)); + let mut s = self.s.borrow_mut(); + s.in_tech = true; + s.passes + } + fn technique_begin_pass(&self, tech: u32, pass: usize) { + self.push(Event::PassBegin(tech, pass)); + let mut s = self.s.borrow_mut(); + assert!(s.in_tech); + s.in_pass = true; + } + fn draw_sprite(&self, tex: u32, flip: u32, width: u32, height: u32) { + assert!(self.s.borrow().in_pass, "sprite outside a pass"); + self.push(Event::Draw(tex, flip, width, height)); + } + fn technique_end_pass(&self, tech: u32) { + self.push(Event::PassEnd(tech)); + let mut s = self.s.borrow_mut(); + assert!(s.in_pass, "pass end without begin"); + s.in_pass = false; + } + fn technique_end(&self, tech: u32) { + self.push(Event::TechEnd(tech)); + let mut s = self.s.borrow_mut(); + assert!(s.in_tech, "technique end without begin"); + s.in_tech = false; + } + fn blend_state_pop(&self) { + self.push(Event::BlendPop); + let mut s = self.s.borrow_mut(); + assert!(s.blend_depth > 0, "blend pop without push"); + s.blend_depth -= 1; + } +} + +use Event as E; + +/// The reads every render starts with, up to the format. +fn opening(current: i32, source: i32) -> Vec { + vec![ + E::Begin, + E::Data, + E::ColorSpace, + E::SourceColorSpace(current), + E::Format(source), + ] +} + +/// The texrender drawn into the target with `technique`, `multiplier`, +/// `passes` sprites of the texture of `texrender`, the flag back to `fb`. +fn drawn( + technique: Technique, + multiplier: f32, + texrender: u32, + passes: usize, + fb: bool, +) -> Vec { + let tex = texrender + 100; + let mut events = vec![ + E::DefaultEffect, + E::Technique(DEFAULT_EFFECT, technique), + E::FbSrgb, + E::EnableFbSrgb(true), + E::Texrender, + E::TexrenderTexture(Some(texrender)), + E::Param(DEFAULT_EFFECT, Param::Image), + E::SetTextureSrgb(IMAGE, tex), + E::Param(DEFAULT_EFFECT, Param::Multiplier), + E::SetFloat(MULTIPLIER, multiplier), + E::BlendPush, + E::BlendFunction(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA), + E::TechBegin(TECH), + ]; + for pass in 0..passes { + events.extend([ + E::PassBegin(TECH, pass), + E::Draw(tex, 0, 0, 0), + E::PassEnd(TECH), + ]); + } + events.extend([E::TechEnd(TECH), E::BlendPop, E::EnableFbSrgb(fb)]); + events +} + +/// The draw into the texrender of 4 x 3 in `space`, from its reset. +fn into_texrender(texrender: u32, space: i32) -> Vec { + vec![ + E::Texrender, + E::Reset(Some(texrender)), + E::Width, + E::Height, + E::Texrender, + E::TexrenderBegin(Some(texrender), 4, 3, space), + E::Blending(false), + E::Clear(GS_CLEAR_COLOR, [0.0; 4], 0.0, 0), + E::Ortho(0.0, 4.0, 0.0, 3.0, -100.0, 100.0), + E::VideoRender(DATA, EFFECT), + E::Blending(true), + E::Texrender, + E::TexrenderEnd(Some(texrender)), + ] +} + +fn seq(parts: &[&[Event]]) -> Vec { + parts.concat() +} + +const END: Event = E::End(START_NS, TIMER); + +#[test] +fn same_space_draws_straight() { + let m = Model::new(); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_SRGB), + &[E::VideoRender(DATA, EFFECT), END] + ]) + ); +} + +#[test] +fn same_space_passes_a_null_effect_on() { + let m = Model::new(); + assert_eq!( + m.run(0), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_SRGB), + &[E::VideoRender(DATA, 0), END] + ]) + ); +} + +#[test] +fn sdr_classes_draw_straight_and_leave_the_texrender() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_SRGB_16F; + s.texrender = Some(TR); + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_SRGB_16F), + &[E::VideoRender(DATA, EFFECT), END] + ]) + ); + assert_eq!(m.s.borrow().texrender, Some(TR)); +} + +#[test] +fn a_space_outside_the_enum_draws_straight() { + let m = Model::new().with(|s| s.source_space = 99); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, 99), + &[E::VideoRender(DATA, EFFECT), END] + ]) + ); +} + +#[test] +fn hdr_into_sdr_creates_the_texrender_and_tonemaps() { + let m = Model::new().with(|s| s.source_space = GS_CS_709_EXTENDED); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_709_EXTENDED), + &[ + E::Texrender, + E::Texrender, + E::Create(GS_RGBA16F, GS_ZS_NONE), + E::SetTexrender(Some(NEW_TR)), + ], + &into_texrender(NEW_TR, GS_CS_709_EXTENDED), + &drawn(Technique::DrawTonemap, 1.0, NEW_TR, 1, false), + &[END], + ]) + ); + assert_eq!(m.s.borrow().texrender, Some(NEW_TR)); +} + +#[test] +fn a_texrender_of_the_same_format_is_kept() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_SRGB; + s.current_space = GS_CS_709_EXTENDED; + s.texrender = Some(TR); + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_709_EXTENDED, GS_CS_SRGB), + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(TR)), + E::Texrender + ], + &into_texrender(TR, GS_CS_SRGB), + &drawn(Technique::Draw, 1.0, TR, 1, false), + &[END], + ]) + ); +} + +#[test] +fn a_texrender_of_another_format_is_destroyed_and_made_again() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_EXTENDED; + s.texrender = Some(TR); + s.fb_srgb = true; + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_709_EXTENDED), + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(TR)), + E::Texrender, + E::Destroy(Some(TR)), + E::SetTexrender(None), + E::Texrender, + E::Create(GS_RGBA16F, GS_ZS_NONE), + E::SetTexrender(Some(NEW_TR)), + ], + &into_texrender(NEW_TR, GS_CS_709_EXTENDED), + &drawn(Technique::DrawTonemap, 1.0, NEW_TR, 1, true), + &[END], + ]) + ); + assert!(m.s.borrow().fb_srgb); +} + +#[test] +fn sdr_into_scrgb_reads_the_white_level_and_multiplies() { + let m = Model::new().with(|s| { + s.current_space = GS_CS_709_SCRGB; + s.texrender = Some(TR); + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_709_SCRGB, GS_CS_SRGB), + &[E::WhiteLevel], + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(TR)), + E::Texrender + ], + &into_texrender(TR, GS_CS_SRGB), + &drawn(Technique::DrawMultiply, 300.0 / 80.0, TR, 1, false), + &[END], + ]) + ); +} + +#[test] +fn scrgb_into_sdr_divides_by_the_white_level() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_SCRGB; + s.texrender = Some(OTHER_TR); + s.white = 200.0; + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_709_SCRGB), + &[E::WhiteLevel], + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(OTHER_TR)), + E::Texrender + ], + &into_texrender(OTHER_TR, GS_CS_709_SCRGB), + &drawn( + Technique::DrawMultiplyTonemap, + 80.0 / 200.0, + OTHER_TR, + 1, + false + ), + &[END], + ]) + ); +} + +#[test] +fn a_begin_that_fails_draws_nothing() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_EXTENDED; + s.texrender = Some(OTHER_TR); + s.begin_ok = false; + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_709_EXTENDED), + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(OTHER_TR)), + E::Texrender, + E::Texrender, + E::Reset(Some(OTHER_TR)), + E::Width, + E::Height, + E::Texrender, + E::TexrenderBegin(Some(OTHER_TR), 4, 3, GS_CS_709_EXTENDED), + END, + ], + ]) + ); +} + +#[test] +fn a_zero_size_draws_nothing() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_EXTENDED; + s.width = 0; + }); + let events = m.run(EFFECT); + assert!(events.contains(&E::TexrenderBegin(Some(NEW_TR), 0, 3, GS_CS_709_EXTENDED))); + assert!(!events.iter().any(|e| matches!(e, E::VideoRender(..)))); + assert_eq!(events.last(), Some(&END)); +} + +#[test] +fn a_create_that_fails_resets_and_begins_null() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_EXTENDED; + s.created = None; + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_SRGB, GS_CS_709_EXTENDED), + &[ + E::Texrender, + E::Texrender, + E::Create(GS_RGBA16F, GS_ZS_NONE), + E::SetTexrender(None), + E::Texrender, + E::Reset(None), + E::Width, + E::Height, + E::Texrender, + E::TexrenderBegin(None, 4, 3, GS_CS_709_EXTENDED), + END, + ], + ]) + ); +} + +#[test] +fn every_pass_draws_one_sprite() { + for passes in [0, 2, 3] { + let m = Model::new().with(|s| { + s.current_space = GS_CS_709_EXTENDED; + s.texrender = Some(TR); + s.passes = passes; + }); + assert_eq!( + m.run(EFFECT), + seq(&[ + &opening(GS_CS_709_EXTENDED, GS_CS_SRGB), + &[ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(TR)), + E::Texrender + ], + &into_texrender(TR, GS_CS_SRGB), + &drawn(Technique::Draw, 1.0, TR, passes, false), + &[END], + ]), + "{passes} passes" + ); + } +} + +/// The texrender is read again after the source's draw: one the source +/// swapped in is ended and drawn. +#[test] +fn the_texrender_is_read_again_after_the_draw() { + let m = Model::new().with(|s| { + s.current_space = GS_CS_709_EXTENDED; + s.texrender = Some(TR); + s.render_sets_texrender = Some(Some(OTHER_TR)); + }); + let events = m.run(EFFECT); + let after = events + .iter() + .position(|e| matches!(e, E::VideoRender(..))) + .unwrap(); + assert_eq!( + events[after + 1..after + 4], + [ + E::Blending(true), + E::Texrender, + E::TexrenderEnd(Some(OTHER_TR)) + ] + ); + assert!(events.contains(&E::TexrenderTexture(Some(OTHER_TR)))); + assert!(events.contains(&E::SetTextureSrgb(IMAGE, OTHER_TR + 100))); +} + +/// The texrender is read again for the destroy: one swapped in by the +/// format query is the one destroyed. +#[test] +fn the_texrender_is_read_again_for_the_destroy() { + let m = Model::new().with(|s| { + s.source_space = GS_CS_709_EXTENDED; + s.texrender = Some(TR); + s.format_sets_texrender = Some(Some(OTHER_TR)); + }); + let events = m.run(EFFECT); + assert_eq!( + events[5..11], + [ + E::Texrender, + E::Texrender, + E::TexrenderFormat(Some(TR)), + E::Texrender, + E::Destroy(Some(OTHER_TR)), + E::SetTexrender(None), + ] + ); +} + +#[test] +fn the_white_level_is_not_read_without_scrgb() { + for (source, current) in [ + (GS_CS_SRGB, GS_CS_SRGB), + (GS_CS_709_EXTENDED, GS_CS_SRGB), + (GS_CS_SRGB, GS_CS_709_EXTENDED), + ] { + let m = Model::new().with(|s| { + s.source_space = source; + s.current_space = current; + }); + assert!(!m.run(EFFECT).contains(&E::WhiteLevel)); + } +} + +#[test] +fn size_f32_rounds_like_the_c_conversion() { + assert_eq!(size_f32(0), 0.0); + assert_eq!(size_f32(1920), 1920.0); + assert_eq!(size_f32(16_777_217), 16_777_216.0); + assert_eq!(size_f32(u32::MAX), 4_294_967_296.0); +} + +#[test] +fn the_param_names_are_the_default_effects() { + assert_eq!(Param::Image.name(), c"image"); + assert_eq!(Param::Multiplier.name(), c"multiplier"); +} diff --git a/rust/obs-source/tests/source/convert_render_parity.rs b/rust/obs-source/tests/source/convert_render_parity.rs new file mode 100644 index 0000000000..519b5515d5 --- /dev/null +++ b/rust/obs-source/tests/source/convert_render_parity.rs @@ -0,0 +1,788 @@ +//! Tier 3: the original C `source_render()` (`source_convert_render.c`, the +//! extracted file compiled with its hidden wrapper renamed, and the +//! oracle's original draw decisions) against the Rust export, each side on +//! its own real-layout source, data, effects, techniques, params, textures, +//! texrenders and timer set up the same way. Both go through the oracle's +//! stand-ins for the profiler, the colour spaces, the format, the white +//! level, the texrender calls, the base size, blending, the clear, the +//! ortho, the source's `video_render`, the default effect, the lookups, the +//! framebuffer sRGB flag, the sets, the blend stack and the technique, pass +//! and sprite calls (the Rust side through the production adapters), so one +//! log holds every call in order with its arguments (floats as bits), the +//! blend depth and the texrender, technique, pass, profiler and blending +//! state; with the clobber bits the stand-ins also repoint `context.data` +//! and `color_space_texrender` and swap `info.video_render` mid-call, so a +//! field read out of place shows. The log, the fields, the graphics state +//! left and every other byte of the source must match over a grid of +//! spaces, held texrenders and their formats, sizes, effects, passes, +//! failures and clobbers, and a proptest. Twelve mutants, built on the same +//! adapters and the same safe core, must not match. No intentional +//! differences or exclusions. +use core::cell::Cell; +use core::ffi::{CStr, c_char, c_void}; +use core::ptr::{self, NonNull}; +use obs_source::convert_render::{self, Host, Param}; +use obs_source::draw_plan::Technique; +use obs_source::ffi::source_convert_render as rust; +use proptest::prelude::*; + +const EVENTS: usize = 64; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +struct Spec { + start: u64, + white: f32, + current_space: i32, + source_space: i32, + width: u32, + height: u32, + texrender: i32, + formats: [i32; 4], + data: i32, + effect: i32, + passes: u32, + clobber: u32, + missing: u32, + timer: bool, + create_fails: bool, + begin_fails: bool, + no_texture: bool, + no_default_effect: bool, + fb_srgb: bool, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RawEvent { + kind: u32, + blend: i32, + state: i32, + pad: i32, + a: i64, + b: i64, + c: i64, + d: i64, +} + +#[repr(C)] +struct Log { + events: u32, + event: [RawEvent; EVENTS], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Outcome { + texrender: i32, + data: i32, + blend: i32, + state: i32, + destroyed: u32, + created_format: i32, + fb_srgb: bool, + render: u8, +} + +unsafe extern "C" { + fn oracle_cr_new(spec: *const Spec, side: i32) -> *mut c_void; + fn oracle_cr_free(side: i32); + fn oracle_cr_watch(side: i32); + fn oracle_cr_log(out: *mut Log); + fn oracle_cr_effect() -> *mut c_void; + fn oracle_cr_result(side: i32, out: *mut Outcome); + fn oracle_cr_same() -> bool; + fn oracle_cr_events() -> usize; + fn oracle_cr_run(effect: *mut c_void); + + fn obs_source_convert_render_begin(timer: *mut *mut c_void) -> u64; + fn obs_source_convert_render_end(source: *mut c_void, start: u64, timer: *mut c_void); + fn obs_source_convert_render_data(source: *const c_void) -> *mut c_void; + fn obs_source_convert_render_color_space() -> i32; + fn obs_source_convert_render_source_space(source: *mut c_void, current: i32) -> i32; + fn obs_source_convert_render_format(space: i32) -> i32; + fn obs_source_convert_render_sdr_white_level() -> f32; + fn obs_source_convert_render_texrender(source: *const c_void) -> *mut c_void; + fn obs_source_convert_render_set_texrender(source: *mut c_void, texrender: *mut c_void); + fn obs_source_convert_render_texrender_format(texrender: *const c_void) -> i32; + fn obs_source_convert_render_texrender_destroy(texrender: *mut c_void); + fn obs_source_convert_render_texrender_create(format: i32, zsformat: i32) -> *mut c_void; + fn obs_source_convert_render_texrender_reset(texrender: *mut c_void); + fn obs_source_convert_render_width(source: *mut c_void) -> u32; + fn obs_source_convert_render_height(source: *mut c_void) -> u32; + fn obs_source_convert_render_texrender_begin( + texrender: *mut c_void, + cx: u32, + cy: u32, + space: i32, + ) -> bool; + fn obs_source_convert_render_enable_blending(enable: bool); + fn obs_source_convert_render_clear(flags: u32, color: *const [f32; 4], depth: f32, stencil: u8); + fn obs_source_convert_render_ortho( + left: f32, + right: f32, + top: f32, + bottom: f32, + znear: f32, + zfar: f32, + ); + fn obs_source_convert_render_video_render( + source: *mut c_void, + data: *mut c_void, + effect: *mut c_void, + ); + fn obs_source_convert_render_texrender_end(texrender: *mut c_void); + fn obs_source_convert_render_default_effect() -> *mut c_void; + fn obs_source_convert_render_technique(effect: *mut c_void, technique: i32) -> *mut c_void; + fn obs_source_convert_render_framebuffer_srgb() -> bool; + fn obs_source_convert_render_enable_framebuffer_srgb(enable: bool); + fn obs_source_convert_render_texrender_texture(texrender: *const c_void) -> *mut c_void; + fn obs_source_convert_render_param(effect: *mut c_void, name: *const c_char) -> *mut c_void; + fn obs_source_convert_render_set_texture_srgb(param: *mut c_void, tex: *mut c_void); + fn obs_source_convert_render_set_float(param: *mut c_void, value: f32); + fn obs_source_convert_render_blend_push(); + fn obs_source_convert_render_blend_function(src: i32, dest: i32); + fn obs_source_convert_render_technique_begin(tech: *mut c_void) -> usize; + fn obs_source_convert_render_begin_pass(tech: *mut c_void, pass: usize); + fn obs_source_convert_render_draw_sprite(tex: *mut c_void, flip: u32, width: u32, height: u32); + fn obs_source_convert_render_end_pass(tech: *mut c_void); + fn obs_source_convert_render_technique_end(tech: *mut c_void); + fn obs_source_convert_render_blend_pop(); +} + +/// The export's core on the adapters, with one change each. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mutant { + /// `context.data` is read before the profiler begins. + DataEarly, + /// The texrender read for the format check is reused for the destroy. + DestroyCached, + /// The texrender is never reset. + NoReset, + /// The texrender read for the reset is reused for the begin. + BeginCached, + /// The base height is the base width. + HeightIsWidth, + /// Blending is never turned back on. + BlendingLeftOff, + /// The texrender read for the begin is reused for the end. + EndCached, + /// The framebuffer sRGB flag is not restored. + FbNotRestored, + /// The multiplier is always 1. + MultiplierOne, + /// One sprite whatever the pass count. + OneSprite, + /// The texrender is created with a depth buffer. + CreateWithDepth, + /// The profiler is never ended. + NoProfilerEnd, +} + +const MUTANTS: [Mutant; 12] = [ + Mutant::DataEarly, + Mutant::DestroyCached, + Mutant::NoReset, + Mutant::BeginCached, + Mutant::HeightIsWidth, + Mutant::BlendingLeftOff, + Mutant::EndCached, + Mutant::FbNotRestored, + Mutant::MultiplierOne, + Mutant::OneSprite, + Mutant::CreateWithDepth, + Mutant::NoProfilerEnd, +]; + +#[derive(Debug, Clone, Copy)] +enum Side { + C, + Rust, + Mutant(Mutant), +} + +#[derive(Clone, Copy)] +struct Src(*mut c_void); + +#[derive(Clone, Copy)] +struct Ptr(*mut c_void); + +#[derive(Clone, Copy)] +struct Tr(NonNull); + +fn tr_ptr(texrender: Option) -> *mut c_void { + texrender.map_or(ptr::null_mut(), |t| t.0.as_ptr()) +} + +struct MutantHost { + mutant: Mutant, + data: Cell>, + last_texrender: Cell>>, + set_fb: Cell, + passes_drawn: Cell, +} + +impl MutantHost { + fn is(&self, m: Mutant) -> bool { + self.mutant == m + } +} + +// SAFETY (every call): the oracle's live source and the pointers its +// stand-ins gave, called as the core calls the production host. +impl Host for MutantHost { + type Source = Src; + type Data = Ptr; + type Effect = Ptr; + type Technique = Ptr; + type Param = Ptr; + type Texture = Ptr; + type Texrender = Tr; + type Timer = Ptr; + fn render_begin(&self) -> (u64, Ptr) { + let mut timer = ptr::null_mut(); + let start = unsafe { obs_source_convert_render_begin(&mut timer) }; + (start, Ptr(timer)) + } + fn render_end(&self, s: Src, start: u64, timer: Ptr) { + if !self.is(Mutant::NoProfilerEnd) { + unsafe { obs_source_convert_render_end(s.0, start, timer.0) } + } + } + fn data(&self, s: Src) -> Ptr { + if let Some(data) = self.data.get() { + return data; + } + Ptr(unsafe { obs_source_convert_render_data(s.0) }) + } + fn color_space(&self) -> i32 { + unsafe { obs_source_convert_render_color_space() } + } + fn source_color_space(&self, s: Src, current: i32) -> i32 { + unsafe { obs_source_convert_render_source_space(s.0, current) } + } + fn format_from_space(&self, space: i32) -> i32 { + unsafe { obs_source_convert_render_format(space) } + } + fn sdr_white_level(&self) -> f32 { + unsafe { obs_source_convert_render_sdr_white_level() } + } + fn texrender(&self, s: Src) -> Option { + let fresh = NonNull::new(unsafe { obs_source_convert_render_texrender(s.0) }).map(Tr); + // BeginCached: the reset's texrender, kept by the reset, is the + // begin's; EndCached: the begin's, kept by the begin, is the end's. + // Each is used by the next read only. + if matches!(self.mutant, Mutant::BeginCached | Mutant::EndCached) + && let Some(cached) = self.last_texrender.take() + { + return cached; + } + fresh + } + fn set_texrender(&self, s: Src, texrender: Option) { + unsafe { obs_source_convert_render_set_texrender(s.0, tr_ptr(texrender)) } + } + fn texrender_format(&self, texrender: Option) -> i32 { + if self.is(Mutant::DestroyCached) { + self.last_texrender.set(Some(texrender)); + } + unsafe { obs_source_convert_render_texrender_format(tr_ptr(texrender)) } + } + fn texrender_destroy(&self, texrender: Option) { + let texrender = if self.is(Mutant::DestroyCached) { + self.last_texrender.take().unwrap_or(texrender) + } else { + texrender + }; + unsafe { obs_source_convert_render_texrender_destroy(tr_ptr(texrender)) } + } + fn texrender_create(&self, format: i32, zsformat: i32) -> Option { + let zsformat = if self.is(Mutant::CreateWithDepth) { + 1 + } else { + zsformat + }; + NonNull::new(unsafe { obs_source_convert_render_texrender_create(format, zsformat) }) + .map(Tr) + } + fn texrender_reset(&self, texrender: Option) { + if self.is(Mutant::BeginCached) { + self.last_texrender.set(Some(texrender)); + } + if !self.is(Mutant::NoReset) { + unsafe { obs_source_convert_render_texrender_reset(tr_ptr(texrender)) } + } + } + fn base_width(&self, s: Src) -> u32 { + unsafe { obs_source_convert_render_width(s.0) } + } + fn base_height(&self, s: Src) -> u32 { + if self.is(Mutant::HeightIsWidth) { + return unsafe { obs_source_convert_render_width(s.0) }; + } + unsafe { obs_source_convert_render_height(s.0) } + } + fn texrender_begin(&self, texrender: Option, cx: u32, cy: u32, space: i32) -> bool { + if self.is(Mutant::EndCached) { + self.last_texrender.set(Some(texrender)); + } + unsafe { obs_source_convert_render_texrender_begin(tr_ptr(texrender), cx, cy, space) } + } + fn enable_blending(&self, enable: bool) { + if !(self.is(Mutant::BlendingLeftOff) && enable) { + unsafe { obs_source_convert_render_enable_blending(enable) } + } + } + fn clear(&self, flags: u32, color: [f32; 4], depth: f32, stencil: u8) { + unsafe { obs_source_convert_render_clear(flags, &color, depth, stencil) } + } + fn ortho(&self, left: f32, right: f32, top: f32, bottom: f32, znear: f32, zfar: f32) { + unsafe { obs_source_convert_render_ortho(left, right, top, bottom, znear, zfar) } + } + fn video_render(&self, s: Src, data: Ptr, effect: Ptr) { + unsafe { obs_source_convert_render_video_render(s.0, data.0, effect.0) } + } + fn texrender_end(&self, texrender: Option) { + unsafe { obs_source_convert_render_texrender_end(tr_ptr(texrender)) } + } + fn default_effect(&self) -> Ptr { + Ptr(unsafe { obs_source_convert_render_default_effect() }) + } + fn technique(&self, effect: Ptr, technique: Technique) -> Ptr { + let value = i32::try_from(technique.value()).unwrap(); + Ptr(unsafe { obs_source_convert_render_technique(effect.0, value) }) + } + fn framebuffer_srgb_enabled(&self) -> bool { + unsafe { obs_source_convert_render_framebuffer_srgb() } + } + fn enable_framebuffer_srgb(&self, enable: bool) { + let n = self.set_fb.get(); + self.set_fb.set(n + 1); + if !(self.is(Mutant::FbNotRestored) && n == 1) { + unsafe { obs_source_convert_render_enable_framebuffer_srgb(enable) } + } + } + fn texrender_texture(&self, texrender: Option) -> Ptr { + Ptr(unsafe { obs_source_convert_render_texrender_texture(tr_ptr(texrender)) }) + } + fn param(&self, effect: Ptr, param: Param) -> Ptr { + let name: &CStr = param.name(); + Ptr(unsafe { obs_source_convert_render_param(effect.0, name.as_ptr()) }) + } + fn set_texture_srgb(&self, param: Ptr, tex: Ptr) { + unsafe { obs_source_convert_render_set_texture_srgb(param.0, tex.0) } + } + fn set_float(&self, param: Ptr, value: f32) { + let value = if self.is(Mutant::MultiplierOne) { + 1.0 + } else { + value + }; + unsafe { obs_source_convert_render_set_float(param.0, value) } + } + fn blend_state_push(&self) { + unsafe { obs_source_convert_render_blend_push() } + } + fn blend_function(&self, src: i32, dest: i32) { + unsafe { obs_source_convert_render_blend_function(src, dest) } + } + fn technique_begin(&self, tech: Ptr) -> usize { + unsafe { obs_source_convert_render_technique_begin(tech.0) } + } + fn technique_begin_pass(&self, tech: Ptr, pass: usize) { + unsafe { obs_source_convert_render_begin_pass(tech.0, pass) } + } + fn draw_sprite(&self, tex: Ptr, flip: u32, width: u32, height: u32) { + let n = self.passes_drawn.get(); + self.passes_drawn.set(n + 1); + if !(self.is(Mutant::OneSprite) && n > 0) { + unsafe { obs_source_convert_render_draw_sprite(tex.0, flip, width, height) } + } + } + fn technique_end_pass(&self, tech: Ptr) { + unsafe { obs_source_convert_render_end_pass(tech.0) } + } + fn technique_end(&self, tech: Ptr) { + unsafe { obs_source_convert_render_technique_end(tech.0) } + } + fn blend_state_pop(&self) { + unsafe { obs_source_convert_render_blend_pop() } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Run { + outcome: Outcome, + log: Vec, +} + +fn take_log() -> Vec { + let mut log = Box::new(Log { + events: 0, + event: [RawEvent { + kind: 0, + blend: 0, + state: 0, + pad: 0, + a: 0, + b: 0, + c: 0, + d: 0, + }; EVENTS], + }); + unsafe { oracle_cr_log(&mut *log) }; + let n = usize::try_from(log.events).unwrap().min(EVENTS); + log.event[..n].to_vec() +} + +fn outcome(side: i32) -> Outcome { + let mut out = Outcome { + texrender: 0, + data: 0, + blend: 0, + state: 0, + destroyed: 0, + created_format: 0, + fb_srgb: false, + render: 0, + }; + unsafe { oracle_cr_result(side, &mut out) }; + out +} + +/// One render of `side` on its own source (side 0 for the C, 1 for the +/// others), the source left for [`compare`]. +fn render(spec: &Spec, side: Side) -> Run { + let k = i32::from(!matches!(side, Side::C)); + let source = unsafe { oracle_cr_new(spec, k) }; + unsafe { oracle_cr_watch(k) }; + let effect = unsafe { oracle_cr_effect() }; + match side { + Side::C => unsafe { oracle_cr_run(effect) }, + Side::Rust => unsafe { rust::obs_source_default_render_source_render(source, effect) }, + Side::Mutant(mutant) => { + let host = MutantHost { + mutant, + data: Cell::new(None), + last_texrender: Cell::new(None), + set_fb: Cell::new(0), + passes_drawn: Cell::new(0), + }; + if mutant == Mutant::DataEarly { + host.data + .set(Some(Ptr(unsafe { obs_source_convert_render_data(source) }))); + } + convert_render::source_render(&host, Src(source), Ptr(effect)); + } + } + Run { + outcome: outcome(k), + log: take_log(), + } +} + +/// The C and `side` over `spec`: both runs, and whether the two sources +/// are byte for byte the same. +fn compare(spec: &Spec, side: Side) -> (Run, Run, bool) { + let c = render(spec, Side::C); + let other = render(spec, side); + let same = unsafe { oracle_cr_same() }; + unsafe { + oracle_cr_free(0); + oracle_cr_free(1); + } + (c, other, same) +} + +fn matches(spec: &Spec, side: Side) -> bool { + let (c, other, same) = compare(spec, side); + c == other && same +} + +// ---------------------------------------------------------------- cases + +/// An sRGB source of 1920 x 1080 into an sRGB target, holding data 0 and +/// texrender 0 (of format 0), the caller's effect, one pass. +fn spec() -> Spec { + Spec { + start: 0xDEAD_BEEF, + white: 300.0, + current_space: 0, + source_space: 0, + width: 1920, + height: 1080, + texrender: 0, + formats: [0, 2, 3, 0], + data: 0, + effect: 0, + passes: 1, + clobber: 0, + missing: 0, + timer: true, + create_fails: false, + begin_fails: false, + no_texture: false, + no_default_effect: false, + fb_srgb: false, + } +} + +const CLOBBERS: [u32; 10] = [0, 1, 2, 4, 8, 16, 32, 64, 128, 255]; + +/// Visits every case of the grid with its index, built one at a time; +/// `visit` returns false to stop. +fn for_each_case(mut visit: impl FnMut(u64, &Spec) -> bool) { + let mut index = 0_u64; + for source_space in [0, 1, 2, 3, 7] { + for current_space in [0, 1, 2, 3, -1] { + for texrender in [-1, 0, 1, 2] { + for size in 0..3_u32 { + for extra in 0..6_u32 { + for clobber in CLOBBERS { + let mut s = spec(); + s.source_space = source_space; + s.current_space = current_space; + s.texrender = texrender; + (s.width, s.height) = match size { + 0 => (1920, 1080), + 1 => (0, 1080), + _ => (7, 0), + }; + s.effect = if extra == 1 { -1 } else { 0 }; + s.data = if extra == 1 { -1 } else { 0 }; + s.passes = match extra { + 2 => 0, + 3 => 3, + _ => 1, + }; + s.timer = extra != 2; + s.create_fails = extra == 4; + s.begin_fails = extra == 5; + s.no_texture = extra == 4; + s.missing = if extra == 5 { 0xff } else { 0 }; + s.no_default_effect = extra == 2; + s.fb_srgb = extra & 1 != 0; + s.white = if extra == 3 { 0.0 } else { 300.0 }; + s.clobber = clobber; + if !visit(index, &s) { + return; + } + index += 1; + } + } + } + } + } + } +} + +/// Whether the parity level runs case `index`: the cases without a clobber +/// always, the rest sampled. +fn sampled(index: u64, s: &Spec) -> bool { + s.clobber == 0 || obs_c_oracle::parity::keep(index) +} + +#[test] +fn the_oracle_logs_the_events_the_test_mirrors() { + assert_eq!(unsafe { oracle_cr_events() }, EVENTS); +} + +#[test] +fn matches_c_over_the_grid() { + let mut ran = 0_u32; + for_each_case(|index, s| { + if sampled(index, s) { + let (c, r, same) = compare(s, Side::Rust); + assert_eq!(c, r, "{s:?}"); + assert!(same, "bytes differ: {s:?}"); + ran += 1; + } + true + }); + assert!(ran > 0); +} + +fn bits(value: f32) -> i64 { + i64::from(value.to_bits()) +} + +/// One event as (kind, blend depth, state, a, b, c, d). +type Row = (u32, i32, i32, i64, i64, i64, i64); + +/// The log of an sRGB source into scRGB through a texrender of another +/// format, two passes: every call, its arguments and the state it ran in, +/// in the C's order. +#[test] +fn the_logs_see_every_call_in_order() { + let mut s = spec(); + s.current_space = 3; + s.texrender = 1; + s.passes = 2; + s.fb_srgb = true; + let (c, r, same) = compare(&s, Side::Rust); + assert_eq!(c, r); + assert!(same); + let events: Vec = c + .log + .iter() + .map(|e| (e.kind, e.blend, e.state, e.a, e.b, e.c, e.d)) + .collect(); + let multiplier = bits(300.0 / 80.0); + assert_eq!( + events, + [ + (1, 0, 0, 1, 0, 0, 0), + (3, 0, 4, 0, 0, 0, 0), + (4, 0, 4, 1, 1, 3, 0), + (5, 0, 4, 0, 0, 0, 0), + (6, 0, 4, 0, 0, 0, 0), + (7, 0, 4, 1, 0, 0, 0), + (8, 0, 4, 1, 0, 0, 0), + (9, 0, 4, 0, 0, 0, 0), + (10, 0, 4, 3, 0, 0, 0), + (11, 0, 4, 1, 0, 0, 0), + (12, 0, 4, 1, 0, 0, 0), + (13, 0, 4, 3, 1920, 1080, 0), + (14, 0, 12, 0, 0, 0, 0), + (15, 0, 28, 1, 0, 0, 0), + (36, 0, 28, 0, 0, 0, 0), + (16, 0, 28, 0, bits(1920.0), 0, bits(1080.0)), + (35, 0, 28, bits(-100.0), bits(100.0), 0, 0), + (17, 0, 28, 0, 0, 0, 0), + (14, 0, 28, 1, 0, 0, 0), + (18, 0, 4, 3, 0, 0, 0), + (19, 0, 4, 1, 1, 0, 0), + (20, 0, 4, 1, 0, 0, 0), + (21, 0, 4, 1, 0, 0, 0), + (22, 0, 4, 3, 0, 0, 0), + (23, 0, 4, 1, 0, 0, 0), + (24, 0, 4, 0, 3, 0, 0), + (23, 0, 4, 1, 1, 0, 0), + (25, 0, 4, 1, multiplier, 0, 0), + (26, 1, 4, 0, 0, 0, 0), + (27, 1, 4, 1, 5, 0, 0), + (28, 1, 4, 1, 0, 0, 0), + (29, 1, 5, 1, 0, 0, 0), + (30, 1, 7, 3, 0, 0, 0), + (31, 1, 5, 1, 0, 0, 0), + (29, 1, 5, 1, 1, 0, 0), + (30, 1, 7, 3, 0, 0, 0), + (31, 1, 5, 1, 0, 0, 0), + (32, 1, 4, 1, 0, 0, 0), + (33, 0, 4, 0, 0, 0, 0), + (21, 0, 4, 1, 0, 0, 0), + (2, 0, 0, 1, 0xDEAD_BEEF, 0, 0), + ] + ); + assert_eq!(c.outcome.texrender, 3); + assert_eq!(c.outcome.destroyed, 1 << 1); + assert_eq!(c.outcome.blend, 0); + assert_eq!(c.outcome.state, 0); + assert!(c.outcome.fb_srgb); +} + +/// Every clobber reaches the C on some case of the grid: its log differs +/// from the same case without it. +#[test] +fn every_clobber_reaches_the_c() { + for bit in 0..8 { + let mut reached = false; + for_each_case(|_, s| { + if s.clobber != 0 { + return true; + } + let mut with = *s; + with.clobber = 1 << bit; + let plain = render(s, Side::C); + unsafe { oracle_cr_free(0) }; + let clobbered = render(&with, Side::C); + unsafe { oracle_cr_free(0) }; + reached = plain != clobbered; + !reached + }); + assert!(reached, "clobber bit {bit} never reaches the C"); + } +} + +#[test] +fn rejects_the_mutants() { + for mutant in MUTANTS { + let mut caught = false; + for_each_case(|_, s| { + caught = !matches(s, Side::Mutant(mutant)); + !caught + }); + assert!(caught, "{mutant:?} survives"); + } +} + +fn any_token(n: i32) -> impl Strategy { + prop_oneof![Just(-1), 0..n] +} + +fn any_spec() -> impl Strategy { + ( + ( + any::(), + any::(), + -2..9_i32, + -2..9_i32, + prop_oneof![Just(0_u32), 1..4096_u32, any::()], + prop_oneof![Just(0_u32), 1..4096_u32, any::()], + ), + ( + any_token(3), + prop::array::uniform4(0..4_i32), + any_token(3), + any_token(1), + 0..4_u32, + any::(), + any::(), + ), + any::<[bool; 6]>(), + ) + .prop_map( + |( + (start, white, current_space, source_space, width, height), + (texrender, formats, data, effect, passes, clobber, missing), + flags, + )| Spec { + start, + white: f32::from_bits(white), + current_space, + source_space, + width, + height, + texrender, + formats, + data, + effect, + passes, + clobber: u32::from(clobber), + missing: u32::from(missing), + timer: flags[0], + create_fails: flags[1], + begin_fails: flags[2], + no_texture: flags[3], + no_default_effect: flags[4], + fb_srgb: flags[5], + }, + ) +} + +#[test] +fn matches_c_on_random_renders() { + let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig { + cases: obs_c_oracle::parity::cases(512), + failure_persistence: None, + ..ProptestConfig::default() + }); + runner + .run(&any_spec(), |s| { + let (c, r, same) = compare(&s, Side::Rust); + prop_assert_eq!(c, r); + prop_assert!(same); + Ok(()) + }) + .unwrap(); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index a17e4341b7..0ea507f859 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -75,6 +75,8 @@ mod configurable; mod configurable_parity; mod conversion_plan; mod conversion_plan_parity; +mod convert_render; +mod convert_render_parity; mod copy_filters; mod copy_filters_parity; mod default_flags; diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index cee666e4db..6b01aa4d6a 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -17985,6 +17985,34 @@ } ] }, + "test_source_convert_render": { + "sources": [ + "test/cmocka/test_source_convert_render.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + { + "name": "m", + "requires": { + "not": "MSVC" + } + }, + "OBS::native-test-cmocka" + ], + "requires": { + "all": [ + "OS_LINUX", + "HAVE_OBS_OPENGL" + ] + }, + "artifact_definitions": { + "GRAPHICS_MODULE_PATH": "OBS::libobs-opengl" + }, + "watch_inputs": [ + "libobs/data" + ] + }, "test_source_copy_filters": { "sources": [ "test/cmocka/test_source_copy_filters.c" @@ -31011,6 +31039,23 @@ ], "suite": "core" }, + "test_source_convert_render": { + "target": "test_source_convert_render", + "command": [ + "${target}" + ], + "suite": "graphics", + "working_directory": "${runtime}", + "timeout_seconds": 120, + "optional_prefixes": [ + [ + "xvfb-run", + "-a", + "-s", + "-screen 0 1280x1024x24 -noreset" + ] + ] + }, "test_source_copy_filters": { "target": "test_source_copy_filters", "command": [ diff --git a/test/cmocka/test_source_convert_render.c b/test/cmocka/test_source_convert_render.c new file mode 100644 index 0000000000..af01875aaf --- /dev/null +++ b/test/cmocka/test_source_convert_render.c @@ -0,0 +1,499 @@ +/* Characterize source_render() (#5976), the draw behind + * obs_source_default_render() and obs_source_main_render(), through the real + * libobs (hybrid and the C reference). It is hidden, so each case reaches it + * through obs_source_video_render(). + * + * A source whose colour space is in the target's class (SDR, extended + * linear or scRGB) is drawn straight: its video_render runs once in the + * target. Any other pair goes through color_space_texrender: created for the + * source's format (dropped and made again when that format changes, kept + * while it matches), begun at the source's base size in the source's own + * colour space, cleared, and the source drawn into it; then the texture is + * drawn into the target with the default effect, blended + * GS_BLEND_ONE/GS_BLEND_INVSRCALPHA, the framebuffer sRGB flag restored. A + * source of size 0 cannot begin the texrender and is not drawn at all. + * + * Each case renders on the test thread inside the graphics context, into a + * CANVAS_SIZE target of the colour space the case picks, and records what + * each video_render callback saw: the effect, gs_get_color_space() and the + * viewport. The custom draw sources draw a solid colour of their own, so the + * SDR targets are read back. + * + * Left to the Rust swap's Tier 1 and Tier 3: the profiler bracket, the + * technique and multiplier picked, the order of every call. These are + * characterized, not endorsed. Rendering needs a display, so the cases run + * (under xvfb-run) on Linux and skip without one. */ + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#define CUSTOM_ID "convert_render_custom" +#define PLAIN_ID "convert_render_plain" +#define FRAME_SIZE 16 +#define CANVAS_SIZE 64 +#define MAX_DRAWS 4 + +static bool obs_up; + +/* What the sources report: their colour space and their size. */ +static enum gs_color_space source_space = GS_CS_SRGB; +static uint32_t source_size = FRAME_SIZE; + +/* ------------------------------------------------------------------------- */ +/* what the callbacks saw */ + +struct draw { + gs_effect_t *effect; + enum gs_color_space space; + struct gs_rect viewport; +}; + +static struct { + int count; + struct draw draw[MAX_DRAWS]; +} drawn; + +static void record(gs_effect_t *effect) +{ + if (drawn.count >= MAX_DRAWS) + return; + struct draw *d = &drawn.draw[drawn.count++]; + d->effect = effect; + d->space = gs_get_color_space(); + gs_get_viewport(&d->viewport); +} + +/* ------------------------------------------------------------------------- */ +/* sources */ + +static const char *any_name(void *type_data) +{ + (void)type_data; + return "convert render"; +} + +static void *keep_source(obs_data_t *settings, obs_source_t *source) +{ + (void)settings; + return source; +} + +static void no_destroy(void *data) +{ + (void)data; +} + +static uint32_t any_size(void *data) +{ + (void)data; + return source_size; +} + +static enum gs_color_space any_space(void *data, size_t count, const enum gs_color_space *preferred_spaces) +{ + (void)data; + (void)count; + (void)preferred_spaces; + return source_space; +} + +/* Custom draw: records, then fills its box with opaque red. */ +static void custom_render(void *data, gs_effect_t *effect) +{ + (void)data; + record(effect); + gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID); + struct vec4 red; + vec4_set(&red, 1.0f, 0.0f, 0.0f, 1.0f); + gs_effect_set_vec4(gs_effect_get_param_by_name(solid, "color"), &red); + while (gs_effect_loop(solid, "Solid")) + gs_draw_sprite(NULL, 0, source_size, source_size); +} + +static void plain_render(void *data, gs_effect_t *effect) +{ + (void)data; + record(effect); +} + +static void settle(void) +{ + uint32_t start = obs_get_total_frames(); + for (int i = 0; i < 500 && obs_get_total_frames() - start < 2; i++) + os_sleep_ms(10); + obs_wait_for_destroy_queue(); +} + +/* What render() saw around the draw. */ +static struct { + gs_effect_t *base_default; + bool fb_srgb_after; + bool rendered; + uint8_t px[CANVAS_SIZE * CANVAS_SIZE * 4]; +} seen; + +static const uint8_t *pixel(int x, int y) +{ + return seen.px + ((size_t)y * CANVAS_SIZE + (size_t)x) * 4; +} + +/* Renders the source on the calling thread into a CANVAS_SIZE target of + * colour space `target` (GS_RGBA for SDR, read back; GS_RGBA16F otherwise), + * with the framebuffer sRGB flag set to `fb_srgb`, and clears what the + * callbacks saw first. */ +static void render(obs_source_t *source, enum gs_color_space target, bool fb_srgb) +{ + uint8_t *data; + uint32_t linesize; + const bool sdr = target == GS_CS_SRGB; + + memset(&drawn, 0, sizeof(drawn)); + memset(&seen, 0, sizeof(seen)); + obs_enter_graphics(); + seen.base_default = obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_texrender_t *tr = gs_texrender_create(sdr ? GS_RGBA : GS_RGBA16F, GS_ZS_NONE); + gs_stagesurf_t *stage = sdr ? gs_stagesurface_create(CANVAS_SIZE, CANVAS_SIZE, GS_RGBA) : NULL; + + if (gs_texrender_begin_with_color_space(tr, CANVAS_SIZE, CANVAS_SIZE, target)) { + struct vec4 clear; + vec4_zero(&clear); + gs_clear(GS_CLEAR_COLOR, &clear, 0.0f, 0); + gs_ortho(0.0f, (float)CANVAS_SIZE, 0.0f, (float)CANVAS_SIZE, -100.0f, 100.0f); + gs_blend_state_push(); + gs_reset_blend_state(); + const bool previous_fb = gs_framebuffer_srgb_enabled(); + gs_enable_framebuffer_srgb(fb_srgb); + obs_source_video_render(source); + seen.fb_srgb_after = gs_framebuffer_srgb_enabled(); + gs_enable_framebuffer_srgb(previous_fb); + gs_blend_state_pop(); + gs_texrender_end(tr); + + if (stage) { + gs_stage_texture(stage, gs_texrender_get_texture(tr)); + if (gs_stagesurface_map(stage, &data, &linesize)) { + for (int y = 0; y < CANVAS_SIZE; y++) + memcpy(seen.px + (size_t)y * CANVAS_SIZE * 4, data + (size_t)y * linesize, + CANVAS_SIZE * 4); + gs_stagesurface_unmap(stage); + seen.rendered = true; + } + } + } + + if (stage) + gs_stagesurface_destroy(stage); + gs_texrender_destroy(tr); + obs_leave_graphics(); +} + +static obs_source_t *create(const char *id) +{ + obs_source_t *source = obs_source_create_private(id, id, NULL); + assert_non_null(source); + return source; +} + +static void assert_viewport(const struct draw *d, int size) +{ + assert_int_equal(d->viewport.x, 0); + assert_int_equal(d->viewport.y, 0); + assert_int_equal(d->viewport.cx, size); + assert_int_equal(d->viewport.cy, size); +} + +static void assert_near(uint8_t value, int expected) +{ + if (abs((int)value - expected) > 2) + fail_msg("%d is not within 2 of %d", value, expected); +} + +/* Opaque colour (r, g, b) inside the source's box, nothing outside. The + * custom draw source fills its box with red: drawn straight that stays + * 0xff0000; through the texrender it is tonemapped (into the target's + * class), which mixes in some green and blue. */ +static void assert_box(int r, int g, int b) +{ + assert_true(seen.rendered); + const uint8_t *in = pixel(FRAME_SIZE / 2, FRAME_SIZE / 2); + assert_near(in[0], r); + assert_near(in[1], g); + assert_near(in[2], b); + assert_int_equal(in[3], 255); + const uint8_t *out = pixel(FRAME_SIZE + FRAME_SIZE / 2, FRAME_SIZE + FRAME_SIZE / 2); + assert_int_equal(out[0] | out[1] | out[2] | out[3], 0); +} + +static void reset(void) +{ + source_space = GS_CS_SRGB; + source_size = FRAME_SIZE; +} + +/* ------------------------------------------------------------------------- */ +/* cases */ + +/* sRGB into sRGB: drawn straight into the target (its viewport), custom + * draw with no effect, no texrender. */ +static void same_space_draws_straight(void **state) +{ + (void)state; + if (!obs_up) + skip(); + reset(); + + obs_source_t *source = create(CUSTOM_ID); + render(source, GS_CS_SRGB, false); + assert_int_equal(drawn.count, 1); + assert_null(drawn.draw[0].effect); + assert_int_equal(drawn.draw[0].space, GS_CS_SRGB); + assert_viewport(&drawn.draw[0], CANVAS_SIZE); + assert_null(source->color_space_texrender); + assert_box(0xff, 0x00, 0x00); + assert_false(seen.fb_srgb_after); + + /* sRGB 16F is SDR too */ + source_space = GS_CS_SRGB_16F; + render(source, GS_CS_SRGB, true); + assert_int_equal(drawn.count, 1); + assert_int_equal(drawn.draw[0].space, GS_CS_SRGB); + assert_null(source->color_space_texrender); + assert_true(seen.fb_srgb_after); + + obs_source_release(source); + settle(); + reset(); +} + +/* Extended linear into sRGB: drawn into color_space_texrender (the source's + * format, the source's base size, the source's colour space), and that + * texture drawn into the target: opaque inside the box, nothing outside; + * the framebuffer sRGB flag is back either way. */ +static void hdr_into_sdr_draws_through_the_texrender(void **state) +{ + (void)state; + if (!obs_up) + skip(); + reset(); + + obs_source_t *source = create(CUSTOM_ID); + source_space = GS_CS_709_EXTENDED; + render(source, GS_CS_SRGB, false); + assert_int_equal(drawn.count, 1); + assert_null(drawn.draw[0].effect); + assert_int_equal(drawn.draw[0].space, GS_CS_709_EXTENDED); + assert_viewport(&drawn.draw[0], FRAME_SIZE); + assert_non_null(source->color_space_texrender); + assert_int_equal(gs_texrender_get_format(source->color_space_texrender), GS_RGBA16F); + assert_box(0xd0, 0x3b, 0x20); + assert_false(seen.fb_srgb_after); + + render(source, GS_CS_SRGB, true); + assert_int_equal(drawn.count, 1); + assert_box(0xd0, 0x3b, 0x20); + assert_true(seen.fb_srgb_after); + + obs_source_release(source); + settle(); + reset(); +} + +/* The texrender is kept while the source's format matches (scRGB is + * GS_RGBA16F as extended linear is), and made again in the new format when + * it does not. */ +static void texrender_follows_the_source_format(void **state) +{ + (void)state; + if (!obs_up) + skip(); + reset(); + + obs_source_t *source = create(CUSTOM_ID); + source_space = GS_CS_709_EXTENDED; + render(source, GS_CS_SRGB, false); + gs_texrender_t *first = source->color_space_texrender; + assert_non_null(first); + + render(source, GS_CS_SRGB, false); + assert_ptr_equal(source->color_space_texrender, first); + + source_space = GS_CS_709_SCRGB; + render(source, GS_CS_SRGB, false); + assert_int_equal(drawn.count, 1); + assert_int_equal(drawn.draw[0].space, GS_CS_709_SCRGB); + assert_ptr_equal(source->color_space_texrender, first); + assert_int_equal(gs_texrender_get_format(source->color_space_texrender), GS_RGBA16F); + assert_box(0x8b, 0x1d, 0x12); + + /* sRGB into extended linear: GS_RGBA */ + source_space = GS_CS_SRGB; + render(source, GS_CS_709_EXTENDED, false); + assert_int_equal(drawn.count, 1); + assert_int_equal(drawn.draw[0].space, GS_CS_SRGB); + assert_viewport(&drawn.draw[0], FRAME_SIZE); + assert_non_null(source->color_space_texrender); + assert_int_equal(gs_texrender_get_format(source->color_space_texrender), GS_RGBA); + + /* back in the target's class: drawn straight, the texrender kept */ + gs_texrender_t *kept = source->color_space_texrender; + render(source, GS_CS_SRGB, false); + assert_int_equal(drawn.count, 1); + assert_viewport(&drawn.draw[0], CANVAS_SIZE); + assert_ptr_equal(source->color_space_texrender, kept); + + obs_source_release(source); + settle(); + reset(); +} + +/* A plain source goes through obs_source_default_render(): converted, it + * still gets the default effect, into scRGB and out of it. */ +static void default_render_converts_with_the_default_effect(void **state) +{ + (void)state; + if (!obs_up) + skip(); + reset(); + + obs_source_t *source = create(PLAIN_ID); + render(source, GS_CS_709_SCRGB, false); + assert_int_equal(drawn.count, 1); + assert_ptr_equal(drawn.draw[0].effect, seen.base_default); + assert_int_equal(drawn.draw[0].space, GS_CS_SRGB); + assert_viewport(&drawn.draw[0], FRAME_SIZE); + assert_int_equal(gs_texrender_get_format(source->color_space_texrender), GS_RGBA); + + source_space = GS_CS_709_SCRGB; + render(source, GS_CS_SRGB, false); + assert_int_equal(drawn.count, 1); + assert_ptr_equal(drawn.draw[0].effect, seen.base_default); + assert_int_equal(drawn.draw[0].space, GS_CS_709_SCRGB); + assert_int_equal(gs_texrender_get_format(source->color_space_texrender), GS_RGBA16F); + + /* same class: straight, with the default effect */ + render(source, GS_CS_709_SCRGB, false); + assert_int_equal(drawn.count, 1); + assert_ptr_equal(drawn.draw[0].effect, seen.base_default); + assert_int_equal(drawn.draw[0].space, GS_CS_709_SCRGB); + assert_viewport(&drawn.draw[0], CANVAS_SIZE); + + obs_source_release(source); + settle(); + reset(); +} + +/* A source of size 0 that needs converting: the texrender is made but + * cannot begin, so the source is not drawn and nothing reaches the + * target. */ +static void zero_size_source_is_not_drawn(void **state) +{ + (void)state; + if (!obs_up) + skip(); + reset(); + + obs_source_t *source = create(CUSTOM_ID); + source_space = GS_CS_709_EXTENDED; + source_size = 0; + render(source, GS_CS_SRGB, true); + assert_int_equal(drawn.count, 0); + assert_non_null(source->color_space_texrender); + assert_true(seen.rendered); + const uint8_t *in = pixel(FRAME_SIZE / 2, FRAME_SIZE / 2); + assert_int_equal(in[0] | in[1] | in[2] | in[3], 0); + assert_true(seen.fb_srgb_after); + + obs_source_release(source); + settle(); + reset(); +} + +static int setup(void **state) +{ + (void)state; + /* obs_startup() needs a display on Linux (run under xvfb-run); the + * cases skip without one. */ + obs_up = obs_startup("en-US", NULL, NULL); + if (!obs_up) { + fprintf(stderr, "skipped: obs_startup failed (no display?)\n"); + return 0; + } + + struct obs_video_info ovi = { + .graphics_module = GRAPHICS_MODULE_PATH, + .fps_num = 30, + .fps_den = 1, + .base_width = CANVAS_SIZE, + .base_height = CANVAS_SIZE, + .output_width = CANVAS_SIZE, + .output_height = CANVAS_SIZE, + .output_format = VIDEO_FORMAT_NV12, + .colorspace = VIDEO_CS_709, + .range = VIDEO_RANGE_PARTIAL, + .scale_type = OBS_SCALE_BICUBIC, + }; + int ret = obs_reset_video(&ovi); + if (ret != OBS_VIDEO_SUCCESS) { + fprintf(stderr, "skipped: obs_reset_video failed: %d\n", ret); + obs_shutdown(); + obs_up = false; + return 0; + } + + struct obs_source_info custom = { + .id = CUSTOM_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW, + .get_name = any_name, + .create = keep_source, + .destroy = no_destroy, + .get_width = any_size, + .get_height = any_size, + .video_render = custom_render, + .video_get_color_space = any_space, + }; + obs_register_source(&custom); + + struct obs_source_info plain = custom; + plain.id = PLAIN_ID; + plain.output_flags = OBS_SOURCE_VIDEO; + plain.video_render = plain_render; + obs_register_source(&plain); + + /* Let the graphics thread get through its first frames before the + * cases render on its context. */ + for (int i = 0; i < 500 && obs_get_total_frames() < 3; i++) + os_sleep_ms(10); + return 0; +} + +static int teardown(void **state) +{ + (void)state; + if (obs_up) + obs_shutdown(); + return 0; +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(same_space_draws_straight), + cmocka_unit_test(hdr_into_sdr_draws_through_the_texrender), + cmocka_unit_test(texrender_follows_the_source_format), + cmocka_unit_test(default_render_converts_with_the_default_effect), + cmocka_unit_test(zero_size_source_is_not_drawn), + }; + + return cmocka_run_group_tests(tests, setup, teardown); +} diff --git a/test/cmocka/tests.d/test_source_convert_render.cmake b/test/cmocka/tests.d/test_source_convert_render.cmake new file mode 100644 index 0000000000..77fb2c85dd --- /dev/null +++ b/test/cmocka/tests.d/test_source_convert_render.cmake @@ -0,0 +1,9 @@ +# source_render() (#5976), the draw behind obs_source_default_render() and +# obs_source_main_render(), reached through obs_source_video_render() on the +# test thread inside the graphics context: a source in the target's colour +# space class drawn straight, any other drawn through color_space_texrender +# (kept while the source's format matches, made again when it changes) and +# that texture drawn into the target, the framebuffer sRGB flag restored, and +# a source of size 0 not drawn. It runs (under xvfb-run) on Linux and skips +# without a display. +# Canonical target and test: test/cmocka/build/test-graph.json.