Skip to content

libobs: Clamp loaded scene item crops and saturate the crop and group size casts - #1840

Merged
zackees merged 4 commits into
obs-rust:masterfrom
rdoupe:fix/scene-crop-clamp
Oct 22, 2026
Merged

zackees merged 4 commits into
obs-rust:masterfrom
rdoupe:fix/scene-crop-clamp

Conversation

@rdoupe

@rdoupe rdoupe commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1839

What and why

When a scene collection is loaded, scene item crops are now clamped the way obs_sceneitem_set_crop() clamps them. Crop and group size values outside their type's range now get the nearest value in range instead of hitting undefined C conversions. OBS never writes such values; hand-edited or generated scene collections can.

  • Load (R4-1). scene_load_item() stored the crop from the file as it was. A negative crop made the unsigned crop sum in calc_cx()/calc_cy() larger than any source, so "crop_left": -100 drew the item 2 px wide (or high). A crop of 2^31 or more came back with the other sign (3000000000 as -1294967296). The load now reads each crop as the nearest int and sets it with obs_sceneitem_set_crop(), so the setter's clamp is the only rule.

  • Casts and sums (R4-2). Four places were undefined out of range:

    • the int crop sum in calc_cx()/calc_cy();
    • the int crop plus bounds crop sum in render_item();
    • the (int) cast of a nested scene's scaled crop (1000000000 × 4000 came out INT_MIN, drawn 2 px wide);
    • the (uint32_t)ceilf() of a group's extent (content 1e20 px wide gave a group 0 px wide).

    The sums are now 64-bit. Each cast takes the nearest value in range (0 for NaN or a negative size).

  • Every value in range gives the result it gave before, so collections OBS writes load and draw the same. The arithmetic moves, first unchanged, to static inline helpers in libobs/obs-scene.h, so test_scene_crop_steps can build it with UBSan.

  • Not a memory-safety issue. The drawn size stays at most the source size or 2, the crop only moves the source in the render matrix, and a huge group size makes texture creation fail. A scene collection can already give a scene a custom size up to UINT32_MAX.

  • Upstream: obsproject/obs-studio master (7fc60ea38) has the same code in libobs/obs-scene.c; no upstream issue found. Line added under "Fixed upstream bugs > Scenes and UI" in docs/features.md.

RED → GREEN

  • RED commit: acfed96 test: Load out-of-range scene item crops and group sizes on master. test_scene_item_crop_load loads sources and scenes from a JSON string with obs_load_sources() through the real libobs. It fails 4 of 6 against C libobs, hybrid libobs and libobs-c-reference: negative_crop_is_clamped_on_load (crop kept at -100, -1, -2147483648; drawn 2 x 2), out_of_range_crop_saturates_on_load (-1294967296, 1294967296), nested_scene_crop_saturates_when_it_grows (INT_MIN) and huge_group_size_saturates (0 x 0). The two controls pass. 7314a8b moves the arithmetic unchanged and adds test_scene_crop_steps (-fsanitize=undefined,float-cast-overflow -fno-sanitize-recover). It fails crop_from_int64, then stops with obs-scene.h: runtime error: signed integer overflow: 2147483647 + 2147483647 cannot be represented in type 'int'. Built with recovering UBSan, it fails all 5 cases, with runtime errors for the crop sum, the nested crop cast (4e+12 is outside the range of representable values of type 'int') and the group size cast (4.29497e+09 ... 'unsigned int').
  • GREEN: 3736be5 (load clamp) and b4bb789 (saturation). The scene, group and transform clipboard tests, including both new ones (23 with C libobs; 24 with hybrid libobs and libobs-c-reference, which add test_scene_bounds_place_rust), pass on all three libraries. The steps test reports no UBSan errors. Full ctest -j4 (private Xvfb, private D-Bus, TMPDIR unset): 378/378 against hybrid libobs and 378/378 against libobs-c-reference. Two cases are skipped by design or environment, in both: open_crashes_without_obs_core, and test_hex_float_values_ignore_comma_locale (no comma-decimal locale installed). Exported symbols are identical across the three libraries (1766). uv run ci/local_gate.py --lane lint passes.
  • Real app (UI, protocol output or logging changes): N/A, no UI, protocol or logging change. The real-libobs test loads scene collections as the app does.

Checklist

  • Base is master (or the description starts with a Stacked: note)
  • I claimed the issue, or no one else has an open PR for it
  • Characterization test (if the unit had none), then RED, then GREEN commits (N/A for docs-only; a focused CI fix may push RED and GREEN together)
  • User-visible change: its line in docs/features.md is added or updated (not applicable: no user-visible change)
  • (Optional) Local gate passed and the pushed head is stamped; otherwise PR CI runs the full suite
  • Warning or flag changes (-W..., ratchets): built with scripting ON (PR CI builds no OBS app: run gh workflow run ci.yml --ref <branch> for the full builds) and cross-checked with clang and MSVC (not applicable: none)
  • Intentional differences from C listed in the parity test header and rust/README.md (ports) (not applicable: not a port)

test_scene_item_crop_load loads sources and scenes from a JSON string
with obs_load_sources(), as a scene collection is loaded, and checks
the crop, the item's drawn size and a group's size:

- a negative crop must load as 0, as obs_sceneitem_set_crop() makes it;
- a crop past the int range must be the nearest int, then clamped;
- a nested scene that grows from 1x1 to 4000x4000 scales its item's
  crop of 1000000000 past the int range: INT_MAX;
- a group whose children are 1e20 px apart is UINT32_MAX wide and high;
- controls: in-range crops, and crops whose sum is past the int range.

