From 5aa4f79efa1b44fb7a2598e99d9e678e9f3b9344 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sun, 29 Nov 2026 00:58:48 -0500 Subject: [PATCH 1/3] libobs: extract obs_source_audio_render and its steps verbatim (Refs #5923) Move obs_source_audio_render() and its three static steps, custom_audio_render(), audio_submix() and process_audio_source_tick(), out of obs-source.c.h into obs-source-audio-render-steps.c.h (live group libobs.core-source), unchanged. obs-internal.h already declares obs_source_audio_render() without EXPORT for obs-audio.c and the Rust audio_callback(). The volume-apply registration test now counts the two obs_source_apply_audio_volume() calls in the new file. No behavior change. The new test_source_audio_render_entry characterizes them through the real libobs, one tick of the audio mix at a time: three children (a custom render, an audio_mix source that takes the tick, and a submix source) under a composite parent on output channel 0. The parent primes the case's child with a sentinel in every buffer and its mixers; in the next tick the child's callback records what it was handed and sets the fields and input, and the parent copies what libobs left. 23 cases: the clears before and after a custom render, its failed and timestamp-less results, the volume over mixer masks and mute; the tick's pending on no timestamp, short and no input, the peek, copy and clear of each mix, the main mix's clear and the volume; a submix source's mix 1 from bit 0 and no volume; and a successful audio_mix block handed to obs_source_output_audio(). Co-Authored-By: Claude Opus 5.5 --- libobs/build/libobs.core-source+.h.c | 1 + libobs/obs-source-audio-render-steps.c.h | 162 ++++ libobs/obs-source.c.h | 155 ---- ...e_audio_volume_apply_swap_is_registered.rs | 7 +- test/cmocka/build/test-graph.json | 45 + test/cmocka/test_source_audio_render_entry.c | 841 ++++++++++++++++++ .../test_source_audio_render_entry.cmake | 4 + 7 files changed, 1058 insertions(+), 157 deletions(-) create mode 100644 libobs/obs-source-audio-render-steps.c.h create mode 100644 test/cmocka/test_source_audio_render_entry.c create mode 100644 test/cmocka/tests.d/test_source_audio_render_entry.cmake diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index 08185b1aef..9e0ee632ed 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -65,6 +65,7 @@ #include "libobs/obs-source-audio-mixers-fields.c.h" #include "libobs/obs-source-audio-output-seam.c.h" #include "libobs/obs-source-audio-pending-speaker-layout-fields.c.h" +#include "libobs/obs-source-audio-render-steps.c.h" #include "libobs/obs-source-audio-settings-seam.c.h" #include "libobs/obs-source-audio-volume-apply-fields.c.h" #include "libobs/obs-source-base-size-fields.c.h" diff --git a/libobs/obs-source-audio-render-steps.c.h b/libobs/obs-source-audio-render-steps.c.h new file mode 100644 index 0000000000..a8bcfbcea5 --- /dev/null +++ b/libobs/obs-source-audio-render-steps.c.h @@ -0,0 +1,162 @@ +#include "libobs/build/libobs.pch.h" + +/* obs_source_audio_render() and its three steps, custom_audio_render(), + * audio_submix() and process_audio_source_tick(), what the audio mix thread + * calls for each source on every tick, moved verbatim out of obs-source.c.h + * (#5923). obs_source_audio_render() is declared in obs-internal.h (hidden, + * no EXPORT) for obs-audio.c and the Rust audio_callback(). */ + +/* Which mixes are cleared before and after the callback, and its timestamp + * and pending result, go through obs-source-audio-render.c, on values. The + * buffers, the callback, audio_buf_mutex, the memsets and + * obs_source_apply_audio_volume() stay here, in the same order; source->audio_mixers is + * read once per mix where it was before, source->audio_ts only after a + * successful callback. */ +static void custom_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate) +{ + struct obs_source_audio_mix audio_data; + bool success; + uint64_t ts; + + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < channels; ch++) { + audio_data.output[mix].data[ch] = source->audio_output_buf[mix][ch]; + } + + if (obs_source_audio_render_custom_clear_before(source->audio_mixers, mixers, mix)) { + memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + } + } + + success = source->info.audio_render(source->context.data, &ts, &audio_data, mixers, channels, sample_rate); + /* The callback may render other sources or submit capture audio. */ + pthread_mutex_lock(&source->audio_buf_mutex); + /* ts is passed but not used when the callback failed. */ + source->audio_ts = obs_source_audio_render_custom_ts(success, ts); + source->audio_pending = obs_source_audio_render_custom_pending(success); + + if (obs_source_audio_render_custom_pending(success) || + obs_source_audio_render_custom_unmixed(source->audio_ts, mixers)) { + pthread_mutex_unlock(&source->audio_buf_mutex); + return; + } + + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + if (!obs_source_audio_render_custom_in_tick(mixers, mix)) + continue; + + if (obs_source_audio_render_custom_clear_after(source->audio_mixers, mix)) { + memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + } + } + + obs_source_apply_audio_volume(source, mixers, channels, sample_rate); + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +static void audio_submix(obs_source_t *source, size_t channels, size_t sample_rate) +{ + struct audio_output_data audio_data; + struct obs_source_audio audio = {0}; + bool success; + uint64_t ts; + + for (size_t ch = 0; ch < channels; ch++) { + audio_data.data[ch] = source->audio_mix_buf[ch]; + } + + memset(source->audio_mix_buf[0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + + success = source->info.audio_mix(source->context.data, &ts, &audio_data, channels, sample_rate); + + if (!success) + return; + + for (size_t i = 0; i < channels; i++) + audio.data[i] = (const uint8_t *)audio_data.data[i]; + + audio.samples_per_sec = (uint32_t)sample_rate; + audio.frames = AUDIO_OUTPUT_FRAMES; + audio.format = AUDIO_FORMAT_FLOAT_PLANAR; + audio.speakers = (enum speaker_layout)channels; + audio.timestamp = ts; + + obs_source_output_audio(source, &audio); +} + +/* The pending check and whether each mix copies mix 0 or is cleared go + * through obs-source-audio-render.c, on values. audio_buf_mutex, + * deque_peek_front(), the memsets, the memcpys and obs_source_apply_audio_volume() stay + * here, in the same order; the input size is read only with a timestamp, and + * source->audio_mixers once per mix where it was before. */ +static inline void process_audio_source_tick(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, + size_t size) +{ + bool audio_submix = !!(source->info.output_flags & OBS_SOURCE_SUBMIX); + + pthread_mutex_lock(&source->audio_buf_mutex); + + if (obs_source_audio_render_tick_unset(source->audio_ts) || + obs_source_audio_render_tick_short(source->audio_input_buf[0].size, size)) { + source->audio_pending = true; + pthread_mutex_unlock(&source->audio_buf_mutex); + return; + } + + for (size_t ch = 0; ch < channels; ch++) + deque_peek_front(&source->audio_input_buf[ch], source->audio_output_buf[0][ch], size); + + for (size_t mix = 1; mix < MAX_AUDIO_MIXES; mix++) { + if (obs_source_audio_render_tick_stop(audio_submix, mix)) + break; + + if (!obs_source_audio_render_tick_copy(audio_submix, source->audio_mixers, mixers, mix)) { + memset(source->audio_output_buf[mix][0], 0, size * channels); + continue; + } + + for (size_t ch = 0; ch < channels; ch++) + memcpy(source->audio_output_buf[mix][ch], source->audio_output_buf[0][ch], size); + } + + if (!obs_source_audio_render_tick_volume(audio_submix)) { + source->audio_pending = false; + pthread_mutex_unlock(&source->audio_buf_mutex); + return; + } + + if (obs_source_audio_render_tick_clear_main(source->audio_mixers, mixers)) + memset(source->audio_output_buf[0][0], 0, size * channels); + + obs_source_apply_audio_volume(source, mixers, channels, sample_rate); + source->audio_pending = false; + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +/* The route goes through obs-source-audio-render.c, on values. Each field is + * read only where the checks before reached it, as before: the audio thread + * can render a source whose context.data is not set yet (432017b2c). */ +void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size) +{ + const bool has_buffer = source->audio_output_buf[0][0] != NULL; + const bool custom = has_buffer && source->info.audio_render != NULL; + const bool has_data = custom && source->context.data != NULL; + + switch (obs_source_audio_render_route(has_buffer, custom, has_data)) { + case OBS_SOURCE_AUDIO_RENDER_PENDING: + source->audio_pending = true; + return; + case OBS_SOURCE_AUDIO_RENDER_CUSTOM: + custom_audio_render(source, mixers, channels, sample_rate); + return; + case OBS_SOURCE_AUDIO_RENDER_TICK: + default: + break; + } + + if (source->info.audio_mix) { + audio_submix(source, channels, sample_rate); + } + + process_audio_source_tick(source, mixers, channels, sample_rate, size); +} diff --git a/libobs/obs-source.c.h b/libobs/obs-source.c.h index a435f33707..3bbcf698c5 100644 --- a/libobs/obs-source.c.h +++ b/libobs/obs-source.c.h @@ -1829,161 +1829,6 @@ obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, const char *na return filter; } -/* Which mixes are cleared before and after the callback, and its timestamp - * and pending result, go through obs-source-audio-render.c, on values. The - * buffers, the callback, audio_buf_mutex, the memsets and - * obs_source_apply_audio_volume() stay here, in the same order; source->audio_mixers is - * read once per mix where it was before, source->audio_ts only after a - * successful callback. */ -static void custom_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate) -{ - struct obs_source_audio_mix audio_data; - bool success; - uint64_t ts; - - for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { - for (size_t ch = 0; ch < channels; ch++) { - audio_data.output[mix].data[ch] = source->audio_output_buf[mix][ch]; - } - - if (obs_source_audio_render_custom_clear_before(source->audio_mixers, mixers, mix)) { - memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); - } - } - - success = source->info.audio_render(source->context.data, &ts, &audio_data, mixers, channels, sample_rate); - /* The callback may render other sources or submit capture audio. */ - pthread_mutex_lock(&source->audio_buf_mutex); - /* ts is passed but not used when the callback failed. */ - source->audio_ts = obs_source_audio_render_custom_ts(success, ts); - source->audio_pending = obs_source_audio_render_custom_pending(success); - - if (obs_source_audio_render_custom_pending(success) || - obs_source_audio_render_custom_unmixed(source->audio_ts, mixers)) { - pthread_mutex_unlock(&source->audio_buf_mutex); - return; - } - - for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { - if (!obs_source_audio_render_custom_in_tick(mixers, mix)) - continue; - - if (obs_source_audio_render_custom_clear_after(source->audio_mixers, mix)) { - memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); - } - } - - obs_source_apply_audio_volume(source, mixers, channels, sample_rate); - pthread_mutex_unlock(&source->audio_buf_mutex); -} - -static void audio_submix(obs_source_t *source, size_t channels, size_t sample_rate) -{ - struct audio_output_data audio_data; - struct obs_source_audio audio = {0}; - bool success; - uint64_t ts; - - for (size_t ch = 0; ch < channels; ch++) { - audio_data.data[ch] = source->audio_mix_buf[ch]; - } - - memset(source->audio_mix_buf[0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); - - success = source->info.audio_mix(source->context.data, &ts, &audio_data, channels, sample_rate); - - if (!success) - return; - - for (size_t i = 0; i < channels; i++) - audio.data[i] = (const uint8_t *)audio_data.data[i]; - - audio.samples_per_sec = (uint32_t)sample_rate; - audio.frames = AUDIO_OUTPUT_FRAMES; - audio.format = AUDIO_FORMAT_FLOAT_PLANAR; - audio.speakers = (enum speaker_layout)channels; - audio.timestamp = ts; - - obs_source_output_audio(source, &audio); -} - -/* The pending check and whether each mix copies mix 0 or is cleared go - * through obs-source-audio-render.c, on values. audio_buf_mutex, - * deque_peek_front(), the memsets, the memcpys and obs_source_apply_audio_volume() stay - * here, in the same order; the input size is read only with a timestamp, and - * source->audio_mixers once per mix where it was before. */ -static inline void process_audio_source_tick(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, - size_t size) -{ - bool audio_submix = !!(source->info.output_flags & OBS_SOURCE_SUBMIX); - - pthread_mutex_lock(&source->audio_buf_mutex); - - if (obs_source_audio_render_tick_unset(source->audio_ts) || - obs_source_audio_render_tick_short(source->audio_input_buf[0].size, size)) { - source->audio_pending = true; - pthread_mutex_unlock(&source->audio_buf_mutex); - return; - } - - for (size_t ch = 0; ch < channels; ch++) - deque_peek_front(&source->audio_input_buf[ch], source->audio_output_buf[0][ch], size); - - for (size_t mix = 1; mix < MAX_AUDIO_MIXES; mix++) { - if (obs_source_audio_render_tick_stop(audio_submix, mix)) - break; - - if (!obs_source_audio_render_tick_copy(audio_submix, source->audio_mixers, mixers, mix)) { - memset(source->audio_output_buf[mix][0], 0, size * channels); - continue; - } - - for (size_t ch = 0; ch < channels; ch++) - memcpy(source->audio_output_buf[mix][ch], source->audio_output_buf[0][ch], size); - } - - if (!obs_source_audio_render_tick_volume(audio_submix)) { - source->audio_pending = false; - pthread_mutex_unlock(&source->audio_buf_mutex); - return; - } - - if (obs_source_audio_render_tick_clear_main(source->audio_mixers, mixers)) - memset(source->audio_output_buf[0][0], 0, size * channels); - - obs_source_apply_audio_volume(source, mixers, channels, sample_rate); - source->audio_pending = false; - pthread_mutex_unlock(&source->audio_buf_mutex); -} - -/* The route goes through obs-source-audio-render.c, on values. Each field is - * read only where the checks before reached it, as before: the audio thread - * can render a source whose context.data is not set yet (432017b2c). */ -void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size) -{ - const bool has_buffer = source->audio_output_buf[0][0] != NULL; - const bool custom = has_buffer && source->info.audio_render != NULL; - const bool has_data = custom && source->context.data != NULL; - - switch (obs_source_audio_render_route(has_buffer, custom, has_data)) { - case OBS_SOURCE_AUDIO_RENDER_PENDING: - source->audio_pending = true; - return; - case OBS_SOURCE_AUDIO_RENDER_CUSTOM: - custom_audio_render(source, mixers, channels, sample_rate); - return; - case OBS_SOURCE_AUDIO_RENDER_TICK: - default: - break; - } - - if (source->info.audio_mix) { - audio_submix(source, channels, sample_rate); - } - - process_audio_source_tick(source, mixers, channels, sample_rate, size); -} - /* hidden/undocumented export to allow source type redefinition for scripts */ EXPORT void obs_enable_source_type(const char *name, bool enable); diff --git a/rust/obs-build/tests/native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs index bd99b5ce27..5091cc3176 100644 --- a/rust/obs-build/tests/native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs +++ b/rust/obs-build/tests/native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs @@ -42,10 +42,13 @@ fn canonical_source_audio_volume_apply_swap_is_registered() { let hybrid = fs::read_to_string(root.join("libobs/build/libobs.core-source+.h.c")).unwrap(); assert!(!hybrid.contains("#include \"libobs/obs-source-audio-volume-apply.c.h\"")); assert!(hybrid.contains("#include \"libobs/obs-source-audio-volume-apply-fields.c.h\"")); - // obs-source.c.h keeps the two callers and no copy of the steps. + // obs-source.c.h keeps no copy of the steps. The two callers' original + // C moved to obs-source-audio-render-steps.c.h (#5923). let source = fs::read_to_string(root.join("libobs/obs-source.c.h")).unwrap(); + let callers = + fs::read_to_string(root.join("libobs/obs-source-audio-render-steps.c.h")).unwrap(); assert_eq!( - source + callers .matches("obs_source_apply_audio_volume(source, mixers, channels, sample_rate);") .count(), 2 diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 547d72d40e..40e4b88bb2 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -17461,6 +17461,34 @@ ], "requires": "OS_LINUX" }, + "test_source_audio_render_entry": { + "sources": [ + "test/cmocka/test_source_audio_render_entry.c" + ], + "libraries": [ + "OBS::libobs", + "OBS::caption", + { + "name": "m", + "requires": { + "not": "MSVC" + } + }, + "OBS::native-test-cmocka" + ], + "requires": { + "all": [ + "OS_LINUX", + "HAVE_OBS_OPENGL" + ] + }, + "artifact_definitions": { + "GRAPHICS_MODULE_PATH": "OBS::libobs-opengl" + }, + "watch_inputs": [ + "libobs/data" + ] + }, "test_source_audio_render_steps": { "sources": [ "test/cmocka/test_source_audio_render_steps.c", @@ -30423,6 +30451,23 @@ "${target}" ] }, + "test_source_audio_render_entry": { + "target": "test_source_audio_render_entry", + "command": [ + "${target}" + ], + "suite": "graphics", + "working_directory": "${runtime}", + "timeout_seconds": 120, + "optional_prefixes": [ + [ + "xvfb-run", + "-a", + "-s", + "-screen 0 1280x1024x24 -noreset" + ] + ] + }, "test_source_audio_render_steps": { "target": "test_source_audio_render_steps", "command": [ diff --git a/test/cmocka/test_source_audio_render_entry.c b/test/cmocka/test_source_audio_render_entry.c new file mode 100644 index 0000000000..2c932c1453 --- /dev/null +++ b/test/cmocka/test_source_audio_render_entry.c @@ -0,0 +1,841 @@ +/* Characterize obs_source_audio_render() (#5923) and its three steps, + * custom_audio_render(), audio_submix() and process_audio_source_tick(), + * through the real libobs (hybrid and the C reference): what the audio mix + * thread does for each source on every tick. + * + * - A source with an audio_render callback (a custom render): the mixes in + * both its audio_mixers and the tick's mixers are cleared before the + * callback, which gets the output buffers; a failed callback leaves the + * source pending with audio_ts 0, a callback with no timestamp stops there, + * and otherwise a tick mix the source is not on is cleared after it and + * the volume is applied. + * - A source with an audio_mix callback: its mix buffer is cleared and the + * callback runs; when it succeeds, the block goes to + * obs_source_output_audio() (seen here through an audio capture callback). + * Then the tick below runs. + * - Every other source (the tick): pending with no timestamp or less input + * than the tick; otherwise the input is peeked into mix 0, mixes 1 to 5 + * copy it when in both masks and are cleared otherwise, mix 0 is cleared + * when not in both masks, and the volume is applied. A submix source + * (OBS_SOURCE_SUBMIX) fills mix 1 from bit 0 of its mixers and stops + * there, without the volume. + * + * The test sees one tick at a time. Three children (a custom render, an + * audio_mix source without OBS_SOURCE_SUBMIX, which takes the tick, and a + * submix source) sit under a composite parent on output channel 0, so the + * mix thread renders them, then the parent, in each tick. When a case is + * armed, the parent's callback first writes a sentinel to every buffer of + * the case's child and sets its audio_mixers and audio_pending; in the next + * tick the child's callback records what it was handed and sets the case's + * fields and input, and the parent's callback copies what libobs left. The + * tick's mixers are the mixes with raw audio callbacks: 0, 2 and 4. The + * timestamps are far ahead of the clock, so nothing else in the tick + * touches the children before the parent looks. + * + * Mixing needs core video, so the cases run (under xvfb-run) on Linux and + * skip without a display. */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#define CUSTOM_ID "test_source_audio_render_entry_custom" +#define TICK_ID "test_source_audio_render_entry_tick" +#define SUBMIX_ID "test_source_audio_render_entry_submix" +#define PARENT_ID "test_source_audio_render_entry_parent" + +#define W 64 +#define H 64 +#define RATE 48000 +#define CHANNELS 2 +/* channels looked at: one past the tick's, which nothing but a clear of + * every channel touches */ +#define SEEN 3 +#define FRAMES AUDIO_OUTPUT_FRAMES +/* far ahead of the clock */ +#define TS (1ULL << 62) +#define TICK_MIXERS ((1u << 0) | (1u << 2) | (1u << 4)) +#define ALL_MIXES 0x3fu +#define SENTINEL (-7.0f) +#define WAIT_MS 10000 + +static bool obs_up; + +static void quiet_log(int level, const char *format, va_list args, void *param) +{ + (void)param; + if (level > LOG_WARNING) + return; + vfprintf(stderr, format, args); + fputc('\n', stderr); +} + +/* ------------------------------------------------------------------------ */ +/* the cases */ + +enum kind { CUSTOM, TICK, SUBMIX }; + +struct rcase { + const char *what; + enum kind kind; + uint32_t audio_mixers; + float volume; + bool muted; + /* the callback's result and timestamp (audio_ts for the tick) */ + bool success; + uint64_t ts; + /* frames of input queued for the tick */ + size_t input_frames; + /* after */ + bool pending; +}; + +static struct rcase cases[] = { + /* custom render */ + {.what = "custom: failed callback is pending", + .kind = CUSTOM, + .audio_mixers = ALL_MIXES, + .volume = 0.5f, + .success = false, + .ts = TS, + .pending = true}, + {.what = "custom: failed callback on no mix", .kind = CUSTOM, .volume = 1.0f, .ts = TS, .pending = true}, + {.what = "custom: no timestamp stops after the callback", + .kind = CUSTOM, + .audio_mixers = 0x01u, + .volume = 0.5f, + .success = true, + .ts = 0}, + {.what = "custom: tick mixes off the source are cleared after", + .kind = CUSTOM, + .audio_mixers = 0x01u, + .volume = 1.0f, + .success = true, + .ts = TS}, + {.what = "custom: volume 0.5 on every mix", + .kind = CUSTOM, + .audio_mixers = ALL_MIXES, + .volume = 0.5f, + .success = true, + .ts = TS}, + {.what = "custom: volume 0.5 on mixes 2 and 4", + .kind = CUSTOM, + .audio_mixers = 0x14u, + .volume = 0.5f, + .success = true, + .ts = TS}, + {.what = "custom: muted clears every mix", + .kind = CUSTOM, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .muted = true, + .success = true, + .ts = TS}, + {.what = "custom: on no mix", .kind = CUSTOM, .volume = 2.0f, .success = true, .ts = TS}, + /* the tick, after an audio_mix callback that fails */ + {.what = "tick: no timestamp is pending", + .kind = TICK, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = 0, + .input_frames = FRAMES, + .pending = true}, + {.what = "tick: short input is pending", + .kind = TICK, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = TS, + .input_frames = FRAMES - 1, + .pending = true}, + {.what = "tick: no input is pending", + .kind = TICK, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = TS, + .input_frames = 0, + .pending = true}, + {.what = "tick: a tick of input on every mix", + .kind = TICK, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = TS, + .input_frames = FRAMES}, + {.what = "tick: two ticks of input on mixes 0 and 1", + .kind = TICK, + .audio_mixers = 0x03u, + .volume = 1.0f, + .ts = TS, + .input_frames = 2 * FRAMES}, + {.what = "tick: mixes 2 and 4 clear mix 0", + .kind = TICK, + .audio_mixers = 0x14u, + .volume = 1.0f, + .ts = TS, + .input_frames = FRAMES}, + {.what = "tick: volume 0.5", + .kind = TICK, + .audio_mixers = ALL_MIXES, + .volume = 0.5f, + .ts = TS, + .input_frames = FRAMES}, + {.what = "tick: muted clears every mix", + .kind = TICK, + .audio_mixers = 0x01u, + .volume = 1.0f, + .muted = true, + .ts = TS, + .input_frames = FRAMES}, + {.what = "tick: on no mix", .kind = TICK, .volume = 0.5f, .ts = TS, .input_frames = FRAMES}, + /* a submix source */ + {.what = "submix: no timestamp is pending", + .kind = SUBMIX, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = 0, + .input_frames = FRAMES, + .pending = true}, + {.what = "submix: short input is pending", + .kind = SUBMIX, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .ts = TS, + .input_frames = FRAMES - 1, + .pending = true}, + {.what = "submix: mix 1 copies, no volume", + .kind = SUBMIX, + .audio_mixers = ALL_MIXES, + .volume = 0.5f, + .ts = TS, + .input_frames = FRAMES}, + {.what = "submix: off mix 0 clears mix 1", + .kind = SUBMIX, + .audio_mixers = 0x02u, + .volume = 1.0f, + .ts = TS, + .input_frames = FRAMES}, + {.what = "submix: on no mix keeps mix 0", + .kind = SUBMIX, + .volume = 1.0f, + .muted = true, + .ts = TS, + .input_frames = 2 * FRAMES}, + {.what = "submix: a successful callback outputs its block", + .kind = SUBMIX, + .audio_mixers = ALL_MIXES, + .volume = 1.0f, + .success = true, + .ts = TS, + .input_frames = 0}, +}; + +#define NUM_CASES (sizeof(cases) / sizeof(cases[0])) + +static bool on(uint32_t mask, size_t mix) +{ + return (mask & (1u << mix)) != 0; +} + +/* What a custom render's callback writes. */ +static float base(size_t mix, size_t ch) +{ + return (float)(1 + 2 * mix + ch); +} + +/* The queued input, and what an audio_mix callback outputs. */ +static float ramp(size_t ch, size_t frame) +{ + return (float)(100 + 10000 * ch + frame); +} + +static float block(size_t ch, size_t frame) +{ + return (float)(-50 - 1000 * (int)ch - (int)frame); +} + +/* What a custom render's callback finds in a mix: cleared when in both + * masks. */ +static float custom_entry(const struct rcase *c, size_t mix, size_t ch) +{ + if (ch < CHANNELS && on(c->audio_mixers & TICK_MIXERS, mix)) + return 0.0f; + return SENTINEL; +} + +static float custom_after(const struct rcase *c, size_t mix, size_t ch) +{ + if (ch >= CHANNELS) + return c->success && c->ts && c->muted ? 0.0f : SENTINEL; + float v = base(mix, ch); + if (!c->success || !c->ts) + return v; + if (on(TICK_MIXERS, mix) && !on(c->audio_mixers, mix)) + v = 0.0f; + if (c->muted || c->volume == 0.0f) + return 0.0f; + if (c->volume != 1.0f && on(c->audio_mixers & TICK_MIXERS, mix)) + v *= c->volume; + return v; +} + +static float tick_after(const struct rcase *c, size_t mix, size_t ch, size_t frame) +{ + if (c->pending) + return SENTINEL; + if (ch >= CHANNELS) + return c->muted && c->kind == TICK ? 0.0f : SENTINEL; + + if (c->kind == SUBMIX) { + if (mix == 0) + return ramp(ch, frame); + if (mix == 1) + return on(c->audio_mixers, 0) ? ramp(ch, frame) : 0.0f; + return SENTINEL; + } + + bool both = on(c->audio_mixers & TICK_MIXERS, mix); + float v = both ? ramp(ch, frame) : 0.0f; + if (c->muted || c->volume == 0.0f) + return 0.0f; + if (c->volume != 1.0f && both) + v *= c->volume; + return v; +} + +/* ------------------------------------------------------------------------ */ +/* the tick */ + +enum state { IDLE, ARMED, PRIMED, RENDERED, DONE }; + +struct snapshot { + /* the callback */ + bool called; + bool buffers_ok; + uint32_t mixers; + size_t channels; + size_t sample_rate; + float entry[MAX_AUDIO_MIXES][SEEN]; + float mix_entry[SEEN]; + /* the capture */ + size_t captures; + uint32_t capture_frames; + float captured[CHANNELS][FRAMES]; + /* after */ + float buf[MAX_AUDIO_MIXES][SEEN][FRAMES]; + bool pending; + uint64_t audio_ts; + size_t input_size; +}; + +static struct { + pthread_mutex_t mutex; + enum state state; + const struct rcase *c; + struct snapshot snap; +} run; + +static obs_source_t *children[3]; +static obs_source_t *parent; + +/* The case armed for `kind` once primed, else NULL; marks it rendered. */ +static const struct rcase *take_case(enum kind kind) +{ + const struct rcase *c = NULL; + pthread_mutex_lock(&run.mutex); + if (run.state == PRIMED && run.c->kind == kind) { + c = run.c; + run.state = RENDERED; + } + pthread_mutex_unlock(&run.mutex); + return c; +} + +static const char *child_name(void *unused) +{ + (void)unused; + return "audio render entry child"; +} + +static void *child_create(obs_data_t *settings, obs_source_t *source) +{ + (void)settings; + return source; +} + +static void child_destroy(void *data) +{ + (void)data; +} + +static bool custom_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) +{ + obs_source_t *source = data; + const struct rcase *c = take_case(CUSTOM); + if (!c) + return false; + + struct snapshot *snap = &run.snap; + snap->called = true; + snap->mixers = mixers; + snap->channels = channels; + snap->sample_rate = sample_rate; + snap->buffers_ok = true; + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < channels; ch++) { + if (audio->output[mix].data[ch] != source->audio_output_buf[mix][ch]) + snap->buffers_ok = false; + } + for (size_t ch = 0; ch < SEEN; ch++) + snap->entry[mix][ch] = source->audio_output_buf[mix][ch][FRAMES - 1]; + } + + source->volume = c->volume; + source->muted = c->muted; + source->audio_mixers = c->audio_mixers; + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < channels && ch < CHANNELS; ch++) { + float *out = audio->output[mix].data[ch]; + for (size_t i = 0; i < FRAMES; i++) + out[i] = base(mix, ch); + } + } + *ts_out = c->ts; + return c->success; +} + +/* The fields and the input the tick reads. */ +static void set_up_tick(obs_source_t *source, const struct rcase *c) +{ + source->volume = c->volume; + source->muted = c->muted; + source->audio_mixers = c->audio_mixers; + + pthread_mutex_lock(&source->audio_buf_mutex); + source->audio_ts = c->ts; + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { + struct deque *dq = &source->audio_input_buf[ch]; + if (dq->size) + deque_pop_front(dq, NULL, dq->size); + if (ch >= CHANNELS) + continue; + for (size_t i = 0; i < c->input_frames; i++) { + float v = ramp(ch, i); + deque_push_back(dq, &v, sizeof(v)); + } + } + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +static bool mix_callback(enum kind kind, void *data, uint64_t *ts_out, struct audio_output_data *audio, size_t channels, + size_t sample_rate) +{ + obs_source_t *source = data; + const struct rcase *c = take_case(kind); + if (!c) + return false; + + struct snapshot *snap = &run.snap; + snap->called = true; + snap->channels = channels; + snap->sample_rate = sample_rate; + snap->buffers_ok = true; + for (size_t ch = 0; ch < channels; ch++) { + if (audio->data[ch] != source->audio_mix_buf[ch]) + snap->buffers_ok = false; + } + for (size_t ch = 0; ch < SEEN; ch++) + snap->mix_entry[ch] = source->audio_mix_buf[ch][FRAMES - 1]; + + set_up_tick(source, c); + if (c->success) { + for (size_t ch = 0; ch < channels && ch < CHANNELS; ch++) { + for (size_t i = 0; i < FRAMES; i++) + audio->data[ch][i] = block(ch, i); + } + } + *ts_out = c->ts; + return c->success; +} + +static bool tick_mix(void *data, uint64_t *ts_out, struct audio_output_data *audio, size_t channels, size_t sample_rate) +{ + return mix_callback(TICK, data, ts_out, audio, channels, sample_rate); +} + +static bool submix_mix(void *data, uint64_t *ts_out, struct audio_output_data *audio, size_t channels, + size_t sample_rate) +{ + return mix_callback(SUBMIX, data, ts_out, audio, channels, sample_rate); +} + +static void capture(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted) +{ + (void)param; + (void)source; + (void)muted; + pthread_mutex_lock(&run.mutex); + if (run.state == RENDERED && run.c->kind == SUBMIX) { + struct snapshot *snap = &run.snap; + if (snap->captures++ == 0) { + snap->capture_frames = audio_data->frames; + for (size_t ch = 0; ch < CHANNELS; ch++) { + if (audio_data->data[ch] && audio_data->frames >= FRAMES) + memcpy(snap->captured[ch], audio_data->data[ch], sizeof(snap->captured[ch])); + } + } + } + pthread_mutex_unlock(&run.mutex); +} + +static struct obs_source_info custom_info = { + .id = CUSTOM_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_COMPOSITE, + .get_name = child_name, + .create = child_create, + .destroy = child_destroy, + .audio_render = custom_render, +}; + +static struct obs_source_info tick_info = { + .id = TICK_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_AUDIO, + .get_name = child_name, + .create = child_create, + .destroy = child_destroy, + .audio_mix = tick_mix, +}; + +static struct obs_source_info submix_info = { + .id = SUBMIX_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_SUBMIX, + .get_name = child_name, + .create = child_create, + .destroy = child_destroy, + .audio_mix = submix_mix, +}; + +/* On the mix thread, in the parent's callback: the sentinel in every + * buffer of the case's child, its mixers, and audio_pending the other way + * round from what the case expects. */ +static void prime(obs_source_t *source, const struct rcase *c) +{ + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { + for (size_t i = 0; i < FRAMES; i++) + source->audio_output_buf[mix][ch][i] = SENTINEL; + } + } + if (source->audio_mix_buf[0]) { + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { + for (size_t i = 0; i < FRAMES; i++) + source->audio_mix_buf[ch][i] = SENTINEL; + } + } + source->audio_mixers = c->audio_mixers; + pthread_mutex_lock(&source->audio_buf_mutex); + source->audio_pending = !c->pending; + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +static void take_snapshot(obs_source_t *source, struct snapshot *snap) +{ + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < SEEN; ch++) + memcpy(snap->buf[mix][ch], source->audio_output_buf[mix][ch], sizeof(snap->buf[mix][ch])); + } + pthread_mutex_lock(&source->audio_buf_mutex); + snap->pending = source->audio_pending; + snap->audio_ts = source->audio_ts; + snap->input_size = source->audio_input_buf[0].size; + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +static const char *parent_name(void *unused) +{ + (void)unused; + return "audio render entry parent"; +} + +static void parent_enum(void *data, obs_source_enum_proc_t enum_callback, void *param) +{ + for (size_t i = 0; i < 3; i++) { + if (children[i]) + enum_callback(data, children[i], param); + } +} + +static bool parent_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) +{ + (void)data; + (void)ts_out; + (void)audio; + (void)mixers; + (void)channels; + (void)sample_rate; + + pthread_mutex_lock(&run.mutex); + if (run.state == ARMED) { + prime(children[run.c->kind], run.c); + run.state = PRIMED; + } else if (run.state == RENDERED) { + take_snapshot(children[run.c->kind], &run.snap); + run.state = DONE; + } + pthread_mutex_unlock(&run.mutex); + return false; +} + +static struct obs_source_info parent_info = { + .id = PARENT_ID, + .type = OBS_SOURCE_TYPE_INPUT, + .output_flags = OBS_SOURCE_COMPOSITE, + .get_name = parent_name, + .create = child_create, + .destroy = child_destroy, + .enum_active_sources = parent_enum, + .audio_render = parent_render, +}; + +static void raw_audio(void *param, size_t mix_idx, struct audio_data *data) +{ + (void)param; + (void)mix_idx; + (void)data; +} + +/* ------------------------------------------------------------------------ */ + +static bool check(bool ok, const struct rcase *c, const char *what) +{ + if (!ok) + fprintf(stderr, "%s: %s\n", c->what, what); + return ok; +} + +static bool check_buffers(const struct rcase *c, const struct snapshot *snap) +{ + size_t bad = 0; + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < SEEN; ch++) { + for (size_t i = 0; i < FRAMES; i++) { + float want = c->kind == CUSTOM ? custom_after(c, mix, ch) : tick_after(c, mix, ch, i); + float got = snap->buf[mix][ch][i]; + if (got != want && bad++ < 4) + fprintf(stderr, "%s: mix %zu channel %zu frame %zu is %g, expected %g\n", + c->what, mix, ch, i, (double)got, (double)want); + } + } + } + if (bad > 4) + fprintf(stderr, "%s: %zu samples differ\n", c->what, bad); + return bad == 0; +} + +static bool check_case(const struct rcase *c, const struct snapshot *snap) +{ + bool ok = true; + + ok &= check(snap->called, c, "the callback did not run"); + ok &= check(snap->buffers_ok, c, "the callback got other buffers"); + ok &= check(snap->channels == CHANNELS && snap->sample_rate == RATE, c, "channels or sample rate"); + + if (c->kind == CUSTOM) { + ok &= check(snap->mixers == TICK_MIXERS, c, "the callback's mixers"); + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < SEEN; ch++) { + if (snap->entry[mix][ch] != custom_entry(c, mix, ch)) { + fprintf(stderr, "%s: mix %zu channel %zu at the callback is %g, expected %g\n", + c->what, mix, ch, (double)snap->entry[mix][ch], + (double)custom_entry(c, mix, ch)); + ok = false; + } + } + } + ok &= check(snap->pending == !c->success, c, "audio_pending"); + ok &= check(snap->audio_ts == (c->success ? c->ts : 0), c, "audio_ts"); + ok &= check_buffers(c, snap); + return ok; + } + + /* the mix buffer is cleared for the tick's channels before audio_mix */ + for (size_t ch = 0; ch < SEEN; ch++) { + float want = ch < CHANNELS ? 0.0f : SENTINEL; + if (snap->mix_entry[ch] != want) { + fprintf(stderr, "%s: mix buffer channel %zu at the callback is %g, expected %g\n", c->what, ch, + (double)snap->mix_entry[ch], (double)want); + ok = false; + } + } + + if (c->success) { + /* the block goes to obs_source_output_audio() */ + ok &= check(snap->captures == 1, c, "the block was not output once"); + ok &= check(snap->capture_frames == FRAMES, c, "the output's frames"); + for (size_t ch = 0; ch < CHANNELS; ch++) { + for (size_t i = 0; i < FRAMES; i++) { + if (snap->captured[ch][i] != block(ch, i)) { + fprintf(stderr, "%s: output channel %zu frame %zu is %g, expected %g\n", + c->what, ch, i, (double)snap->captured[ch][i], (double)block(ch, i)); + ok = false; + break; + } + } + } + return ok; + } + + ok &= check(snap->captures == 0, c, "a failed audio_mix output audio"); + ok &= check(snap->pending == c->pending, c, "audio_pending"); + ok &= check(snap->audio_ts == c->ts, c, "audio_ts"); + /* the tick peeks; it does not take the input */ + ok &= check(snap->input_size == c->input_frames * sizeof(float), c, "the input left"); + ok &= check_buffers(c, snap); + return ok; +} + +static void run_case(void **state) +{ + const struct rcase *c = *state; + if (!obs_up) + skip(); + + pthread_mutex_lock(&run.mutex); + memset(&run.snap, 0, sizeof(run.snap)); + run.c = c; + run.state = ARMED; + pthread_mutex_unlock(&run.mutex); + + bool done = false; + for (int waited = 0; waited < WAIT_MS && !done; waited += 5) { + os_sleep_ms(5); + pthread_mutex_lock(&run.mutex); + done = run.state == DONE; + pthread_mutex_unlock(&run.mutex); + } + + pthread_mutex_lock(&run.mutex); + run.state = IDLE; + run.c = NULL; + struct snapshot *snap = &run.snap; + pthread_mutex_unlock(&run.mutex); + + if (!done) { + fprintf(stderr, "%s: the mix thread did not render the case in %d ms\n", c->what, WAIT_MS); + fail(); + } + /* the mix thread no longer writes the snapshot */ + if (!check_case(c, snap)) + fail(); +} + +static int group_setup(void **state) +{ + (void)state; + base_set_log_handler(quiet_log, NULL); + pthread_mutex_init(&run.mutex, NULL); + + const char *display = getenv("DISPLAY"); + if (!display || !*display) { + fprintf(stderr, "skipped: no display\n"); + return 0; + } + if (!obs_startup("en-US", NULL, NULL)) { + fprintf(stderr, "skipped: obs_startup failed\n"); + return 0; + } + struct obs_video_info ovi = { + .graphics_module = GRAPHICS_MODULE_PATH, + .fps_num = 30, + .fps_den = 1, + .base_width = W, + .base_height = H, + .output_width = W, + .output_height = H, + .output_format = VIDEO_FORMAT_NV12, + .colorspace = VIDEO_CS_709, + .range = VIDEO_RANGE_PARTIAL, + .scale_type = OBS_SCALE_BICUBIC, + }; + if (obs_reset_video(&ovi) != OBS_VIDEO_SUCCESS) { + fprintf(stderr, "skipped: obs_reset_video failed\n"); + obs_shutdown(); + return 0; + } + struct obs_audio_info oai = {.samples_per_sec = RATE, .speakers = SPEAKERS_STEREO}; + if (!obs_reset_audio(&oai)) { + fprintf(stderr, "skipped: obs_reset_audio failed\n"); + obs_shutdown(); + return 0; + } + + obs_register_source(&custom_info); + obs_register_source(&tick_info); + obs_register_source(&submix_info); + obs_register_source(&parent_info); + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + if (TICK_MIXERS & (1u << mix)) + obs_add_raw_audio_callback(mix, NULL, raw_audio, NULL); + } + + children[CUSTOM] = obs_source_create_private(CUSTOM_ID, "audio render entry custom", NULL); + children[TICK] = obs_source_create_private(TICK_ID, "audio render entry tick", NULL); + children[SUBMIX] = obs_source_create_private(SUBMIX_ID, "audio render entry submix", NULL); + for (size_t i = 0; i < 3; i++) + assert_non_null(children[i]); + obs_source_add_audio_capture_callback(children[SUBMIX], capture, NULL); + parent = obs_source_create_private(PARENT_ID, "audio render entry parent", NULL); + assert_non_null(parent); + obs_set_output_source(0, parent); + obs_up = true; + return 0; +} + +static int group_teardown(void **state) +{ + (void)state; + if (obs_up) { + obs_set_output_source(0, NULL); + /* the mix thread is done with them */ + os_sleep_ms(100); + obs_source_remove_audio_capture_callback(children[SUBMIX], capture, NULL); + obs_source_release(parent); + parent = NULL; + for (size_t i = 0; i < 3; i++) { + obs_source_release(children[i]); + children[i] = NULL; + } + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + if (TICK_MIXERS & (1u << mix)) + obs_remove_raw_audio_callback(mix, raw_audio, NULL); + } + obs_shutdown(); + obs_up = false; + } + pthread_mutex_destroy(&run.mutex); + return 0; +} + +int main(void) +{ + struct CMUnitTest tests[NUM_CASES]; + for (size_t i = 0; i < NUM_CASES; i++) { + struct CMUnitTest t = cmocka_unit_test_prestate(run_case, &cases[i]); + t.name = cases[i].what; + tests[i] = t; + } + return cmocka_run_group_tests_name("test_source_audio_render_entry", tests, group_setup, group_teardown); +} diff --git a/test/cmocka/tests.d/test_source_audio_render_entry.cmake b/test/cmocka/tests.d/test_source_audio_render_entry.cmake new file mode 100644 index 0000000000..ec8f35b3e3 --- /dev/null +++ b/test/cmocka/tests.d/test_source_audio_render_entry.cmake @@ -0,0 +1,4 @@ +# obs_source_audio_render() (#5923) and its custom, submix and tick steps, +# one tick of the audio mix at a time. Mixing needs core video, so it runs +# (under xvfb-run) on Linux and skips without a display. +# Canonical target and test: test/cmocka/build/test-graph.json. From 1ea4006738c725ad760199fb4df748b9ac53e8b0 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sun, 29 Nov 2026 01:17:26 -0500 Subject: [PATCH 2/3] obs-source: Tier 1 for obs_source_audio_render and its steps, RED (Refs #5923) The safe core's Host trait (the route's reads, the submix flag, audio_buf_mutex, audio_pending, audio_ts, audio_mixers, the input size, the callbacks' buffers, the memsets, the peek and the memcpy, the two plugin callbacks, the volume and the output) and todo!() steps, with 20 Tier 1 tests over a recording model: each route's reads behind the checks before it, the custom render's clears before and after with audio_mixers read once per mix, its failed, timestamp-less and unmixed results, the submix's clear and its output of the planes the callback left, the tick's pending checks (the input size only with a timestamp), peek, copy or clear of each mix, the main mix's clear and the volume, a submix source's mix 1 and stop, and size_t wrapping. The model fails a test on a field or buffer touched under the wrong lock state. All 20 fail on the todo!() core. Co-Authored-By: Claude Opus 5.5 --- rust/obs-source/src/audio_render_steps.rs | 194 +++++ rust/obs-source/src/lib.rs | 1 + .../tests/source/audio_render_steps.rs | 706 ++++++++++++++++++ rust/obs-source/tests/source/main.rs | 1 + 4 files changed, 902 insertions(+) create mode 100644 rust/obs-source/src/audio_render_steps.rs create mode 100644 rust/obs-source/tests/source/audio_render_steps.rs diff --git a/rust/obs-source/src/audio_render_steps.rs b/rust/obs-source/src/audio_render_steps.rs new file mode 100644 index 0000000000..3708f1f6fd --- /dev/null +++ b/rust/obs-source/src/audio_render_steps.rs @@ -0,0 +1,194 @@ +//! Safe core of `libobs/obs-source-audio-render-steps.c.h`: what the audio +//! mix thread calls for each source on every tick, the hidden +//! `obs_source_audio_render()` (declared in `obs-internal.h` without +//! `EXPORT`) and its three steps. +//! +//! - [`audio_render`]: the output buffer, then `info.audio_render`, then +//! `context.data`, each read only where the checks before reached it (the +//! audio thread can render a source whose `context.data` is not set yet, +//! 432017b2c), into [`crate::audio_render_plan::route`]: pending sets +//! `audio_pending`; a custom render runs [`custom_audio_render`]; the +//! tick runs [`audio_submix`] when `info.audio_mix` is set, then +//! [`process_audio_source_tick`]. +//! - [`custom_audio_render`]: per mix, the callback's buffers pointed at the +//! output buffers and the mix cleared before when the plan says +//! (`audio_mixers` read once per mix); the plugin's `audio_render` +//! outside the lock; then under `audio_buf_mutex` `audio_ts` and +//! `audio_pending`, an early return when pending or unmixed (`audio_ts` +//! read again only then), the clears after for the tick's mixes, and +//! `obs_source_apply_audio_volume()`. +//! - [`audio_submix`]: the callback's planes pointed at the mix buffer, the +//! mix buffer cleared, the plugin's `audio_mix`, and on success the +//! planes (as the callback left them) handed to `obs_source_output_audio()` +//! with the tick's rate, frames, layout and timestamp. +//! - [`process_audio_source_tick`]: the submix flag, then under +//! `audio_buf_mutex` pending when `audio_ts` is unset or the input is +//! short (the input size read only with a timestamp); otherwise each +//! channel's input peeked into mix 0, mixes 1 to 5 copied or cleared +//! (`audio_mixers` once per mix), then either the stop of a submix source +//! or the main mix's clear and the volume. +//! +//! Every decision is [`crate::audio_render_plan`]. The fields, the lock, the +//! deques, the memsets and memcpys, the callbacks, +//! `obs_source_apply_audio_volume()` and `obs_source_output_audio()` stay C, +//! reached through the [`Host`] trait one access at a time. Byte counts +//! wrap as the C's `size_t` does. +//! +//! No intentional differences from C. + +#![deny( + clippy::arithmetic_side_effects, + clippy::indexing_slicing, + clippy::as_conversions, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unimplemented, + clippy::unreachable +)] + +use crate::audio_render_plan as plan; + +/// `MAX_AUDIO_MIXES`. +pub const MAX_AUDIO_MIXES: usize = plan::MAX_AUDIO_MIXES; + +/// `sizeof(float) * AUDIO_OUTPUT_FRAMES`: one channel of one tick, in bytes. +pub const CHANNEL_BYTES: usize = 4 * 1024; + +/// The source's fields, lock, buffers and callbacks the steps use, in the +/// C's terms. +pub trait Host { + /// A live, non-null source. + type Source: Copy; + /// A `struct obs_source_audio_mix`: the custom render's buffers. + type Mix; + /// A `struct audio_output_data`: the submix's planes. + type Planes; + + /// `source->audio_output_buf[0][0] != NULL`. + fn has_output_buffer(&self, source: Self::Source) -> bool; + /// `source->info.audio_render != NULL`. + fn has_audio_render(&self, source: Self::Source) -> bool; + /// `source->context.data != NULL`. + fn has_context_data(&self, source: Self::Source) -> bool; + /// `source->info.audio_mix != NULL`. + fn has_audio_mix(&self, source: Self::Source) -> bool; + /// `!!(source->info.output_flags & OBS_SOURCE_SUBMIX)`. + fn is_submix(&self, source: Self::Source) -> bool; + /// `pthread_mutex_lock(&source->audio_buf_mutex)`. + fn lock(&self, source: Self::Source); + /// `pthread_mutex_unlock(&source->audio_buf_mutex)`. + fn unlock(&self, source: Self::Source); + /// `source->audio_pending = pending`. + fn set_audio_pending(&self, source: Self::Source, pending: bool); + /// `source->audio_ts`. + fn audio_ts(&self, source: Self::Source) -> u64; + /// `source->audio_ts = ts`. + fn set_audio_ts(&self, source: Self::Source, ts: u64); + /// `source->audio_mixers`. + fn audio_mixers(&self, source: Self::Source) -> u32; + /// `source->audio_input_buf[0].size`. + fn input_size(&self, source: Self::Source) -> usize; + + /// The custom render's buffers before they are pointed (the C's + /// uninitialized local). + fn new_mix(&self) -> Self::Mix; + /// `audio_data.output[mix].data[channel] = + /// source->audio_output_buf[mix][channel]`. + fn point_output(&self, source: Self::Source, data: &mut Self::Mix, mix: usize, channel: usize); + /// `memset(source->audio_output_buf[mix][0], 0, bytes)`. + fn clear_output(&self, source: Self::Source, mix: usize, bytes: usize); + /// `source->info.audio_render(source->context.data, &ts, data, mixers, + /// channels, sample_rate)`: its result and `ts`. + fn audio_render( + &self, + source: Self::Source, + data: &mut Self::Mix, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> (bool, u64); + /// `obs_source_apply_audio_volume(source, mixers, channels, + /// sample_rate)`. + fn apply_volume(&self, source: Self::Source, mixers: u32, channels: usize, sample_rate: usize); + + /// The submix's planes before they are pointed (the C's uninitialized + /// local). + fn new_planes(&self) -> Self::Planes; + /// `audio_data.data[channel] = source->audio_mix_buf[channel]`. + fn point_plane(&self, source: Self::Source, data: &mut Self::Planes, channel: usize); + /// `memset(source->audio_mix_buf[0], 0, bytes)`. + fn clear_mix_buffer(&self, source: Self::Source, bytes: usize); + /// `source->info.audio_mix(source->context.data, &ts, data, channels, + /// sample_rate)`: its result and `ts`. + fn audio_mix( + &self, + source: Self::Source, + data: &mut Self::Planes, + channels: usize, + sample_rate: usize, + ) -> (bool, u64); + /// `obs_source_output_audio(source, &audio)` with `audio.data[i] = + /// data->data[i]` for each channel, `samples_per_sec = sample_rate`, + /// `frames = AUDIO_OUTPUT_FRAMES`, `format = AUDIO_FORMAT_FLOAT_PLANAR`, + /// `speakers = channels` and `timestamp = ts`. + fn output_audio( + &self, + source: Self::Source, + data: &Self::Planes, + channels: usize, + sample_rate: usize, + ts: u64, + ); + + /// `deque_peek_front(&source->audio_input_buf[channel], + /// source->audio_output_buf[0][channel], size)`. + fn peek_input(&self, source: Self::Source, channel: usize, size: usize); + /// `memcpy(source->audio_output_buf[mix][channel], + /// source->audio_output_buf[0][channel], size)`. + fn copy_output(&self, source: Self::Source, mix: usize, channel: usize, size: usize); +} + +/// `custom_audio_render(source, mixers, channels, sample_rate)`. +pub fn custom_audio_render( + host: &H, + source: H::Source, + mixers: u32, + channels: usize, + sample_rate: usize, +) { + let _ = (host, source, mixers, channels, sample_rate); + todo!() +} + +/// `audio_submix(source, channels, sample_rate)`. +pub fn audio_submix(host: &H, source: H::Source, channels: usize, sample_rate: usize) { + let _ = (host, source, channels, sample_rate); + todo!() +} + +/// `process_audio_source_tick(source, mixers, channels, sample_rate, size)`. +pub fn process_audio_source_tick( + host: &H, + source: H::Source, + mixers: u32, + channels: usize, + sample_rate: usize, + size: usize, +) { + let _ = (host, source, mixers, channels, sample_rate, size); + todo!() +} + +/// `obs_source_audio_render(source, mixers, channels, sample_rate, size)`. +pub fn audio_render( + host: &H, + source: H::Source, + mixers: u32, + channels: usize, + sample_rate: usize, + size: usize, +) { + let _ = (host, source, mixers, channels, sample_rate, size); + todo!() +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index af990c1b9f..7540028773 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -297,6 +297,7 @@ pub mod audio_pause_callbacks; pub mod audio_pending_speaker_layout; pub mod audio_place; pub mod audio_render_plan; +pub mod audio_render_steps; pub mod audio_settings; pub mod audio_timing; pub mod audio_volume_apply; diff --git a/rust/obs-source/tests/source/audio_render_steps.rs b/rust/obs-source/tests/source/audio_render_steps.rs new file mode 100644 index 0000000000..43ea656879 --- /dev/null +++ b/rust/obs-source/tests/source/audio_render_steps.rs @@ -0,0 +1,706 @@ +//! Tier 1: `obs_source_audio_render()` and its custom, submix and tick +//! steps (`obs_source::audio_render_steps`) on a recording model of the +//! source. Every access the core makes is recorded in order, so each test +//! pins the C's sequence: which fields are read where (the output buffer, +//! `audio_render` and `context.data` only behind the checks before them, +//! `audio_mixers` once per mix, `audio_ts` after a successful callback, the +//! input size only with a timestamp), the lock around what the C locks, the +//! callbacks outside it, and the byte counts of every clear, peek and copy. +//! The model fails a test when a field is written or a buffer touched under +//! the wrong lock state. + +use std::cell::RefCell; + +use obs_source::audio_render_steps::{ + self, CHANNEL_BYTES, Host, MAX_AUDIO_MIXES, audio_submix, custom_audio_render, + process_audio_source_tick, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Ev { + HasBuffer, + HasRender, + HasData, + HasMix, + IsSubmix, + Lock, + Unlock, + SetPending(bool), + AudioTs, + SetAudioTs(u64), + AudioMixers, + InputSize, + PointOutput(usize, usize), + ClearOutput(usize, usize), + Render(u32, usize, usize), + Volume(u32, usize, usize), + PointPlane(usize), + ClearMix(usize), + Mix(usize, usize), + /// channels, sample rate, ts, the planes handed over + Output(usize, usize, u64, [usize; 8]), + Peek(usize, usize), + Copy(usize, usize, usize), +} + +#[derive(Debug, Clone)] +struct Model { + has_buffer: bool, + has_render: bool, + has_data: bool, + has_mix: bool, + submix: bool, + audio_ts: u64, + /// Each read of `audio_mixers` takes the next value; the last repeats. + audio_mixers: Vec, + input_size: usize, + render: (bool, u64), + mix: (bool, u64), + /// The audio_mix callback moves plane 0 to this marker. + redirect: Option, +} + +impl Default for Model { + fn default() -> Self { + Self { + has_buffer: true, + has_render: false, + has_data: true, + has_mix: false, + submix: false, + audio_ts: 1000, + audio_mixers: vec![0x3f], + input_size: CHANNEL_BYTES, + render: (true, 1000), + mix: (false, 0), + redirect: None, + } + } +} + +struct Rec { + m: RefCell, + reads: RefCell, + locked: RefCell, + log: RefCell>, +} + +impl Rec { + fn new(m: Model) -> Self { + Self { + m: RefCell::new(m), + reads: RefCell::new(0), + locked: RefCell::new(false), + log: RefCell::new(Vec::new()), + } + } + fn push(&self, ev: Ev) { + self.log.borrow_mut().push(ev); + } + fn locked(&self) -> bool { + *self.locked.borrow() + } + fn log(&self) -> Vec { + self.log.borrow().clone() + } +} + +/// Planes as the model points them: 100 + channel, 0 unset. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Planes([usize; 8]); + +impl Host for Rec { + type Source = (); + type Mix = Vec<(usize, usize)>; + type Planes = Planes; + + fn has_output_buffer(&self, (): ()) -> bool { + self.push(Ev::HasBuffer); + self.m.borrow().has_buffer + } + fn has_audio_render(&self, (): ()) -> bool { + self.push(Ev::HasRender); + self.m.borrow().has_render + } + fn has_context_data(&self, (): ()) -> bool { + self.push(Ev::HasData); + self.m.borrow().has_data + } + fn has_audio_mix(&self, (): ()) -> bool { + self.push(Ev::HasMix); + self.m.borrow().has_mix + } + fn is_submix(&self, (): ()) -> bool { + self.push(Ev::IsSubmix); + self.m.borrow().submix + } + fn lock(&self, (): ()) { + assert!(!self.locked(), "locked twice"); + *self.locked.borrow_mut() = true; + self.push(Ev::Lock); + } + fn unlock(&self, (): ()) { + assert!(self.locked(), "unlocked twice"); + *self.locked.borrow_mut() = false; + self.push(Ev::Unlock); + } + fn set_audio_pending(&self, (): (), pending: bool) { + self.push(Ev::SetPending(pending)); + } + fn audio_ts(&self, (): ()) -> u64 { + assert!(self.locked(), "audio_ts read without audio_buf_mutex"); + self.push(Ev::AudioTs); + self.m.borrow().audio_ts + } + fn set_audio_ts(&self, (): (), ts: u64) { + assert!(self.locked(), "audio_ts written without audio_buf_mutex"); + self.push(Ev::SetAudioTs(ts)); + self.m.borrow_mut().audio_ts = ts; + } + fn audio_mixers(&self, (): ()) -> u32 { + self.push(Ev::AudioMixers); + let mut reads = self.reads.borrow_mut(); + let m = self.m.borrow(); + let value = m.audio_mixers[(*reads).min(m.audio_mixers.len() - 1)]; + *reads += 1; + value + } + fn input_size(&self, (): ()) -> usize { + assert!(self.locked(), "input read without audio_buf_mutex"); + self.push(Ev::InputSize); + self.m.borrow().input_size + } + fn new_mix(&self) -> Vec<(usize, usize)> { + Vec::new() + } + fn point_output(&self, (): (), data: &mut Vec<(usize, usize)>, mix: usize, channel: usize) { + self.push(Ev::PointOutput(mix, channel)); + data.push((mix, channel)); + } + fn clear_output(&self, (): (), mix: usize, bytes: usize) { + self.push(Ev::ClearOutput(mix, bytes)); + } + fn audio_render( + &self, + (): (), + data: &mut Vec<(usize, usize)>, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + assert!(!self.locked(), "audio_render called under audio_buf_mutex"); + assert_eq!( + data.len(), + MAX_AUDIO_MIXES * channels, + "every buffer pointed" + ); + self.push(Ev::Render(mixers, channels, sample_rate)); + self.m.borrow().render + } + fn apply_volume(&self, (): (), mixers: u32, channels: usize, sample_rate: usize) { + assert!(self.locked(), "volume applied without audio_buf_mutex"); + self.push(Ev::Volume(mixers, channels, sample_rate)); + } + fn new_planes(&self) -> Planes { + Planes([0; 8]) + } + fn point_plane(&self, (): (), data: &mut Planes, channel: usize) { + self.push(Ev::PointPlane(channel)); + data.0[channel] = 100 + channel; + } + fn clear_mix_buffer(&self, (): (), bytes: usize) { + self.push(Ev::ClearMix(bytes)); + } + fn audio_mix( + &self, + (): (), + data: &mut Planes, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + assert!(!self.locked(), "audio_mix called under audio_buf_mutex"); + self.push(Ev::Mix(channels, sample_rate)); + if let Some(marker) = self.m.borrow().redirect { + data.0[0] = marker; + } + self.m.borrow().mix + } + fn output_audio(&self, (): (), data: &Planes, channels: usize, sample_rate: usize, ts: u64) { + assert!(!self.locked(), "audio output under audio_buf_mutex"); + self.push(Ev::Output(channels, sample_rate, ts, data.0)); + } + fn peek_input(&self, (): (), channel: usize, size: usize) { + assert!(self.locked(), "input peeked without audio_buf_mutex"); + self.push(Ev::Peek(channel, size)); + } + fn copy_output(&self, (): (), mix: usize, channel: usize, size: usize) { + assert!(self.locked(), "mix copied without audio_buf_mutex"); + self.push(Ev::Copy(mix, channel, size)); + } +} + +const RATE: usize = 48_000; +const SIZE: usize = CHANNEL_BYTES; + +fn render(m: Model, mixers: u32, channels: usize) -> Vec { + let rec = Rec::new(m); + audio_render_steps::audio_render(&rec, (), mixers, channels, RATE, SIZE); + assert!(!rec.locked(), "left locked"); + rec.log() +} + +fn custom(m: Model) -> Model { + Model { + has_render: true, + ..m + } +} + +/// The custom render's events up to and including the callback. +fn custom_head(audio_mixers: &[u32], mixers: u32, channels: usize) -> Vec { + let mut want = Vec::new(); + for mix in 0..MAX_AUDIO_MIXES { + for ch in 0..channels { + want.push(Ev::PointOutput(mix, ch)); + } + want.push(Ev::AudioMixers); + let am = audio_mixers[mix.min(audio_mixers.len() - 1)]; + if am & mixers & (1 << mix) != 0 { + want.push(Ev::ClearOutput(mix, CHANNEL_BYTES * channels)); + } + } + want.push(Ev::Render(mixers, channels, RATE)); + want +} + +#[test] +fn no_output_buffer_is_pending_and_reads_nothing_else() { + let log = render( + Model { + has_buffer: false, + has_render: true, + ..Model::default() + }, + 0x3f, + 2, + ); + assert_eq!(log, [Ev::HasBuffer, Ev::SetPending(true)]); +} + +#[test] +fn custom_render_without_data_is_pending() { + let log = render( + custom(Model { + has_data: false, + ..Model::default() + }), + 0x3f, + 2, + ); + assert_eq!( + log, + [ + Ev::HasBuffer, + Ev::HasRender, + Ev::HasData, + Ev::SetPending(true) + ] + ); +} + +#[test] +fn custom_render_clears_before_and_after_and_applies_the_volume() { + // On mixes 0 and 2; the tick has 0, 1 and 2. + let log = render( + custom(Model { + audio_mixers: vec![0x05], + render: (true, 77), + ..Model::default() + }), + 0x07, + 2, + ); + let mut want = vec![Ev::HasBuffer, Ev::HasRender, Ev::HasData]; + want.extend(custom_head(&[0x05], 0x07, 2)); + want.extend([ + Ev::Lock, + Ev::SetAudioTs(77), + Ev::SetPending(false), + Ev::AudioTs, + // mixes 0, 1 and 2 of the tick, each its own read + Ev::AudioMixers, + Ev::AudioMixers, + Ev::ClearOutput(1, 2 * CHANNEL_BYTES), + Ev::AudioMixers, + Ev::Volume(0x07, 2, RATE), + Ev::Unlock, + ]); + assert_eq!(log, want); +} + +#[test] +fn custom_render_failure_is_pending_with_no_timestamp() { + let rec = Rec::new(custom(Model { + render: (false, 99), + ..Model::default() + })); + custom_audio_render(&rec, (), 0x3f, 2, RATE); + let mut want = custom_head(&[0x3f], 0x3f, 2); + // ts is not used when the callback failed; audio_ts is not read. + want.extend([ + Ev::Lock, + Ev::SetAudioTs(0), + Ev::SetPending(true), + Ev::Unlock, + ]); + assert_eq!(rec.log(), want); +} + +#[test] +fn custom_render_with_no_timestamp_stops_after_the_callback() { + let rec = Rec::new(custom(Model { + render: (true, 0), + ..Model::default() + })); + custom_audio_render(&rec, (), 0x3f, 2, RATE); + let mut want = custom_head(&[0x3f], 0x3f, 2); + want.extend([ + Ev::Lock, + Ev::SetAudioTs(0), + Ev::SetPending(false), + Ev::AudioTs, + Ev::Unlock, + ]); + assert_eq!(rec.log(), want); +} + +#[test] +fn custom_render_with_no_tick_mixers_stops_after_the_callback() { + let rec = Rec::new(custom(Model::default())); + custom_audio_render(&rec, (), 0, 2, RATE); + let mut want = custom_head(&[0x3f], 0, 2); + want.extend([ + Ev::Lock, + Ev::SetAudioTs(1000), + Ev::SetPending(false), + Ev::AudioTs, + Ev::Unlock, + ]); + assert_eq!(rec.log(), want); +} + +#[test] +fn custom_render_reads_audio_mixers_once_per_mix() { + // Each read sees a new value: before the callback mix m reads value m, + // after it the tick's mixes read values 6, 7 and 8. + let seq = vec![0x01, 0x00, 0x04, 0x08, 0x10, 0x20, 0x00, 0x3f, 0x00]; + let rec = Rec::new(custom(Model { + audio_mixers: seq.clone(), + ..Model::default() + })); + custom_audio_render(&rec, (), 0x15, 1, RATE); + let mut want = custom_head(&seq, 0x15, 1); + want.extend([ + Ev::Lock, + Ev::SetAudioTs(1000), + Ev::SetPending(false), + Ev::AudioTs, + // mix 0 reads 0x00: cleared + Ev::AudioMixers, + Ev::ClearOutput(0, CHANNEL_BYTES), + // mix 2 reads 0x3f: kept + Ev::AudioMixers, + // mix 4 reads 0x00 again: cleared + Ev::AudioMixers, + Ev::ClearOutput(4, CHANNEL_BYTES), + Ev::Volume(0x15, 1, RATE), + Ev::Unlock, + ]); + assert_eq!(rec.log(), want); +} + +#[test] +fn custom_render_with_mixers_past_six_still_applies_the_volume() { + let rec = Rec::new(custom(Model::default())); + custom_audio_render(&rec, (), 0x40, 8, RATE); + let mut want = custom_head(&[0x3f], 0x40, 8); + want.extend([ + Ev::Lock, + Ev::SetAudioTs(1000), + Ev::SetPending(false), + Ev::AudioTs, + Ev::Volume(0x40, 8, RATE), + Ev::Unlock, + ]); + assert_eq!(rec.log(), want); +} + +#[test] +fn custom_render_with_no_channels_points_nothing() { + let rec = Rec::new(custom(Model::default())); + custom_audio_render(&rec, (), 0x01, 0, 1); + let log = rec.log(); + assert!(!log.iter().any(|e| matches!(e, Ev::PointOutput(..)))); + assert_eq!(log[1], Ev::ClearOutput(0, 0)); + assert!(log.contains(&Ev::Volume(0x01, 0, 1))); +} + +#[test] +fn submix_clears_the_mix_buffer_and_outputs_what_the_callback_left() { + let rec = Rec::new(Model { + mix: (true, 4242), + redirect: Some(7), + ..Model::default() + }); + audio_submix(&rec, (), 3, 44_100); + assert_eq!( + rec.log(), + [ + Ev::PointPlane(0), + Ev::PointPlane(1), + Ev::PointPlane(2), + Ev::ClearMix(3 * CHANNEL_BYTES), + Ev::Mix(3, 44_100), + Ev::Output(3, 44_100, 4242, [7, 101, 102, 0, 0, 0, 0, 0]), + ] + ); +} + +#[test] +fn failed_submix_outputs_nothing() { + let rec = Rec::new(Model { + mix: (false, 4242), + ..Model::default() + }); + audio_submix(&rec, (), 2, RATE); + assert_eq!( + rec.log(), + [ + Ev::PointPlane(0), + Ev::PointPlane(1), + Ev::ClearMix(2 * CHANNEL_BYTES), + Ev::Mix(2, RATE), + ] + ); +} + +#[test] +fn tick_without_a_timestamp_is_pending_and_skips_the_input() { + let rec = Rec::new(Model { + audio_ts: 0, + input_size: 0, + ..Model::default() + }); + process_audio_source_tick(&rec, (), 0x3f, 2, RATE, SIZE); + assert_eq!( + rec.log(), + [ + Ev::IsSubmix, + Ev::Lock, + Ev::AudioTs, + Ev::SetPending(true), + Ev::Unlock + ] + ); +} + +#[test] +fn tick_with_short_input_is_pending() { + let rec = Rec::new(Model { + input_size: SIZE - 1, + ..Model::default() + }); + process_audio_source_tick(&rec, (), 0x3f, 2, RATE, SIZE); + assert_eq!( + rec.log(), + [ + Ev::IsSubmix, + Ev::Lock, + Ev::AudioTs, + Ev::InputSize, + Ev::SetPending(true), + Ev::Unlock + ] + ); +} + +/// The tick's events after the pending check for a source that is not a +/// submix, with `audio_mixers` read as `seq`. +fn tick_body(seq: &[u32], mixers: u32, channels: usize, size: usize) -> Vec { + let at = |i: usize| seq[i.min(seq.len() - 1)]; + let mut want = Vec::new(); + for ch in 0..channels { + want.push(Ev::Peek(ch, size)); + } + for mix in 1..MAX_AUDIO_MIXES { + want.push(Ev::AudioMixers); + let bit = 1 << mix; + if at(mix - 1) & bit != 0 && mixers & bit != 0 { + for ch in 0..channels { + want.push(Ev::Copy(mix, ch, size)); + } + } else { + want.push(Ev::ClearOutput(mix, size.wrapping_mul(channels))); + } + } + want.push(Ev::AudioMixers); + if at(5) & 1 == 0 || mixers & 1 == 0 { + want.push(Ev::ClearOutput(0, size.wrapping_mul(channels))); + } + want.extend([ + Ev::Volume(mixers, channels, RATE), + Ev::SetPending(false), + Ev::Unlock, + ]); + want +} + +#[test] +fn tick_peeks_copies_or_clears_each_mix_and_applies_the_volume() { + for (audio_mixers, mixers) in [ + (0x3f, 0x3f), + (0x3f, 0x15), + (0x14, 0x3f), + (0x00, 0x3f), + (0x3f, 0x00), + (0x02, 0x03), + ] { + let rec = Rec::new(Model { + audio_mixers: vec![audio_mixers], + input_size: 2 * SIZE, + ..Model::default() + }); + process_audio_source_tick(&rec, (), mixers, 2, RATE, SIZE); + let mut want = vec![Ev::IsSubmix, Ev::Lock, Ev::AudioTs, Ev::InputSize]; + want.extend(tick_body(&[audio_mixers], mixers, 2, SIZE)); + assert_eq!(rec.log(), want, "{audio_mixers:#x} {mixers:#x}"); + } +} + +#[test] +fn tick_reads_audio_mixers_once_per_mix() { + let seq = vec![0x02, 0x00, 0x08, 0x10, 0x00, 0x00]; + let rec = Rec::new(Model { + audio_mixers: seq.clone(), + ..Model::default() + }); + process_audio_source_tick(&rec, (), 0x3f, 1, RATE, SIZE); + let mut want = vec![Ev::IsSubmix, Ev::Lock, Ev::AudioTs, Ev::InputSize]; + want.extend(tick_body(&seq, 0x3f, 1, SIZE)); + assert_eq!(rec.log(), want); + // mixes 1, 3 and 4 copied, 2 and 5 cleared, mix 0 cleared + assert!(want.contains(&Ev::Copy(1, 0, SIZE)) && want.contains(&Ev::ClearOutput(0, SIZE))); +} + +#[test] +fn tick_byte_counts_wrap_as_size_t() { + let size = usize::MAX / 2 + 1; + let rec = Rec::new(Model { + audio_mixers: vec![0x00], + input_size: usize::MAX, + ..Model::default() + }); + process_audio_source_tick(&rec, (), 0x3f, 2, RATE, size); + let log = rec.log(); + assert!(log.contains(&Ev::Peek(1, size))); + assert!(log.contains(&Ev::ClearOutput(5, 0))); + assert!(log.contains(&Ev::ClearOutput(0, 0))); +} + +#[test] +fn submix_tick_fills_mix_one_from_bit_zero_and_stops() { + for (audio_mixers, copy) in [(0x01, true), (0x3e, false), (0x00, false), (0x3f, true)] { + let rec = Rec::new(Model { + submix: true, + audio_mixers: vec![audio_mixers], + ..Model::default() + }); + // The tick's mixers do not matter to a submix source. + process_audio_source_tick(&rec, (), 0x00, 2, RATE, SIZE); + let mut want = vec![ + Ev::IsSubmix, + Ev::Lock, + Ev::AudioTs, + Ev::InputSize, + Ev::Peek(0, SIZE), + Ev::Peek(1, SIZE), + Ev::AudioMixers, + ]; + if copy { + want.extend([Ev::Copy(1, 0, SIZE), Ev::Copy(1, 1, SIZE)]); + } else { + want.push(Ev::ClearOutput(1, 2 * SIZE)); + } + want.extend([Ev::SetPending(false), Ev::Unlock]); + assert_eq!(rec.log(), want, "{audio_mixers:#x}"); + } +} + +#[test] +fn tick_route_runs_the_submix_first_and_never_reads_context_data() { + let log = render( + Model { + has_mix: true, + submix: true, + mix: (true, 5), + ..Model::default() + }, + 0x01, + 1, + ); + assert_eq!( + log, + [ + Ev::HasBuffer, + Ev::HasRender, + Ev::HasMix, + Ev::PointPlane(0), + Ev::ClearMix(CHANNEL_BYTES), + Ev::Mix(1, RATE), + Ev::Output(1, RATE, 5, [100, 0, 0, 0, 0, 0, 0, 0]), + Ev::IsSubmix, + Ev::Lock, + Ev::AudioTs, + Ev::InputSize, + Ev::Peek(0, SIZE), + Ev::AudioMixers, + Ev::Copy(1, 0, SIZE), + Ev::SetPending(false), + Ev::Unlock, + ] + ); +} + +#[test] +fn tick_route_without_audio_mix_goes_straight_to_the_tick() { + let log = render(Model::default(), 0x3f, 2); + let mut want = vec![ + Ev::HasBuffer, + Ev::HasRender, + Ev::HasMix, + Ev::IsSubmix, + Ev::Lock, + Ev::AudioTs, + Ev::InputSize, + ]; + want.extend(tick_body(&[0x3f], 0x3f, 2, SIZE)); + assert_eq!(log, want); +} + +#[test] +fn custom_route_never_runs_the_submix_or_the_tick() { + let log = render( + custom(Model { + has_mix: true, + submix: true, + ..Model::default() + }), + 0x3f, + 2, + ); + assert!( + !log.iter() + .any(|e| matches!(e, Ev::HasMix | Ev::IsSubmix | Ev::Mix(..) | Ev::Peek(..))) + ); + assert_eq!(log.last(), Some(&Ev::Unlock)); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index f926c738bf..301397d4a3 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -42,6 +42,7 @@ mod audio_place; mod audio_place_parity; mod audio_render_plan; mod audio_render_plan_parity; +mod audio_render_steps; mod audio_settings; mod audio_timing; mod audio_timing_parity; From 838378f444a11d91ec323e9df1af3c3ba81af161 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sun, 29 Nov 2026 01:31:41 -0500 Subject: [PATCH 3/3] obs-source: port obs_source_audio_render and its custom, submix and tick steps to Rust (Fixes #5923) Swap obs_source_audio_render() (with custom_audio_render(), audio_submix() and process_audio_source_tick()) in hybrid libobs for a safe Rust core over a Host trait, behind the hidden export (rust-hidden.d). The output buffer, info.audio_render and context.data are read only where the checks before reached them (432017b2c); a custom render points the callback's buffers, clears before per the plan with audio_mixers read once per mix, calls audio_render outside the lock, then under audio_buf_mutex sets audio_ts and audio_pending, returns when pending or unmixed, clears after and applies the volume; the tick runs the submix when info.audio_mix is set (the mix buffer cleared, audio_mix, and on success the planes as the callback left them to obs_source_output_audio()), then under the mutex the pending checks (the input size only with a timestamp), the peek, copy or clear of each mix, and the submix stop or the main mix's clear and the volume. Every decision is obs-source::audio_render_plan. The fields, the mutex, the deques, the memsets and memcpys, both callbacks, obs_source_apply_audio_volume() and obs_source_output_audio() stay C in obs-source-audio-render-steps-fields.c.h (live group, no EXPORT). The original moves to the ported group libobs.ported-source-audio-render-steps for the C reference. The test binaries' obs_source_audio_render() stand-in in oracle/audio_callback_links.c gives way to the export. Tier 3 runs the original C (with the oracle's original plan) and the Rust export on real-layout sources through shared recorders of the lock, every memset, memcpy and peek, the volume, the output and both callbacks, with clobbers that rewrite audio_mixers and audio_ts mid-call, over every route against the masks, the pending checks with sizes and channel counts, odd sample rates and a proptest; it compares the fields, every sample's bits, the event log, the deques and every other byte, and rejects six mutants. Tier 2 is test_source_audio_render_entry. No intentional differences. Co-Authored-By: Claude Opus 5.5 Ci-Attestation: {"at":1795935077,"gate":"data/all/compatibility","host":"linux-x86_64","key":"","lane":"client-checks","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":77,"stamp":"1209e9d0a7f53ae53ae7f06ea7d788af","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795935077,"gate":"data/all/flatpak-manifest","host":"linux-x86_64","key":"","lane":"client-checks","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":77,"stamp":"45f3eb7ed68c75f903d95544d5ae2e8e","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795935077,"gate":"data/all/qt-xml","host":"linux-x86_64","key":"","lane":"client-checks","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":77,"stamp":"2e74117dc79868b9c53c3dd951491cab","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795935077,"gate":"data/all/services-schema","host":"linux-x86_64","key":"","lane":"client-checks","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":77,"stamp":"f0ca0f690efa2c256e7663851308b090","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"general/all/client-lint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"5225e45f35be15fdb3ab2b5218998a5d","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795935077,"gate":"python/all/self-test","host":"linux-x86_64","key":"","lane":"client-checks","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":77,"stamp":"8c8e13cc37a8b1e37045f21f67116251","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-apple-darwin/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"c3b0bc580123bb36c33e7df2d4d8f307","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-apple-darwin/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"31dee13f757f99e233f100c74c3be6dd","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"dcf617be1b8c9a3a7e59ed0a2c212494","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"7b4fc84905b598bed36099343ba59db4","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"163ea5516595248795872f90254a5027","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/aarch64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"cef6f0175203f1df3e0a3fbd35798c57","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-apple-darwin/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"d28aa40c5ba03590cd2e0b2695fcf4e3","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-apple-darwin/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"5eae98d72ffd7251379c230e0cc1269e","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-pc-windows-msvc/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"7b46a8b394d9c0933291ebdecfe6da49","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-pc-windows-msvc/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"12ce6fc57413d26b50227edfe7b72d7c","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-unknown-linux-gnu/client-clippy","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"9b7507adf87c628d91e9d70de04b7720","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795934999,"gate":"rust/x86_64-unknown-linux-gnu/client-dylint","host":"linux-x86_64","key":"0e8e445ec1e834d8d336e042133c258e039e1dbe23f3cd7c7f0f838940eac18d","lane":"client-lint","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":150,"stamp":"3ce012c85b79b22f2ced62f37303ddf4","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Ci-Attestation: {"at":1795935444,"gate":"rust/x86_64-unknown-linux-gnu/client-test","host":"linux-x86_64","key":"0bd362aea827853382fd8985e39e24dd96362d0abbed6361211eaef8ac9fbe05","lane":"client-test-x86_64-unknown-linux-gnu","parents":["1ea4006738c725ad760199fb4df748b9ac53e8b0"],"secs":366,"stamp":"9fa2459692f6296d02fed30fc121ba22","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36","v":1,"via":"run"} Client-Checks: {"checks":{"base":"90aaafe0a82b08af7550e9523bd756a3208d89b4","coverage":"all-tracked-applicable-files","diff":["libobs/build/libobs.core-source+.h.c","libobs/build/libobs.ported-source-audio-render-steps+.h.c","libobs/build/ported-source-sets/source-audio-render-steps.json","libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt","libobs/obs-source-audio-render-steps-fields.c.h","libobs/obs-source-audio-render-steps.c.h","libobs/obs-source.c.h","rust/README.md","rust/obs-build/tests/native.rs","rust/obs-build/tests/native/registration/canonical_source_audio_render_steps_swap_is_registered.rs","rust/obs-build/tests/native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs","rust/obs-c-oracle/oracle.d/source-audio-render-steps.list","rust/obs-c-oracle/oracle/audio_callback_links.c","rust/obs-c-oracle/oracle/source_audio_render_steps.c","rust/obs-source/src/audio_render_steps.rs","rust/obs-source/src/ffi/mod.rs","rust/obs-source/src/ffi/source_audio_render_steps.rs","rust/obs-source/src/lib.rs","rust/obs-source/tests/source/audio_render_steps.rs","rust/obs-source/tests/source/audio_render_steps_parity.rs","rust/obs-source/tests/source/main.rs","test/cmocka/build/test-graph.json","test/cmocka/test_source_audio_render_entry.c","test/cmocka/tests.d/test_source_audio_render_entry.cmake"],"head":"1647f328b2837f979c105b0f42ec986eefa2146e","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":"c902f950e25ca9f25b56db3c0881c8ec78688c62c4a581ad681963bc4967b71b","tree":"d8e36f0eda51337e83f7e7ce22915ac6e52f5c36"}} --- libobs/build/libobs.core-source+.h.c | 2 +- ...bobs.ported-source-audio-render-steps+.h.c | 4 + .../source-audio-render-steps.json | 5 + .../obs-source-source_audio_render_steps.txt | 4 + .../obs-source-audio-render-steps-fields.c.h | 172 +++++ rust/README.md | 1 + rust/obs-build/tests/native.rs | 2 + ...e_audio_render_steps_swap_is_registered.rs | 70 ++ .../oracle.d/source-audio-render-steps.list | 1 + .../oracle/audio_callback_links.c | 17 +- .../oracle/source_audio_render_steps.c | 493 +++++++++++++ rust/obs-source/src/audio_render_steps.rs | 127 +++- rust/obs-source/src/ffi/mod.rs | 1 + .../src/ffi/source_audio_render_steps.rs | 298 ++++++++ rust/obs-source/src/lib.rs | 6 +- .../tests/source/audio_render_steps_parity.rs | 665 ++++++++++++++++++ rust/obs-source/tests/source/main.rs | 1 + 17 files changed, 1846 insertions(+), 23 deletions(-) create mode 100644 libobs/build/libobs.ported-source-audio-render-steps+.h.c create mode 100644 libobs/build/ported-source-sets/source-audio-render-steps.json create mode 100644 libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt create mode 100644 libobs/obs-source-audio-render-steps-fields.c.h create mode 100644 rust/obs-build/tests/native/registration/canonical_source_audio_render_steps_swap_is_registered.rs create mode 100644 rust/obs-c-oracle/oracle.d/source-audio-render-steps.list create mode 100644 rust/obs-c-oracle/oracle/source_audio_render_steps.c create mode 100644 rust/obs-source/src/ffi/source_audio_render_steps.rs create mode 100644 rust/obs-source/tests/source/audio_render_steps_parity.rs diff --git a/libobs/build/libobs.core-source+.h.c b/libobs/build/libobs.core-source+.h.c index 9e0ee632ed..c6620ae033 100644 --- a/libobs/build/libobs.core-source+.h.c +++ b/libobs/build/libobs.core-source+.h.c @@ -65,7 +65,7 @@ #include "libobs/obs-source-audio-mixers-fields.c.h" #include "libobs/obs-source-audio-output-seam.c.h" #include "libobs/obs-source-audio-pending-speaker-layout-fields.c.h" -#include "libobs/obs-source-audio-render-steps.c.h" +#include "libobs/obs-source-audio-render-steps-fields.c.h" #include "libobs/obs-source-audio-settings-seam.c.h" #include "libobs/obs-source-audio-volume-apply-fields.c.h" #include "libobs/obs-source-base-size-fields.c.h" diff --git a/libobs/build/libobs.ported-source-audio-render-steps+.h.c b/libobs/build/libobs.ported-source-audio-render-steps+.h.c new file mode 100644 index 0000000000..c785efc5f9 --- /dev/null +++ b/libobs/build/libobs.ported-source-audio-render-steps+.h.c @@ -0,0 +1,4 @@ +/* Unity group (BUILD.md): original obs_source_audio_render and its steps for C reference. */ +#include "libobs/build/libobs.pch.h" + +#include "libobs/obs-source-audio-render-steps.c.h" diff --git a/libobs/build/ported-source-sets/source-audio-render-steps.json b/libobs/build/ported-source-sets/source-audio-render-steps.json new file mode 100644 index 0000000000..bab4368a32 --- /dev/null +++ b/libobs/build/ported-source-sets/source-audio-render-steps.json @@ -0,0 +1,5 @@ +{ + "LIBOBS_PORTED_SOURCES": [ + "build/libobs.ported-source-audio-render-steps+.h.c" + ] +} diff --git a/libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt b/libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt new file mode 100644 index 0000000000..ec666020c0 --- /dev/null +++ b/libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt @@ -0,0 +1,4 @@ +# obs-source-audio-render-steps.c.h (#5923): what the audio mix thread +# calls for each source on every tick, with its custom, submix and tick +# steps. Declared in obs-internal.h without EXPORT, so the shim stays hidden. +obs_source_audio_render diff --git a/libobs/obs-source-audio-render-steps-fields.c.h b/libobs/obs-source-audio-render-steps-fields.c.h new file mode 100644 index 0000000000..7106dcb00d --- /dev/null +++ b/libobs/obs-source-audio-render-steps-fields.c.h @@ -0,0 +1,172 @@ +#include "libobs/build/libobs.pch.h" + +/* Private adapters of the Rust obs_source_audio_render() (obs-internal.h, + * no EXPORT; obs-source::ffi::source_audio_render_steps, #5923), each one + * access of obs-source-audio-render-steps.c.h: the route's reads, the + * submix flag, audio_buf_mutex, audio_pending, audio_ts, audio_mixers and + * the input size, the buffers the callbacks get, the memsets, the peek and + * the memcpy, the two plugin callbacks, obs_source_apply_audio_volume() and + * obs_source_output_audio(). The callers pass a live source; the buffer + * adapters are reached only with its output (or mix) buffers, a mix below + * MAX_AUDIO_MIXES and a channel below MAX_AUDIO_CHANNELS. */ + +/* The Rust side mirrors the callbacks' buffer structs. */ +_Static_assert(MAX_AUDIO_MIXES == 6, "MAX_AUDIO_MIXES"); +_Static_assert(MAX_AUDIO_CHANNELS == 8, "MAX_AUDIO_CHANNELS"); +_Static_assert(sizeof(struct audio_output_data) == sizeof(float *) * MAX_AUDIO_CHANNELS, "audio_output_data"); +_Static_assert(sizeof(struct obs_source_audio_mix) == sizeof(struct audio_output_data) * MAX_AUDIO_MIXES, + "obs_source_audio_mix"); + +bool obs_source_audio_render_steps_has_output_buffer(const obs_source_t *source); +bool obs_source_audio_render_steps_has_output_buffer(const obs_source_t *source) +{ + return source->audio_output_buf[0][0] != NULL; +} + +bool obs_source_audio_render_steps_has_audio_render(const obs_source_t *source); +bool obs_source_audio_render_steps_has_audio_render(const obs_source_t *source) +{ + return source->info.audio_render != NULL; +} + +bool obs_source_audio_render_steps_has_context_data(const obs_source_t *source); +bool obs_source_audio_render_steps_has_context_data(const obs_source_t *source) +{ + return source->context.data != NULL; +} + +bool obs_source_audio_render_steps_has_audio_mix(const obs_source_t *source); +bool obs_source_audio_render_steps_has_audio_mix(const obs_source_t *source) +{ + return source->info.audio_mix != NULL; +} + +bool obs_source_audio_render_steps_is_submix(const obs_source_t *source); +bool obs_source_audio_render_steps_is_submix(const obs_source_t *source) +{ + return !!(source->info.output_flags & OBS_SOURCE_SUBMIX); +} + +void obs_source_audio_render_steps_lock(obs_source_t *source); +void obs_source_audio_render_steps_lock(obs_source_t *source) +{ + pthread_mutex_lock(&source->audio_buf_mutex); +} + +void obs_source_audio_render_steps_unlock(obs_source_t *source); +void obs_source_audio_render_steps_unlock(obs_source_t *source) +{ + pthread_mutex_unlock(&source->audio_buf_mutex); +} + +void obs_source_audio_render_steps_set_audio_pending(obs_source_t *source, bool pending); +void obs_source_audio_render_steps_set_audio_pending(obs_source_t *source, bool pending) +{ + source->audio_pending = pending; +} + +uint64_t obs_source_audio_render_steps_audio_ts(const obs_source_t *source); +uint64_t obs_source_audio_render_steps_audio_ts(const obs_source_t *source) +{ + return source->audio_ts; +} + +void obs_source_audio_render_steps_set_audio_ts(obs_source_t *source, uint64_t ts); +void obs_source_audio_render_steps_set_audio_ts(obs_source_t *source, uint64_t ts) +{ + source->audio_ts = ts; +} + +uint32_t obs_source_audio_render_steps_audio_mixers(const obs_source_t *source); +uint32_t obs_source_audio_render_steps_audio_mixers(const obs_source_t *source) +{ + return source->audio_mixers; +} + +size_t obs_source_audio_render_steps_input_size(const obs_source_t *source); +size_t obs_source_audio_render_steps_input_size(const obs_source_t *source) +{ + return source->audio_input_buf[0].size; +} + +float *obs_source_audio_render_steps_output_buf(obs_source_t *source, size_t mix, size_t channel); +float *obs_source_audio_render_steps_output_buf(obs_source_t *source, size_t mix, size_t channel) +{ + return source->audio_output_buf[mix][channel]; +} + +float *obs_source_audio_render_steps_mix_buf(obs_source_t *source, size_t channel); +float *obs_source_audio_render_steps_mix_buf(obs_source_t *source, size_t channel) +{ + return source->audio_mix_buf[channel]; +} + +void obs_source_audio_render_steps_clear_output(obs_source_t *source, size_t mix, size_t bytes); +void obs_source_audio_render_steps_clear_output(obs_source_t *source, size_t mix, size_t bytes) +{ + memset(source->audio_output_buf[mix][0], 0, bytes); +} + +void obs_source_audio_render_steps_clear_mix_buf(obs_source_t *source, size_t bytes); +void obs_source_audio_render_steps_clear_mix_buf(obs_source_t *source, size_t bytes) +{ + memset(source->audio_mix_buf[0], 0, bytes); +} + +void obs_source_audio_render_steps_peek_input(obs_source_t *source, size_t channel, size_t size); +void obs_source_audio_render_steps_peek_input(obs_source_t *source, size_t channel, size_t size) +{ + deque_peek_front(&source->audio_input_buf[channel], source->audio_output_buf[0][channel], size); +} + +void obs_source_audio_render_steps_copy_output(obs_source_t *source, size_t mix, size_t channel, size_t size); +void obs_source_audio_render_steps_copy_output(obs_source_t *source, size_t mix, size_t channel, size_t size) +{ + memcpy(source->audio_output_buf[mix][channel], source->audio_output_buf[0][channel], size); +} + +bool obs_source_audio_render_steps_audio_render(obs_source_t *source, uint64_t *ts, + struct obs_source_audio_mix *audio_data, uint32_t mixers, + size_t channels, size_t sample_rate); +bool obs_source_audio_render_steps_audio_render(obs_source_t *source, uint64_t *ts, + struct obs_source_audio_mix *audio_data, uint32_t mixers, + size_t channels, size_t sample_rate) +{ + return source->info.audio_render(source->context.data, ts, audio_data, mixers, channels, sample_rate); +} + +bool obs_source_audio_render_steps_audio_mix(obs_source_t *source, uint64_t *ts, struct audio_output_data *audio_data, + size_t channels, size_t sample_rate); +bool obs_source_audio_render_steps_audio_mix(obs_source_t *source, uint64_t *ts, struct audio_output_data *audio_data, + size_t channels, size_t sample_rate) +{ + return source->info.audio_mix(source->context.data, ts, audio_data, channels, sample_rate); +} + +void obs_source_audio_render_steps_apply_volume(obs_source_t *source, uint32_t mixers, size_t channels, + size_t sample_rate); +void obs_source_audio_render_steps_apply_volume(obs_source_t *source, uint32_t mixers, size_t channels, + size_t sample_rate) +{ + obs_source_apply_audio_volume(source, mixers, channels, sample_rate); +} + +/* audio_submix()'s hand-off: the planes as the callback left them. */ +void obs_source_audio_render_steps_output_audio(obs_source_t *source, const struct audio_output_data *audio_data, + size_t channels, size_t sample_rate, uint64_t ts); +void obs_source_audio_render_steps_output_audio(obs_source_t *source, const struct audio_output_data *audio_data, + size_t channels, size_t sample_rate, uint64_t ts) +{ + struct obs_source_audio audio = {0}; + + for (size_t i = 0; i < channels; i++) + audio.data[i] = (const uint8_t *)audio_data->data[i]; + + audio.samples_per_sec = (uint32_t)sample_rate; + audio.frames = AUDIO_OUTPUT_FRAMES; + audio.format = AUDIO_FORMAT_FLOAT_PLANAR; + audio.speakers = (enum speaker_layout)channels; + audio.timestamp = ts; + + obs_source_output_audio(source, &audio); +} diff --git a/rust/README.md b/rust/README.md index 876c0a723d..8564d143aa 100644 --- a/rust/README.md +++ b/rust/README.md @@ -446,6 +446,7 @@ The private output starting/encoder-demand queries use lazy safe Rust decisions | `libobs/obs-source-audio-place.c.h` | `obs-source::audio_place` | Swapped in hybrid `libobs` (group `libobs.ported-source-audio-place`). The source audio placement and action timeline, which every audio packet a source outputs and every tick with queued audio actions go through, as eleven functions on plain values, each asked where the C made the decision: `obs_source_audio_place_started()` and `_older()` (`audio_ts != 0` and `timestamp < audio_ts`: the reset of `source_output_audio_place()` with no `audio_ts` or an older packet, the push-back rule of `source_output_audio_data()` and the action clamp of `apply_audio_actions()`), `_size()`, `_offset()`, `_fits()` and `_pop_back()` (the packet's bytes, `frames * sizeof(float)`; its byte placement, `get_buf_placement()`'s `(size_t)util_mul_div64(timestamp - audio_ts, rate, 1e9) * sizeof(float)`; the drop when the place or the push back would pass `MAX_BUF_SIZE`; the bytes popped off the back of each channel after the place), `_outputs()` (nothing for `OBS_MONITORING_TYPE_MONITOR_ONLY`), `_action_frame()` (`conv_time_to_frames()`, which goes), `_action_stops()` (at `AUDIO_OUTPUT_FRAMES`), `_fill_end()` (how far the previous volume fills) and `_mix_on()` (the mixes the volume array multiplies). They are declared in `obs-source-audio-place.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps every read where it was, with the C's `&&` and `||` around the calls: `audio_ts` once or twice for the place's reset, again after `reset_audio_data()` for the placement, in the route only when `push_back` is set, and in the action loop once for the clamp, again when it applies and again for the frame; `monitoring_type` before `audio_ts`; each channel's size after its `deque_place()` and the first channel's before a push back; `audio_mixers` once per mix. It keeps `audio_buf_mutex` and `audio_actions_mutex`, `audio_output_get_channels()`, `get_buf_placement()` with its `audio_output_get_sample_rate()` call (the timestamps are read before it, as when their difference was its argument), `reset_audio_data()`, the deques, the `DEBUG_AUDIO` log, the stores of `last_audio_input_buf_size`, `da_erase()`, `apply_audio_action()`, every `get_source_volume()` call (before the loop and after each applied action, so each action's push-to-talk and push-to-mute state is seen), the volume array and `multiply_vol_data()`. The header mirrors `AUDIO_OUTPUT_FRAMES`, `MAX_BUF_SIZE` and `OBS_MONITORING_TYPE_MONITOR_ONLY`, and `obs-source.c.h` checks them and the enum's size. No pointer crosses. The arithmetic wraps where the C's does; the conversion is `obs-source::transition_render`'s `util_mul_div64()` per host. Kept, characterized, not endorsed: a packet or action less than one sample after `audio_ts` lands on frame 0, on top of the samples there; a packet larger than `MAX_BUF_SIZE` on its own is dropped whole; a push back checks only the first channel's size; an action before `audio_ts` applies at frame 0, and once one is at frame 1024 or later every later action waits, even a due one; a monitoring type outside the enum outputs. Intentional differences, on inputs libobs never passes: `_mix_on()` with a mix of 32 or more says no mix (the C's `int` shift is undefined from 31 on; libobs asks 0 to 5), and on MSVC x64 a frame count past 64 bits (a rate above 1e9 Hz), where the C's `_udiv128()` faults, saturates. `test_source_audio_place_steps` compiles the C into itself, and `test_source_audio_place_steps_rust` runs the same test source against `libobs_rust-static`; `test_async_delay_audio`, `test_audio_sync_offset_change`, `test_audio_clock_drift`, `test_audio_buffering_subsample`, `test_media_sync_offset_restart`, `test_audio_restart_resampler_tail`, `test_source_volume_mix`, `test_source_audio_ranges` and `test_audio_controls` see the swap through the real libobs. Tier 3 compares the oracle, the shims and the core: the header's values, the reset rules, the placement and the action frame over every pair of 30 special timestamps at 16 rates (to `u32::MAX`, and `size_t` rates for the frame), every frame edge to 2048 at eleven rates, the sizes over every pair and triple of 17 special values, every monitoring type from -100,000 to 100,000, the mix rule for every low 16-bit mask under eight high words at every mix to 30, the callers copied onto a stand-in source over 36,864 packet pairs and 21,316 action lists, and full-range proptests. | | `libobs/obs-source-audio-capture-callbacks.c.h` | `obs-source::audio_capture_callbacks` (shared ordered-pair update in `obs-source::callback_registry`) | Public audio-capture registration swapped in hybrid libobs (group `libobs.ported-source-audio-capture-callbacks`); append order and duplicates, first exact-pair removal, NULL callback/param entries and the exact NULL-source diagnostics preserved. The real private adapter (`obs-source-audio-capture-callback-fields.c.h`) keeps `audio_cb_mutex`, the C darray and its bmem storage; audio delivery and teardown are unchanged. `test_source_audio_capture_callbacks` compiles the C into itself, and `test_audio_capture_callbacks_rust` runs the same source against `libobs_rust-static` through the private `_rust` entries and the real adapter compiled over its recording mutex. Tier 3 compares generated operation sequences, both entry pairs, the diagnostics and real-header layouts against the original C. | None. | | `libobs/obs-source-audio-hotkeys.c.h` | `obs-source::audio_hotkeys`, shim in `obs-source::ffi::source_audio_hotkeys` | #5897: `obs_source_init_audio_hotkeys()` swapped in hybrid `libobs` (group `libobs.ported-source-audio-hotkeys`). `obs_source_create_internal()` calls it for every source that is not private (that check stays C). A source without `OBS_SOURCE_AUDIO` (its type then not read), or whose type is not `OBS_SOURCE_TYPE_INPUT`, stores `OBS_INVALID_HOTKEY_PAIR_ID` in `mute_unmute_key` and `monitor_on_off_key` and `OBS_INVALID_HOTKEY_ID` in `push_to_mute_key` and `push_to_talk_key` and registers nothing. An audio input registers the `libobs.mute`/`libobs.unmute` pair, the `libobs.monitor-on`/`libobs.monitor-off` pair, `libobs.push-to-mute` and `libobs.push-to-talk`, in that order, with the core's `obs->hotkeys` descriptions (NULL passed on), the source as owner and data, and stores each ID as it comes back (a failed registration's invalid ID too). Safe Rust core over an `AudioHotkeys` trait; the flags and type, the descriptions, the registrations with their static callbacks (reached through two hidden getters in `obs-source.c.h`) and the four fields stay behind `obs-source-audio-hotkeys-fields.c.h` (live group `libobs.core-source`, no `EXPORT`). The new `test_source_audio_hotkeys` (Linux) creates sources through the real core against hybrid and reference libraries: the six hotkeys of an audio input in order with their pairs, descriptions, data and stored IDs, each callback acting on the source; a video input, an audio filter, a private audio input and an unknown type register nothing. Tier 3 runs the original C and the Rust export on a noise-filled real-header source and private core with recording stand-ins for both registrations and the callback getters, over a grid of flags, types, NULL descriptions and noise plus a proptest, comparing every registration in order with its arguments and which fields were already stored, the four fields and every other byte; it rejects six mutants. No intentional differences; Tier 4 does not apply. | None. | +| `libobs/obs-source-audio-render-steps.c.h` | `obs-source::audio_render_steps`, shim in `obs-source::ffi::source_audio_render_steps` | #5923: swapped in hybrid `libobs` (group `libobs.ported-source-audio-render-steps`). `obs_source_audio_render()` and its three steps, `custom_audio_render()`, `audio_submix()` and `process_audio_source_tick()`, what the audio mix thread (`obs-audio.c` and the Rust `audio_callback()`) calls for each source on every tick, now the hidden Rust export (declared in `obs-internal.h` without `EXPORT`, hidden through `rust-hidden.d`). The output buffer, then `info.audio_render`, then `context.data`, each read only where the checks before reached it (432017b2c), into the plan's route: pending sets `audio_pending`; a custom render points the callback's buffers, clears each mix the plan says before (`audio_mixers` read once per mix), calls the plugin's `audio_render` outside the lock, then under `audio_buf_mutex` sets `audio_ts` and `audio_pending`, returns when pending or unmixed, clears the tick's mixes the source is not on and applies the volume; the tick runs `audio_submix()` when `info.audio_mix` is set (the mix buffer cleared, the plugin's `audio_mix`, and on success the planes as the callback left them to `obs_source_output_audio()` with the tick's rate, frames, layout and timestamp), then under the mutex pending without a timestamp or with short input (the size read only with a timestamp), else the peek into mix 0, mixes 1 to 5 copied or cleared, and the submix stop or the main mix's clear and the volume. Every decision is `obs-source::audio_render_plan`. Safe core over a `Host` trait; the fields, the mutex, the deques, the memsets and memcpys, the callbacks, `obs_source_apply_audio_volume()` and `obs_source_output_audio()` stay C in `obs-source-audio-render-steps-fields.c.h` (live group `libobs.core-source`, no `EXPORT`); the callbacks get a mirrored `struct obs_source_audio_mix` or `struct audio_output_data` whose slots past the tick's channels, uninitialized in the C, are null. The test binaries' link stand-in in `oracle/audio_callback_links.c` gave way to the export. The new `test_source_audio_render_entry` (Linux with OpenGL; the mix needs core video) runs against hybrid and reference libraries, one mix tick at a time through a custom render, an `audio_mix` source and a submix source under a composite parent: 23 cases of the clears before and after, failed and timestamp-less callbacks, the volume over mixer masks and mute, pending without a timestamp or with short or no input, the peek, copy and clear of each mix, the submix's mix 1 and stop, and a successful `audio_mix` block reaching `obs_source_output_audio()`. Tier 3 runs the original C (with the oracle's original plan) and the Rust export on real-layout sources through shared recorders of the lock, every memset, memcpy and peek, the volume, the output and both callbacks, with clobbers that rewrite `audio_mixers` and `audio_ts` mid-call, over every route against the masks, the pending checks with sizes and channel counts, odd sample rates and a proptest, comparing the fields, every sample's bits, the event log, the deques and every other byte; it rejects six mutants. No intentional differences; Tier 4 does not apply. | | `libobs/obs-source-audio-render.c.h` | `obs-source::audio_render_plan` | Swapped in hybrid `libobs` (group `libobs.ported-source-audio-render`). The audio render mix plan of `obs_source_audio_render()`, `custom_audio_render()` and `process_audio_source_tick()`, which decide for every audio source on every tick of the mix which mixes are cleared, copied and scaled, as thirteen functions on plain values: `obs_source_audio_render_route()` (pending without an output buffer, or for a custom render without data, 432017b2c and cf0a5e5c9; the custom render; else the tick), `_custom_clear_before()` (a mix in both masks is cleared before the plugin's `audio_render` callback), `_custom_ts()` and `_custom_pending()` (its timestamp when it succeeds, else 0 and pending), `_custom_unmixed()` (no timestamp or no tick mixers: nothing after it), `_custom_in_tick()` and `_custom_clear_after()` (a mix of the tick the source is not on is cleared after it, d6ac45702), `_tick_unset()` and `_tick_short()` (pending with no timestamp or less input than the tick, #130), `_tick_stop()` and `_tick_copy()` (mixes 1 to 5 copy mix 0 when in both masks, else are cleared; a submix source, `OBS_SOURCE_SUBMIX`, does mix 1 only, from bit 0 of its mixers), and `_tick_volume()` and `_tick_clear_main()` (a submix source stops there; any other clears mix 0 unless in both masks, then scales). They are declared in `obs-source-audio-render.h` without `EXPORT`, so the shims stay hidden. The plan is one function per decision, not one call per tick, because `obs-source.c.h` keeps each read where it was: `audio_mixers` (set by other threads without a lock) once per mix before and after the callback, the input size only with a timestamp, `audio_ts` only after a successful callback, and the output buffer, `audio_render` and `context.data` only where the checks before reached them. It keeps `audio_buf_mutex`, `deque_peek_front()`, every memset and memcpy, the plugin callbacks, `audio_submix()` and `apply_audio_volume()`. No pointer crosses; the route goes back as the C enum's value; the callback's `ts` crosses by value also when the callback failed and is not looked at. Kept, characterized, not endorsed: tick mixers past the six mixes (0x40 and up) are not "no mixers", so a custom render's clears look at each mix and its volume runs; a submix source keeps the peeked input in mix 0 even when it is on no mix, and fills mix 1 whatever the tick's mixers. Intentional difference: a mix of 31 or more for the shifting decisions, where the C's `int` shift is undefined, names bit 31 and then no mix (libobs passes a mix below 6). `test_source_audio_render_steps` compiles the C into itself, and `test_source_audio_render_steps_rust` runs the same test source against `libobs_rust-static`; `test_source_volume_mix`, `test_source_audio_ranges`, `test_audio_capture_mix_race`, `test_group_hide_transition_audio` and the transition audio tests see the swap through the real libobs. Tier 3 compares the oracle, the shims and the core: every mask decision over every pair of the low seven mask bits with and without the high ones and every mix up to 30, the submix copy and the stop over any index, the timestamp, pending and size decisions over every pair of 30 special values, the three callers copied onto a stand-in source over every combination of seven flags with every pair of the low seven mask bits and edge timestamps, masks, sizes and channels (the recorded lock, peeks, memsets, memcpys, callbacks and volume, `audio_ts` and `audio_pending`), and full-range proptests. | | `libobs/obs-source-audio-settings.c.h` | `obs-source::audio_settings`, shims in `obs-source-seam::ffi::source_audio_settings` | Swapped in hybrid `libobs` (group `libobs.ported-source-audio-settings`); Tier 3 in `obs-source-seam/tests/source_seam/audio_settings_parity.rs` | None. | | `libobs/obs-source-audio-timing.c.h` | `obs-source::audio_timing` | Swapped in hybrid `libobs` (group `libobs.ported-source-audio-timing`). The audio timestamp placement of `source_output_audio_data()`, in two pure steps around `audio_buf_mutex`: `obs_source_audio_timing_pre_lock()` (the direct timestamp check, then reset, jump, smooth with the drift error and the async decoupled re-anchor, or the log, and `next_audio_ts_min`) and `obs_source_audio_timing_under_lock()` (append or place, the reset when the system time jumped and the audio was not continuous, #522, the sync and resampler offsets, `next_audio_sys_ts_min`, and "the sync offset changed, so place", #333), plus `obs_source_audio_timing_buffer_start()` (where `reset_audio_data_at_sys_time()` starts an emptied buffer, #286). They are declared in `obs-source-audio-timing.h` without `EXPORT`, so the shims stay hidden. `obs-source.c.h` keeps the field reads and the stores, in their order (the volatile `timing_set` and `timing_adjust` included), the lock, `handle_ts_jump()`, `audio_resampler_set_compensation_error()`, `conv_frames_to_time()` (it passes the packet's duration, so nothing in the port divides), the deque, the signal, the muting and the log lines. The shims read the struct's input fields and write its output fields one at a time, so the inputs and the padding keep their bytes. Every sum and difference wraps as the C's `uint64_t` does; the drift error is `cast_signed()` and the sync offset `cast_unsigned()`, the C's conversions. The crate depends on no other crate. Kept, characterized, not endorsed: a timestamp ahead of the clock gives a `timing_adjust` near `u64::MAX`; `timestamp + timing_adjust`, the packet's end, a negative sync offset larger than the packet's system time and a resampler offset larger than it wrap; the distance is not modular; a direct timestamp more than 2 s from the expected one is logged, not a jump. Intentional difference: a null struct pointer does nothing (the C dereferences it; libobs passes one on its stack). `test_source_audio_timing_steps` compiles the C into itself, and `test_source_audio_timing_steps_rust` runs the same test source against `libobs_rust-static` (the first `_rust` variant since `test_scene_bounds_place_rust`: the `obs-source` member links on its own); `test_async_delay_audio`, `test_audio_sync_offset_change`, `test_media_sync_offset_restart`, `test_audio_restart_resampler_tail` and `test_audio_clock_drift` see the swap through the real libobs. Tier 3 compares every byte of the step structs (padding included, from a random fill) over the special values with every flag, proptests of each step, and 2-50-packet sequences through a model of the caller, with the written-back state. | diff --git a/rust/obs-build/tests/native.rs b/rust/obs-build/tests/native.rs index 15a638705e..eb1452ff51 100644 --- a/rust/obs-build/tests/native.rs +++ b/rust/obs-build/tests/native.rs @@ -49,6 +49,8 @@ mod canonical_source_audio_buffer_getters_swap_is_registered; mod canonical_source_audio_hotkeys_swap_is_registered; #[path = "native/registration/canonical_source_audio_pending_speaker_layout_swap_is_registered.rs"] mod canonical_source_audio_pending_speaker_layout_swap_is_registered; +#[path = "native/registration/canonical_source_audio_render_steps_swap_is_registered.rs"] +mod canonical_source_audio_render_steps_swap_is_registered; #[path = "native/registration/canonical_source_audio_volume_apply_swap_is_registered.rs"] mod canonical_source_audio_volume_apply_swap_is_registered; #[path = "native/registration/canonical_source_canvas_getter_swap_is_registered.rs"] diff --git a/rust/obs-build/tests/native/registration/canonical_source_audio_render_steps_swap_is_registered.rs b/rust/obs-build/tests/native/registration/canonical_source_audio_render_steps_swap_is_registered.rs new file mode 100644 index 0000000000..365a45671b --- /dev/null +++ b/rust/obs-build/tests/native/registration/canonical_source_audio_render_steps_swap_is_registered.rs @@ -0,0 +1,70 @@ +use super::*; + +#[test] +fn canonical_source_audio_render_steps_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_audio_render_entry"; + graph.targets.retain(|key, _| key == name); + graph.tests.retain(|key, _| key == name); + // The test compiles no copy of the steps: the audio mix of the real + // libobs reaches the hidden symbol (Rust in hybrid, the original C in + // the reference). The mix needs the OpenGL core, so only Linux selects + // it. + let selected = graph + .select(&[("OS_LINUX".into(), true), ("HAVE_OBS_OPENGL".into(), true)].into()) + .unwrap(); + assert!( + matches!(selected.targets[name].sources.as_slice(), [Source::Path(path)] + if path == "test/cmocka/test_source_audio_render_entry.c") + ); + assert!(selected.targets[name].definitions.is_empty()); + assert_eq!(selected.tests[name].target, name); + for os in ["OS_MACOS", "OS_WINDOWS"] { + let facts = [ + (os.into(), true), + ("OS_LINUX".into(), false), + ("HAVE_OBS_OPENGL".into(), true), + ]; + let selected = graph.select(&facts.into()).unwrap(); + assert!(selected.targets.is_empty(), "{os}"); + } + let ported = fs::read_to_string( + root.join("libobs/build/ported-source-sets/source-audio-render-steps.json"), + ) + .unwrap(); + assert!(ported.contains("build/libobs.ported-source-audio-render-steps+.h.c")); + let group = + fs::read_to_string(root.join("libobs/build/libobs.ported-source-audio-render-steps+.h.c")) + .unwrap(); + assert!(group.contains("#include \"libobs/obs-source-audio-render-steps.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-audio-render-steps.c.h\"")); + assert!(hybrid.contains("#include \"libobs/obs-source-audio-render-steps-fields.c.h\"")); + // obs-source.c.h keeps no copy of the entry or its steps. + let source = fs::read_to_string(root.join("libobs/obs-source.c.h")).unwrap(); + for step in [ + "void obs_source_audio_render(obs_source_t *source", + "custom_audio_render(obs_source_t *source", + "audio_submix(obs_source_t *source", + "process_audio_source_tick(obs_source_t *source", + ] { + assert!(!source.contains(step), "{step}"); + } + let hidden = fs::read_to_string( + root.join("libobs/cmake/rust-hidden.d/obs-source-source_audio_render_steps.txt"), + ) + .unwrap(); + let step = "obs_source_audio_render"; + assert!(hidden.lines().any(|line| line == step)); + // Hidden, not exported: obs-internal.h declares it without EXPORT. + for entry in fs::read_dir(root.join("libobs/cmake/rust-exports.d")).unwrap() { + let text = fs::read_to_string(entry.unwrap().path()).unwrap(); + assert!(!text.lines().any(|line| line == step)); + } + // The test binaries' link stand-in gave way to the Rust export. + let links = + fs::read_to_string(root.join("rust/obs-c-oracle/oracle/audio_callback_links.c")).unwrap(); + assert!(!links.contains("void obs_source_audio_render(")); +} diff --git a/rust/obs-c-oracle/oracle.d/source-audio-render-steps.list b/rust/obs-c-oracle/oracle.d/source-audio-render-steps.list new file mode 100644 index 0000000000..3880ef2a41 --- /dev/null +++ b/rust/obs-c-oracle/oracle.d/source-audio-render-steps.list @@ -0,0 +1 @@ +source-audio-render-steps.inc|libobs/obs-source-audio-render-steps.c.h|auto diff --git a/rust/obs-c-oracle/oracle/audio_callback_links.c b/rust/obs-c-oracle/oracle/audio_callback_links.c index 51210b2759..65aa8b9bfd 100644 --- a/rust/obs-c-oracle/oracle/audio_callback_links.c +++ b/rust/obs-c-oracle/oracle/audio_callback_links.c @@ -1,10 +1,12 @@ -/* Test-only link stand-in: obs_source_audio_render() under libobs's own - * name, for the test binaries that link the obs-core shims without libobs. +/* Test-only link notes for the test binaries that link the obs-core shims + * without libobs. * * The audio tick's shim (rust/obs-core/src/ffi/audio_callback.rs) exports * audio_callback(), whose libobs calls name it. The MSVC, MinGW and macOS * linkers want every symbol an object names resolved, used or not, so - * obs-tests-core needs a definition; libobs has the real ones. + * obs-tests-core needs a definition of each; libobs has the real ones. + * obs_source_audio_render() is the real Rust export of obs-source (#5923), + * whose adapters oracle/source_audio_render_steps.c compiles. * obs_source_active() is the real Rust export of obs-source (#5401), whose * counter adapters oracle/source_showing_active.c compiles, and * obs_source_removed() is its export too (#5587), whose flag adapter @@ -21,12 +23,3 @@ #include "obs.h" #include "obs-internal.h" - -void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size) -{ - UNUSED_PARAMETER(source); - UNUSED_PARAMETER(mixers); - UNUSED_PARAMETER(channels); - UNUSED_PARAMETER(sample_rate); - UNUSED_PARAMETER(size); -} diff --git a/rust/obs-c-oracle/oracle/source_audio_render_steps.c b/rust/obs-c-oracle/oracle/source_audio_render_steps.c new file mode 100644 index 0000000000..ee24e7c08c --- /dev/null +++ b/rust/obs-c-oracle/oracle/source_audio_render_steps.c @@ -0,0 +1,493 @@ +/* Tier 3: the unchanged extracted obs_source_audio_render() + * (libobs/obs-source-audio-render-steps.c.h: with custom_audio_render(), + * audio_submix() and process_audio_source_tick()), renamed oracle_*, + * against the Rust export, over the real source layout. The plan's + * decisions it calls are the oracle's original C (source_audio_render.c). + * + * The production adapters the Rust export calls + * (libobs/obs-source-audio-render-steps-fields.c.h) are compiled here under + * their real names, the one definition of each in the test binaries. Both + * they and the original go through the same recorders: audio_buf_mutex's + * lock and unlock, every memset and memcpy, deque_peek_front(), + * obs_source_apply_audio_volume() and obs_source_output_audio() log one + * event each, and the plugin callbacks the source carries log theirs and + * write a known pattern. With the clobber bits set, the recorders also + * rewrite audio_mixers and audio_ts as they go, so a field read in another + * place than the C's shows. The log is per thread. */ +#define _NO_CRT_STDIO_INLINE +#include +#include +#include "libobs/build/libobs.pch.h" + +#define RS_EVENTS 128 + +enum rs_kind { + RS_LOCK = 1, + RS_UNLOCK, + RS_OTHER_MUTEX, + RS_MEMSET, + RS_MEMCPY, + RS_PEEK, + RS_RENDER, + RS_RENDER_BUFS, + RS_MIX, + RS_MIX_BUFS, + RS_OUTPUT, + RS_OUTPUT_BUFS, + RS_VOLUME, +}; + +struct oracle_rs_event { + uint32_t kind; + uint64_t x[4]; +}; + +struct oracle_rs_log { + uint32_t events; + struct oracle_rs_event event[RS_EVENTS]; +}; + +/* What the callbacks return and how the recorders clobber: bit 0 the + * callbacks set audio_mixers and audio_ts, bit 1 each memset and memcpy + * rotates audio_mixers, bit 2 each lock flips audio_ts, bit 3 audio_mix + * moves plane 0 to plane 1's buffer. */ +struct oracle_rs_script { + bool render_ok; + uint64_t render_ts; + bool mix_ok; + uint64_t mix_ts; + uint32_t clobber; + uint32_t clob_mixers; + uint64_t clob_ts; +}; + +static THREAD_LOCAL struct obs_source *rs_watched; +static THREAD_LOCAL struct oracle_rs_log rs_log; +static THREAD_LOCAL struct oracle_rs_script rs_script; +static THREAD_LOCAL uint32_t rs_calls; + +#define RS_OUT_SAMPLES (AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS * MAX_AUDIO_MIXES) +#define RS_MIX_SAMPLES (AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS) + +static void rs_record(uint32_t kind, uint64_t a, uint64_t b, uint64_t c, uint64_t d) +{ + if (rs_log.events >= RS_EVENTS) + return; + struct oracle_rs_event *e = &rs_log.event[rs_log.events++]; + e->kind = kind; + e->x[0] = a; + e->x[1] = b; + e->x[2] = c; + e->x[3] = d; +} + +/* Where a pointer points: 1 the output buffers, 2 the mix buffer, each with + * the float offset; 0 NULL; 3 anything else. */ +static uint64_t rs_where(const void *p) +{ + if (!p) + return 0; + const char *c = p; + if (rs_watched && rs_watched->audio_output_buf[0][0]) { + const char *base = (const char *)rs_watched->audio_output_buf[0][0]; + if (c >= base && c < base + sizeof(float) * RS_OUT_SAMPLES) + return (1ULL << 32) | (uint64_t)(c - base); + } + if (rs_watched && rs_watched->audio_mix_buf[0]) { + const char *base = (const char *)rs_watched->audio_mix_buf[0]; + if (c >= base && c < base + sizeof(float) * RS_MIX_SAMPLES) + return (2ULL << 32) | (uint64_t)(c - base); + } + return 3ULL << 32; +} + +static uint64_t rs_hash(uint64_t h, uint64_t v) +{ + return (h ^ v) * 1099511628211ULL; +} + +static void rs_rotate_mixers(void) +{ + if (rs_watched && (rs_script.clobber & 2)) { + uint32_t m = rs_watched->audio_mixers; + rs_watched->audio_mixers = ((m << 1) | (m >> 5)) & 0x3f; + rs_watched->audio_mixers ^= 0x40; + } +} + +static int rs_mutex_lock(pthread_mutex_t *mutex) +{ + int ret = pthread_mutex_lock(mutex); + bool mine = rs_watched && mutex == &rs_watched->audio_buf_mutex; + rs_record(mine ? RS_LOCK : RS_OTHER_MUTEX, rs_watched ? rs_watched->audio_ts : 0, 0, 0, 0); + if (mine && (rs_script.clobber & 4)) + rs_watched->audio_ts ^= rs_script.clob_ts; + return ret; +} + +static int rs_mutex_unlock(pthread_mutex_t *mutex) +{ + bool mine = rs_watched && mutex == &rs_watched->audio_buf_mutex; + rs_record(mine ? RS_UNLOCK : RS_OTHER_MUTEX, rs_watched ? rs_watched->audio_pending : 0, + rs_watched ? rs_watched->audio_ts : 0, 0, 0); + return pthread_mutex_unlock(mutex); +} + +static void *rs_memset(void *dst, int value, size_t n) +{ + rs_record(RS_MEMSET, rs_where(dst), (uint64_t)value, n, 0); + void *ret = memset(dst, value, n); + rs_rotate_mixers(); + return ret; +} + +static void *rs_memcpy(void *dst, const void *src, size_t n) +{ + rs_record(RS_MEMCPY, rs_where(dst), rs_where(src), n, 0); + void *ret = memcpy(dst, src, n); + rs_rotate_mixers(); + return ret; +} + +static void rs_peek(struct deque *dq, void *data, size_t size) +{ + uint64_t channel = rs_watched ? (uint64_t)(dq - &rs_watched->audio_input_buf[0]) : 99; + rs_record(RS_PEEK, channel, rs_where(data), size, dq->size); + deque_peek_front(dq, data, size); +} + +/* obs_source_apply_audio_volume(): the call, and a mark in mix 0. */ +static void rs_apply_volume(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate) +{ + rs_record(RS_VOLUME, mixers, channels, sample_rate, source->audio_ts); + if (source->audio_output_buf[0][0]) + source->audio_output_buf[0][0][1] += 1000.0f; +} + +/* obs_source_output_audio(): every field of the block, and its planes. */ +static void rs_output_audio(obs_source_t *source, const struct obs_source_audio *audio) +{ + (void)source; + rs_record(RS_OUTPUT, audio->frames | ((uint64_t)audio->format << 32), (uint64_t)audio->speakers, + audio->samples_per_sec, audio->timestamp); + uint64_t h = 14695981039346656037ULL; + for (size_t i = 0; i < MAX_AV_PLANES; i++) + h = rs_hash(h, rs_where(audio->data[i])); + rs_record(RS_OUTPUT_BUFS, h, 0, 0, 0); +} + +#pragma push_macro("pthread_mutex_lock") +#pragma push_macro("pthread_mutex_unlock") +#pragma push_macro("memset") +#pragma push_macro("memcpy") +#undef pthread_mutex_lock +#undef pthread_mutex_unlock +#undef memset +#undef memcpy +#define pthread_mutex_lock rs_mutex_lock +#define pthread_mutex_unlock rs_mutex_unlock +#define memset rs_memset +#define memcpy rs_memcpy +#define deque_peek_front rs_peek +#define obs_source_apply_audio_volume rs_apply_volume +#define obs_source_output_audio rs_output_audio + +#define obs_source_audio_render oracle_obs_source_audio_render +#define obs_source_audio_render_route oracle_obs_source_audio_render_route +#define obs_source_audio_render_custom_clear_before oracle_obs_source_audio_render_custom_clear_before +#define obs_source_audio_render_custom_ts oracle_obs_source_audio_render_custom_ts +#define obs_source_audio_render_custom_pending oracle_obs_source_audio_render_custom_pending +#define obs_source_audio_render_custom_unmixed oracle_obs_source_audio_render_custom_unmixed +#define obs_source_audio_render_custom_in_tick oracle_obs_source_audio_render_custom_in_tick +#define obs_source_audio_render_custom_clear_after oracle_obs_source_audio_render_custom_clear_after +#define obs_source_audio_render_tick_unset oracle_obs_source_audio_render_tick_unset +#define obs_source_audio_render_tick_short oracle_obs_source_audio_render_tick_short +#define obs_source_audio_render_tick_stop oracle_obs_source_audio_render_tick_stop +#define obs_source_audio_render_tick_copy oracle_obs_source_audio_render_tick_copy +#define obs_source_audio_render_tick_volume oracle_obs_source_audio_render_tick_volume +#define obs_source_audio_render_tick_clear_main oracle_obs_source_audio_render_tick_clear_main + +void oracle_obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, + size_t size); +/* The route as its enum's underlying int: the rename above also renames the + * enum's tag. */ +unsigned oracle_obs_source_audio_render_route(bool has_buffer, bool custom, bool has_data); +bool oracle_obs_source_audio_render_custom_clear_before(uint32_t audio_mixers, uint32_t mixers, size_t mix); +uint64_t oracle_obs_source_audio_render_custom_ts(bool success, uint64_t ts); +bool oracle_obs_source_audio_render_custom_pending(bool success); +bool oracle_obs_source_audio_render_custom_unmixed(uint64_t audio_ts, uint32_t mixers); +bool oracle_obs_source_audio_render_custom_in_tick(uint32_t mixers, size_t mix); +bool oracle_obs_source_audio_render_custom_clear_after(uint32_t audio_mixers, size_t mix); +bool oracle_obs_source_audio_render_tick_unset(uint64_t audio_ts); +bool oracle_obs_source_audio_render_tick_short(size_t input_size, size_t size); +bool oracle_obs_source_audio_render_tick_stop(bool submix, size_t mix); +bool oracle_obs_source_audio_render_tick_copy(bool submix, uint32_t audio_mixers, uint32_t mixers, size_t mix); +bool oracle_obs_source_audio_render_tick_volume(bool submix); +bool oracle_obs_source_audio_render_tick_clear_main(uint32_t audio_mixers, uint32_t mixers); + +#include "source-audio-render-steps.inc" + +#undef obs_source_audio_render_tick_clear_main +#undef obs_source_audio_render_tick_volume +#undef obs_source_audio_render_tick_copy +#undef obs_source_audio_render_tick_stop +#undef obs_source_audio_render_tick_short +#undef obs_source_audio_render_tick_unset +#undef obs_source_audio_render_custom_clear_after +#undef obs_source_audio_render_custom_in_tick +#undef obs_source_audio_render_custom_unmixed +#undef obs_source_audio_render_custom_pending +#undef obs_source_audio_render_custom_ts +#undef obs_source_audio_render_custom_clear_before +#undef obs_source_audio_render_route +#undef obs_source_audio_render + +#include "source-audio-render-steps-fields.inc" + +#undef obs_source_output_audio +#undef obs_source_apply_audio_volume +#undef deque_peek_front +#undef memcpy +#undef memset +#undef pthread_mutex_unlock +#undef pthread_mutex_lock +#pragma pop_macro("memcpy") +#pragma pop_macro("memset") +#pragma pop_macro("pthread_mutex_unlock") +#pragma pop_macro("pthread_mutex_lock") + +/* ------------------------------------------------------------------------ */ +/* the callbacks */ + +static float rs_pattern(uint32_t call, size_t mix, size_t ch, size_t i) +{ + return (float)(call * 100000 + mix * 10000 + ch * 1000 + (i % 1000)) + 0.25f; +} + +static void rs_clobber_fields(obs_source_t *source) +{ + if (rs_script.clobber & 1) { + source->audio_mixers = rs_script.clob_mixers; + source->audio_ts = rs_script.clob_ts; + } +} + +static bool rs_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) +{ + obs_source_t *source = rs_watched; + uint32_t call = ++rs_calls; + rs_record(RS_RENDER, mixers, channels, sample_rate, (uint64_t)(uintptr_t)data); + uint64_t h = 14695981039346656037ULL; + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + for (size_t ch = 0; ch < channels && ch < MAX_AUDIO_CHANNELS; ch++) { + h = rs_hash(h, rs_where(audio->output[mix].data[ch])); + float *out = audio->output[mix].data[ch]; + for (size_t i = 0; i < AUDIO_OUTPUT_FRAMES; i += 7) + out[i] = rs_pattern(call, mix, ch, i); + } + } + rs_record(RS_RENDER_BUFS, h, 0, 0, 0); + if (source) + rs_clobber_fields(source); + *ts_out = rs_script.render_ts; + return rs_script.render_ok; +} + +static bool rs_mix(void *data, uint64_t *ts_out, struct audio_output_data *audio, size_t channels, size_t sample_rate) +{ + obs_source_t *source = rs_watched; + uint32_t call = ++rs_calls; + rs_record(RS_MIX, channels, sample_rate, (uint64_t)(uintptr_t)data, 0); + uint64_t h = 14695981039346656037ULL; + for (size_t ch = 0; ch < channels && ch < MAX_AUDIO_CHANNELS; ch++) { + h = rs_hash(h, rs_where(audio->data[ch])); + for (size_t i = 0; i < AUDIO_OUTPUT_FRAMES; i += 5) + audio->data[ch][i] = rs_pattern(call, 9, ch, i); + } + rs_record(RS_MIX_BUFS, h, 0, 0, 0); + if ((rs_script.clobber & 8) && channels > 1) + audio->data[0] = audio->data[1]; + if (source) + rs_clobber_fields(source); + *ts_out = rs_script.mix_ts; + return rs_script.mix_ok; +} + +/* ------------------------------------------------------------------------ */ +/* the fixtures */ + +/* The source's fields; the input is `input_bytes` of a pattern in every + * channel, after `input_skip` bytes pushed and taken (so the deque can + * wrap). Mirrored by the parity test. */ +struct oracle_rs_fields { + uint64_t audio_ts; + uint32_t audio_mixers; + uint32_t output_flags; + size_t input_bytes; + size_t input_skip; + bool has_output; + bool has_mix_buf; + bool audio_render; + bool audio_mix; + bool has_data; + bool audio_pending; +}; + +/* A zeroed source of the real layout, set to `f`, with its buffers (as + * allocate_audio_output_buffer() and allocate_audio_mix_buffer() lay them + * out) filled from `seed`. */ +struct obs_source *oracle_rs_source_new(const struct oracle_rs_fields *f, uint32_t seed); +struct obs_source *oracle_rs_source_new(const struct oracle_rs_fields *f, uint32_t seed) +{ + struct obs_source *source = bzalloc(sizeof(struct obs_source)); + uint32_t x = seed * 2654435761u + 1; + + if (f->has_output) { + float *ptr = bmalloc(sizeof(float) * RS_OUT_SAMPLES); + for (size_t i = 0; i < RS_OUT_SAMPLES; i++) { + x = x * 1664525u + 1013904223u; + ptr[i] = (float)(x >> 16) - 32768.0f; + } + for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { + size_t mix_pos = mix * AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS; + for (size_t i = 0; i < MAX_AUDIO_CHANNELS; i++) + source->audio_output_buf[mix][i] = ptr + mix_pos + AUDIO_OUTPUT_FRAMES * i; + } + } + if (f->has_mix_buf) { + float *ptr = bmalloc(sizeof(float) * RS_MIX_SAMPLES); + for (size_t i = 0; i < RS_MIX_SAMPLES; i++) { + x = x * 1664525u + 1013904223u; + ptr[i] = (float)(x >> 16) + 0.5f; + } + for (size_t i = 0; i < MAX_AUDIO_CHANNELS; i++) + source->audio_mix_buf[i] = ptr + AUDIO_OUTPUT_FRAMES * i; + } + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { + uint8_t byte = 0; + for (size_t i = 0; i < f->input_skip; i++) + deque_push_back(&source->audio_input_buf[ch], &byte, 1); + deque_pop_front(&source->audio_input_buf[ch], NULL, f->input_skip); + for (size_t i = 0; i < f->input_bytes; i++) { + byte = (uint8_t)(seed + 31 * ch + 7 * i); + deque_push_back(&source->audio_input_buf[ch], &byte, 1); + } + } + + source->audio_ts = f->audio_ts; + source->audio_mixers = f->audio_mixers; + source->audio_pending = f->audio_pending; + source->info.output_flags = f->output_flags; + source->info.audio_render = f->audio_render ? rs_render : NULL; + source->info.audio_mix = f->audio_mix ? rs_mix : NULL; + source->context.data = f->has_data ? (void *)(uintptr_t)0x5a5a0 : NULL; + pthread_mutex_init(&source->audio_buf_mutex, NULL); + return source; +} + +void oracle_rs_source_free(struct obs_source *source); +void oracle_rs_source_free(struct obs_source *source) +{ + if (rs_watched == source) + rs_watched = NULL; + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) + deque_free(&source->audio_input_buf[ch]); + pthread_mutex_destroy(&source->audio_buf_mutex); + bfree(source->audio_output_buf[0][0]); + bfree(source->audio_mix_buf[0]); + bfree(source); +} + +size_t oracle_rs_out_samples(void); +size_t oracle_rs_out_samples(void) +{ + return RS_OUT_SAMPLES; +} + +size_t oracle_rs_mix_samples(void); +size_t oracle_rs_mix_samples(void) +{ + return RS_MIX_SAMPLES; +} + +/* The fields back, and the buffers when the source has them. */ +void oracle_rs_get(const struct obs_source *source, struct oracle_rs_fields *f, float *out, float *mix); +void oracle_rs_get(const struct obs_source *source, struct oracle_rs_fields *f, float *out, float *mix) +{ + f->audio_ts = source->audio_ts; + f->audio_mixers = source->audio_mixers; + f->audio_pending = source->audio_pending; + f->input_bytes = source->audio_input_buf[0].size; + if (source->audio_output_buf[0][0]) + memcpy(out, source->audio_output_buf[0][0], sizeof(float) * RS_OUT_SAMPLES); + if (source->audio_mix_buf[0]) + memcpy(mix, source->audio_mix_buf[0], sizeof(float) * RS_MIX_SAMPLES); +} + +/* Whether the two sources are byte for byte the same outside their own + * allocations: the buffer pointers, the deques and the mutex are taken from + * `a`, and the deques' positions and queued bytes must match. */ +bool oracle_rs_same(const struct obs_source *a, const struct obs_source *b); +bool oracle_rs_same(const struct obs_source *a, const struct obs_source *b) +{ + for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { + const struct deque *x = &a->audio_input_buf[ch]; + const struct deque *y = &b->audio_input_buf[ch]; + if (x->size != y->size || x->start_pos != y->start_pos || x->end_pos != y->end_pos || + x->capacity != y->capacity) + return false; + if (!x->size) + continue; + /* the bytes queued, not the unwritten rest of the allocation */ + uint8_t *bx = bmalloc(x->size); + uint8_t *by = bmalloc(y->size); + struct deque cx = *x; + struct deque cy = *y; + deque_peek_front(&cx, bx, x->size); + deque_peek_front(&cy, by, y->size); + bool same = memcmp(bx, by, x->size) == 0; + bfree(bx); + bfree(by); + if (!same) + return false; + } + struct obs_source *x = bmemdup(a, sizeof(*a)); + struct obs_source *y = bmemdup(b, sizeof(*b)); + memcpy(y->audio_output_buf, x->audio_output_buf, sizeof(x->audio_output_buf)); + memcpy(y->audio_mix_buf, x->audio_mix_buf, sizeof(x->audio_mix_buf)); + memcpy(y->audio_input_buf, x->audio_input_buf, sizeof(x->audio_input_buf)); + memcpy(&y->audio_buf_mutex, &x->audio_buf_mutex, sizeof(x->audio_buf_mutex)); + bool same = memcmp(x, y, sizeof(*x)) == 0; + bfree(x); + bfree(y); + return same; +} + +/* Watch `source` on this thread with `script`, and clear the log. */ +void oracle_rs_watch(struct obs_source *source, const struct oracle_rs_script *script); +void oracle_rs_watch(struct obs_source *source, const struct oracle_rs_script *script) +{ + rs_watched = source; + if (script) + rs_script = *script; + else + memset(&rs_script, 0, sizeof(rs_script)); + rs_calls = 0; + memset(&rs_log, 0, sizeof(rs_log)); +} + +/* This thread's log since the last watch; clears it. */ +void oracle_rs_log(struct oracle_rs_log *out); +void oracle_rs_log(struct oracle_rs_log *out) +{ + *out = rs_log; + memset(&rs_log, 0, sizeof(rs_log)); +} + +/* The original, as the C reference runs it. */ +void oracle_rs_render(struct obs_source *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size); +void oracle_rs_render(struct obs_source *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size) +{ + oracle_obs_source_audio_render(source, mixers, channels, sample_rate, size); +} diff --git a/rust/obs-source/src/audio_render_steps.rs b/rust/obs-source/src/audio_render_steps.rs index 3708f1f6fd..4a70758b9f 100644 --- a/rust/obs-source/src/audio_render_steps.rs +++ b/rust/obs-source/src/audio_render_steps.rs @@ -47,7 +47,7 @@ clippy::unreachable )] -use crate::audio_render_plan as plan; +use crate::audio_render_plan::{self as plan, Route}; /// `MAX_AUDIO_MIXES`. pub const MAX_AUDIO_MIXES: usize = plan::MAX_AUDIO_MIXES; @@ -157,14 +157,62 @@ pub fn custom_audio_render( channels: usize, sample_rate: usize, ) { - let _ = (host, source, mixers, channels, sample_rate); - todo!() + let mut data = host.new_mix(); + let bytes = CHANNEL_BYTES.wrapping_mul(channels); + + for mix in 0..MAX_AUDIO_MIXES { + for channel in 0..channels { + host.point_output(source, &mut data, mix, channel); + } + + if plan::custom_clear_before(host.audio_mixers(source), mixers, mix) { + host.clear_output(source, mix, bytes); + } + } + + let (success, ts) = host.audio_render(source, &mut data, mixers, channels, sample_rate); + // The callback may render other sources or submit capture audio. + host.lock(source); + // ts is passed but not used when the callback failed. + host.set_audio_ts(source, plan::custom_ts(success, ts)); + host.set_audio_pending(source, plan::custom_pending(success)); + + if plan::custom_pending(success) || plan::custom_unmixed(host.audio_ts(source), mixers) { + host.unlock(source); + return; + } + + for mix in 0..MAX_AUDIO_MIXES { + if !plan::custom_in_tick(mixers, mix) { + continue; + } + + if plan::custom_clear_after(host.audio_mixers(source), mix) { + host.clear_output(source, mix, bytes); + } + } + + host.apply_volume(source, mixers, channels, sample_rate); + host.unlock(source); } /// `audio_submix(source, channels, sample_rate)`. pub fn audio_submix(host: &H, source: H::Source, channels: usize, sample_rate: usize) { - let _ = (host, source, channels, sample_rate); - todo!() + let mut data = host.new_planes(); + + for channel in 0..channels { + host.point_plane(source, &mut data, channel); + } + + host.clear_mix_buffer(source, CHANNEL_BYTES.wrapping_mul(channels)); + + let (success, ts) = host.audio_mix(source, &mut data, channels, sample_rate); + + if !success { + return; + } + + host.output_audio(source, &data, channels, sample_rate, ts); } /// `process_audio_source_tick(source, mixers, channels, sample_rate, size)`. @@ -176,8 +224,50 @@ pub fn process_audio_source_tick( sample_rate: usize, size: usize, ) { - let _ = (host, source, mixers, channels, sample_rate, size); - todo!() + let submix = host.is_submix(source); + let bytes = size.wrapping_mul(channels); + + host.lock(source); + + // The input size is read only with a timestamp, as the C's `||` does. + if plan::tick_unset(host.audio_ts(source)) || plan::tick_short(host.input_size(source), size) { + host.set_audio_pending(source, true); + host.unlock(source); + return; + } + + for channel in 0..channels { + host.peek_input(source, channel, size); + } + + for mix in 1..MAX_AUDIO_MIXES { + if plan::tick_stop(submix, mix) { + break; + } + + if !plan::tick_copy(submix, host.audio_mixers(source), mixers, mix) { + host.clear_output(source, mix, bytes); + continue; + } + + for channel in 0..channels { + host.copy_output(source, mix, channel, size); + } + } + + if !plan::tick_volume(submix) { + host.set_audio_pending(source, false); + host.unlock(source); + return; + } + + if plan::tick_clear_main(host.audio_mixers(source), mixers) { + host.clear_output(source, 0, bytes); + } + + host.apply_volume(source, mixers, channels, sample_rate); + host.set_audio_pending(source, false); + host.unlock(source); } /// `obs_source_audio_render(source, mixers, channels, sample_rate, size)`. @@ -189,6 +279,25 @@ pub fn audio_render( sample_rate: usize, size: usize, ) { - let _ = (host, source, mixers, channels, sample_rate, size); - todo!() + let has_buffer = host.has_output_buffer(source); + let custom = has_buffer && host.has_audio_render(source); + let has_data = custom && host.has_context_data(source); + + match plan::route(has_buffer, custom, has_data) { + Route::Pending => { + host.set_audio_pending(source, true); + return; + } + Route::Custom => { + custom_audio_render(host, source, mixers, channels, sample_rate); + return; + } + Route::Tick => {} + } + + if host.has_audio_mix(source) { + audio_submix(host, source, channels, sample_rate); + } + + process_audio_source_tick(host, source, mixers, channels, sample_rate, size); } diff --git a/rust/obs-source/src/ffi/mod.rs b/rust/obs-source/src/ffi/mod.rs index 6dd83ae3c0..7891bf1314 100644 --- a/rust/obs-source/src/ffi/mod.rs +++ b/rust/obs-source/src/ffi/mod.rs @@ -21,6 +21,7 @@ pub mod source_audio_pause_callbacks; pub mod source_audio_pending_speaker_layout; pub mod source_audio_place; pub mod source_audio_render; +pub mod source_audio_render_steps; pub mod source_audio_timing; pub mod source_audio_volume_apply; pub mod source_base_size; diff --git a/rust/obs-source/src/ffi/source_audio_render_steps.rs b/rust/obs-source/src/ffi/source_audio_render_steps.rs new file mode 100644 index 0000000000..429bfa1aff --- /dev/null +++ b/rust/obs-source/src/ffi/source_audio_render_steps.rs @@ -0,0 +1,298 @@ +//! C ABI for `libobs/obs-source-audio-render-steps.c.h`: +//! `obs_source_audio_render()`, what the audio mix thread (`obs-audio.c` +//! and the Rust `audio_callback()`) calls for each source on every tick, +//! with its custom, submix and tick steps. Declared in `obs-internal.h` +//! without `EXPORT`, so the shim stays hidden (`rust-hidden.d`). +//! +//! Runs the safe core ([`crate::audio_render_steps`]) over the C-owned +//! source: every field, `audio_buf_mutex`, the buffers, the input deques, +//! the memsets, the peek and the memcpy, the plugin's `audio_render` and +//! `audio_mix`, `obs_source_apply_audio_volume()` and +//! `obs_source_output_audio()` are one access each through the adapters of +//! `obs-source-audio-render-steps-fields.c.h`. The callbacks get a +//! `struct obs_source_audio_mix` or `struct audio_output_data` mirrored +//! here; the slots past the tick's channels, which the C leaves +//! uninitialized, are null. Like the C, nothing checks the source: the +//! callers pass a live one. +//! +//! No intentional differences from C. + +use core::ffi::c_void; + +use crate::audio_render_steps::{self, Host, MAX_AUDIO_MIXES}; + +/// `MAX_AUDIO_CHANNELS` (checked in the adapters). +pub const MAX_AUDIO_CHANNELS: usize = 8; + +/// `struct audio_output_data`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct AudioOutputData { + /// `float *data[MAX_AUDIO_CHANNELS]`. + pub data: [*mut f32; MAX_AUDIO_CHANNELS], +} + +/// `struct obs_source_audio_mix`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct AudioMix { + /// `struct audio_output_data output[MAX_AUDIO_MIXES]`. + pub output: [AudioOutputData; MAX_AUDIO_MIXES], +} + +const NO_PLANES: AudioOutputData = AudioOutputData { + data: [core::ptr::null_mut(); MAX_AUDIO_CHANNELS], +}; + +unsafe extern "C" { + fn obs_source_audio_render_steps_has_output_buffer(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_audio_render(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_context_data(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_audio_mix(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_is_submix(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_lock(source: *mut c_void); + fn obs_source_audio_render_steps_unlock(source: *mut c_void); + fn obs_source_audio_render_steps_set_audio_pending(source: *mut c_void, pending: bool); + fn obs_source_audio_render_steps_audio_ts(source: *const c_void) -> u64; + fn obs_source_audio_render_steps_set_audio_ts(source: *mut c_void, ts: u64); + fn obs_source_audio_render_steps_audio_mixers(source: *const c_void) -> u32; + fn obs_source_audio_render_steps_input_size(source: *const c_void) -> usize; + fn obs_source_audio_render_steps_output_buf( + source: *mut c_void, + mix: usize, + channel: usize, + ) -> *mut f32; + fn obs_source_audio_render_steps_mix_buf(source: *mut c_void, channel: usize) -> *mut f32; + fn obs_source_audio_render_steps_clear_output(source: *mut c_void, mix: usize, bytes: usize); + fn obs_source_audio_render_steps_clear_mix_buf(source: *mut c_void, bytes: usize); + fn obs_source_audio_render_steps_peek_input(source: *mut c_void, channel: usize, size: usize); + fn obs_source_audio_render_steps_copy_output( + source: *mut c_void, + mix: usize, + channel: usize, + size: usize, + ); + fn obs_source_audio_render_steps_audio_render( + source: *mut c_void, + ts: *mut u64, + audio_data: *mut AudioMix, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> bool; + fn obs_source_audio_render_steps_audio_mix( + source: *mut c_void, + ts: *mut u64, + audio_data: *mut AudioOutputData, + channels: usize, + sample_rate: usize, + ) -> bool; + fn obs_source_audio_render_steps_apply_volume( + source: *mut c_void, + mixers: u32, + channels: usize, + sample_rate: usize, + ); + fn obs_source_audio_render_steps_output_audio( + source: *mut c_void, + audio_data: *const AudioOutputData, + channels: usize, + sample_rate: usize, + ts: u64, + ); +} + +/// The caller's live source. +#[derive(Clone, Copy)] +struct Source(*mut c_void); + +/// The live libobs source the caller hands over. +struct Libobs; + +// SAFETY (every method): `source` is the caller's live, non-null source; +// the buffer methods run only on the routes that found its output buffer +// (and, for the submix, its `audio_mix`, which comes with the mix buffer), +// with a mix below MAX_AUDIO_MIXES and channels at most MAX_AUDIO_CHANNELS, +// as libobs calls it. +impl Host for Libobs { + type Source = Source; + type Mix = AudioMix; + type Planes = AudioOutputData; + + fn has_output_buffer(&self, source: Source) -> bool { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_has_output_buffer(source.0) } + } + fn has_audio_render(&self, source: Source) -> bool { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_has_audio_render(source.0) } + } + fn has_context_data(&self, source: Source) -> bool { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_has_context_data(source.0) } + } + fn has_audio_mix(&self, source: Source) -> bool { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_has_audio_mix(source.0) } + } + fn is_submix(&self, source: Source) -> bool { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_is_submix(source.0) } + } + fn lock(&self, source: Source) { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_lock(source.0) } + } + fn unlock(&self, source: Source) { + // SAFETY: a live source whose mutex this thread holds. + unsafe { obs_source_audio_render_steps_unlock(source.0) } + } + fn set_audio_pending(&self, source: Source, pending: bool) { + // SAFETY: a live source. + unsafe { obs_source_audio_render_steps_set_audio_pending(source.0, pending) } + } + fn audio_ts(&self, source: Source) -> u64 { + // SAFETY: a live source; audio_buf_mutex held. + unsafe { obs_source_audio_render_steps_audio_ts(source.0) } + } + fn set_audio_ts(&self, source: Source, ts: u64) { + // SAFETY: a live source; audio_buf_mutex held. + unsafe { obs_source_audio_render_steps_set_audio_ts(source.0, ts) } + } + fn audio_mixers(&self, source: Source) -> u32 { + // SAFETY: a live source; read without a lock, as in the C. + unsafe { obs_source_audio_render_steps_audio_mixers(source.0) } + } + fn input_size(&self, source: Source) -> usize { + // SAFETY: a live source; audio_buf_mutex held. + unsafe { obs_source_audio_render_steps_input_size(source.0) } + } + fn new_mix(&self) -> AudioMix { + AudioMix { + output: [NO_PLANES; MAX_AUDIO_MIXES], + } + } + fn point_output(&self, source: Source, data: &mut AudioMix, mix: usize, channel: usize) { + if let Some(slot) = data + .output + .get_mut(mix) + .and_then(|planes| planes.data.get_mut(channel)) + { + // SAFETY: a live source; mix and channel in range. + *slot = unsafe { obs_source_audio_render_steps_output_buf(source.0, mix, channel) }; + } + } + fn clear_output(&self, source: Source, mix: usize, bytes: usize) { + // SAFETY: a live source with its output buffers; the C's count. + unsafe { obs_source_audio_render_steps_clear_output(source.0, mix, bytes) } + } + fn audio_render( + &self, + source: Source, + data: &mut AudioMix, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + let mut ts = 0_u64; + // SAFETY: a live source with an audio_render callback and data; the + // buffers and ts outlive the call. + let success = unsafe { + obs_source_audio_render_steps_audio_render( + source.0, + &raw mut ts, + core::ptr::from_mut(data), + mixers, + channels, + sample_rate, + ) + }; + (success, ts) + } + fn apply_volume(&self, source: Source, mixers: u32, channels: usize, sample_rate: usize) { + // SAFETY: a live source with its output buffers; audio_buf_mutex + // held. + unsafe { + obs_source_audio_render_steps_apply_volume(source.0, mixers, channels, sample_rate) + } + } + fn new_planes(&self) -> AudioOutputData { + NO_PLANES + } + fn point_plane(&self, source: Source, data: &mut AudioOutputData, channel: usize) { + if let Some(slot) = data.data.get_mut(channel) { + // SAFETY: a live source; channel in range. + *slot = unsafe { obs_source_audio_render_steps_mix_buf(source.0, channel) }; + } + } + fn clear_mix_buffer(&self, source: Source, bytes: usize) { + // SAFETY: a live source with its mix buffer; the C's count. + unsafe { obs_source_audio_render_steps_clear_mix_buf(source.0, bytes) } + } + fn audio_mix( + &self, + source: Source, + data: &mut AudioOutputData, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + let mut ts = 0_u64; + // SAFETY: a live source with an audio_mix callback; the planes and + // ts outlive the call. + let success = unsafe { + obs_source_audio_render_steps_audio_mix( + source.0, + &raw mut ts, + core::ptr::from_mut(data), + channels, + sample_rate, + ) + }; + (success, ts) + } + fn output_audio( + &self, + source: Source, + data: &AudioOutputData, + channels: usize, + sample_rate: usize, + ts: u64, + ) { + // SAFETY: a live source; the planes as the callback left them. + unsafe { + obs_source_audio_render_steps_output_audio( + source.0, + core::ptr::from_ref(data), + channels, + sample_rate, + ts, + ); + } + } + fn peek_input(&self, source: Source, channel: usize, size: usize) { + // SAFETY: a live source with its output buffers; the input holds at + // least `size` bytes (the tick checked channel 0, as the C does). + unsafe { obs_source_audio_render_steps_peek_input(source.0, channel, size) } + } + fn copy_output(&self, source: Source, mix: usize, channel: usize, size: usize) { + // SAFETY: a live source with its output buffers; the C's count. + unsafe { obs_source_audio_render_steps_copy_output(source.0, mix, channel, size) } + } +} + +/// `obs_source_audio_render(source, mixers, channels, sample_rate, size)`. +/// +/// # Safety +/// `source` is a live source, `channels` at most `MAX_AUDIO_CHANNELS` and +/// `size` at most `AUDIO_OUTPUT_FRAMES * sizeof(float)`, as the audio mix +/// calls it. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn obs_source_audio_render( + source: *mut c_void, + mixers: u32, + channels: usize, + sample_rate: usize, + size: usize, +) { + audio_render_steps::audio_render(&Libobs, Source(source), mixers, channels, sample_rate, size); +} diff --git a/rust/obs-source/src/lib.rs b/rust/obs-source/src/lib.rs index 7540028773..abbb0341ba 100644 --- a/rust/obs-source/src/lib.rs +++ b/rust/obs-source/src/lib.rs @@ -33,6 +33,10 @@ //! `libobs/obs-source-audio-render.c.h`, the audio render mix plan of //! `obs_source_audio_render()`, `custom_audio_render()` and //! `process_audio_source_tick()`; +//! `libobs/obs-source-audio-render-steps.c.h`, the hidden +//! `obs_source_audio_render()` with `custom_audio_render()`, +//! `audio_submix()` and `process_audio_source_tick()` (every field, the +//! lock, the buffers and the callbacks stay in a C fields adapter); //! `libobs/obs-source-audio-volume-apply.c.h`, the hidden //! `obs_source_apply_audio_volume()` and `apply_audio_actions()` (every //! field, the action queue and its mutex and the buffers stay in a C fields @@ -259,7 +263,7 @@ //! The safe cores are [`async_filter`], [`async_pacing`], [`async_upload`], [`audio_input`], //! [`audio_input_path`], //! [`audio_output`], [`audio_place`], -//! [`audio_render_plan`], [`audio_timing`], [`audio_volume_apply`], +//! [`audio_render_plan`], [`audio_render_steps`], [`audio_timing`], [`audio_volume_apply`], //! [`color_space`], [`conversion_plan`], [`deinterlace`], [`deinterlace_draw`], //! [`deinterlace_pacing`], [`deinterlace_select`], [`draw_plan`], [`source_draw`], [`filter_backup`], [`frame_copy`], [`media_admission`], [`monitoring`], [`muted_volume`], [`own_clock_drift`] (new code with no C original, #4182), [`ptm_gate`], [`render_route`], [`set_name`], [`size_route`], [`source_duplicate`], [`source_filter_chain`], //! [`transition_access`], [`transition_audio`], [`transition_clock`], [`transition_load`], [`transition_render`], diff --git a/rust/obs-source/tests/source/audio_render_steps_parity.rs b/rust/obs-source/tests/source/audio_render_steps_parity.rs new file mode 100644 index 0000000000..ccfac5fbad --- /dev/null +++ b/rust/obs-source/tests/source/audio_render_steps_parity.rs @@ -0,0 +1,665 @@ +//! Tier 3: the original C `obs_source_audio_render()` +//! (`source_audio_render_steps.c`, the extracted file compiled renamed, with +//! `custom_audio_render()`, `audio_submix()`, `process_audio_source_tick()` +//! and the oracle's original plan decisions) against the Rust export, each +//! call on its own real-layout source set to the same fields, buffers and +//! input. Both sides go through the oracle's recorders: `audio_buf_mutex`'s +//! lock and unlock, every memset and memcpy, `deque_peek_front()`, +//! `obs_source_apply_audio_volume()`, `obs_source_output_audio()` (every +//! field of the block and its planes) and the plugin's `audio_render` and +//! `audio_mix` (their arguments, the buffers they get, and a pattern they +//! write). With the clobber bits set, the callbacks rewrite `audio_mixers` +//! and `audio_ts`, every memset and memcpy rotates `audio_mixers`, every +//! lock flips `audio_ts`, and `audio_mix` moves a plane, so a field read in +//! another place than the C's changes the outcome. The fields after the +//! call, every sample of the output and mix buffers by its bits, the event +//! log, the deques and every other byte of the source must match, over a +//! grid of routes, masks and clobbers, a grid of the pending checks with +//! sizes and channel counts, and a proptest. Six mutants, built on the same +//! adapters and the same safe core, must not. +//! No intentional differences or exclusions. + +use core::ffi::c_void; + +use obs_source::audio_render_steps::{self, Host, MAX_AUDIO_MIXES}; +use obs_source::ffi::source_audio_render_steps::{self as rust, AudioMix, AudioOutputData}; +use proptest::prelude::*; + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Fields { + audio_ts: u64, + audio_mixers: u32, + output_flags: u32, + input_bytes: usize, + input_skip: usize, + has_output: bool, + has_mix_buf: bool, + audio_render: bool, + audio_mix: bool, + has_data: bool, + audio_pending: bool, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +struct Script { + render_ok: bool, + render_ts: u64, + mix_ok: bool, + mix_ts: u64, + clobber: u32, + clob_mixers: u32, + clob_ts: u64, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct Event { + kind: u32, + x: [u64; 4], +} + +const EVENTS: usize = 128; + +#[repr(C)] +struct Log { + events: u32, + event: [Event; EVENTS], +} + +unsafe extern "C" { + fn oracle_rs_source_new(fields: *const Fields, seed: u32) -> *mut c_void; + fn oracle_rs_source_free(source: *mut c_void); + fn oracle_rs_out_samples() -> usize; + fn oracle_rs_mix_samples() -> usize; + fn oracle_rs_get(source: *const c_void, fields: *mut Fields, out: *mut f32, mix: *mut f32); + fn oracle_rs_same(a: *const c_void, b: *const c_void) -> bool; + fn oracle_rs_watch(source: *mut c_void, script: *const Script); + fn oracle_rs_log(out: *mut Log); + fn oracle_rs_render( + source: *mut c_void, + mixers: u32, + channels: usize, + sample_rate: usize, + size: usize, + ); + + // The production adapters, for the mutants. + fn obs_source_audio_render_steps_has_output_buffer(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_audio_render(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_context_data(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_has_audio_mix(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_is_submix(source: *const c_void) -> bool; + fn obs_source_audio_render_steps_lock(source: *mut c_void); + fn obs_source_audio_render_steps_unlock(source: *mut c_void); + fn obs_source_audio_render_steps_set_audio_pending(source: *mut c_void, pending: bool); + fn obs_source_audio_render_steps_audio_ts(source: *const c_void) -> u64; + fn obs_source_audio_render_steps_set_audio_ts(source: *mut c_void, ts: u64); + fn obs_source_audio_render_steps_audio_mixers(source: *const c_void) -> u32; + fn obs_source_audio_render_steps_input_size(source: *const c_void) -> usize; + fn obs_source_audio_render_steps_output_buf( + source: *mut c_void, + mix: usize, + channel: usize, + ) -> *mut f32; + fn obs_source_audio_render_steps_mix_buf(source: *mut c_void, channel: usize) -> *mut f32; + fn obs_source_audio_render_steps_clear_output(source: *mut c_void, mix: usize, bytes: usize); + fn obs_source_audio_render_steps_clear_mix_buf(source: *mut c_void, bytes: usize); + fn obs_source_audio_render_steps_peek_input(source: *mut c_void, channel: usize, size: usize); + fn obs_source_audio_render_steps_copy_output( + source: *mut c_void, + mix: usize, + channel: usize, + size: usize, + ); + fn obs_source_audio_render_steps_audio_render( + source: *mut c_void, + ts: *mut u64, + audio_data: *mut AudioMix, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> bool; + fn obs_source_audio_render_steps_audio_mix( + source: *mut c_void, + ts: *mut u64, + audio_data: *mut AudioOutputData, + channels: usize, + sample_rate: usize, + ) -> bool; + fn obs_source_audio_render_steps_apply_volume( + source: *mut c_void, + mixers: u32, + channels: usize, + sample_rate: usize, + ); + fn obs_source_audio_render_steps_output_audio( + source: *mut c_void, + audio_data: *const AudioOutputData, + channels: usize, + sample_rate: usize, + ts: u64, + ); +} + +const OBS_SOURCE_SUBMIX: u32 = 1 << 12; +const T: u64 = 10_000_000_000_000; +const T2: u64 = 1_234_567_890_123; +const TICK: usize = 4096; +const RATE: usize = 48_000; +const NONE: AudioOutputData = AudioOutputData { + data: [core::ptr::null_mut(); 8], +}; + +/// The exports' core on the adapters, with one change each. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mutant { + /// `audio_mixers` is read once, at the first read. + MixersOnce, + /// `audio_buf_mutex` is never taken. + NoLock, + /// Every clear covers one channel. + ClearOneChannel, + /// `audio_ts` reads the value from before the lock. + TsBeforeLock, + /// The submix flag reads as clear. + NoSubmix, + /// The output gets the mix buffer's planes, not the callback's. + OutputOwnPlanes, +} + +const MUTANTS: [Mutant; 6] = [ + Mutant::MixersOnce, + Mutant::NoLock, + Mutant::ClearOneChannel, + Mutant::TsBeforeLock, + Mutant::NoSubmix, + Mutant::OutputOwnPlanes, +]; + +#[derive(Debug, Clone, Copy)] +enum Side { + C, + Rust, + Mutant(Mutant), +} + +#[derive(Clone, Copy)] +struct Src(*mut c_void); + +struct MutantHost { + mutant: Mutant, + mixers: core::cell::Cell>, + ts: core::cell::Cell>, +} + +// SAFETY (every call): the oracle's live source with the buffers its route +// needs, called as the core calls the production host. +impl Host for MutantHost { + type Source = Src; + type Mix = AudioMix; + type Planes = AudioOutputData; + + fn has_output_buffer(&self, s: Src) -> bool { + unsafe { obs_source_audio_render_steps_has_output_buffer(s.0) } + } + fn has_audio_render(&self, s: Src) -> bool { + unsafe { obs_source_audio_render_steps_has_audio_render(s.0) } + } + fn has_context_data(&self, s: Src) -> bool { + unsafe { obs_source_audio_render_steps_has_context_data(s.0) } + } + fn has_audio_mix(&self, s: Src) -> bool { + unsafe { obs_source_audio_render_steps_has_audio_mix(s.0) } + } + fn is_submix(&self, s: Src) -> bool { + if self.mutant == Mutant::TsBeforeLock { + self.ts + .set(Some(unsafe { obs_source_audio_render_steps_audio_ts(s.0) })); + } + self.mutant != Mutant::NoSubmix && unsafe { obs_source_audio_render_steps_is_submix(s.0) } + } + fn lock(&self, s: Src) { + if self.mutant != Mutant::NoLock { + unsafe { obs_source_audio_render_steps_lock(s.0) } + } + } + fn unlock(&self, s: Src) { + if self.mutant != Mutant::NoLock { + unsafe { obs_source_audio_render_steps_unlock(s.0) } + } + } + fn set_audio_pending(&self, s: Src, pending: bool) { + unsafe { obs_source_audio_render_steps_set_audio_pending(s.0, pending) } + } + fn audio_ts(&self, s: Src) -> u64 { + if let (Mutant::TsBeforeLock, Some(ts)) = (self.mutant, self.ts.get()) { + return ts; + } + unsafe { obs_source_audio_render_steps_audio_ts(s.0) } + } + fn set_audio_ts(&self, s: Src, ts: u64) { + unsafe { obs_source_audio_render_steps_set_audio_ts(s.0, ts) } + } + fn audio_mixers(&self, s: Src) -> u32 { + if self.mutant == Mutant::MixersOnce + && let Some(m) = self.mixers.get() + { + return m; + } + let m = unsafe { obs_source_audio_render_steps_audio_mixers(s.0) }; + self.mixers.set(Some(m)); + m + } + fn input_size(&self, s: Src) -> usize { + unsafe { obs_source_audio_render_steps_input_size(s.0) } + } + fn new_mix(&self) -> AudioMix { + AudioMix { + output: [NONE; MAX_AUDIO_MIXES], + } + } + fn point_output(&self, s: Src, data: &mut AudioMix, mix: usize, channel: usize) { + data.output[mix].data[channel] = + unsafe { obs_source_audio_render_steps_output_buf(s.0, mix, channel) }; + } + fn clear_output(&self, s: Src, mix: usize, bytes: usize) { + let bytes = if self.mutant == Mutant::ClearOneChannel { + bytes.min(TICK) + } else { + bytes + }; + unsafe { obs_source_audio_render_steps_clear_output(s.0, mix, bytes) } + } + fn audio_render( + &self, + s: Src, + data: &mut AudioMix, + mixers: u32, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + let mut ts = 0; + let ok = unsafe { + obs_source_audio_render_steps_audio_render( + s.0, + &mut ts, + data, + mixers, + channels, + sample_rate, + ) + }; + (ok, ts) + } + fn apply_volume(&self, s: Src, mixers: u32, channels: usize, sample_rate: usize) { + unsafe { obs_source_audio_render_steps_apply_volume(s.0, mixers, channels, sample_rate) } + } + fn new_planes(&self) -> AudioOutputData { + NONE + } + fn point_plane(&self, s: Src, data: &mut AudioOutputData, channel: usize) { + data.data[channel] = unsafe { obs_source_audio_render_steps_mix_buf(s.0, channel) }; + } + fn clear_mix_buffer(&self, s: Src, bytes: usize) { + let bytes = if self.mutant == Mutant::ClearOneChannel { + bytes.min(TICK) + } else { + bytes + }; + unsafe { obs_source_audio_render_steps_clear_mix_buf(s.0, bytes) } + } + fn audio_mix( + &self, + s: Src, + data: &mut AudioOutputData, + channels: usize, + sample_rate: usize, + ) -> (bool, u64) { + let mut ts = 0; + let ok = unsafe { + obs_source_audio_render_steps_audio_mix(s.0, &mut ts, data, channels, sample_rate) + }; + (ok, ts) + } + fn output_audio( + &self, + s: Src, + data: &AudioOutputData, + channels: usize, + sample_rate: usize, + ts: u64, + ) { + let mut own = NONE; + if self.mutant == Mutant::OutputOwnPlanes { + for (ch, slot) in own.data.iter_mut().enumerate().take(channels) { + *slot = unsafe { obs_source_audio_render_steps_mix_buf(s.0, ch) }; + } + } + let data = if self.mutant == Mutant::OutputOwnPlanes { + &own + } else { + data + }; + unsafe { obs_source_audio_render_steps_output_audio(s.0, data, channels, sample_rate, ts) } + } + fn peek_input(&self, s: Src, channel: usize, size: usize) { + unsafe { obs_source_audio_render_steps_peek_input(s.0, channel, size) } + } + fn copy_output(&self, s: Src, mix: usize, channel: usize, size: usize) { + unsafe { obs_source_audio_render_steps_copy_output(s.0, mix, channel, size) } + } +} + +#[derive(Debug, Clone, Copy)] +struct Case { + fields: Fields, + script: Script, + mixers: u32, + channels: usize, + sample_rate: usize, + size: usize, + seed: u32, +} + +#[derive(Debug, PartialEq, Eq)] +struct Outcome { + fields: Fields, + out: Vec, + mix: Vec, + log: Vec, +} + +/// Runs one side on a fresh source; returns what it left and the source. +fn run(case: &Case, side: Side) -> (Outcome, *mut c_void) { + // SAFETY: the oracle's fixtures, freed by the caller. + unsafe { + let source = oracle_rs_source_new(&case.fields, case.seed); + oracle_rs_watch(source, &case.script); + match side { + Side::C => oracle_rs_render( + source, + case.mixers, + case.channels, + case.sample_rate, + case.size, + ), + Side::Rust => rust::obs_source_audio_render( + source, + case.mixers, + case.channels, + case.sample_rate, + case.size, + ), + Side::Mutant(mutant) => audio_render_steps::audio_render( + &MutantHost { + mutant, + mixers: core::cell::Cell::new(None), + ts: core::cell::Cell::new(None), + }, + Src(source), + case.mixers, + case.channels, + case.sample_rate, + case.size, + ), + } + let mut log = Log { + events: 0, + event: [Event::default(); EVENTS], + }; + oracle_rs_log(&mut log); + oracle_rs_watch(core::ptr::null_mut(), core::ptr::null()); + + let mut fields = Fields::default(); + let mut out = vec![0.0_f32; oracle_rs_out_samples()]; + let mut mix = vec![0.0_f32; oracle_rs_mix_samples()]; + oracle_rs_get(source, &mut fields, out.as_mut_ptr(), mix.as_mut_ptr()); + let events = usize::try_from(log.events).unwrap(); + ( + Outcome { + fields, + out: out.iter().map(|s| s.to_bits()).collect(), + mix: mix.iter().map(|s| s.to_bits()).collect(), + log: log.event[..events].to_vec(), + }, + source, + ) + } +} + +/// The C and `side` on the case: their outcomes and whether the sources' +/// other bytes match. +fn compare(case: &Case, side: Side) -> (Outcome, Outcome, bool) { + let (c, c_source) = run(case, Side::C); + let (other, other_source) = run(case, side); + // SAFETY: both sources are live, then freed once each. + let bytes = unsafe { oracle_rs_same(c_source, other_source) }; + unsafe { + oracle_rs_source_free(c_source); + oracle_rs_source_free(other_source); + } + (c, other, bytes) +} + +fn summary(c: &Outcome, r: &Outcome) -> String { + let first = |a: &[u32], b: &[u32]| a.iter().zip(b).position(|(x, y)| x != y); + format!( + "fields {:?} / {:?}\nlog {:?}\n / {:?}\nfirst output diff {:?}, first mix diff {:?}", + c.fields, + r.fields, + c.log, + r.log, + first(&c.out, &r.out), + first(&c.mix, &r.mix) + ) +} + +fn check(case: &Case) { + let (c, r, bytes) = compare(case, Side::Rust); + assert!(c == r, "{case:?}\n{}", summary(&c, &r)); + assert!(bytes, "{case:?}: the sources' other bytes differ"); +} + +/// A case that keeps every buffer access in range: the mix buffer with +/// `audio_mix`, and every channel holding the same input. +fn case( + route: u32, + audio_mixers: u32, + mixers: u32, + clobber: u32, + channels: usize, + size: usize, + seed: u32, +) -> Case { + let bit = |i: u32| route & (1 << i) != 0; + Case { + fields: Fields { + audio_ts: if bit(5) { 0 } else { T }, + audio_mixers, + output_flags: if bit(4) { OBS_SOURCE_SUBMIX } else { 0 } | 0x2, + input_bytes: match route >> 6 & 3 { + 0 => size, + 1 => size.saturating_sub(4), + 2 => 2 * TICK, + _ => 0, + }, + input_skip: (seed as usize % 3) * 1000, + has_output: !bit(0), + has_mix_buf: bit(3), + audio_render: bit(1), + audio_mix: bit(3), + has_data: !bit(2), + audio_pending: seed.is_multiple_of(2), + }, + script: Script { + render_ok: route >> 8 & 3 != 0, + render_ts: match route >> 8 & 3 { + 0 => 7, + 1 => 0, + _ => T2, + }, + mix_ok: bit(10), + mix_ts: T2.wrapping_add(u64::from(seed)), + clobber, + clob_mixers: audio_mixers.rotate_left(3) ^ 0x2a, + clob_ts: T, + }, + mixers, + channels, + sample_rate: RATE, + size, + seed, + } +} + +const MASKS: [u32; 5] = [0, 0x01, 0x02, 0x14, 0x3f]; +/// None; the callbacks, the rotation and the moved plane; and the flip of +/// `audio_ts` at the lock too (which leaves it 0, so the tick is pending). +const CLOBBERS: [u32; 3] = [0, 0xb, 0xf]; +const TICK_MASKS: [u32; 5] = [0, 0x01, 0x15, 0x3f, 0x40]; + +/// Every route (output buffer, audio_render, data, audio_mix, submix flag, +/// callbacks' results) against the masks, with and without clobbers. +fn route_grid() -> Vec { + let mut cases = Vec::new(); + let mut i = 0_u64; + // Without an output buffer nothing else is read: one such route. + for route in (0..32_u32).filter(|r| r & 1 == 0 || *r == 1) { + for result in [0_u32, 1 << 8, 2 << 8 | 1 << 10] { + for &audio_mixers in &MASKS { + for &mixers in &TICK_MASKS { + for clobber in CLOBBERS { + i += 1; + if !obs_c_oracle::parity::keep(i) { + continue; + } + let seed = u32::try_from(i).unwrap(); + cases.push(case( + route | result, + audio_mixers, + mixers, + clobber, + 2, + TICK, + seed, + )); + } + } + } + } + } + cases +} + +/// The pending checks (timestamp, input), tick sizes and channel counts on +/// the three routes that reach them. +fn tick_grid() -> Vec { + let mut cases = Vec::new(); + let mut i = 0_u64; + for route in [0_u32, 1 << 3, 1 << 3 | 1 << 4, 1 << 4, 1 << 1 | 2 << 8] { + for unset in [0, 1 << 5] { + for input in 0..4_u32 { + for size in [TICK, 0, 8] { + for channels in [0, 1, 2, 8] { + for clobber in CLOBBERS { + i += 1; + if !obs_c_oracle::parity::keep(i) { + continue; + } + let seed = u32::try_from(i).unwrap(); + cases.push(case( + route | unset | input << 6 | 1 << 10, + 0x3f, + 0x15, + clobber, + channels, + size, + seed, + )); + } + } + } + } + } + } + cases +} + +#[test] +fn matches_c_over_routes_masks_and_clobbers() { + for case in route_grid() { + check(&case); + } +} + +#[test] +fn matches_c_over_pending_checks_sizes_and_channels() { + for case in tick_grid() { + check(&case); + } +} + +#[test] +fn matches_c_with_odd_sample_rates_and_timestamps() { + for sample_rate in [0, 1, 44_100, usize::MAX] { + for audio_ts in [1, u64::MAX] { + for route in [1 << 1 | 2 << 8, 1 << 3 | 1 << 10, 1 << 3 | 1 << 4 | 1 << 10] { + let mut c = case(route, 0x3f, 0x3f, 0, 2, TICK, 3); + c.sample_rate = sample_rate; + c.fields.audio_ts = audio_ts; + c.script.render_ts = audio_ts; + c.script.mix_ts = audio_ts; + check(&c); + } + } + } +} + +#[test] +fn mutants_differ_from_c() { + let cases: Vec = route_grid().into_iter().chain(tick_grid()).collect(); + for mutant in MUTANTS { + let caught = cases.iter().any(|case| { + let (c, m, bytes) = compare(case, Side::Mutant(mutant)); + c != m || !bytes + }); + assert!(caught, "{mutant:?} matched the C on every case"); + } +} + +#[test] +fn matches_c_on_random_cases() { + let mut runner = proptest::test_runner::TestRunner::new(ProptestConfig { + cases: obs_c_oracle::parity::cases(256), + failure_persistence: None, + ..ProptestConfig::default() + }); + let strategy = ( + 0_u32..2048, + any::(), + any::(), + 0_u32..16, + 0_usize..=8, + prop_oneof![Just(TICK), 0_usize..=TICK], + any::(), + any::(), + ); + runner + .run( + &strategy, + |(route, audio_mixers, mixers, clobber, channels, size, seed, ts)| { + let mut case = case(route, audio_mixers, mixers, clobber, channels, size, seed); + if ts.is_multiple_of(3) { + case.fields.audio_ts = ts; + case.script.render_ts = ts.rotate_left(7); + } + let (c, r, bytes) = compare(&case, Side::Rust); + prop_assert!(c == r, "{}\n{case:?}", summary(&c, &r)); + prop_assert!(bytes); + Ok(()) + }, + ) + .unwrap(); +} diff --git a/rust/obs-source/tests/source/main.rs b/rust/obs-source/tests/source/main.rs index 301397d4a3..8f590c4e89 100644 --- a/rust/obs-source/tests/source/main.rs +++ b/rust/obs-source/tests/source/main.rs @@ -43,6 +43,7 @@ mod audio_place_parity; mod audio_render_plan; mod audio_render_plan_parity; mod audio_render_steps; +mod audio_render_steps_parity; mod audio_settings; mod audio_timing; mod audio_timing_parity;