From ea785ba5c3ac98542c63c94d7655467033dc6af5 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Wed, 25 Nov 2026 12:01:43 -0500 Subject: [PATCH 1/4] libobs: extract obs_source_frame_copy verbatim (Refs #5714) Moves frame_copy_lines, copy_frame_data_plane, copy_frame_data and obs_source_frame_copy, with the plane-count _Static_assert, into libobs/obs-source-frame-copy-data.c.h in the live core-source group. cache_video() and the two preload paths now call the exported obs_source_frame_copy() (it only calls copy_frame_data()), so they no longer need the static function. No behavior change. Co-Authored-By: Claude Opus 5.5 --- libobs/build/libobs.core-source+.h.c | 1 + libobs/obs-source-frame-copy-data.c.h | 58 ++++++++++++++++++++++++ libobs/obs-source.c.h | 63 ++------------------------- 3 files changed, 62 insertions(+), 60 deletions(-) create mode 100644 libobs/obs-source-frame-copy-data.c.h diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index a294f84a8f..08cdbc49d8 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -79,6 +79,7 @@ #include "libobs/obs-source-filter-index-fields.c.h" #include "libobs/obs-source-filter-relationship-fields.c.h" #include "libobs/obs-source-flags-mixers-fields.c.h" +#include "libobs/obs-source-frame-copy-data.c.h" #include "libobs/obs-source-get-weak-fields.c.h" #include "libobs/obs-source-handler-getters-fields.c.h" #include "libobs/obs-source-hidden-setter-fields.c.h" diff --git a/libobs/obs-source-frame-copy-data.c.h b/libobs/obs-source-frame-copy-data.c.h new file mode 100644 index 0000000000..66de5ab126 --- /dev/null +++ b/libobs/obs-source-frame-copy-data.c.h @@ -0,0 +1,58 @@ +#include "libobs/build/libobs.pch.h" + +_Static_assert(OBS_SOURCE_FRAME_COPY_PLANES <= MAX_AV_PLANES, "a copy plan's planes are frame planes"); + +static inline struct obs_source_frame_copy_lines frame_copy_lines(const struct obs_source_frame *frame) +{ + struct obs_source_frame_copy_lines lines; + + for (size_t i = 0; i < OBS_SOURCE_FRAME_COPY_PLANES; i++) + lines.linesize[i] = frame->linesize[i]; + + return lines; +} + +/* Runs one copy of the plan: copy_frame_data_plane() and + * copy_frame_data_line(). */ +static inline void copy_frame_data_plane(struct obs_source_frame *dst, const struct obs_source_frame *src, size_t plane, + const struct obs_source_frame_plane_copy *copy) +{ + if (!copy->whole) { + for (uint32_t y = 0; y < copy->rows; y++) { + uint32_t pos_src = y * copy->src_stride; + uint32_t pos_dst = y * copy->dst_stride; + + memcpy(dst->data[plane] + pos_dst, src->data[plane] + pos_src, copy->bytes); + } + } else { + memcpy(dst->data[plane], src->data[plane], copy->bytes); + } +} + +static void copy_frame_data(struct obs_source_frame *dst, const struct obs_source_frame *src) +{ + dst->flip = src->flip; + dst->flags = src->flags; + dst->trc = src->trc; + dst->full_range = src->full_range; + dst->max_luminance = src->max_luminance; + dst->timestamp = src->timestamp; + memcpy(dst->color_matrix, src->color_matrix, sizeof(float) * 16); + + const struct obs_source_frame_copy_plan plan = obs_source_frame_copy_plan( + (int)src->format, dst->full_range, dst->height, frame_copy_lines(src), frame_copy_lines(dst)); + + if (plan.color_range) { + size_t const size = sizeof(float) * 3; + memcpy(dst->color_range_min, src->color_range_min, size); + memcpy(dst->color_range_max, src->color_range_max, size); + } + + for (size_t i = 0; i < plan.count && i < OBS_SOURCE_FRAME_COPY_PLANES; i++) + copy_frame_data_plane(dst, src, i, &plan.planes[i]); +} + +void obs_source_frame_copy(struct obs_source_frame *dst, const struct obs_source_frame *src) +{ + copy_frame_data(dst, src); +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index 677b288010..53bfe52a71 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -2201,63 +2201,6 @@ struct obs_source_frame *filter_async_video(obs_source_t *source, struct obs_sou return in; } -_Static_assert(OBS_SOURCE_FRAME_COPY_PLANES <= MAX_AV_PLANES, "a copy plan's planes are frame planes"); - -static inline struct obs_source_frame_copy_lines frame_copy_lines(const struct obs_source_frame *frame) -{ - struct obs_source_frame_copy_lines lines; - - for (size_t i = 0; i < OBS_SOURCE_FRAME_COPY_PLANES; i++) - lines.linesize[i] = frame->linesize[i]; - - return lines; -} - -/* Runs one copy of the plan: copy_frame_data_plane() and - * copy_frame_data_line(). */ -static inline void copy_frame_data_plane(struct obs_source_frame *dst, const struct obs_source_frame *src, size_t plane, - const struct obs_source_frame_plane_copy *copy) -{ - if (!copy->whole) { - for (uint32_t y = 0; y < copy->rows; y++) { - uint32_t pos_src = y * copy->src_stride; - uint32_t pos_dst = y * copy->dst_stride; - - memcpy(dst->data[plane] + pos_dst, src->data[plane] + pos_src, copy->bytes); - } - } else { - memcpy(dst->data[plane], src->data[plane], copy->bytes); - } -} - -static void copy_frame_data(struct obs_source_frame *dst, const struct obs_source_frame *src) -{ - dst->flip = src->flip; - dst->flags = src->flags; - dst->trc = src->trc; - dst->full_range = src->full_range; - dst->max_luminance = src->max_luminance; - dst->timestamp = src->timestamp; - memcpy(dst->color_matrix, src->color_matrix, sizeof(float) * 16); - - const struct obs_source_frame_copy_plan plan = obs_source_frame_copy_plan( - (int)src->format, dst->full_range, dst->height, frame_copy_lines(src), frame_copy_lines(dst)); - - if (plan.color_range) { - size_t const size = sizeof(float) * 3; - memcpy(dst->color_range_min, src->color_range_min, size); - memcpy(dst->color_range_max, src->color_range_max, size); - } - - for (size_t i = 0; i < plan.count && i < OBS_SOURCE_FRAME_COPY_PLANES; i++) - copy_frame_data_plane(dst, src, i, &plan.planes[i]); -} - -void obs_source_frame_copy(struct obs_source_frame *dst, const struct obs_source_frame *src) -{ - copy_frame_data(dst, src); -} - /* What async_texture_changed() compared: the cache's size and convert type, * and the frame's. */ static inline struct obs_source_frame_copy_key async_cache_key(const struct obs_source *source) @@ -2377,7 +2320,7 @@ static inline struct obs_source_frame *cache_video(struct obs_source *source, co pthread_mutex_unlock(&source->async_mutex); - copy_frame_data(new_frame, frame); + obs_source_frame_copy(new_frame, frame); return new_frame; } @@ -2523,7 +2466,7 @@ static void obs_source_preload_video_internal(obs_source_t *source, const struct source->async_preload_frame = obs_source_frame_create(frame->format, frame->width, frame->height); } - copy_frame_data(source->async_preload_frame, frame); + obs_source_frame_copy(source->async_preload_frame, frame); pthread_mutex_lock(&source->async_mutex); source->last_frame_ts = frame->timestamp; @@ -2624,7 +2567,7 @@ static void obs_source_set_video_frame_internal(obs_source_t *source, const stru source->async_preload_frame = obs_source_frame_create(frame->format, frame->width, frame->height); } - copy_frame_data(source->async_preload_frame, frame); + obs_source_frame_copy(source->async_preload_frame, frame); set_async_texture_size(source, source->async_preload_frame); update_async_textures(source, source->async_preload_frame, source->async_textures, source->async_texrender); os_atomic_set_bool(&source->async_textures_stale, false); From 7f0b9156b79f3ce0cd8100d532537add40b4812c Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Wed, 25 Nov 2026 12:03:29 -0500 Subject: [PATCH 2/4] test: characterize obs_source_frame_copy (Refs #5714) A cmocka test through the exported obs_source_frame_copy() on frames of the same format and size, the source from obs_source_frame_create(): every format's planes at four sizes with equal line sizes, then with the destination's line sizes longer, shorter and mixed per plane (each row copies the smaller line size, the rest of a longer destination row stays untouched; P216 and P416 copy no plane), the metadata copied bit for bit, the colour range only when the source is not full range, and format, size, data, line sizes, refs and prev_frame left alone. Co-Authored-By: Claude Opus 5.5 --- test/cmocka/build/test-graph.json | 22 ++ test/cmocka/test_source_frame_copy.c | 321 ++++++++++++++++++ .../tests.d/test_source_frame_copy.cmake | 1 + 3 files changed, 344 insertions(+) create mode 100644 test/cmocka/test_source_frame_copy.c create mode 100644 test/cmocka/tests.d/test_source_frame_copy.cmake diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 74844d0278..ac5aefab78 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -18073,6 +18073,21 @@ } ] }, + "test_source_frame_copy": { + "sources": [ + "test/cmocka/test_source_frame_copy.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + "Uthash::Uthash", + "OBS::native-test-cmocka", + { + "name": "OBS::w32-pthreads", + "requires": "OS_WINDOWS" + } + ] + }, "test_source_frame_copy_steps": { "sources": [ "test/cmocka/test_source_frame_copy_steps.c", @@ -29948,6 +29963,13 @@ "${target}" ] }, + "test_source_frame_copy": { + "target": "test_source_frame_copy", + "command": [ + "${target}" + ], + "timeout_seconds": 30 + }, "test_source_frame_copy_steps": { "target": "test_source_frame_copy_steps", "command": [ diff --git a/test/cmocka/test_source_frame_copy.c b/test/cmocka/test_source_frame_copy.c new file mode 100644 index 0000000000..27d9088efb --- /dev/null +++ b/test/cmocka/test_source_frame_copy.c @@ -0,0 +1,321 @@ +/* Characterize obs_source_frame_copy() (copy_frame_data()) through the + * exported function, before its Rust replacement (#5714). Every frame pair + * has the same format, width and height, as libobs's own callers pass: + * the source comes from obs_source_frame_create(), the destination either + * from obs_source_frame_create() too (equal line sizes) or built here with + * its own line sizes per plane. No OBS core, video device or graphics + * context is needed. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "obs.h" + +#define FILL_SRC(plane, i) ((uint8_t)((plane) * 61u + (i) * 7u + 3u)) +#define FILL_DST 0xEE +#define PLANES 4 + +/* The planes obs_source_frame_create() gives each format, and how many of + * them copy_frame_data() copies, with the rows of each ((height + 1) / 2 + * for 4:2:0 chroma). Characterized, not endorsed: P216 and P416 copy no + * plane. */ +struct format_case { + enum video_format format; + size_t planes; + size_t copied; + bool half[PLANES]; +}; + +static const struct format_case formats[] = { + {VIDEO_FORMAT_I420, 3, 3, {false, true, true, false}}, + {VIDEO_FORMAT_NV12, 2, 2, {false, true, false, false}}, + {VIDEO_FORMAT_YVYU, 1, 1, {false}}, + {VIDEO_FORMAT_YUY2, 1, 1, {false}}, + {VIDEO_FORMAT_UYVY, 1, 1, {false}}, + {VIDEO_FORMAT_RGBA, 1, 1, {false}}, + {VIDEO_FORMAT_BGRA, 1, 1, {false}}, + {VIDEO_FORMAT_BGRX, 1, 1, {false}}, + {VIDEO_FORMAT_Y800, 1, 1, {false}}, + {VIDEO_FORMAT_I444, 3, 3, {false}}, + {VIDEO_FORMAT_BGR3, 1, 1, {false}}, + {VIDEO_FORMAT_I422, 3, 3, {false}}, + {VIDEO_FORMAT_I40A, 4, 4, {false, true, true, false}}, + {VIDEO_FORMAT_I42A, 4, 4, {false}}, + {VIDEO_FORMAT_YUVA, 4, 4, {false}}, + {VIDEO_FORMAT_AYUV, 1, 1, {false}}, + {VIDEO_FORMAT_I010, 3, 3, {false, true, true, false}}, + {VIDEO_FORMAT_P010, 2, 2, {false, true, false, false}}, + {VIDEO_FORMAT_I210, 3, 3, {false}}, + {VIDEO_FORMAT_I412, 3, 3, {false}}, + {VIDEO_FORMAT_YA2L, 4, 4, {false}}, + {VIDEO_FORMAT_P216, 2, 0, {false}}, + {VIDEO_FORMAT_P416, 2, 0, {false}}, + {VIDEO_FORMAT_V210, 1, 1, {false}}, + {VIDEO_FORMAT_R10L, 1, 1, {false}}, +}; + +#define FORMAT_COUNT (sizeof(formats) / sizeof(formats[0])) + +static const uint32_t sizes[][2] = {{1, 1}, {13, 7}, {32, 16}, {5, 2}}; + +#define SIZE_COUNT (sizeof(sizes) / sizeof(sizes[0])) + +static uint32_t plane_rows(const struct format_case *fc, size_t plane, uint32_t height) +{ + return fc->half[plane] ? (height + 1) / 2 : height; +} + +static void fill_source(struct obs_source_frame *src, const struct format_case *fc) +{ + for (size_t p = 0; p < fc->planes; p++) { + size_t len = (size_t)src->linesize[p] * plane_rows(fc, p, src->height); + for (size_t i = 0; i < len; i++) + src->data[p][i] = FILL_SRC(p, i); + } +} + +/* A destination of the source's format and size with its own line size per + * plane, each plane exactly line size x rows, filled with FILL_DST. */ +static void build_destination(struct obs_source_frame *dst, const struct format_case *fc, uint32_t width, + uint32_t height, const uint32_t *linesize) +{ + memset(dst, 0, sizeof(*dst)); + dst->format = fc->format; + dst->width = width; + dst->height = height; + for (size_t p = 0; p < fc->planes; p++) { + size_t len = (size_t)linesize[p] * plane_rows(fc, p, height); + dst->linesize[p] = linesize[p]; + dst->data[p] = malloc(len); + assert_non_null(dst->data[p]); + memset(dst->data[p], FILL_DST, len); + } +} + +static void free_destination(struct obs_source_frame *dst) +{ + for (size_t p = 0; p < MAX_AV_PLANES; p++) + free(dst->data[p]); +} + +/* Row y of every copied plane holds the source's row y up to the smaller + * line size; the rest of a longer destination row is untouched. Planes that + * are not copied are untouched. */ +static void check_planes(const struct obs_source_frame *dst, const struct obs_source_frame *src, + const struct format_case *fc) +{ + for (size_t p = 0; p < fc->planes; p++) { + uint32_t rows = plane_rows(fc, p, dst->height); + uint32_t dst_line = dst->linesize[p]; + uint32_t src_line = src->linesize[p]; + uint32_t bytes = dst_line < src_line ? dst_line : src_line; + for (uint32_t y = 0; y < rows; y++) { + const uint8_t *row = dst->data[p] + (size_t)y * dst_line; + const uint8_t *from = src->data[p] + (size_t)y * src_line; + for (uint32_t x = 0; x < dst_line; x++) { + uint8_t want = (p < fc->copied && x < bytes) ? from[x] : FILL_DST; + if (row[x] != want) { + fprintf(stderr, "format %d %ux%u plane %zu row %u byte %u: got %u, want %u\n", + (int)fc->format, dst->width, dst->height, p, y, x, row[x], want); + fail(); + } + } + } + } +} + +static void check_equal_line_sizes(const struct format_case *fc, uint32_t width, uint32_t height) +{ + struct obs_source_frame *src = obs_source_frame_create(fc->format, width, height); + struct obs_source_frame *dst = obs_source_frame_create(fc->format, width, height); + assert_non_null(src); + assert_non_null(dst); + fill_source(src, fc); + for (size_t p = 0; p < fc->planes; p++) { + assert_int_equal(dst->linesize[p], src->linesize[p]); + memset(dst->data[p], FILL_DST, (size_t)dst->linesize[p] * plane_rows(fc, p, height)); + } + + obs_source_frame_copy(dst, src); + check_planes(dst, src, fc); + + obs_source_frame_destroy(dst); + obs_source_frame_destroy(src); +} + +static void every_format_equal_line_sizes(void **state) +{ + (void)state; + for (size_t f = 0; f < FORMAT_COUNT; f++) + for (size_t s = 0; s < SIZE_COUNT; s++) + check_equal_line_sizes(&formats[f], sizes[s][0], sizes[s][1]); +} + +/* Each plane's destination line size is the source's plus delta[plane] + * (never 0). */ +static void check_unequal_line_sizes(const struct format_case *fc, uint32_t width, uint32_t height, const int *delta) +{ + struct obs_source_frame *src = obs_source_frame_create(fc->format, width, height); + struct obs_source_frame dst; + uint32_t linesize[PLANES] = {0}; + assert_non_null(src); + fill_source(src, fc); + for (size_t p = 0; p < fc->planes; p++) { + int64_t line = (int64_t)src->linesize[p] + delta[p]; + linesize[p] = line < 1 ? 1 : (uint32_t)line; + } + build_destination(&dst, fc, width, height, linesize); + + obs_source_frame_copy(&dst, src); + check_planes(&dst, src, fc); + for (size_t p = 0; p < fc->planes; p++) + assert_int_equal(dst.linesize[p], linesize[p]); + + free_destination(&dst); + obs_source_frame_destroy(src); +} + +static void every_format_unequal_line_sizes(void **state) +{ + (void)state; + /* Longer, shorter, mixed per plane, and one plane equal. */ + const int deltas[][PLANES] = { + {16, 16, 16, 16}, {-1, -1, -1, -1}, {5, -1, 3, -1}, {-3, 0, 7, 0}, {0, 9, -1, 2}, + }; + for (size_t f = 0; f < FORMAT_COUNT; f++) + for (size_t s = 0; s < SIZE_COUNT; s++) + for (size_t d = 0; d < sizeof(deltas) / sizeof(deltas[0]); d++) + check_unequal_line_sizes(&formats[f], sizes[s][0], sizes[s][1], deltas[d]); +} + +static const uint32_t matrix_bits[16] = { + 0x3f800000, 0x00000000, 0x80000000, 0x7f800000, 0xff800000, 0x7fc00001, 0x7f800001, 0x00000001, + 0x3eaaaaab, 0xbf000000, 0x41200000, 0x12345678, 0xffffffff, 0x7f7fffff, 0x00800000, 0xc2c80000, +}; +static const uint32_t range_min_bits[3] = {0x3d808081, 0x7fc00002, 0x80000000}; +static const uint32_t range_max_bits[3] = {0x3f6b6b6c, 0x3f700000, 0x7f800001}; + +static void set_source_metadata(struct obs_source_frame *src, bool full_range) +{ + src->flip = true; + src->flags = 0xa5; + src->trc = 0x3c; + src->full_range = full_range; + src->max_luminance = 0xbeef; + src->timestamp = 0x0123456789abcdefULL; + memcpy(src->color_matrix, matrix_bits, sizeof(matrix_bits)); + memcpy(src->color_range_min, range_min_bits, sizeof(range_min_bits)); + memcpy(src->color_range_max, range_max_bits, sizeof(range_max_bits)); + src->refs = 3; + src->prev_frame = false; +} + +static void set_destination_metadata(struct obs_source_frame *dst, bool full_range) +{ + dst->flip = false; + dst->flags = 0x11; + dst->trc = 0x01; + dst->full_range = full_range; + dst->max_luminance = 7; + dst->timestamp = 42; + memset(dst->color_matrix, 0x22, sizeof(dst->color_matrix)); + memset(dst->color_range_min, 0x33, sizeof(dst->color_range_min)); + memset(dst->color_range_max, 0x44, sizeof(dst->color_range_max)); + dst->refs = 9; + dst->prev_frame = true; +} + +/* Copies flip, flags, trc, full_range, max_luminance, timestamp and the + * colour matrix bit for bit; the colour range only when the destination is + * not full range after full_range was copied, so it follows the source's + * full_range, not the destination's. format, width, height, data, linesize, + * refs and prev_frame stay the destination's. */ +static void check_metadata(bool src_full, bool dst_full) +{ + struct obs_source_frame *src = obs_source_frame_create(VIDEO_FORMAT_NV12, 6, 4); + struct obs_source_frame *dst = obs_source_frame_create(VIDEO_FORMAT_NV12, 6, 4); + assert_non_null(src); + assert_non_null(dst); + set_source_metadata(src, src_full); + set_destination_metadata(dst, dst_full); + struct obs_source_frame before = *dst; + + obs_source_frame_copy(dst, src); + + assert_true(dst->flip); + assert_int_equal(dst->flags, 0xa5); + assert_int_equal(dst->trc, 0x3c); + assert_int_equal(dst->full_range, src_full); + assert_int_equal(dst->max_luminance, 0xbeef); + assert_true(dst->timestamp == 0x0123456789abcdefULL); + assert_memory_equal(dst->color_matrix, matrix_bits, sizeof(matrix_bits)); + if (src_full) { + assert_memory_equal(dst->color_range_min, before.color_range_min, sizeof(before.color_range_min)); + assert_memory_equal(dst->color_range_max, before.color_range_max, sizeof(before.color_range_max)); + } else { + assert_memory_equal(dst->color_range_min, range_min_bits, sizeof(range_min_bits)); + assert_memory_equal(dst->color_range_max, range_max_bits, sizeof(range_max_bits)); + } + assert_int_equal(dst->format, before.format); + assert_int_equal(dst->width, before.width); + assert_int_equal(dst->height, before.height); + assert_memory_equal(dst->data, before.data, sizeof(before.data)); + assert_memory_equal(dst->linesize, before.linesize, sizeof(before.linesize)); + assert_int_equal(dst->refs, 9); + assert_true(dst->prev_frame); + + /* The source is only read. */ + assert_int_equal(src->full_range, src_full); + assert_int_equal(src->refs, 3); + assert_false(src->prev_frame); + assert_true(src->timestamp == 0x0123456789abcdefULL); + + obs_source_frame_destroy(dst); + obs_source_frame_destroy(src); +} + +static void metadata_and_colour_range(void **state) +{ + (void)state; + check_metadata(false, false); + check_metadata(false, true); + check_metadata(true, false); + check_metadata(true, true); +} + +/* The planes the metadata test leaves alone are still copied. */ +static void metadata_copy_also_copies_planes(void **state) +{ + (void)state; + const struct format_case *fc = &formats[1]; /* NV12 */ + struct obs_source_frame *src = obs_source_frame_create(fc->format, 6, 4); + struct obs_source_frame *dst = obs_source_frame_create(fc->format, 6, 4); + assert_non_null(src); + assert_non_null(dst); + fill_source(src, fc); + set_source_metadata(src, false); + for (size_t p = 0; p < fc->planes; p++) + memset(dst->data[p], FILL_DST, (size_t)dst->linesize[p] * plane_rows(fc, p, 4)); + + obs_source_frame_copy(dst, src); + check_planes(dst, src, fc); + assert_memory_equal(dst->color_range_min, range_min_bits, sizeof(range_min_bits)); + + obs_source_frame_destroy(dst); + obs_source_frame_destroy(src); +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(every_format_equal_line_sizes), + cmocka_unit_test(every_format_unequal_line_sizes), + cmocka_unit_test(metadata_and_colour_range), + cmocka_unit_test(metadata_copy_also_copies_planes), + }; + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/test/cmocka/tests.d/test_source_frame_copy.cmake b/test/cmocka/tests.d/test_source_frame_copy.cmake new file mode 100644 index 0000000000..c98f9a81ac --- /dev/null +++ b/test/cmocka/tests.d/test_source_frame_copy.cmake @@ -0,0 +1 @@ +# Canonical target and test: test/cmocka/build/test-graph.json. From 736fd91a366abcdc32abafce77e41fcbfe4e67c0 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Wed, 25 Nov 2026 12:08:01 -0500 Subject: [PATCH 3/4] test: RED obs_source_frame_copy safe core (Refs #5714) Tier 1 mirrors of test_source_frame_copy.c (same cases, formats, sizes, line sizes and fills) and new edge cases (the order of the writes, the plane extents with wrapping row starts, short slices) against a todo!() core in obs_source::frame_copy_data. Co-Authored-By: Claude Opus 5.5 --- rust/obs-source/src/frame_copy_data.rs | 120 ++++ rust/obs-source/src/lib.rs | 1 + .../tests/source/frame_copy_data.rs | 530 ++++++++++++++++++ rust/obs-source/tests/source/main.rs | 1 + 4 files changed, 652 insertions(+) create mode 100644 rust/obs-source/src/frame_copy_data.rs create mode 100644 rust/obs-source/tests/source/frame_copy_data.rs diff --git a/rust/obs-source/src/frame_copy_data.rs b/rust/obs-source/src/frame_copy_data.rs new file mode 100644 index 0000000000..3a4184a607 --- /dev/null +++ b/rust/obs-source/src/frame_copy_data.rs @@ -0,0 +1,120 @@ +//! Safe core of `libobs/obs-source-frame-copy-data.c.h`: +//! `obs_source_frame_copy()` and the `copy_frame_data()` it runs, which +//! `cache_video()` and the two preload paths of `obs-source.c.h` call too. +//! +//! [`copy_frame_data`] does what the C does, in its order: write the +//! source's [`Metadata`] into the destination (flip, flags, transfer, range, +//! maximum luminance, timestamp and colour matrix); ask +//! [`frame_copy::copy_plan`] for the copies, with the destination's range +//! (now the source's), height and line sizes; write the source's +//! [`ColorRange`] when the plan says so; then run each plane's copy in +//! order. The decisions are the plan's (no new plan logic here); this module +//! only runs it. +//! +//! The frames are behind [`Frames`], so the core never sees a pointer: the +//! C ABI shim writes the fields and builds each plane's slices from +//! [`plane_extent`], and [`copy_plane`] copies between them as +//! `copy_frame_data_plane()` does: one copy of the plan's bytes when the line +//! sizes are equal, else row `y` from `y * src_stride` into `y * dst_stride`, +//! each product in `u32` as the C's `uint32_t` (wrap for wrap), the smaller +//! line size each. The colour values are the floats' bits: they are copied, +//! never computed. +//! +//! Nothing here allocates, keeps state, takes a lock or panics. + +#![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::frame_copy::{self, PLANES, PlaneCopy}; + +/// The fields `copy_frame_data()` always copies, in its order. The colour +/// matrix is the 16 floats' bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Metadata { + pub flip: bool, + pub flags: u8, + pub trc: u8, + pub full_range: bool, + pub max_luminance: u16, + pub timestamp: u64, + pub color_matrix: [u32; 16], +} + +/// `color_range_min` and `color_range_max`, the floats' bits: copied only +/// when the plan says so. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ColorRange { + pub min: [u32; 3], + pub max: [u32; 3], +} + +/// What `copy_frame_data()` reads of the source frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Source { + pub metadata: Metadata, + pub color_range: ColorRange, + /// An `enum video_format` value, as the C's `int`. + pub format: i32, + /// The first [`PLANES`] line sizes. + pub linesize: [u32; PLANES], +} + +/// What `copy_frame_data()` reads of the destination frame's shape. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Destination { + pub height: u32, + /// The first [`PLANES`] line sizes. + pub linesize: [u32; PLANES], +} + +/// The destination and source frames, as `copy_frame_data()` writes them. +pub trait Frames { + /// Writes the source's metadata into the destination, field by field in + /// [`Metadata`]'s order. + fn write_metadata(&mut self, metadata: Metadata); + /// Writes the source's colour range into the destination. + fn write_color_range(&mut self, range: ColorRange); + /// Runs one plane's copy (with [`copy_plane`] over the plane's slices). + fn copy_plane(&mut self, plane: usize, copy: &PlaneCopy); +} + +/// `copy_frame_data()`: the metadata, then the plan of the source's format +/// for the destination's range (the source's, just written), height and +/// line sizes: the colour range when the plan says so, then each planned +/// plane in order. +#[expect(clippy::todo)] +pub fn copy_frame_data(frames: &mut impl Frames, src: &Source, dst: Destination) { + let _ = (frames, src, dst, frame_copy::copy_plan); + todo!("#5714") +} + +/// The bytes of the destination and of the source plane one copy touches, +/// from each plane's start: `(dst, src)`. The plan's bytes for one copy; +/// else up to the end of the row that starts furthest in (in `u32`, as the +/// C computes each row's start); `(0, 0)` when nothing is copied. +#[must_use] +#[expect(clippy::todo)] +pub fn plane_extent(copy: &PlaneCopy) -> (usize, usize) { + let _ = copy; + todo!("#5714") +} + +/// `copy_frame_data_plane()`: one copy of the plan's bytes when the line +/// sizes are equal, else row `y` from `y * src_stride` into `y * +/// dst_stride` (each in `u32`), the plan's bytes each. `dst` and `src` start +/// at the planes' starts and hold [`plane_extent`]'s bytes; a row outside +/// them is not copied (the shim's slices always hold every row). +#[expect(clippy::todo)] +pub fn copy_plane(dst: &mut [u8], src: &[u8], copy: &PlaneCopy) { + let _ = (dst, src, copy); + todo!("#5714") +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 9b6e2add83..d8bd072b33 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -230,6 +230,7 @@ pub mod filter_index; pub mod filter_relationship_getters; pub mod flags_mixers; pub mod frame_copy; +pub mod frame_copy_data; pub mod frame_init; pub mod get_weak; pub mod handler_getters; diff --git a/rust/obs-source/tests/source/frame_copy_data.rs b/rust/obs-source/tests/source/frame_copy_data.rs new file mode 100644 index 0000000000..f02354a0e1 --- /dev/null +++ b/rust/obs-source/tests/source/frame_copy_data.rs @@ -0,0 +1,530 @@ +//! Tier 1: `obs_source::frame_copy_data`, `copy_frame_data()` of +//! `obs_source_frame_copy()`. +//! +//! The `test_source_frame_copy_*` cases port +//! `test/cmocka/test_source_frame_copy.c` 1:1, under the same case names, +//! with the same formats, sizes, line sizes, fills and expectations: every +//! frame pair has the same format, width and height, the source laid out as +//! `obs_source_frame_create()` lays it out. +//! +//! The `edge_*` cases are new: the order of the writes, [`plane_extent`] +//! for one copy, no rows, no bytes and row starts that wrap in `u32`, and +//! [`copy_plane`] on slices too short for a row. + +use obs_media_io::video_frame::{linesizes, plane_heights}; +use obs_media_io::video_io::video_format_from_c; +use obs_source::frame_copy::{PLANES, PlaneCopy, video_format as F}; +use obs_source::frame_copy_data::{ + ColorRange, Destination, Frames, Metadata, Source, copy_frame_data, copy_plane, plane_extent, +}; + +const FILL_DST: u8 = 0xEE; + +fn fill_src(plane: usize, i: usize) -> u8 { + (plane * 61 + i * 7 + 3) as u8 +} + +/// The C test's `formats`: the planes `obs_source_frame_create()` gives, +/// how many `copy_frame_data()` copies, and which are 4:2:0 chroma. +struct FormatCase { + format: i32, + planes: usize, + copied: usize, + half: [bool; PLANES], +} + +const fn case(format: i32, planes: usize, copied: usize, half: [bool; PLANES]) -> FormatCase { + FormatCase { + format, + planes, + copied, + half, + } +} + +const NO: [bool; PLANES] = [false; PLANES]; +const HALF3: [bool; PLANES] = [false, true, true, false]; +const HALF2: [bool; PLANES] = [false, true, false, false]; + +const FORMATS: [FormatCase; 25] = [ + case(F::I420, 3, 3, HALF3), + case(F::NV12, 2, 2, HALF2), + case(F::YVYU, 1, 1, NO), + case(F::YUY2, 1, 1, NO), + case(F::UYVY, 1, 1, NO), + case(F::RGBA, 1, 1, NO), + case(F::BGRA, 1, 1, NO), + case(F::BGRX, 1, 1, NO), + case(F::Y800, 1, 1, NO), + case(F::I444, 3, 3, NO), + case(F::BGR3, 1, 1, NO), + case(F::I422, 3, 3, NO), + case(F::I40A, 4, 4, HALF3), + case(F::I42A, 4, 4, NO), + case(F::YUVA, 4, 4, NO), + case(F::AYUV, 1, 1, NO), + case(F::I010, 3, 3, HALF3), + case(F::P010, 2, 2, HALF2), + case(F::I210, 3, 3, NO), + case(F::I412, 3, 3, NO), + case(F::YA2L, 4, 4, NO), + // Characterized, not endorsed: P216 and P416 copy no plane. + case(F::P216, 2, 0, NO), + case(F::P416, 2, 0, NO), + case(F::V210, 1, 1, NO), + case(F::R10L, 1, 1, NO), +]; + +const SIZES: [(u32, u32); 4] = [(1, 1), (13, 7), (32, 16), (5, 2)]; + +fn plane_rows(fc: &FormatCase, plane: usize, height: u32) -> u32 { + if fc.half[plane] { + height.div_ceil(2) + } else { + height + } +} + +/// A frame: its metadata, colour range, format, size, line sizes and one +/// buffer per plane. +#[derive(Debug, Clone, PartialEq)] +struct Frame { + metadata: Metadata, + color_range: ColorRange, + format: i32, + width: u32, + height: u32, + linesize: [u32; PLANES], + planes: Vec>, +} + +impl Frame { + /// `obs_source_frame_create()`'s layout, every plane exactly line size x + /// rows (the frame's planes are one block; each plane's part of it). + fn create(fc: &FormatCase, width: u32, height: u32) -> Self { + let format = video_format_from_c(fc.format).unwrap(); + let lines = linesizes(format, width); + let heights = plane_heights(format, height); + let mut linesize = [0; PLANES]; + let mut planes = Vec::new(); + for p in 0..fc.planes { + assert_eq!(heights[p], plane_rows(fc, p, height)); + linesize[p] = lines[p]; + planes.push(vec![0; lines[p] as usize * heights[p] as usize]); + } + Self { + metadata: Metadata::default(), + color_range: ColorRange::default(), + format: fc.format, + width, + height, + linesize, + planes, + } + } + + /// The C test's `build_destination()`: the format and size, its own line + /// sizes, each plane filled with `FILL_DST`. + fn build(fc: &FormatCase, width: u32, height: u32, linesize: [u32; PLANES]) -> Self { + let planes = (0..fc.planes) + .map(|p| vec![FILL_DST; linesize[p] as usize * plane_rows(fc, p, height) as usize]) + .collect(); + Self { + metadata: Metadata::default(), + color_range: ColorRange::default(), + format: fc.format, + width, + height, + linesize, + planes, + } + } + + fn fill_source(&mut self) { + for (p, plane) in self.planes.iter_mut().enumerate() { + for (i, byte) in plane.iter_mut().enumerate() { + *byte = fill_src(p, i); + } + } + } + + fn fill_destination(&mut self) { + for plane in &mut self.planes { + plane.fill(FILL_DST); + } + } +} + +struct Pair<'a> { + dst: &'a mut Frame, + src: &'a Frame, +} + +impl Frames for Pair<'_> { + fn write_metadata(&mut self, metadata: Metadata) { + self.dst.metadata = metadata; + } + + fn write_color_range(&mut self, range: ColorRange) { + self.dst.color_range = range; + } + + fn copy_plane(&mut self, plane: usize, copy: &PlaneCopy) { + let (dst, src) = (&mut self.dst.planes[plane], &self.src.planes[plane]); + // Every row the plan copies lies inside both planes. + let (dst_len, src_len) = plane_extent(copy); + assert!( + dst_len <= dst.len(), + "plane {plane}: {dst_len} > {}", + dst.len() + ); + assert!( + src_len <= src.len(), + "plane {plane}: {src_len} > {}", + src.len() + ); + copy_plane(dst, src, copy); + } +} + +/// `obs_source_frame_copy(dst, src)`. +fn frame_copy(dst: &mut Frame, src: &Frame) { + let source = Source { + metadata: src.metadata, + color_range: src.color_range, + format: src.format, + linesize: src.linesize, + }; + let shape = Destination { + height: dst.height, + linesize: dst.linesize, + }; + copy_frame_data(&mut Pair { dst, src }, &source, shape); +} + +/// The C test's `check_planes()`. +fn check_planes(dst: &Frame, src: &Frame, fc: &FormatCase) { + for p in 0..fc.planes { + let rows = plane_rows(fc, p, dst.height) as usize; + let (dst_line, src_line) = (dst.linesize[p] as usize, src.linesize[p] as usize); + let bytes = dst_line.min(src_line); + for y in 0..rows { + let row = &dst.planes[p][y * dst_line..][..dst_line]; + let from = &src.planes[p][y * src_line..]; + for (x, &got) in row.iter().enumerate() { + let want = if p < fc.copied && x < bytes { + from[x] + } else { + FILL_DST + }; + assert_eq!( + got, want, + "format {} {}x{} plane {p} row {y} byte {x}", + fc.format, dst.width, dst.height + ); + } + } + } +} + +fn check_equal_line_sizes(fc: &FormatCase, width: u32, height: u32) { + let mut src = Frame::create(fc, width, height); + let mut dst = Frame::create(fc, width, height); + src.fill_source(); + assert_eq!(dst.linesize, src.linesize); + dst.fill_destination(); + + frame_copy(&mut dst, &src); + check_planes(&dst, &src, fc); +} + +#[test] +fn test_source_frame_copy_every_format_equal_line_sizes() { + for fc in &FORMATS { + for (width, height) in SIZES { + check_equal_line_sizes(fc, width, height); + } + } +} + +fn check_unequal_line_sizes(fc: &FormatCase, width: u32, height: u32, delta: [i64; PLANES]) { + let mut src = Frame::create(fc, width, height); + src.fill_source(); + let mut linesize = [0; PLANES]; + for p in 0..fc.planes { + linesize[p] = (i64::from(src.linesize[p]) + delta[p]).max(1) as u32; + } + let mut dst = Frame::build(fc, width, height, linesize); + + frame_copy(&mut dst, &src); + check_planes(&dst, &src, fc); + assert_eq!(dst.linesize, linesize); +} + +#[test] +fn test_source_frame_copy_every_format_unequal_line_sizes() { + const DELTAS: [[i64; PLANES]; 5] = [ + [16, 16, 16, 16], + [-1, -1, -1, -1], + [5, -1, 3, -1], + [-3, 0, 7, 0], + [0, 9, -1, 2], + ]; + for fc in &FORMATS { + for (width, height) in SIZES { + for delta in DELTAS { + check_unequal_line_sizes(fc, width, height, delta); + } + } + } +} + +const MATRIX_BITS: [u32; 16] = [ + 0x3f80_0000, + 0x0000_0000, + 0x8000_0000, + 0x7f80_0000, + 0xff80_0000, + 0x7fc0_0001, + 0x7f80_0001, + 0x0000_0001, + 0x3eaa_aaab, + 0xbf00_0000, + 0x4120_0000, + 0x1234_5678, + 0xffff_ffff, + 0x7f7f_ffff, + 0x0080_0000, + 0xc2c8_0000, +]; +const RANGE_MIN_BITS: [u32; 3] = [0x3d80_8081, 0x7fc0_0002, 0x8000_0000]; +const RANGE_MAX_BITS: [u32; 3] = [0x3f6b_6b6c, 0x3f70_0000, 0x7f80_0001]; + +fn set_source_metadata(src: &mut Frame, full_range: bool) { + src.metadata = Metadata { + flip: true, + flags: 0xa5, + trc: 0x3c, + full_range, + max_luminance: 0xbeef, + timestamp: 0x0123_4567_89ab_cdef, + color_matrix: MATRIX_BITS, + }; + src.color_range = ColorRange { + min: RANGE_MIN_BITS, + max: RANGE_MAX_BITS, + }; +} + +fn set_destination_metadata(dst: &mut Frame, full_range: bool) { + dst.metadata = Metadata { + flip: false, + flags: 0x11, + trc: 0x01, + full_range, + max_luminance: 7, + timestamp: 42, + color_matrix: [0x2222_2222; 16], + }; + dst.color_range = ColorRange { + min: [0x3333_3333; 3], + max: [0x4444_4444; 3], + }; +} + +const NV12: usize = 1; + +fn check_metadata(src_full: bool, dst_full: bool) { + let fc = &FORMATS[NV12]; + let mut src = Frame::create(fc, 6, 4); + let mut dst = Frame::create(fc, 6, 4); + set_source_metadata(&mut src, src_full); + set_destination_metadata(&mut dst, dst_full); + let before = dst.clone(); + let source = src.clone(); + + frame_copy(&mut dst, &src); + + assert_eq!(dst.metadata, src.metadata); + if src_full { + assert_eq!(dst.color_range, before.color_range); + } else { + assert_eq!(dst.color_range.min, RANGE_MIN_BITS); + assert_eq!(dst.color_range.max, RANGE_MAX_BITS); + } + assert_eq!(dst.format, before.format); + assert_eq!(dst.width, before.width); + assert_eq!(dst.height, before.height); + assert_eq!(dst.linesize, before.linesize); + // The source is only read. + assert_eq!(src, source); +} + +#[test] +fn test_source_frame_copy_metadata_and_colour_range() { + check_metadata(false, false); + check_metadata(false, true); + check_metadata(true, false); + check_metadata(true, true); +} + +#[test] +fn test_source_frame_copy_metadata_copy_also_copies_planes() { + let fc = &FORMATS[NV12]; + let mut src = Frame::create(fc, 6, 4); + let mut dst = Frame::create(fc, 6, 4); + src.fill_source(); + set_source_metadata(&mut src, false); + dst.fill_destination(); + + frame_copy(&mut dst, &src); + check_planes(&dst, &src, fc); + assert_eq!(dst.color_range.min, RANGE_MIN_BITS); +} + +/// Records the order of the writes. +#[derive(Default)] +struct Recorder { + calls: Vec, +} + +impl Frames for Recorder { + fn write_metadata(&mut self, metadata: Metadata) { + self.calls.push(format!("metadata {}", metadata.full_range)); + } + + fn write_color_range(&mut self, _range: ColorRange) { + self.calls.push("range".into()); + } + + fn copy_plane(&mut self, plane: usize, copy: &PlaneCopy) { + self.calls.push(format!("plane {plane} {}", copy.rows)); + } +} + +#[test] +fn edge_metadata_then_range_then_planes_in_order() { + let mut src = Source { + format: F::I40A, + linesize: [8, 4, 4, 8], + ..Source::default() + }; + let dst = Destination { + height: 5, + linesize: [8, 4, 4, 8], + }; + let mut rec = Recorder::default(); + copy_frame_data(&mut rec, &src, dst); + assert_eq!( + rec.calls, + [ + "metadata false", + "range", + "plane 0 5", + "plane 1 3", + "plane 2 3", + "plane 3 5" + ] + ); + + // A full-range source writes no range, whatever the destination was. + src.metadata.full_range = true; + let mut rec = Recorder::default(); + copy_frame_data(&mut rec, &src, dst); + assert_eq!(rec.calls[..2], ["metadata true", "plane 0 5"]); + + // P216 copies no plane. + src.format = F::P216; + let mut rec = Recorder::default(); + copy_frame_data(&mut rec, &src, dst); + assert_eq!(rec.calls, ["metadata true"]); +} + +fn rows(rows: u32, src_stride: u32, dst_stride: u32, bytes: usize) -> PlaneCopy { + PlaneCopy { + whole: false, + bytes, + rows, + src_stride, + dst_stride, + } +} + +#[test] +fn edge_plane_extent() { + let whole = PlaneCopy { + whole: true, + bytes: 1920 * 1080, + rows: 1080, + src_stride: 1920, + dst_stride: 1920, + }; + assert_eq!(plane_extent(&whole), (1920 * 1080, 1920 * 1080)); + assert_eq!( + plane_extent(&rows(4, 10, 12, 10)), + (3 * 12 + 10, 3 * 10 + 10) + ); + assert_eq!( + plane_extent(&rows(4, 12, 10, 10)), + (3 * 10 + 10, 3 * 12 + 10) + ); + assert_eq!(plane_extent(&rows(1, 12, 10, 10)), (10, 10)); + assert_eq!(plane_extent(&rows(0, 12, 10, 10)), (0, 0)); + assert_eq!(plane_extent(&rows(5, 12, 10, 0)), (0, 0)); + // Row starts wrap in u32: rows 0..3 at 2^31 start at 0, 2^31, 0. + assert_eq!( + plane_extent(&rows(3, 0x8000_0000, 1, 1)), + (2 + 1, 0x8000_0000 + 1) + ); + // The furthest row is not the last one once the starts wrap. + let stride = 0x6000_0000u32; + let furthest = (0..4u32).map(|y| y.wrapping_mul(stride)).max().unwrap() as usize; + assert_eq!(furthest, 0xc000_0000); + assert_eq!(plane_extent(&rows(4, stride, 1, 7)).1, furthest + 7); +} + +#[test] +fn edge_copy_plane_rows_and_whole() { + let src: Vec = (0..40).collect(); + let mut dst = vec![0xff; 40]; + copy_plane(&mut dst, &src, &rows(3, 10, 12, 4)); + for y in 0..3 { + assert_eq!(dst[y * 12..y * 12 + 4], src[y * 10..y * 10 + 4]); + assert!(dst[y * 12 + 4..y * 12 + 12].iter().all(|&b| b == 0xff)); + } + assert!(dst[28..].iter().all(|&b| b == 0xff)); + + let mut dst = vec![0xff; 40]; + let whole = PlaneCopy { + whole: true, + bytes: 30, + rows: 3, + src_stride: 10, + dst_stride: 10, + }; + copy_plane(&mut dst, &src, &whole); + assert_eq!(dst[..30], src[..30]); + assert!(dst[30..].iter().all(|&b| b == 0xff)); +} + +#[test] +fn edge_copy_plane_short_slices_copy_what_fits() { + let src: Vec = (0..20).collect(); + let mut dst = vec![0xff; 15]; + // Rows 0 and 1 fit; row 2 (dst 12..17) does not and is skipped. + copy_plane(&mut dst, &src, &rows(3, 6, 6, 5)); + assert_eq!(dst[..5], src[..5]); + assert_eq!(dst[6..11], src[6..11]); + assert!(dst[12..].iter().all(|&b| b == 0xff)); + + let mut dst = vec![0xff; 4]; + let whole = PlaneCopy { + whole: true, + bytes: 8, + rows: 1, + src_stride: 8, + dst_stride: 8, + }; + copy_plane(&mut dst, &src, &whole); + assert_eq!(dst, [0xff; 4]); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 964b479714..89d89ef96f 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -85,6 +85,7 @@ mod filter_relationship_getters_parity; mod flags_mixers; mod flags_mixers_parity; mod frame_copy; +mod frame_copy_data; mod frame_copy_parity; mod frame_init; mod frame_init_parity; From 59d8dbca7b4fb4ac24a1843661f882edb42c11aa Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Wed, 25 Nov 2026 12:19:56 -0500 Subject: [PATCH 4/4] obs-source: port obs_source_frame_copy to Rust (Fixes #5714) Safe core frame_copy_data::copy_frame_data writes the metadata, asks the existing frame_copy::copy_plan, writes the colour range when the plan says so and runs each plane copy through frame_copy_data::copy_plane over slices the shim builds from plane_extent (row starts in u32, as the C computes them). The C ABI shim mirrors the public struct obs_source_frame and writes each field through the pointer. cache_video() and the two preload paths reach it through the exported obs_source_frame_copy(). The extracted C moves to the reference-only group libobs.ported-source-frame-copy-data. Tier 3 parity against the original C over every format, seven sizes and six line-size patterns, and a proptest over same-shape frames. Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795655480,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":93,"stamp":"6eb78adf660271b68d6d201bef38bf04","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655480,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":93,"stamp":"ed13aecc41336dbc8b58ae2eb145a132","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655480,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":93,"stamp":"a5323f8165dceb55bdbe6f07b1ad47ae","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655480,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":93,"stamp":"f03b85df1b3a02cf2d16a5722a3fd8bd","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"general/all/client-lint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"5f66ddf545df2d40d90292ac818dfa62","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655480,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":93,"stamp":"f589f637c69716edcbc2c55dbb73d317","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"f60685b3f19de6abefba990c81b14d60","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"6f0964d4948f8514891947565aebbf36","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"575b97a9c110507b09bab1d256b0f402","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"3e3b533c9d90ef9e16c8014d42fa2aeb","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"96ad65cd71bc5cbae9f26f9a58edec69","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"e3c586bd31587e8daa68b139c7de9a4f","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"67a717335f95c4c04518b6e4ff092f4a","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"3f0b0529180c22c94a9f2650cde61e36","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"8b8b15aa697252ced257f7f0efaadf8d","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"21c24c146cb8d10a6e6e5172ac248f95","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"f37f67fbb787ff7ecf71e8ec4e561bb1","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655386,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"ba618f321d17f7ec6047b7687078ec63937be1a44724e00e36fb766b846cb0d0","lane":"client-lint","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":10,"stamp":"32e893afc3044d736e3bcfd9172140c9","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Ci-Attestation: {"at":1795655644,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"49587e5440f1978772c3d9d3e97ce51c084e66021005445d96ceb793304b201f","lane":"client-test-x86_64-unknown-linux-gnu","parents":["736fd91a366abcdc32abafce77e41fcbfe4e67c0"],"secs":164,"stamp":"32467eaf3c4731135d949704421f7472","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44","v":1,"via":"run"} Client-Checks: {"checks":{"base":"7f54bf96e78bc88fc3ea6a698513e38131e7932e","coverage":"all-tracked-applicable-files","diff":["libobs/build/libobs.ported-source-frame-copy-data+.h.c","libobs/build/ported-source-sets/source-frame-copy-data.json","libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt","libobs/obs-source-frame-copy-data.c.h","libobs/obs-source.c.h","rust/README.md","rust/obs-build/tests/native.rs","rust/obs-build/tests/native/registration/canonical_source_frame_copy_data_swap_is_registered.rs","rust/obs-c-oracle/oracle.d/source-frame-copy-data.list","rust/obs-c-oracle/oracle/source_frame_copy_data.c","rust/obs-source/Cargo.toml","rust/obs-source/src/ffi/mod.rs","rust/obs-source/src/ffi/source_frame_copy_data.rs","rust/obs-source/src/frame_copy_data.rs","rust/obs-source/src/lib.rs","rust/obs-source/tests/source/frame_copy_data.rs","rust/obs-source/tests/source/frame_copy_data_parity.rs","rust/obs-source/tests/source/main.rs","test/cmocka/build/test-graph.json","test/cmocka/test_source_frame_copy.c","test/cmocka/tests.d/test_source_frame_copy.cmake"],"head":"e543bfee7ee8cc80188acce181553d85642043cb","tools":{"orchestrator-python":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]","schema-dependencies":"3.13.16 (main, Oct 14 2026, 01:04:01) [Clang 23.1.3 ]\n{'jsonschema': '4.26.0', 'json_source_map': '1.0.5'}","uv":"uv 0.13.5 (x86_64-unknown-linux-gnu)","xmllint":"xmllint: using libxml version 21504-GITv2.15.4\n compiled with: Threads Tree Output Push Reader Patterns Writer SAXv1 DTDValid HTML C14N Catalog XPath XPointer XInclude Iconv ICU ISO8859X Regexps Automata RelaxNG Schemas Schematron Modules Debug Zlib"},"tracked-digest":"3fb3223eb3447aea49eca9e9441be52328bdccc7f3f1f03377b40ecf99ebe582","tree":"9727ee1e3c9c055f0ae3737a61c4c91dd3f58d44"}} --- libobs/build/libobs.core-source+.h.c | 1 - .../libobs.ported-source-frame-copy-data+.h.c | 5 + .../source-frame-copy-data.json | 5 + .../obs-source-source_frame_copy_data.txt | 1 + rust/README.md | 1 + rust/obs-build/tests/native.rs | 2 + ...urce_frame_copy_data_swap_is_registered.rs | 42 ++ .../oracle.d/source-frame-copy-data.list | 1 + .../oracle/source_frame_copy_data.c | 46 ++ rust/obs-source/Cargo.toml | 2 +- rust/obs-source/src/ffi/mod.rs | 1 + .../src/ffi/source_frame_copy_data.rs | 169 ++++++++ rust/obs-source/src/frame_copy_data.rs | 67 ++- rust/obs-source/src/lib.rs | 3 + .../tests/source/frame_copy_data_parity.rs | 394 ++++++++++++++++++ rust/obs-source/tests/source/main.rs | 1 + 16 files changed, 730 insertions(+), 11 deletions(-) create mode 100644 libobs/build/libobs.ported-source-frame-copy-data+.h.c create mode 100644 libobs/build/ported-source-sets/source-frame-copy-data.json create mode 100644 libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt create mode 100644 rust/obs-build/tests/native/registration/canonical_source_frame_copy_data_swap_is_registered.rs create mode 100644 rust/obs-c-oracle/oracle.d/source-frame-copy-data.list create mode 100644 rust/obs-c-oracle/oracle/source_frame_copy_data.c create mode 100644 rust/obs-source/src/ffi/source_frame_copy_data.rs create mode 100644 rust/obs-source/tests/source/frame_copy_data_parity.rs diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index 08cdbc49d8..a294f84a8f 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -79,7 +79,6 @@ #include "libobs/obs-source-filter-index-fields.c.h" #include "libobs/obs-source-filter-relationship-fields.c.h" #include "libobs/obs-source-flags-mixers-fields.c.h" -#include "libobs/obs-source-frame-copy-data.c.h" #include "libobs/obs-source-get-weak-fields.c.h" #include "libobs/obs-source-handler-getters-fields.c.h" #include "libobs/obs-source-hidden-setter-fields.c.h" diff --git a/libobs/build/libobs.ported-source-frame-copy-data+.h.c b/libobs/build/libobs.ported-source-frame-copy-data+.h.c new file mode 100644 index 0000000000..12dce06dd6 --- /dev/null +++ b/libobs/build/libobs.ported-source-frame-copy-data+.h.c @@ -0,0 +1,5 @@ +/* Unity group (BUILD.md): original obs_source_frame_copy for C reference. */ + +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-frame-copy-data.c.h" diff --git a/libobs/build/ported-source-sets/source-frame-copy-data.json b/libobs/build/ported-source-sets/source-frame-copy-data.json new file mode 100644 index 0000000000..b31bb46035 --- /dev/null +++ b/libobs/build/ported-source-sets/source-frame-copy-data.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-frame-copy-data+.h.c" + ] +} diff --git a/libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt b/libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt new file mode 100644 index 0000000000..9ee57fa465 --- /dev/null +++ b/libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt @@ -0,0 +1 @@ +obs_source_frame_copy diff --git a/rust/README.md b/rust/README.md index c27db31b30..50df56bee2 100644 --- a/rust/README.md +++ b/rust/README.md @@ -467,6 +467,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-source-filter-index.c.h` | `obs-source::filter_index` | Pointer-identity lookup under the original filter mutex, first duplicate wins, absent/empty returns -1. Preserves NULL validation order and exact debug logs. Private C adapters retain field access and locking; unchanged C characterization and real-header differential tests cover state and mutex release. No intentional differences; Tier 4 inapplicable. | | `libobs/obs-source-filter-relationship-getters.c.h` | `obs-source::filter_relationship_getters` | Borrowed parent/target getters preserve pointer identity, NULL defaults and exact debug logs. No source-type validation, lock or reference acquisition. Private field-pointer seam avoids mirroring `obs_source`. Unchanged actual-library C characterization, real-header view layout and Tier 3 check pointer identity and complete fixture immutability. No intentional differences; Tier 4 not applicable. | | `libobs/obs-source-flags-mixers.c.h` | `obs-source::flags_mixers`, shims in `obs-source::ffi::source_flags_mixers` | #5610: swapped in hybrid `libobs` (group `libobs.ported-source-flags-mixers`). `obs_source_set_flags()` stores a changed value, then emits `update_flags` with the source and the stored flags; an unchanged value stores and emits nothing. `obs_source_set_audio_mixers()` leaves a source without `OBS_SOURCE_AUDIO` that does not own its info id alone; on a change it emits `audio_mixers` before the store (handlers see the old field and getter answer and may rewrite `mixers`), then stores the low 32 bits of what the calldata holds afterwards (0 when a handler left it with another size). Both signals go through libobs's signal handler on a fixed 128-byte calldata. A NULL source logs one `LOG_DEBUG` line naming the function. The same-value, audio and truncation rules are `obs-source::monitoring`'s. Safe core over a `Source` trait; the shims reject NULL before calling the adapters of `obs-source-flags-mixers-fields.c.h` (live group `libobs.core-source`, no `EXPORT`). `signal_flags_updated()` moved with its only caller. The unchanged `test_source_flags_mixers` runs against hybrid and reference libraries through the real libobs. Tier 3 runs the original C and the Rust exports on noise-filled real-header sources with a real signal handler, over handlers that leave, rewrite, resize or re-set the value from inside (every event, value, field seen, calldata shape, stored fields, every other byte, NULL log lines), a proptest, and rejects five mutants. | None. | +| `libobs/obs-source-frame-copy-data.c.h` | `obs-source::frame_copy_data` | #5714: `obs_source_frame_copy()` and the `copy_frame_data()` behind it, which `cache_video()` and the two preload paths now reach through the exported function. Swapped in hybrid `libobs` (group `libobs.ported-source-frame-copy-data`). Safe core `frame_copy_data::copy_frame_data` writes the metadata (flip, flags, transfer, range, maximum luminance, timestamp, colour matrix bit for bit), asks the existing `frame_copy::copy_plan` (no new plan logic), writes the colour range only when the plan says so (the source is not full range), then runs each plane: one copy for equal line sizes, else row by row at each stride with the smaller line size, row starts in `u32` as the C computes them. The shim mirrors the public `struct obs_source_frame`, writes each field through the pointer and builds each plane's slices from `plane_extent`; `format`, size, `data`, line sizes, `refs` and `prev_frame` are never written. Unchanged C characterization `test_source_frame_copy` (every format, equal and unequal line sizes, metadata and colour range, same-shape frames) runs against hybrid and reference libraries; Tier 3 compares the original C over every format, seven sizes and six line-size patterns, and a proptest over same-shape frames, fields as bits and plane bytes with guards. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-frame-copy.c.h` | `obs-source::frame_copy` | Swapped in hybrid `libobs` (group `libobs.ported-source-frame-copy`). The async frame copy plan and cache decisions of `obs-source.c`, as six functions on plain values: `obs_source_frame_copy_plan()` (`copy_frame_data()`, `copy_frame_data_plane()` and `copy_frame_data_line()`: the colour range only when the frame is not full range, 065379b; then per format each plane's rows, `(height + 1) / 2` for 4:2:0 chroma, 8440a53; one copy of line size x rows in `size_t` when the two line sizes are equal, else rows of the smaller line size; no plane for P216, P416 and values outside the enum), `obs_source_frame_copy_cache_step()` (`cache_video()`'s queue limit at `MAX_ASYNC_FRAMES`, 7f7901b, which clears the cache and refuses the frame, then `async_texture_changed()`'s reset on a new size or convert type), `obs_source_frame_copy_cache_clean()` (one entry of `clean_cache()`: an unused entry counts one more call and is dropped at `MAX_UNUSED_FRAME_DURATION`, 3a90be3, 0815d5c), `obs_source_frame_copy_full_range()` and `_full_range2()` (a frame given to `obs_source_output_video()`, `obs_source_preload_video()` or `obs_source_set_video_frame()` that is not YUV is full range, 8d125dc; their `*2()` variants are full range when `resolve_video_range()` gives `VIDEO_RANGE_FULL`) and `obs_source_frame_copy_preload_changed()` (`preload_frame_changed()`). They are declared in `obs-source-frame-copy.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every `memcpy()` (it runs the plan, each row at `y * line size` in `uint32_t`), the metadata copy, `obs_source_frame_create()` and `_destroy()`, the `async_cache` and `async_frames` darrays and the walk that picks the first unused entry (with #2048's `prev_frame` reset, #2009), `async_mutex`, the refcount atomics, and `get_convert_type()` (it passes the two convert types). Everything crosses by value, as `#[repr(C)]` mirrors of the header's structs: no pointer crosses. The formats and ranges cross as `int`, so values outside the enums take the C's paths. The arithmetic is the C's, wrap for wrap: `(height + 1) / 2` in `u32` and the one copy's size as a `usize` product. Kept, characterized, not endorsed: P216 and P416 copy no plane ("Unimplemented"); `UINT32_MAX` rows have 0 chroma rows; an unused count past 5 is never dropped (unreachable); the `*2()` rule keeps an explicit `VIDEO_RANGE_PARTIAL` on an RGB frame, which the first rule would make full range. Intentional difference, unreachable: `clean_cache()`'s `++unused_count` overflows a `long` at `LONG_MAX`, which is undefined in C; the port wraps. No entry gets past 5. `test_source_frame_copy_steps` compiles the C into itself, and `test_source_frame_copy_steps_rust` runs the same test source against `libobs_rust-static`; `test_video_frame`, the media restart tests, the v4l2 and PipeWire camera tests, `test_async_rotation_normalize` and the deinterlace tests see the swap through the real libobs. Tier 3 compares every field of every result over every C format value against every pattern of the four planes' line sizes (equal, smaller, larger, 0, or a destination of 0) at the `u32` height edges (2,280,000 plans), real frame line sizes, the queue limit over every length up to 64 with each key field changed alone, every count from -1000 to 1000 and the `c_long` ends but `LONG_MAX`, the range rules over formats -300 to 300 and every range from -10 to 10 with the `i32` ends, every preload combination around the edges, and proptests over each. | | `libobs/obs-source-get-name.c.h` | `obs-source::source_name` | Borrowed source context name getter (#4505): unchanged NULL debug diagnostic, private nameless NULL, pointer identity and original lifetime. Lazy safe core, opaque C field adapter and real standalone link support; Tier 1 getter assertions, original-C differential and mutation checks, unchanged context-name Tier 2. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-get-weak.c.h` | `obs-source::get_weak` | #5228: `obs_source_get_weak_source()` swapped in hybrid `libobs` (group `libobs.ported-source-get-weak`). A NULL source returns NULL without reading anything or logging; otherwise the source's own `context.control`, read through the narrow private adapter `obs-source-get-weak-fields.c.h`, goes once through the C-owned `obs_weak_source_addref()` (also for a NULL control, a no-op there) and is returned. The strong count, the control and the source bytes stay untouched; release and the atomics stay in C. The unchanged `test_source_get_weak` runs against hybrid and reference libraries; Tier 3 runs the original C and the Rust export over present/absent sources and controls, noise-filled layouts and repeated calls, comparing returns, addref calls and arguments, weak and strong counts and source bytes. 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 0fa76254a7..75110b0b73 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -53,6 +53,8 @@ mod canonical_source_draw_swap_is_registered; mod canonical_source_enum_filters_swap_is_registered; #[path = "native/registration/canonical_source_flags_mixers_swap_is_registered.rs"] mod canonical_source_flags_mixers_swap_is_registered; +#[path = "native/registration/canonical_source_frame_copy_data_swap_is_registered.rs"] +mod canonical_source_frame_copy_data_swap_is_registered; #[path = "native/registration/canonical_source_get_weak_swap_is_registered.rs"] mod canonical_source_get_weak_swap_is_registered; #[path = "native/registration/canonical_source_media_controls_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_frame_copy_data_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_frame_copy_data_swap_is_registered.rs new file mode 100644 index 0000000000..c9d709fda5 --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_frame_copy_data_swap_is_registered.rs @@ -0,0 +1,42 @@ +use super::*; + +#[test] +fn canonical_source_frame_copy_data_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_frame_copy"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + for os in ["OS_LINUX", "OS_MACOS", "OS_WINDOWS"] { + let selected = graph.select(&[(os.into(), true)].into()).unwrap(); + // The unchanged test compiles no copy of the C: it calls the exported + // obs_source_frame_copy() of the real libobs (Rust in hybrid, the + // original C in the reference). + assert!( + matches!(selected.targets[name].sources.as_slice(), [Source::Path(path)] + if path == "test/cmocka/test_source_frame_copy.c") + ); + assert_eq!(selected.tests[name].target, name); + } + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/source-frame-copy-data.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-frame-copy-data+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-frame-copy-data+.h.c")) + .unwrap(); + assert!(group.contains("#include \"libobs/obs-source-frame-copy-data.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-frame-copy-data.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source.c.h\"")); + let exports = fs::read_to_string( + root.join("libobs/cmake/rust-exports.d/obs-source-source_frame_copy_data.txt"), + ) + .unwrap(); + assert_eq!( + exports.lines().collect::>(), + ["obs_source_frame_copy"] + ); +} diff --git a/rust/obs-c-oracle/oracle.d/source-frame-copy-data.list b/rust/obs-c-oracle/oracle.d/source-frame-copy-data.list new file mode 100644 index 0000000000..1f04dc91bb --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-frame-copy-data.list @@ -0,0 +1 @@ +source-frame-copy-data.inc|libobs/obs-source-frame-copy-data.c.h|auto diff --git a/rust/obs-c-oracle/oracle/source_frame_copy_data.c b/rust/obs-c-oracle/oracle/source_frame_copy_data.c new file mode 100644 index 0000000000..8f78d55fcb --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_frame_copy_data.c @@ -0,0 +1,46 @@ +/* Tier 3: the unchanged extracted obs_source_frame_copy() (copy_frame_data() + * and its helpers) against the Rust export. Both ask the same + * obs_source_frame_copy_plan() (the Rust one; its own parity is + * source_frame_copy.c), so this compares running the plan: the fields + * written and the bytes copied. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#define obs_source_frame_copy oracle_obs_source_frame_copy +#include "libobs/build/libobs.pch.h" +#include "source-frame-copy-data.inc" +#undef obs_source_frame_copy + +/* The layout of struct obs_source_frame, in the order of + * rust/obs-source/tests/source/frame_copy_data_parity.rs; SIZE_MAX past + * the end. */ +size_t oracle_source_frame_copy_data_layout(size_t which); + +#define OFF(member) offsetof(struct obs_source_frame, member) + +size_t oracle_source_frame_copy_data_layout(size_t which) +{ + const size_t values[] = { + sizeof(struct obs_source_frame), + _Alignof(struct obs_source_frame), + OFF(data), + OFF(linesize), + OFF(width), + OFF(height), + OFF(timestamp), + OFF(format), + OFF(color_matrix), + OFF(full_range), + OFF(max_luminance), + OFF(color_range_min), + OFF(color_range_max), + OFF(flip), + OFF(flags), + OFF(trc), + OFF(refs), + OFF(prev_frame), + sizeof(enum video_format), + MAX_AV_PLANES, + }; + return which < sizeof(values) / sizeof(values[0]) ? values[which] : SIZE_MAX; +} diff --git a/rust/obs-source/Cargo.toml b/rust/obs-source/Cargo.toml index a8a9934322..6d9b205d5f 100644 --- a/rust/obs-source/Cargo.toml +++ b/rust/obs-source/Cargo.toml @@ -2,7 +2,7 @@ autotests = false name = "obs-source" version = "0.1.0" -description = "Rust ports of libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-set-name.c.h (the source rename), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-access.c.h (the transition getters and manual controls; C shims in obs-source-seam), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-load.c.h (the transition load, scale type and swap checks), libobs/obs-source-transition-restore.c.h (the transition load; C shim in obs-source-seam), libobs/obs-source-transition-render.c.h (the transition render and audio steps), libobs/obs-source-transition-sample-time.c.h (the transition's per-sample audio time), libobs/obs-source-transition-settings.c.h (the transition settings; C shims in obs-source-seam), libobs/obs-source-transition-size.c.h (the transition size, child matrices and tick; C shims in obs-source-seam), libobs/obs-source-transition-slots.c.h (the transition child slots and swap; C shims in obs-source-seam), libobs/obs-source-transition-start.c.h (the transition start checks and child handover), libobs/obs-source-transition-stop.c.h (the transition clock read and stop; C shims in obs-source-seam), libobs/obs-source-transition-switch.c.h (the transition start and set; C shims in obs-source-seam), libobs/obs-source-transition-video.c.h (the transition video render; C shims in obs-source-seam), the rest of libobs/obs-source-transition.c.h (the transition audio render, init and free; C shims in obs-source-seam), libobs/obs-source-video-tick.c.h (the per-frame video tick decisions) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions), libobs/obs-source-volume-mul.c.h (the source volume multiply kernels)" +description = "Rust ports of libobs/obs-source-async-decoupled.c.h (the async decoupled setter; C shim in obs-source-seam), libobs/obs-source-async-pacing.c.h (the async video frame pacing), libobs/obs-source-async-upload.c.h (the async video upload decisions), libobs/obs-source-audio-input.c.h (the source audio input steps), libobs/obs-source-audio-place.c.h (the source audio placement and action timeline), libobs/obs-source-audio-render.c.h (the source audio render mix plan), libobs/obs-source-audio-timing.c.h (the source audio timestamp placement), libobs/obs-source-color-space.c.h (the colour space query routing), libobs/obs-source-conversion-plan.c.h (the async video GPU conversion plan), the rest of libobs/obs-source-deinterlace.c.h (the deinterlace frame take, texture update, render and setters), libobs/obs-source-deinterlace-draw.c.h (the deinterlace draw decisions), libobs/obs-source-deinterlace-pacing.c.h (the 2x deinterlace frame pacing), libobs/obs-source-deinterlace-select.c.h (the deinterlace frame selection), libobs/obs-source-deinterlace-texture.c.h (the deinterlace texture size), libobs/obs-source-draw.c.h (obs_source_draw and obs_source_draw_set_color_matrix), libobs/obs-source-draw-plan.c.h (the source draw decisions), libobs/obs-source-duplicate.c.h (the source and scene duplicate plans), libobs/obs-source-filter-backup.c.h (the filter backup), libobs/obs-source-filter-chain.c.h (the filter chain rules), libobs/obs-source-frame-copy.c.h (the async frame copy plan and cache decisions), libobs/obs-source-frame-copy-data.c.h (obs_source_frame_copy, running the copy plan), libobs/obs-source-info-lookup.c.h (the source type lookup), libobs/obs-source-media-admission.c.h (the media action admission decisions), libobs/obs-source-monitoring.c.h (the source monitoring, monitor-only mute and balance rules), libobs/obs-source-private-settings.c.h (the source private-settings getter), libobs/obs-source-ptm-gate.c.h (the push-to-mute and push-to-talk gate), libobs/obs-source-push-to-enable.c.h (the push-to-mute and push-to-talk enable setters), libobs/obs-source-render-route.c.h (the source and filter render routing), libobs/obs-source-set-name.c.h (the source rename), libobs/obs-source-size.c.h (the size query routing), libobs/obs-source-transition-access.c.h (the transition getters and manual controls; C shims in obs-source-seam), libobs/obs-source-transition-clock.c.h (the transition clock and fit), libobs/obs-source-transition-load.c.h (the transition load, scale type and swap checks), libobs/obs-source-transition-restore.c.h (the transition load; C shim in obs-source-seam), libobs/obs-source-transition-render.c.h (the transition render and audio steps), libobs/obs-source-transition-sample-time.c.h (the transition's per-sample audio time), libobs/obs-source-transition-settings.c.h (the transition settings; C shims in obs-source-seam), libobs/obs-source-transition-size.c.h (the transition size, child matrices and tick; C shims in obs-source-seam), libobs/obs-source-transition-slots.c.h (the transition child slots and swap; C shims in obs-source-seam), libobs/obs-source-transition-start.c.h (the transition start checks and child handover), libobs/obs-source-transition-stop.c.h (the transition clock read and stop; C shims in obs-source-seam), libobs/obs-source-transition-switch.c.h (the transition start and set; C shims in obs-source-seam), libobs/obs-source-transition-video.c.h (the transition video render; C shims in obs-source-seam), the rest of libobs/obs-source-transition.c.h (the transition audio render, init and free; C shims in obs-source-seam), libobs/obs-source-video-tick.c.h (the per-frame video tick decisions) and libobs/obs-source-volume.c.h (the source volume snap and apply decisions), libobs/obs-source-volume-mul.c.h (the source volume multiply kernels)" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/rust/obs-source/src/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index 573ec8430f..7b4f652b94 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -46,6 +46,7 @@ pub mod source_filter_index; pub mod source_filter_relationship_getters; pub mod source_flags_mixers; pub mod source_frame_copy; +pub mod source_frame_copy_data; pub mod source_frame_init; pub mod source_get_weak; pub mod source_handler_getters; diff --git a/rust/obs-source/src/ffi/source_frame_copy_data.rs b/rust/obs-source/src/ffi/source_frame_copy_data.rs new file mode 100644 index 0000000000..e45e229b61 --- /dev/null +++ b/rust/obs-source/src/ffi/source_frame_copy_data.rs @@ -0,0 +1,169 @@ +//! C ABI for `libobs/obs-source-frame-copy-data.c.h`: +//! `obs_source_frame_copy()` (`EXPORT` in `obs.h`), which `cache_video()` +//! and the two preload paths of `obs-source.c.h` call too. +//! +//! [`obs_source_frame`] mirrors the public `struct obs_source_frame`. The +//! shim reads what `copy_frame_data()` reads (the source's metadata, colour +//! range, format and first four line sizes; the destination's height and +//! first four line sizes) and hands the writes to +//! [`frame_copy_data::copy_frame_data`] through [`Frames`]: each field is +//! written through the raw pointer, never through a reference to the whole +//! struct (another thread may touch `refs`), and each planned plane gets one +//! slice of the destination's plane and one of the source's, as long as +//! [`plane_extent`] says that copy reaches. `format`, `width`, `height`, +//! `data`, `linesize`, `refs` and `prev_frame` are never written. +//! +//! No intentional differences from C. + +use core::ffi::{c_int, c_long}; +use core::slice; + +use crate::frame_copy::{PLANES, PlaneCopy}; +use crate::frame_copy_data::{ + self, ColorRange, Destination, Frames, Metadata, Source, plane_extent, +}; + +/// `MAX_AV_PLANES` (`media-io/media-io-defs.h`). +pub const MAX_AV_PLANES: usize = 8; + +/// `struct obs_source_frame` (`obs.h`). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +#[allow(non_camel_case_types)] +pub struct obs_source_frame { + pub data: [*mut u8; MAX_AV_PLANES], + pub linesize: [u32; MAX_AV_PLANES], + pub width: u32, + pub height: u32, + pub timestamp: u64, + /// `enum video_format`, an `int`. + pub format: c_int, + pub color_matrix: [f32; 16], + pub full_range: bool, + pub max_luminance: u16, + pub color_range_min: [f32; 3], + pub color_range_max: [f32; 3], + pub flip: bool, + pub flags: u8, + /// `enum video_trc`. + pub trc: u8, + /// `volatile long`. + pub refs: c_long, + pub prev_frame: bool, +} + +fn bits(floats: [f32; N]) -> [u32; N] { + floats.map(f32::to_bits) +} + +fn floats(bits: [u32; N]) -> [f32; N] { + bits.map(f32::from_bits) +} + +/// The first [`PLANES`] of a frame's line sizes. +fn lines(linesize: [u32; MAX_AV_PLANES]) -> [u32; PLANES] { + let mut lines = [0; PLANES]; + for (line, size) in lines.iter_mut().zip(linesize) { + *line = size; + } + lines +} + +/// The two frames, behind their raw pointers. +struct RawFrames { + dst: *mut obs_source_frame, + src: *const obs_source_frame, +} + +impl Frames for RawFrames { + fn write_metadata(&mut self, m: Metadata) { + let dst = self.dst; + // SAFETY: `obs_source_frame_copy`'s caller passes a valid, writable + // destination; each field is written in place, the C's order. + unsafe { + (*dst).flip = m.flip; + (*dst).flags = m.flags; + (*dst).trc = m.trc; + (*dst).full_range = m.full_range; + (*dst).max_luminance = m.max_luminance; + (*dst).timestamp = m.timestamp; + (*dst).color_matrix = floats(m.color_matrix); + } + } + + fn write_color_range(&mut self, range: ColorRange) { + let dst = self.dst; + // SAFETY: as in `write_metadata`. + unsafe { + (*dst).color_range_min = floats(range.min); + (*dst).color_range_max = floats(range.max); + } + } + + fn copy_plane(&mut self, plane: usize, copy: &PlaneCopy) { + let (dst_len, src_len) = plane_extent(copy); + if dst_len == 0 || src_len == 0 { + return; + } + // SAFETY: both frames are valid (the caller's contract); the data + // arrays are read by value. + let (to, from) = unsafe { ((*self.dst).data, (*self.src).data) }; + let (Some(&to), Some(&from)) = (to.get(plane), from.get(plane)) else { + return; + }; + // SAFETY: the caller's contract: each plane the plan copies holds + // the bytes the plan reaches in both frames, and the two frames' + // planes do not overlap (as `memcpy()` requires). + let (to, from) = unsafe { + ( + slice::from_raw_parts_mut(to, dst_len), + slice::from_raw_parts(from, src_len), + ) + }; + frame_copy_data::copy_plane(to, from, copy); + } +} + +/// `void obs_source_frame_copy(struct obs_source_frame *dst, const struct +/// obs_source_frame *src)`: `copy_frame_data(dst, src)`. +/// +/// # Safety +/// +/// `dst` and `src` point to valid frames, `dst` writable. For each plane +/// the copy plan of the source's format and the destination's height and +/// line sizes copies, the planes hold the bytes it reaches, and the two +/// frames' planes do not overlap: what the C's `memcpy()`s need. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_frame_copy( + dst: *mut obs_source_frame, + src: *const obs_source_frame, +) { + // SAFETY: the caller passes two valid frames; each field is read by + // value through the pointer, with no reference to the whole struct. + let (source, destination) = unsafe { + ( + Source { + metadata: Metadata { + flip: (*src).flip, + flags: (*src).flags, + trc: (*src).trc, + full_range: (*src).full_range, + max_luminance: (*src).max_luminance, + timestamp: (*src).timestamp, + color_matrix: bits((*src).color_matrix), + }, + color_range: ColorRange { + min: bits((*src).color_range_min), + max: bits((*src).color_range_max), + }, + format: (*src).format, + linesize: lines((*src).linesize), + }, + Destination { + height: (*dst).height, + linesize: lines((*dst).linesize), + }, + ) + }; + frame_copy_data::copy_frame_data(&mut RawFrames { dst, src }, &source, destination); +} diff --git a/rust/obs-source/src/frame_copy_data.rs b/rust/obs-source/src/frame_copy_data.rs index 3a4184a607..07e60dc900 100644 --- a/rust/obs-source/src/frame_copy_data.rs +++ b/rust/obs-source/src/frame_copy_data.rs @@ -91,10 +91,38 @@ pub trait Frames { /// for the destination's range (the source's, just written), height and /// line sizes: the colour range when the plan says so, then each planned /// plane in order. -#[expect(clippy::todo)] pub fn copy_frame_data(frames: &mut impl Frames, src: &Source, dst: Destination) { - let _ = (frames, src, dst, frame_copy::copy_plan); - todo!("#5714") + frames.write_metadata(src.metadata); + let plan = frame_copy::copy_plan( + src.format, + src.metadata.full_range, + dst.height, + src.linesize, + dst.linesize, + ); + if plan.color_range { + frames.write_color_range(src.color_range); + } + for (plane, copy) in plan.planes.iter().take(plan.count).enumerate() { + frames.copy_plane(plane, copy); + } +} + +/// `size_t` of a `u32`. +#[allow(clippy::as_conversions)] +const fn size(value: u32) -> usize { + value as usize +} + +/// The greatest `y * stride` (in `u32`, wrapping) over the rows `0..rows`. +fn last_row(rows: u32, stride: u32) -> u32 { + let Some(last) = rows.checked_sub(1) else { + return 0; + }; + match last.checked_mul(stride) { + Some(offset) => offset, + None => (0..rows).map(|y| y.wrapping_mul(stride)).max().unwrap_or(0), + } } /// The bytes of the destination and of the source plane one copy touches, @@ -102,10 +130,15 @@ pub fn copy_frame_data(frames: &mut impl Frames, src: &Source, dst: Destination) /// else up to the end of the row that starts furthest in (in `u32`, as the /// C computes each row's start); `(0, 0)` when nothing is copied. #[must_use] -#[expect(clippy::todo)] pub fn plane_extent(copy: &PlaneCopy) -> (usize, usize) { - let _ = copy; - todo!("#5714") + if copy.whole { + return (copy.bytes, copy.bytes); + } + if copy.bytes == 0 || copy.rows == 0 { + return (0, 0); + } + let end = |stride| size(last_row(copy.rows, stride)).saturating_add(copy.bytes); + (end(copy.dst_stride), end(copy.src_stride)) } /// `copy_frame_data_plane()`: one copy of the plan's bytes when the line @@ -113,8 +146,24 @@ pub fn plane_extent(copy: &PlaneCopy) -> (usize, usize) { /// dst_stride` (each in `u32`), the plan's bytes each. `dst` and `src` start /// at the planes' starts and hold [`plane_extent`]'s bytes; a row outside /// them is not copied (the shim's slices always hold every row). -#[expect(clippy::todo)] pub fn copy_plane(dst: &mut [u8], src: &[u8], copy: &PlaneCopy) { - let _ = (dst, src, copy); - todo!("#5714") + if copy.whole { + if let (Some(to), Some(from)) = (dst.get_mut(..copy.bytes), src.get(..copy.bytes)) { + to.copy_from_slice(from); + } + return; + } + for y in 0..copy.rows { + let pos_src = size(y.wrapping_mul(copy.src_stride)); + let pos_dst = size(y.wrapping_mul(copy.dst_stride)); + let (Some(src_end), Some(dst_end)) = ( + pos_src.checked_add(copy.bytes), + pos_dst.checked_add(copy.bytes), + ) else { + continue; + }; + if let (Some(to), Some(from)) = (dst.get_mut(pos_dst..dst_end), src.get(pos_src..src_end)) { + to.copy_from_slice(from); + } + } } diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index d8bd072b33..fcc448be87 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -67,6 +67,9 @@ //! `libobs/obs-source-frame-copy.c.h`, the async frame copy plan and cache //! decisions of `copy_frame_data()`, `cache_video()`, `clean_cache()` and the //! `obs_source_output_video()` families; +//! `libobs/obs-source-frame-copy-data.c.h`, `obs_source_frame_copy()` and +//! the `copy_frame_data()` it runs (the metadata, the colour range and the +//! plane copies of the plan above); //! `libobs/obs-source-info-lookup.c.h`, the source type lookup of //! `get_source_info()` (the first registered type with the asked ID; a NULL //! ID finds nothing, an intentional difference); diff --git a/rust/obs-source/tests/source/frame_copy_data_parity.rs b/rust/obs-source/tests/source/frame_copy_data_parity.rs new file mode 100644 index 0000000000..6c72736518 --- /dev/null +++ b/rust/obs-source/tests/source/frame_copy_data_parity.rs @@ -0,0 +1,394 @@ +//! Tier 3: the Rust `obs_source_frame_copy()` against the original C +//! (`obs-c-oracle`, `oracle/source_frame_copy_data.c`: the unmodified +//! `libobs/obs-source-frame-copy-data.c.h` with `obs_source_frame_copy` +//! renamed). Both ask the same `obs_source_frame_copy_plan()`. +//! +//! Every case builds the same destination twice and one source, runs the C +//! on one destination and the Rust on the other, and compares every field +//! of the two destinations (the colour values as bits), every byte of their +//! planes and of a guard after each plane, and the source, which neither +//! may change. +//! +//! The frames are what libobs's callers pass: a source of any format that +//! has planes, laid out as `obs_source_frame_create()` lays it out, and a +//! destination of the same format, width and height whose line sizes are +//! the source's or differ per plane (longer or shorter, never 0), each of +//! its planes line size x rows. +//! +//! Runs: +//! - the layout of `struct obs_source_frame` against the C header; +//! - every format at seven sizes against the C test's five line-size +//! patterns and equal line sizes, both ranges; +//! - a proptest (512 cases) over the format, the size up to 48 x 24, each +//! plane's line size, every metadata field and the plane bytes. + +use core::ffi::c_long; +use std::mem::{align_of, offset_of, size_of}; + +use obs_media_io::video_frame::{linesizes, plane_heights}; +use obs_media_io::video_io::video_format_from_c; +use obs_source::ffi::source_frame_copy_data::{ + MAX_AV_PLANES, obs_source_frame, obs_source_frame_copy, +}; +use obs_source::frame_copy::{PLANES, video_format as F}; +use proptest::prelude::*; + +unsafe extern "C" { + fn oracle_obs_source_frame_copy(dst: *mut obs_source_frame, src: *const obs_source_frame); + fn oracle_source_frame_copy_data_layout(which: usize) -> usize; +} + +#[test] +fn layout_matches_c() { + let rust = [ + size_of::(), + align_of::(), + offset_of!(obs_source_frame, data), + offset_of!(obs_source_frame, linesize), + offset_of!(obs_source_frame, width), + offset_of!(obs_source_frame, height), + offset_of!(obs_source_frame, timestamp), + offset_of!(obs_source_frame, format), + offset_of!(obs_source_frame, color_matrix), + offset_of!(obs_source_frame, full_range), + offset_of!(obs_source_frame, max_luminance), + offset_of!(obs_source_frame, color_range_min), + offset_of!(obs_source_frame, color_range_max), + offset_of!(obs_source_frame, flip), + offset_of!(obs_source_frame, flags), + offset_of!(obs_source_frame, trc), + offset_of!(obs_source_frame, refs), + offset_of!(obs_source_frame, prev_frame), + size_of::(), + MAX_AV_PLANES, + ]; + for (i, &value) in rust.iter().enumerate() { + // SAFETY: a pure query of constants. + assert_eq!( + unsafe { oracle_source_frame_copy_data_layout(i) }, + value, + "entry {i}" + ); + } + // SAFETY: as above. + assert_eq!( + unsafe { oracle_source_frame_copy_data_layout(rust.len()) }, + usize::MAX + ); +} + +/// Every format that has planes. +const FORMATS: [i32; 25] = [ + F::I420, + F::NV12, + F::YVYU, + F::YUY2, + F::UYVY, + F::RGBA, + F::BGRA, + F::BGRX, + F::Y800, + F::I444, + F::BGR3, + F::I422, + F::I40A, + F::I42A, + F::YUVA, + F::AYUV, + F::I010, + F::P010, + F::I210, + F::I412, + F::YA2L, + F::P216, + F::P416, + F::V210, + F::R10L, +]; + +/// Bytes after each plane that no copy may touch. +const GUARD: usize = 32; + +/// The fields a frame carries besides its planes, as bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Fields { + flip: bool, + flags: u8, + trc: u8, + full_range: bool, + max_luminance: u16, + timestamp: u64, + color_matrix: [u32; 16], + color_range_min: [u32; 3], + color_range_max: [u32; 3], + refs: c_long, + prev_frame: bool, +} + +/// A frame and the buffers its planes point into. +struct Owned { + frame: obs_source_frame, + planes: Vec>, +} + +impl Owned { + fn new(format: i32, width: u32, height: u32, linesize: [u32; PLANES], fill: &mut Fill) -> Self { + let heights = plane_heights(video_format_from_c(format).unwrap(), height); + let mut planes: Vec> = (0..PLANES) + .filter(|&p| heights[p] != 0 && linesize[p] != 0) + .map(|p| { + let len = linesize[p] as usize * heights[p] as usize + GUARD; + (0..len).map(|_| fill.byte()).collect() + }) + .collect(); + let mut data = [core::ptr::null_mut(); MAX_AV_PLANES]; + let mut lines = [0; MAX_AV_PLANES]; + for (p, plane) in planes.iter_mut().enumerate() { + data[p] = plane.as_mut_ptr(); + lines[p] = linesize[p]; + } + let frame = obs_source_frame { + data, + linesize: lines, + width, + height, + timestamp: 0, + format, + color_matrix: [0.0; 16], + full_range: false, + max_luminance: 0, + color_range_min: [0.0; 3], + color_range_max: [0.0; 3], + flip: false, + flags: 0, + trc: 0, + refs: 0, + prev_frame: false, + }; + Self { frame, planes } + } + + fn set(&mut self, f: &Fields) { + let frame = &mut self.frame; + frame.flip = f.flip; + frame.flags = f.flags; + frame.trc = f.trc; + frame.full_range = f.full_range; + frame.max_luminance = f.max_luminance; + frame.timestamp = f.timestamp; + frame.color_matrix = f.color_matrix.map(f32::from_bits); + frame.color_range_min = f.color_range_min.map(f32::from_bits); + frame.color_range_max = f.color_range_max.map(f32::from_bits); + frame.refs = f.refs; + frame.prev_frame = f.prev_frame; + } + + fn fields(&self) -> Fields { + let frame = &self.frame; + Fields { + flip: frame.flip, + flags: frame.flags, + trc: frame.trc, + full_range: frame.full_range, + max_luminance: frame.max_luminance, + timestamp: frame.timestamp, + color_matrix: frame.color_matrix.map(f32::to_bits), + color_range_min: frame.color_range_min.map(f32::to_bits), + color_range_max: frame.color_range_max.map(f32::to_bits), + refs: frame.refs, + prev_frame: frame.prev_frame, + } + } + + /// Everything but the plane bytes: the fields, and the shape and data + /// pointers, which must still point at this frame's own planes. + fn check_shape(&self, format: i32, width: u32, height: u32) { + let frame = &self.frame; + assert_eq!( + (frame.format, frame.width, frame.height), + (format, width, height) + ); + for (p, plane) in self.planes.iter().enumerate() { + assert_eq!(frame.data[p], plane.as_ptr().cast_mut()); + } + assert!(frame.data[self.planes.len()..].iter().all(|d| d.is_null())); + } +} + +/// xorshift64: the plane bytes of a case from its seed. +struct Fill(u64); + +impl Fill { + fn byte(&mut self) -> u8 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 24) as u8 + } +} + +struct Case { + format: i32, + width: u32, + height: u32, + /// Added to each plane's source line size for the destination's (at + /// least 1). + delta: [i64; PLANES], + src: Fields, + dst: Fields, + seed: u64, +} + +fn check(case: &Case) { + let (format, width, height) = (case.format, case.width, case.height); + let src_lines = linesizes(video_format_from_c(format).unwrap(), width); + let mut linesize = [0; PLANES]; + let mut dst_lines = [0; PLANES]; + for p in 0..PLANES { + linesize[p] = src_lines[p]; + if src_lines[p] != 0 { + dst_lines[p] = (i64::from(src_lines[p]) + case.delta[p]).max(1) as u32; + } + } + let mut fill = Fill(case.seed | 1); + let mut src = Owned::new(format, width, height, linesize, &mut fill); + src.set(&case.src); + let mut c = Owned::new(format, width, height, dst_lines, &mut fill); + c.set(&case.dst); + let mut rust = Owned::new(format, width, height, dst_lines, &mut fill); + rust.set(&case.dst); + rust.planes.clone_from(&c.planes); + for (p, plane) in rust.planes.iter_mut().enumerate() { + rust.frame.data[p] = plane.as_mut_ptr(); + } + let source_before = (src.fields(), src.planes.clone()); + + // SAFETY: both destinations and the source are valid frames of one + // format, width and height; each plane holds line size x rows bytes of + // its own buffer, so every planned copy fits, and no buffers overlap. + unsafe { + oracle_obs_source_frame_copy(&mut c.frame, &src.frame); + obs_source_frame_copy(&mut rust.frame, &src.frame); + } + + let what = format!( + "format {format} {width}x{height} delta {:?} src full {}", + case.delta, case.src.full_range + ); + assert_eq!(rust.fields(), c.fields(), "{what}"); + assert_eq!(rust.frame.linesize, c.frame.linesize, "{what}"); + assert!(rust.planes == c.planes, "{what}: planes differ"); + c.check_shape(format, width, height); + rust.check_shape(format, width, height); + assert_eq!((src.fields(), src.planes.clone()), source_before, "{what}"); + src.check_shape(format, width, height); +} + +fn fields(seed: u32, full_range: bool) -> Fields { + let bits = |i: u32| { + seed.wrapping_mul(0x9e37_79b9) + .wrapping_add(i.wrapping_mul(0x7f4a_7c15)) + }; + Fields { + flip: seed & 1 == 1, + flags: seed as u8, + trc: (seed >> 8) as u8, + full_range, + max_luminance: (seed >> 16) as u16, + timestamp: u64::from(seed) << 29 | 0x1f, + color_matrix: core::array::from_fn(|i| bits(i as u32)), + color_range_min: [0x7fc0_0001, bits(20), 0x8000_0000], + color_range_max: [0x7f80_0001, bits(21), 0xffff_ffff], + refs: c_long::from(seed as u16), + prev_frame: seed & 2 == 2, + } +} + +#[test] +fn every_format_size_and_line_size_pattern_matches_c() { + const SIZES: [(u32, u32); 7] = [(1, 1), (2, 2), (5, 2), (13, 7), (32, 16), (47, 3), (6, 9)]; + const DELTAS: [[i64; PLANES]; 6] = [ + [0, 0, 0, 0], + [16, 16, 16, 16], + [-1, -1, -1, -1], + [5, -1, 3, -1], + [-3, 0, 7, 0], + [0, 9, -1, 2], + ]; + let mut seed = 1u32; + for format in FORMATS { + for (width, height) in SIZES { + for delta in DELTAS { + for full in [false, true] { + seed = seed.wrapping_add(1); + check(&Case { + format, + width, + height, + delta, + src: fields(seed, full), + dst: fields(!seed, !full), + seed: u64::from(seed), + }); + } + } + } + } +} + +fn any_fields() -> impl Strategy { + ( + ( + any::(), + any::(), + any::(), + any::(), + any::(), + any::(), + ), + prop::array::uniform16(any::()), + prop::array::uniform3(any::()), + prop::array::uniform3(any::()), + any::(), + any::(), + ) + .prop_map( + |( + (flip, flags, trc, full_range, max_luminance, timestamp), + color_matrix, + color_range_min, + color_range_max, + refs, + prev_frame, + )| Fields { + flip, + flags, + trc, + full_range, + max_luminance, + timestamp, + color_matrix, + color_range_min, + color_range_max, + refs, + prev_frame, + }, + ) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(obs_c_oracle::parity::cases(512)))] + + #[test] + fn any_same_shape_frames_match_c( + format in prop::sample::select(FORMATS.to_vec()), + width in 1u32..=48, + height in 1u32..=24, + delta in prop::array::uniform4(prop_oneof![Just(0i64), -64i64..=64]), + src in any_fields(), + dst in any_fields(), + seed in any::(), + ) { + check(&Case { format, width, height, delta, src, dst, seed }); + } +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 89d89ef96f..185590c1b1 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -86,6 +86,7 @@ mod flags_mixers; mod flags_mixers_parity; mod frame_copy; mod frame_copy_data; +mod frame_copy_data_parity; mod frame_copy_parity; mod frame_init; mod frame_init_parity;