Fails 4 of 6 on master: the negative crop is kept (-100, the item is
drawn 2 x 2), 3000000000 comes back as -1294967296, the grown nested
crop is INT_MIN, and the group is 0 x 0.

Refs obs-rust#1839
The crop sum in calc_cx() and calc_cy(), the nested scene crop scale,
the crop offset render_item() draws with, the crop read from a scene
collection and a group's size from its content move, unchanged, to
static inline helpers in obs-scene.h, so a test can build them on their
own with UBSan.

test_scene_crop_steps does that (-fno-sanitize-recover) and asks for
the nearest value in range for values out of range. At this commit it
fails: crop_from_int64 gives -1294967296 for 3000000000, then
obs_scene_cropped_size() stops UBSan:

  obs-scene.h: runtime error: signed integer overflow:
  2147483647 + 2147483647 cannot be represented in type 'int'

Built with UBSan that recovers, every case fails, with a runtime error
for the crop sum, the nested crop cast (4e+12 is outside the range of
int) and the group size cast (4.29497e+09 is outside the range of
unsigned int). test_scene_item_crop_load fails as before.

Refs obs-rust#1839
scene_load_item() stored the crop as it was in the file, while
obs_sceneitem_set_crop() clamps a negative crop to 0. A scene
collection that OBS did not write (hand-edited or generated) with
"crop_left": -100 drew the item 2 px wide: the crop sum, read as
unsigned, is larger than any source. A crop past the int range came
back with the other sign (3000000000 as -1294967296).

The load now reads each crop as the nearest int and sets the crop
through obs_sceneitem_set_crop(), so the setter's clamp is the only
rule. Collections OBS writes hold crops of 0 and up and load as
before.

test_scene_item_crop_load: negative_crop_is_clamped_on_load and
out_of_range_crop_saturates_on_load pass; test_scene_crop_steps:
crop_from_int64 passes.

Refs obs-rust#1839
@rdoupe
rdoupe requested a review from zackees as a code owner October 22, 2026 22:40
Values from a scene collection could reach C conversions and sums that
are undefined out of range:

- calc_cx() and calc_cy() summed four int crops in an int;
- a nested scene that changed size scaled its item's crop with an
  (int) cast of the float product: 1000000000 x 4000 came out INT_MIN,
  and the item was drawn 2 px wide;
- render_item() summed the crop and the bounds crop in an int;
- a group's size was a (uint32_t) cast of ceilf() of its content's
  extent: content 1e20 px wide gave a group 0 px wide.

The sums are now done in 64 bits, and each cast takes the nearest value
in range (0 for NaN and for a negative size). Every value in range
gives the result it gave before. The results were only wrong sizes:
the drawn size stays at most the source size or 2, and the crop only
moves the source in the render matrix.

test_scene_item_crop_load and test_scene_crop_steps pass, the steps
test with UBSan and no runtime error.

Fixes obs-rust#1839
@rdoupe
rdoupe force-pushed the fix/scene-crop-clamp branch from 16d37f3 to b4bb789 Compare October 22, 2026 22:41
@zackees
zackees enabled auto-merge October 22, 2026 22:41
@zackees
zackees added this pull request to the merge queue Oct 22, 2026
Merged via the queue into obs-rust:master with commit 811cb34 Oct 22, 2026
30 checks passed
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
The min/max fold over the four corners of each item's box transform
and the size step of resize_scene_base now live in
obs-scene-extent.c.h, behind obs_scene_extent_init(),
obs_scene_extent_add() and obs_scene_extent_size(). They are declared
in obs-scene-extent.h without EXPORT. The scene still walks its items,
still shifts the children so the content starts at the origin, and
resize_scene and resize_group are unchanged. Same behavior.

obs_scene_size_from_extent(), the static inline from obs-rust#1840, moves with
them into obs-scene-extent.h, which obs-scene.h now includes, so its
users see it as before. The new file then needs no core header (not
obs-scene.h, whose structs need the pthread types), and a test or the
oracle can compile it on its own on every platform.

Refs obs-rust#1919
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
The min/max fold over the four corners of each item's box transform
and the size step of resize_scene_base now live in
obs-scene-extent.c.h, behind obs_scene_extent_init(),
obs_scene_extent_add() and obs_scene_extent_size(). They are declared
in obs-scene-extent.h without EXPORT. The scene still walks its items,
still shifts the children so the content starts at the origin, and
resize_scene and resize_group are unchanged. Same behavior.

obs_scene_size_from_extent(), the static inline from obs-rust#1840, moves with
them into obs-scene-extent.h, which obs-scene.h now includes, so its
users see it as before. The new file then needs no core header (not
obs-scene.h, whose structs need the pthread types), and a test or the
oracle can compile it on its own on every platform.

Refs obs-rust#1919
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
The min/max fold over the four corners of each item's box transform
and the size step of resize_scene_base now live in
obs-scene-extent.c.h, behind obs_scene_extent_init(),
obs_scene_extent_add() and obs_scene_extent_size(). They are declared
in obs-scene-extent.h without EXPORT. The scene still walks its items,
still shifts the children so the content starts at the origin, and
resize_scene and resize_group are unchanged. Same behavior.

obs_scene_size_from_extent(), the static inline from obs-rust#1840, moves with
them into obs-scene-extent.h, which obs-scene.h now includes, so its
users see it as before. The new file then needs no core header (not
obs-scene.h, whose structs need the pthread types), and a test or the
oracle can compile it on its own on every platform.

Refs obs-rust#1919
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
The min/max fold over the four corners of each item's box transform
and the size step of resize_scene_base now live in
obs-scene-extent.c.h, behind obs_scene_extent_init(),
obs_scene_extent_add() and obs_scene_extent_size(). They are declared
in obs-scene-extent.h without EXPORT. The scene still walks its items,
still shifts the children so the content starts at the origin, and
resize_scene and resize_group are unchanged. Same behavior.

obs_scene_size_from_extent(), the static inline from obs-rust#1840, moves with
them into obs-scene-extent.h, which obs-scene.h now includes, so its
users see it as before. The new file then needs no core header (not
obs-scene.h, whose structs need the pthread types), and a test or the
oracle can compile it on its own on every platform.

Refs obs-rust#1919
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
* libobs: Move the scene content extent out

The min/max fold over the four corners of each item's box transform
and the size step of resize_scene_base now live in
obs-scene-extent.c.h, behind obs_scene_extent_init(),
obs_scene_extent_add() and obs_scene_extent_size(). They are declared
in obs-scene-extent.h without EXPORT. The scene still walks its items,
still shifts the children so the content starts at the origin, and
resize_scene and resize_group are unchanged. Same behavior.

obs_scene_size_from_extent(), the static inline from obs-rust#1840, moves with
them into obs-scene-extent.h, which obs-scene.h now includes, so its
users see it as before. The new file then needs no core header (not
obs-scene.h, whose structs need the pthread types), and a test or the
oracle can compile it on its own on every platform.

Refs obs-rust#1919

* test: Characterize the scene content extent

The symbols are not exported, so the test compiles
obs-scene-extent.c.h and pins what it does today: one item, several,
a rotated one (the corners, not the box), a fractional extent rounded
up, the empty fold, NaN, the infinities and out-of-range sizes.

The fold starts at M_INFINITE, which is 3.4e38 and not infinity, so an
item at +inf or -inf alone is UINT32_MAX wide, and one wholly past
3.4e38 leaves the start value in place. A NaN corner fails both
compares and is skipped. A tie keeps the value already there, so -0
and +0 keep the first. No display.

Refs obs-rust#1919

* obs-scene: Add the scene content extent tests

Tier 1 mirrors test_group_extent case for case, and adds the size step
on its own, a NaN in the y column, an infinite z row, and the ties of
-0 and +0 on the min side and on y. The core is still todo, so all 15
cases panic: not yet implemented.

Refs obs-rust#1919

* obs-scene: Port the scene content extent

The safe core matches obs-scene-extent.c.h: the fold starts at
M_INFINITE, takes the four corners of each box transform through
vec3_transform's sum order, and keeps the C's strict < and >, so a NaN
corner is skipped and a tie keeps the first value. The size is
max - min rounded up and saturated as obs_scene_size_from_extent does.

The three shims stay hidden. The scene still walks its items, still
shifts the children with update_item_transform, and resize_scene and
resize_group stay C. The C file moves to libobs.ported-scene-extent
with its own PCH. obs-scene gains no dependency.

Tier 1 scene::extent is 15/15.

Refs obs-rust#1919

* obs-scene: Check the scene content extent port against the C

The oracle is obs-scene-extent.c.h, unmodified, with its three
functions renamed and vec3_transform taken from the graphics oracle.
Each run starts the fold, adds every item and sizes it on both sides,
and compares min and max after every add bit for bit, then the scale
bit for bit and cx and cy.

The proptests cover lists of up to 8 matrices with finite, huge, NaN,
infinite, M_INFINITE, 2^32 and any-bit entries, box transforms as the
scene builds them, matrices of only 0, -0, 1 and -1 (so -0 and +0
corners tie), and the add and size shims from any state.

Breaking the core: f32::min/max for the compares, <= on the min, >=
on the max, an infinite start, three corners, y compared against x,
round for ceil, saturating one step early, a swapped scale and a
plain product for the C's dot each fail parity. Dropping the NaN check
in the size survives: Rust's `as u32` gives 0 for NaN, the same value.
Reverted. No intentional differences.

Refs obs-rust#1919

* docs: Record the scene content extent port

rust/README.md: the obs-scene layout row names
libobs/obs-scene-extent.c.h, and its row of the ported table gives the
swap, what stays in obs-scene.c.h, what C passes in, the compares the
fold keeps, the behavior kept from the characterization and what Tier 3
compares. No intentional differences. The naming.md row
(libobs/obs-scene*.c.h) already covers the file.

port_comparison: scene_extent/fold/{1,16}, shim against oracle, in
benches/port_comparison/scene.rs: start the fold, add 1 or 16 turned
boxes, size it. Pinned to one core, the medians are 10.3 ns (Rust)
against 71.7 ns (C) for one item, and 55.5 ns against 1.02 us for 16.
The C calls vec3_transform out of line for every corner, with its
transpose; the Rust core has the four dots inline. It runs once per
group or scene resize.

Fixes obs-rust#1919
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
obs_scene_cropped_size(), obs_scene_scale_crop() and
obs_scene_crop_offset(), the static inlines obs-rust#1840 made defined on
every input, move verbatim from obs-scene.h into obs-scene-crop.c.h.
The negative-crop clamp of obs_sceneitem_set_crop() moves with them as
obs_scene_clamp_crop(), applied to each side. They are declared in
obs-scene-crop.h without EXPORT, and obs-scene.h includes that header,
so calc_cx, calc_cy, update_nested_scene_crop and render_item call
them as before. Same behavior.

The new file needs no core header (not obs-scene.h, whose structs
need the pthread types), so a test or the oracle can compile it on its
own on every platform. obs_scene_crop_from_int64(), the load clamp,
stays in obs-scene.h.

test_scene_crop_steps calls the three functions, which are now hidden
in libobs, so its build compiles obs-scene-crop.c.h into it, still
with UBSan. The test source is unchanged.

Refs obs-rust#1937
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
obs_scene_cropped_size(), obs_scene_scale_crop() and
obs_scene_crop_offset(), the static inlines obs-rust#1840 made defined on
every input, move verbatim from obs-scene.h into obs-scene-crop.c.h.
The negative-crop clamp of obs_sceneitem_set_crop() moves with them as
obs_scene_clamp_crop(), applied to each side. They are declared in
obs-scene-crop.h without EXPORT, and obs-scene.h includes that header,
so calc_cx, calc_cy, update_nested_scene_crop and render_item call
them as before. Same behavior.

The new file needs no core header (not obs-scene.h, whose structs
need the pthread types), so a test or the oracle can compile it on its
own on every platform. obs_scene_crop_from_int64(), the load clamp,
stays in obs-scene.h.

test_scene_crop_steps calls the three functions, which are now hidden
in libobs, so its build compiles obs-scene-crop.c.h into it, still
with UBSan. The test source is unchanged.

Refs obs-rust#1937
chriscoveries pushed a commit to chriscoveries/obsrust-fork that referenced this pull request Oct 23, 2026
* libobs: Move the scene item crop arithmetic out

obs_scene_cropped_size(), obs_scene_scale_crop() and
obs_scene_crop_offset(), the static inlines obs-rust#1840 made defined on
every input, move verbatim from obs-scene.h into obs-scene-crop.c.h.
The negative-crop clamp of obs_sceneitem_set_crop() moves with them as
obs_scene_clamp_crop(), applied to each side. They are declared in
obs-scene-crop.h without EXPORT, and obs-scene.h includes that header,
so calc_cx, calc_cy, update_nested_scene_crop and render_item call
them as before. Same behavior.

The new file needs no core header (not obs-scene.h, whose structs
need the pthread types), so a test or the oracle can compile it on its
own on every platform. obs_scene_crop_from_int64(), the load clamp,
stays in obs-scene.h.

test_scene_crop_steps calls the three functions, which are now hidden
in libobs, so its build compiles obs-scene-crop.c.h into it, still
with UBSan. The test source is unchanged.

Refs obs-rust#1937

* test: Characterize the scene item crop arithmetic

The four functions are hidden in libobs, so the test compiles
obs-scene-crop.c.h and pins what it does today: sums equal to and over
the size and sums past the int range, a negative sum and negative crops
made up for by the others, the rescale's truncation toward 0 at every
edge of the int range, with NaN, the infinities, the largest and the
smallest factors, the offset's rounding past 2^24, and the clamp.

Through the real libobs: negative crops set with obs_sceneitem_set_crop()
are clamped on each side, crops summing to and past the size and past
the int range draw the item 0 or 2 px wide, and a nested scene that
grows and shrinks rescales its item's crop. Characterized, not
endorsed: the truncation is lossy (10 at x 0.25 then x 4 comes back as
8), and a crop saturated at INT_MAX shrinks from INT_MAX. These cases
need core video (Linux, under xvfb-run) and skip without a display.
No assert_in_range, so it builds with cmocka 1.x and 2.x.

Refs obs-rust#1937

* obs-scene: Add the scene item crop arithmetic tests

Tier 1 ports the eight cases of test_scene_item_crop that call the
functions directly, and adds every small sum against every small
size, the u32 edges of the size, the floats next to the rescale's
edges, NaN payloads, the product's rounding, the offset's ties and
the clamp of every sign. The core is still todo, so all 15 cases
panic: not yet implemented.

Refs obs-rust#1937

* obs-scene: Port the scene item crop arithmetic

The safe core matches obs-scene-crop.c.h: the size sums the four
crops in 64 bits and leaves 2 for a negative sum or one past the size,
the rescale is one f32 multiply of the crop as a float, then NaN is 0,
2^31 and up INT_MAX, -2^31 and down INT_MIN, and the rest truncated
toward 0; the offset is the 64-bit sum as the nearest f32, and the
clamp makes a negative crop 0. No unsafe.

The four shims take and return values, so no struct is mirrored, and
stay hidden. calc_cx, calc_cy, update_nested_scene_crop, render_item,
the load clamp and the setter's change check stay C. The C file moves
to libobs.ported-scene-crop with its own PCH. obs-scene gains no
dependency.

test_scene_item_crop_rust runs the unchanged characterization against
libobs_rust-static. It links libobs first, so the archive gives only
the four hidden functions; with the archive first its obs-data members
come in and need libjansson.

Tier 1 scene::crop is 15/15.

Refs obs-rust#1937

* obs-scene: Check the scene item crop port against the C

The oracle is obs-scene-crop.c.h, unmodified, with its four functions
renamed. Every output is compared bit for bit, the offset as f32 bits:
the test_scene_item_crop values, sweeps of the factor's bit patterns
around 2^31, 2^30, 1, 0.5, 0, the infinities and the NaNs, every sum
from the size - 3 to the size + 3 at the u32 edges, and proptests over
full i32 crops, u32 sizes and any-bit f32 factors, with crops near the
int edges and factors that put the product next to +/-2^31 or a whole
number. No input is excluded.

Breaking the core: < for <= at the size, 0 for 2, a 32-bit sum, a
crop left out, a negative sum read as unsigned, NaN as 1, either edge
one float in, INT_MAX - 1 or INT_MIN + 1 on saturation, round or floor
for the truncation, the product in f64, the crop kept exact, a 32-bit
or twice-rounded offset, the offset without the bounds crop, and three
wrong clamps each fail Tier 1 and Tier 3. The f64 product first passed
Tier 1; edge_scale_crop_product_is_f32 is added for it. Four survive
and are equivalent: dropping the NaN check, > for >= at 2^31, < for <=
at -2^31 (Rust's as i32 already gives 0, INT_MAX and INT_MIN there),
and <= 0 for < 0 in the clamp. Reverted. The seeds the mutants failed
on are kept in proptest-regressions/crop_parity.txt. No intentional
differences.

Refs obs-rust#1937

* docs: Record the scene item crop port

rust/README.md: the obs-scene layout row names
libobs/obs-scene-crop.c.h, and its row of the ported table gives the
swap, what stays in obs-scene.c.h, what is passed by value, the
rescale's branches and truncation, the behavior kept from the
characterization, the _rust variant and what Tier 3 compares. No
intentional differences. The obs-scene Cargo description and crate
docs name the new module. The naming.md row (libobs/obs-scene*.c.h)
already covers the file.

port_comparison: scene_crop/{cropped_size,scale_crop,crop_offset}/16,
shim against oracle, in benches/port_comparison/scene_crop.rs: the
calls for 16 items. Pinned to one core, the medians are 64.7 ns (Rust)
against 58.0 ns (C) for the sizes, 109.1 ns against 84.0 ns for the
rescales, and 35.5 ns against 36.1 ns for the offsets: about 0.4 and
1.6 ns more per call for the first two (not looked into further). They
run when an item's transform is updated and when a cropped item is
drawn, a few calls per item.

Fixes obs-rust#1937
rdoupe added a commit to rdoupe/obs-studio that referenced this pull request Oct 23, 2026
obs_encoder_add_roi() is meant to refuse ROIs smaller than one 16 x 16
block and priorities outside [-1, 1]. Two inputs got past both checks:

- an upside-down rectangle (bottom above top, or right left of left):
  the uint32_t subtractions of the size check wrapped to huge sizes;
- a NaN priority: NaN < -1 and NaN > 1 are both false.

obs_encoder_roi_admit() now refuses bottom <= top, right <= left and
a NaN priority before the size check. The rest of the checks are as
before.

obs_encoder_enum_roi() scaled each edge with a (uint32_t) cast of the
float product, which is undefined in C from 2^32 up (a large ROI on an
upscaled encoder; on x86_64 with GCC it gave 0). Each edge now takes the
nearest uint32_t: 0 for NaN and below 0, UINT32_MAX from 2^32 up, as
obs_scene_scale_crop() does (obs-rust#1840). Every valid ROI, and every scaled
edge in range, gives the value it gave before.

The five ROI functions now check the encoder with obs_encoder_valid(),
as the other obs_encoder_* functions do, and return false, 0 or
nothing for NULL; before, they dereferenced it.

Only plugins and scripts reach these functions; upstream has the same
code. NVENC and AMF clip each ROI to their map, where an upside-down
ROI covered no block, and QSV passed it to the SDK as it was. All three
convert the priority to an integer, which was undefined for NaN.

test_encoder_roi passes 12/12 against the C libobs, the hybrid libobs
and libobs-c-reference.

Fixes obs-rust#1959
chriscoveries pushed a commit to chriscoveries/obsrust-fork that referenced this pull request Oct 23, 2026
…1964)

* libobs: Move the encoder ROI checks and scaling out

The checks obs_encoder_add_roi() makes before it stores an ROI (the
encoder has OBS_ENCODER_CAP_ROI, the ROI is at least one 16 x 16 block,
its priority is in [-1, 1]) move verbatim into obs_encoder_roi_admit(),
and the scaling in obs_encoder_enum_roi() into
obs_encoder_roi_scale_factors() (scaled size / video size, false when
the video has no size) and obs_encoder_roi_scale() (the scaled
rectangle). They are in obs-encoder-roi.c.h, declared in
obs-encoder-roi.h without EXPORT, and the file is in the encoder's unity
group, libobs.core-output.

The NULL check, roi_mutex, the list, roi_increment, the walk (last
added first) and the callback stay in obs-encoder.c.h. Same behavior.

The naming.md row for rust/obs-output names the new file.

Refs obs-rust#1959

* test: Characterize the encoder ROI checks and scaling

test_encoder_roi registers two test video encoders, one with
OBS_ENCODER_CAP_ROI and one without, and pins through the exported
ROI functions what they do today:

- a NULL roi, and an encoder without the cap, are refused;
- the 16 x 16 minimum at 15, 16 and 17 in each direction, and at the
  top of the uint32_t range;
- priorities of -1, 0, -0, 1, the floats just outside [-1, 1] and the
  infinities;
- roi_increment after adds, refused adds and clears (a clear of an
  empty list changes nothing);
- the enumeration order, last added first, unscaled and scaled (2/3,
  and 2 x 1/2: each edge multiplied in float and truncated), and a
  scaled size with no video, which passes nothing on.

Characterized, not endorsed: a NaN priority, and an upside-down
rectangle (bottom above top, or right left of left: the uint32_t size
check wraps), are stored.

The scaled cases give the encoder a video output of its own with
video_output_open(), so no graphics are needed. The test is in the
core suite; it skips without a display. No assert_in_range, so it
builds with cmocka 1.x and 2.x.

Refs obs-rust#1959

* test: Expect upside-down encoder ROIs and NaN priorities to be refused

Test expectation change: test_nan_priority and test_upside_down_rect
now expect a NaN priority and an upside-down rectangle (bottom above
top, or right left of left) to be refused. The characterization pinned
them as stored, not endorsed: the priority range check is false for
NaN, and the size check subtracts in uint32_t and wraps. Two more
upside-down cases are added, right one left of left and top at
UINT32_MAX.

New cases:
- test_enum_scaled_saturates: an encoder scaled x 256 from a 16 x 16
  video. Edges of 2^24 - 1 scale to 2^32 - 256, in range; edges of 2^24
  and up scale to 2^32 or past it, which must be UINT32_MAX. The
  (uint32_t) cast of such a float is undefined in C.
- test_null_encoder: the five ROI functions with a NULL encoder return
  false, 0 or nothing, as the other obs_encoder_* functions do.

On this commit, in all three libraries (C, hybrid and
libobs-c-reference), 8 of 12 pass. test_nan_priority and
test_upside_down_rect fail (1 != 0: stored), test_enum_scaled_saturates
fails with 0 != 4294967295 (x86_64, GCC: the undefined cast gives 0
there; another platform may give another value), and test_null_encoder
fails with a segmentation fault in obs_encoder_add_roi().

Refs obs-rust#1959

* libobs: Refuse upside-down encoder ROIs and NaN priorities

obs_encoder_add_roi() is meant to refuse ROIs smaller than one 16 x 16
block and priorities outside [-1, 1]. Two inputs got past both checks:

- an upside-down rectangle (bottom above top, or right left of left):
  the uint32_t subtractions of the size check wrapped to huge sizes;
- a NaN priority: NaN < -1 and NaN > 1 are both false.

obs_encoder_roi_admit() now refuses bottom <= top, right <= left and
a NaN priority before the size check. The rest of the checks are as
before.

obs_encoder_enum_roi() scaled each edge with a (uint32_t) cast of the
float product, which is undefined in C from 2^32 up (a large ROI on an
upscaled encoder; on x86_64 with GCC it gave 0). Each edge now takes the
nearest uint32_t: 0 for NaN and below 0, UINT32_MAX from 2^32 up, as
obs_scene_scale_crop() does (obs-rust#1840). Every valid ROI, and every scaled
edge in range, gives the value it gave before.

The five ROI functions now check the encoder with obs_encoder_valid(),
as the other obs_encoder_* functions do, and return false, 0 or
nothing for NULL; before, they dereferenced it.

Only plugins and scripts reach these functions; upstream has the same
code. NVENC and AMF clip each ROI to their map, where an upside-down
ROI covered no block, and QSV passed it to the SDK as it was. All three
convert the priority to an integer, which was undefined for NaN.

test_encoder_roi passes 12/12 against the C libobs, the hybrid libobs
and libobs-c-reference.

Fixes obs-rust#1959
chriscoveries pushed a commit to chriscoveries/obsrust-fork that referenced this pull request Oct 24, 2026
* libobs: Move the scene item names and coordinate keys out

Behaviour-neutral extraction before the Rust port. The name tables and
the coordinate-key choice of scene_load_item() and scene_save_item() in
obs-scene.c.h move to libobs/obs-scene-item-names.c.h, declared in the
new libobs/obs-scene-item-names.h without EXPORT (hidden, as
-fvisibility=hidden keeps them):

- obs_scene_item_scale_filter_from_name(),
  obs_scene_item_blend_method_from_name() and
  obs_scene_item_blend_type_from_name(): the value a saved name loads
  as. obs-scene.c.h passes libobs's astrcmpi() as the compare, which is
  called as before: (name, known) for each known name in the old order,
  stopping at the first match, and not at all for NULL. NULL or any
  other name loads as Disable, Default or Normal, as before. Taking the
  compare as a parameter keeps the one astrcmpi implementation for the
  port: the Rust side calls whatever libobs passes, so rust/obs-scene
  needs no obs-util objects (whose system libraries would break the
  obs-scene _rust test links).
- obs_scene_item_scale_filter_name(), obs_scene_item_blend_method_name()
  and obs_scene_item_blend_type_name(): the name a value is saved
  under, a static string, with the old fallbacks ("disable", "default",
  "normal").
- obs_scene_item_transform_keys() and obs_scene_item_bounds_keys():
  read the relative keys, the absolute keys converted, or the absolute
  keys as they are (enum obs_scene_item_keys).
- obs_scene_item_save_relative(): write the relative keys (and the
  absolute ones for older versions) or the absolute keys alone.

obs-scene.c.h keeps every obs_data_* call in its order, the coordinate
conversions (obs-scene-coords.c), the source lookup, the transitions,
the private settings and the crop clamp of obs-rust#1840, and stores the results
in the item.

One read changed: obs_data_has_user_value() of "pos_rel", "scale_rel"
and "scale_ref" is now asked for all three, in that order, before the
choice, where the old && chain stopped at absolute coordinates or at the
first missing key. It is a plain lookup in item_data with no side
effect, and "bounds_rel" is still asked where it was.

The enum values cross as int, so the header needs only stdbool.h;
obs-scene.c.h checks at compile time that the mirrored scale filter,
blend method and blend type values match obs.h.

The new file joins libobs.core-source with libobs.pch.h, which includes
the new header. The exported symbol sets are unchanged (1766).

Refs obs-rust#2114

* test: Characterize the scene item names and coordinate keys

test_scene_item_names_steps compiles libobs/obs-scene-item-names.c.h
(ASan and UBSan, no libobs core) and calls only its hidden functions,
so it runs on every platform. 14 cases, all calling the loaders with
libobs's astrcmpi() as obs-scene.c.h does:

- the loaders: every scale filter, blend method and blend type name in
  lower, upper and mixed case;
- unknown names load as Disable, Default and Normal: the empty string,
  a trailing or leading space, a tab or newline after the name, a name
  cut short or one byte long, "srgb-off", the saver's own fallback names
  ("disable", "default", "normal"), NULL, and bytes above 0x7F (lone
  0x80 and 0xFF, UTF-8 look-alikes such as a dotted capital I, a
  no-break space and a zero-width space);
- each table knows only its own names; numbers are names, not values
  (characterized, not endorsed);
- the compare's calls, through a recording wrapper around astrcmpi():
  (name, known) for each known name in the C's order, stopping at the
  first match, every known name for an unknown one, none for NULL;
- the savers: every value of each enum, and -1, one past the last,
  INT_MIN and INT_MAX (the fallbacks); every value from -2 to 8 loads
  back as itself inside the enum and as the default outside it;
- the transform and bounds keys for all 16 patterns of pos_rel,
  scale_rel, scale_ref and bounds_rel, with and without absolute
  coordinates; bounds_rel is read without the transform's three keys
  (characterized, not endorsed); the save choice; the key values and
  that the enum is int-sized.

It is in the native test graph, in the core suite, so no pinned count
changes. It reports failures with fprintf(stderr, ...) and fail(), not
fail_msg(), and uses no assert_in_range; it needs no libm. It passes
14/14 on the C backend, and builds with -Werror and passes 14/14
against cmocka 2.0.2 and 1.1.7. The real-libobs scene tests
are unchanged.

Refs obs-rust#2114

* obs-scene: Add the scene item names and coordinate keys tests

RED for the port of libobs/obs-scene-item-names.c.h to a new item_names
module of rust/obs-scene. The safe core is a stub (todo!()), one
function per hidden C function: scale_filter_from_name(),
blend_method_from_name() and blend_type_from_name() over Option<&CStr>
(None is the C's NULL) and the compare the caller gives (C passes
libobs's astrcmpi); scale_filter_name(), blend_method_name() and
blend_type_name() giving a &'static CStr; transform_keys() and
bounds_keys() giving a Keys (Relative, FromAbsolute, Absolute); and
save_relative(). The enum values and the three name tables, in the C's
order, are constants.

tests/scene/item_names.rs ports test_scene_item_names_steps 1:1: its 14
cases under the same names (steps_*), in the same order, with the same
inputs and expectations, the characterized-not-endorsed cases included.
Like the C test, it gives the loaders astrcmpi: obs-util's, the one the
hybrid libobs passes (obs-util is already a dev-dependency of the
obs-tests-core binary).

Edge cases (edge_*): the tables' shape (lower-case ASCII names, distinct
names and values, none the default, each saved under its own name);
every upper/lower-case spelling of every name; every name with one byte
changed to any other byte, cut short, or with any byte added at either
end; the keys' invariants over all 16 patterns; and two proptests (4000
cases each): the loaders against a model (the first table entry equal
with ASCII case folded, and the compares made: the table up to and
including that entry) over any byte string with no NUL, biased towards
the names, and the savers over any i32.

The tests are a module of obs-tests-core (rust/obs-data/tests/core.rs),
as the other obs-scene units' are.

soldr cargo test -p obs-data --test obs-tests-core scene::item_names
fails 19 of 20 with "not yet implemented"; steps_key_values, which
checks only the Keys discriminants and calls no stub, passes.

Refs obs-rust#2114

* obs-scene: Port the scene item names and coordinate keys

Ports libobs/obs-scene-item-names.c.h, the name tables and the
coordinate-key choice of scene_load_item() and scene_save_item(), to the
item_names module of rust/obs-scene. scene_load_item() and
scene_save_item() stay C in obs-scene.c.h: every obs_data_* call in its
order, the coordinate conversions (obs-scene-coords.c), the source
lookup, the transitions, the private settings and the crop clamp of
obs-rust#1840. The hybrid libobs drops the C file and links the Rust shims in
its place.

Safe core (src/item_names.rs), one function per hidden C function:
- scale_filter_from_name(), blend_method_from_name() and
  blend_type_from_name(): the first entry of the table, in the C's
  order, that the given compare finds equal to the name, else Disable,
  Default or Normal. The compare is asked as (name, known) and not past
  the first match; None (the C's NULL) is the default without a compare.
- scale_filter_name(), blend_method_name() and blend_type_name(): a
  match over the enum value giving a &'static CStr, with the C's
  fallbacks ("disable", "default", "normal") for any other i32.
- transform_keys() and bounds_keys(): Relative when the coordinates are
  not absolute and every relative key is there, FromAbsolute when they
  are not absolute, Absolute otherwise; save_relative().
Values from the item are i32, compared as they are. The module denies
clippy's arithmetic, indexing, as, unwrap, expect, panic, unimplemented
and unreachable lints, allocates nothing, keeps no state and takes no
lock.

astrcmpi: the loaders call the compare C passes, which obs-scene.c.h
gives as libobs's own astrcmpi (in the hybrid, obs-util's Rust one). So
the case rules stay one implementation, called the same number of times
in the same order, and rust/obs-scene still depends on no obs-util code.
Calling obs-util's astrcmpi from the crate was tried first: its archive
member pulls in obs-util objects that need libuuid, and every obs-scene
_rust test (test_scene_bounds_place_rust, test_scene_item_crop_rust,
test_scene_render_plan_steps_rust and the new one) failed to link.

Shim (src/ffi/scene_item_names.rs): the nine functions with the C
signatures. The loaders read the name through &CStr and call the C
compare with the name's own pointer and a static known name; the savers
return the &'static CStr's pointer, so nothing is allocated. Keys cross
as the C's enum values. No item pointer crosses.

C side: the file leaves libobs.core-source for its own group,
libobs.ported-scene-item-names (LIBOBS_PORTED_SOURCES), whose PCH has
only obs-scene-item-names.h; libobs.pch.h keeps the header for
obs-scene.c. The functions are not EXPORT, so the shims are hidden:
rust-hidden.txt, the local: list of rust-exports.map and
rust-unexports-macos.txt. libobs-rust already links the crate's ffi.
ci/test_ported_sources.py checks the group on every host. The exported
symbol sets are unchanged and equal (1766 on the C backend, the hybrid
and libobs-c-reference).

test_scene_item_names_steps still compiles the C file into itself,
unchanged. The new test_scene_item_names_steps_rust builds the same test
source against libobs_rust-static, after OBS::libobs (for astrcmpi), as
test_transition_clock_steps_rust does. The real-libobs scene tests see
the swap through the hybrid.

Tier 1 scene::item_names passes 20/20.

Refs obs-rust#2114

* obs-scene: Check the scene item names and coordinate keys port against the C

Oracle (oracle/scene_item_names.c): the original
obs-scene-item-names.c.h, unmodified, with its nine functions renamed to
oracle_*, plus the size of enum obs_scene_item_keys, its values and the
mirrored scale filter, blend method and blend type values (19 values).
The loaders take the compare as a parameter, so the oracle needs no
renamed astrcmpi of its own.

Tier 3 (tests/scene/item_names_parity.rs, 9 tests). The value runs give
the shims obs-util's astrcmpi (what the hybrid passes) and the oracle the
C dstr.c's (oracle_astrcmpi, what libobs-c-reference passes), so they
compare the two libraries' whole name match. The compare runs give both
sides one recording compare and check that they ask it the same
questions in the same order: the name's own pointer and each known
name's bytes, stopping at the first match, none for NULL.
- the enum values and constants against the C header;
- exhaustive: the transform and bounds keys and the save choice over all
  16 patterns of the four relative keys, with and without absolute
  coordinates; the three savers over every value from -4096 to 4096 and
  the ends of i32 (names compared byte for byte); the loaders over NULL,
  every string of one or two bytes (65,280 strings), every upper/lower
  case spelling of every name (the savers' 15 names, fallbacks
  included), every name with one byte changed to any other byte, cut
  short, or with any byte added at either end, and the
  characterization's other names; the compares for all of them but the
  two-byte strings;
- proptests (10,000 cases each): the loaders, values and compares, over
  arbitrary byte strings with no interior NUL (biased towards the names,
  their case and up to two bytes changed), and the savers over any i32.

The module passed 4 runs in a row with fresh seeds. obs-util's astrcmpi
and the C one agree on every byte tried, those above 0x7F included.

Mutation check (done once, not committed): 22 mutants, 16 in the core
and 6 in the shim; all fail.

| Mutant | Tier 1 | Tier 3 |
|---|---|---|
| scale: bilinear loads as bicubic | 4 | 2 |
| scale: area loads as Disable | 4 | 2 |
| blend type: darken misspelt | 5 | 4 |
| blend method: sRGB off the default | 6 | 5 |
| load: table tried in reverse | 2 | 4 |
| load: NULL compared as "" | 1 | 1 |
| load: compares past the first match | 2 | 2 |
| load: byte compare instead of the given one | 6 | 4 |
| save: Area saved as "Area" | 2 | 1 |
| save: blend type fallback "default" | 1 | 2 |
| save: any non-zero method is sRGB off | 3 | 2 |
| save: Disable saved as "" | 2 | 2 |
| keys: scale_ref ignored | 2 | 1 |
| keys: absolute converted too | 3 | 1 |
| keys: bounds need the transform keys | 2 | 1 |
| save: relative inverted | 2 | 1 |
| keys: Relative = 3 in the core enum | 1 | 0 |
| shim: FromAbsolute and Absolute swapped | 0 | 1 |
| shim: compare arguments swapped | 0 | 4 |
| shim: <= 0 for == 0 | 0 | 4 |
| shim: blend method and type loaders swapped | 0 | 4 |
| shim: name copied to a new string for the compare | 0 | 4 |

Tier 1 does not reach the shims, and "Relative = 3" changes only the
core enum's discriminant, which the shim maps to the C value
explicitly, so Tier 3 does not see it. "table tried in reverse" and
"compares past the first match" give the same values (the names are
distinct) and are caught by the compare order. The proptest regression
files keep the seeds the mutants failed on.

Refs obs-rust#2114

* docs: Record the scene item names and coordinate keys port

The rust/README.md crate table now lists libobs/obs-scene-item-names.c.h
among the rust/obs-scene units, and its port table has a row for it: the
nine functions, what stays C (every obs_data_* call in its order, the
coordinate conversions, the source lookup, the transitions, the private
settings and the obs-rust#1840 crop clamp), the one read that changed (the three
has_user_value lookups asked before the choice), why the loaders take
the compare as a parameter (one astrcmpi, and no obs-util object in the
obs-scene _rust links), the compile-time checks, what the
characterization pins and the port keeps, the _rust variant of the
steps test, the real-libobs tests that see the swap and what Tier 3
compares. The crate's description and lib.rs say what it holds.
docs/rust-port/naming.md already maps libobs/obs-scene*.c.h to
rust/obs-scene. No docs/features.md line: no user-visible change.

port_comparison gets its own bench file,
benches/port_comparison/scene_item_names.rs, for 16 items: the three
loaders and both key choices (load), and the three savers (save), each
folded into a checksum both sides must match. Each loader gets its
library's astrcmpi. On x86_64 Linux (GCC, pinned to one core, load
average near 20, so noisy; medians per 16 items, two runs): load 3.25 /
2.35 us Rust against 1.68 us / 896 ns C, save 164 / 67 ns against 370 /
194 ns. Given the C astrcmpi too, the Rust load is 932 ns against
902 ns: the load gap is obs-util's astrcmpi, which the hybrid already
uses for every astrcmpi call before this port, not the table logic.
About 90 ns per item on scene collection load.

Fixes obs-rust#2114
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug: libobs: scene item crops load unclamped, and out-of-range crop and group size casts give wrong sizes

2 participants