diff --git a/ci/vcam_av_sync.py b/ci/vcam_av_sync.py index ec7eb1e611..65964e64b4 100644 --- a/ci/vcam_av_sync.py +++ b/ci/vcam_av_sync.py @@ -349,6 +349,64 @@ async def measure(args: argparse.Namespace) -> dict: return result +async def video_probe(args: argparse.Namespace) -> dict: + """Render-to-device latency of the Virtual Camera alone: a full-canvas + white color source is shown and hidden at known times, so no media + decoding is in the path (#4119).""" + import av + import websockets + + work = Path(tempfile.mkdtemp(prefix="vcam-video-probe-")) + capture = work / "video.mkv" + toggles: list[tuple[float, bool]] = [] + async with websockets.connect(args.url, subprotocols=["obswebsocket.json"]) as ws: + await ws.recv() + await ws.send(json.dumps({"op": 1, "d": {"rpcVersion": 1}})) + await ws.recv() + video = await obs_request(ws, "GetVideoSettings") + scene = (await obs_request(ws, "GetCurrentProgramScene"))["currentProgramSceneName"] + if not (await obs_request(ws, "GetVirtualCamStatus"))["outputActive"]: + await obs_request(ws, "StartVirtualCam") + await asyncio.sleep(2) + created = await obs_request(ws, "CreateInput", { + "sceneName": scene, "inputName": SOURCE_NAME, "inputKind": "color_source_v3", + "inputSettings": {"color": 0xFFFFFFFF, "width": video["baseWidth"], "height": video["baseHeight"]}, + "sceneItemEnabled": False}) + item = created["sceneItemId"] + try: + recorder = subprocess.Popen( + ["ffmpeg", "-loglevel", "error", "-y", "-f", "v4l2", "-ts", "abs", "-i", args.device, + "-map", "0:v", "-c:v", "ffv1", "-copyts", str(capture)]) + await asyncio.sleep(1.5) + for i in range(2 * args.toggles): + on = i % 2 == 0 + sent = time.time() + await obs_request(ws, "SetSceneItemEnabled", + {"sceneName": scene, "sceneItemId": item, "sceneItemEnabled": on}) + toggles.append(((sent + time.time()) / 2, on)) + await asyncio.sleep(0.7) + recorder.send_signal(signal.SIGINT) + await asyncio.to_thread(recorder.wait) + finally: + await obs_request(ws, "RemoveInput", {"inputName": SOURCE_NAME}) + times, luma = [], [] + with av.open(str(capture)) as container: + stream = container.streams.video[0] + for frame in container.decode(stream): + if frame.pts is not None: + times.append(float(frame.pts * stream.time_base)) + luma.append(float(frame.to_ndarray(format="gray").mean())) + mid = (min(luma) + max(luma)) / 2 + lat = [] + for t, on in toggles: + edge = next((ft for ft, lv in zip(times, luma) if ft > t and (lv > mid) == on), None) + if edge is not None: + lat.append(round((edge - t) * 1000, 1)) + fps = video["fpsNumerator"] / video["fpsDenominator"] + return {"fps": fps, "frame_ms": round(1000 / fps, 1), "video_latency_ms": lat, + "median_ms": float(np.median(lat)) if lat else None, "capture": str(capture)} + + def analyze(capture: Path, events: list[float], restarted: float | None = None) -> dict: flashes, beeps = read_capture(capture) vlag, vmatched = align(flashes, events, CLIP_SECONDS) @@ -381,7 +439,14 @@ def main(argv: list[str]) -> int: a.add_argument("capture", type=Path) c = sub.add_parser("clip") c.add_argument("out", type=Path) + v = sub.add_parser("video-probe", help="render-to-device latency, no media source") + v.add_argument("--url", default="ws://127.0.0.1:4455") + v.add_argument("--device", default="/dev/video9") + v.add_argument("--toggles", type=int, default=5) args = parser.parse_args(argv) + if args.cmd == "video-probe": + print(json.dumps(asyncio.run(video_probe(args)))) + return 0 if args.cmd == "clip": write_clip(args.out) print(json.dumps({"clip": str(args.out), "events": EVENTS})) diff --git a/plugins/linux-v4l2/CMakeLists.txt b/plugins/linux-v4l2/CMakeLists.txt index 47b2fa7a1d..392a1dc6c5 100644 --- a/plugins/linux-v4l2/CMakeLists.txt +++ b/plugins/linux-v4l2/CMakeLists.txt @@ -39,6 +39,14 @@ if(PulseAudio_FOUND) target_compile_definitions(linux-v4l2 PRIVATE HAVE_LIBPULSE) endif() +# With PipeWire the microphone is a native Audio/Source node: module-pipe-source +# under pipewire-pulse buffers a fixed 8192 frames (obs-rust/obs-studio#4119). +find_package(PipeWire 0.3.33) +if(PipeWire_FOUND) + target_link_libraries(linux-v4l2 PRIVATE PipeWire::PipeWire) + target_compile_definitions(linux-v4l2 PRIVATE HAVE_PIPEWIRE) +endif() + if(ENABLE_UDEV) find_package(Libudev REQUIRED) target_sources(linux-v4l2 PRIVATE build/linux-v4l2.nix-udev+.h.c) diff --git a/plugins/linux-v4l2/build/linux-v4l2-nix-output.pch.h b/plugins/linux-v4l2/build/linux-v4l2-nix-output.pch.h index bc900a77e7..6f6c095b81 100644 --- a/plugins/linux-v4l2/build/linux-v4l2-nix-output.pch.h +++ b/plugins/linux-v4l2/build/linux-v4l2-nix-output.pch.h @@ -27,6 +27,11 @@ #include "vcam-format.h" +#ifdef HAVE_PIPEWIRE +#include +#include +#include +#endif #ifdef HAVE_LIBPULSE #include #endif diff --git a/plugins/linux-v4l2/v4l2-output.c.h b/plugins/linux-v4l2/v4l2-output.c.h index b52e1c4172..3e05cec2c3 100644 --- a/plugins/linux-v4l2/v4l2-output.c.h +++ b/plugins/linux-v4l2/v4l2-output.c.h @@ -25,6 +25,9 @@ struct vcam_sync { uint64_t audio_end; }; +/* The OBS Audio node when PipeWire runs (#4119); defined below. */ +struct vmic_pw; + struct virtualcam_data { obs_output_t *output; int device; @@ -38,6 +41,7 @@ struct virtualcam_data { uint32_t mic_rate; /* How much longer than the video the audio takes past the FIFO. */ uint64_t mic_lead_ns; + struct vmic_pw *mic_pw; struct vcam_sync sync; size_t mic_pipe_size; struct vmic_tail mic_tail; @@ -307,6 +311,35 @@ static uint64_t vmic_tunnel_lead_ns(const char *sources, uint32_t rate) return 0; } +/* The PipeWire node's reader is a jitter buffer (#4119). libobs hands over + * 1024-frame packets on its audio thread, not evenly enough to read the ring + * down to empty, so the reader starts (and, after running dry, restarts) only + * once VMIC_PW_KEEP_FRAMES beyond a cycle's request are waiting, and drops + * older audio only past VMIC_PW_HIGH_FRAMES, back down to the keep level. */ +#define VMIC_PW_KEEP_FRAMES 2048 +#define VMIC_PW_HIGH_FRAMES 4096 +struct vmic_pw_read { + uint32_t skip; /* frames to drop first */ + uint32_t take; /* frames to copy; the rest of the cycle is silence */ +}; +static struct vmic_pw_read vmic_pw_plan(uint32_t have, uint32_t want, bool *primed) +{ + struct vmic_pw_read r = {0, 0}; + if (!*primed) { + if (have < want || have - want < VMIC_PW_KEEP_FRAMES) + return r; + *primed = true; + } + if (have > want && have - want > VMIC_PW_HIGH_FRAMES) { + r.skip = have - want - VMIC_PW_KEEP_FRAMES; + have -= r.skip; + } + r.take = have < want ? have : want; + if (have < want) + *primed = false; + return r; +} + /* Frees the frames waiting for their audio; under sync.mutex. */ static void vcam_sync_free(struct vcam_sync *sync) { @@ -581,6 +614,215 @@ static char *vmic_pa_list(bool modules) #endif /* Whether pactl itself can run at all, whatever the sound server would say (#3797). */ +#ifdef HAVE_PIPEWIRE +/* OBS Audio as a native PipeWire Audio/Source node (#4119). The output thread + * writes libobs packets into the ring; PipeWire's process callback reads it. + * One writer, one reader: spa_ringbuffer needs no lock. */ +#define VMIC_PW_RING (1u << 18) +#define VMIC_PW_STRIDE ((uint32_t)(VMIC_CHANNELS * sizeof(float))) +struct vmic_pw { + struct pw_thread_loop *loop; + struct pw_stream *stream; + struct spa_hook listener; + struct spa_ringbuffer ring; + bool primed; + /* Counted on PipeWire's thread, logged from the output thread. */ + volatile long underruns; + volatile long skipped; + uint64_t next_report; + uint8_t data[VMIC_PW_RING]; +}; + +static void vmic_pw_process(void *arg) +{ + struct vmic_pw *pw = arg; + struct pw_buffer *b = pw_stream_dequeue_buffer(pw->stream); + if (!b) + return; + struct spa_data *d = &b->buffer->datas[0]; + if (!d->data) { + pw_stream_queue_buffer(pw->stream, b); + return; + } + uint32_t want = d->maxsize / VMIC_PW_STRIDE; + if (b->requested && b->requested < want) + want = (uint32_t)b->requested; + + uint32_t index; + int32_t avail = spa_ringbuffer_get_read_index(&pw->ring, &index); + uint32_t have = avail > 0 ? (uint32_t)avail / VMIC_PW_STRIDE : 0; + /* Audio nobody read (no app linked) or a backlog that grew: start + * from the newest instead of staying behind. */ + bool was_primed = pw->primed; + struct vmic_pw_read plan = vmic_pw_plan(have, want, &pw->primed); + if (was_primed && !pw->primed) + os_atomic_inc_long(&pw->underruns); + if (plan.skip) + os_atomic_store_long(&pw->skipped, os_atomic_load_long(&pw->skipped) + (long)plan.skip); + index += plan.skip * VMIC_PW_STRIDE; + uint32_t n = plan.take; + spa_ringbuffer_read_data(&pw->ring, pw->data, VMIC_PW_RING, index % VMIC_PW_RING, d->data, n * VMIC_PW_STRIDE); + spa_ringbuffer_read_update(&pw->ring, (int32_t)(index + n * VMIC_PW_STRIDE)); + if (n < want) + memset((uint8_t *)d->data + n * VMIC_PW_STRIDE, 0, (want - n) * VMIC_PW_STRIDE); + d->chunk->offset = 0; + d->chunk->stride = (int32_t)VMIC_PW_STRIDE; + d->chunk->size = want * VMIC_PW_STRIDE; + pw_stream_queue_buffer(pw->stream, b); +} + +static void vmic_pw_state_changed(void *arg, enum pw_stream_state old, enum pw_stream_state state, const char *error) +{ + UNUSED_PARAMETER(old); + UNUSED_PARAMETER(state); + UNUSED_PARAMETER(error); + struct vmic_pw *pw = arg; + pw_thread_loop_signal(pw->loop, false); +} + +static const struct pw_stream_events vmic_pw_events = { + PW_VERSION_STREAM_EVENTS, + .state_changed = vmic_pw_state_changed, + .process = vmic_pw_process, +}; + +/* Fails (and the pipe source is used instead) when no PipeWire daemon + * answers or the node cannot be made. */ +static bool vmic_pw_start(struct virtualcam_data *vcam, const char *name, const char *description, uint32_t rate) +{ + if (rate == 0) + return false; + pw_init(NULL, NULL); + struct vmic_pw *pw = bzalloc(sizeof(*pw)); + spa_ringbuffer_init(&pw->ring); + pw->loop = pw_thread_loop_new("obs-virtual-microphone", NULL); + if (!pw->loop) { + bfree(pw); + return false; + } + + char latency[32]; + snprintf(latency, sizeof(latency), "256/%u", rate); + struct pw_properties *props = pw_properties_new(PW_KEY_MEDIA_CLASS, "Audio/Source", PW_KEY_NODE_NAME, name, + PW_KEY_NODE_DESCRIPTION, description, PW_KEY_NODE_LATENCY, + latency, PW_KEY_NODE_VIRTUAL, "true", PW_KEY_MEDIA_ROLE, + "Communication", NULL); + + pw_thread_loop_lock(pw->loop); + if (pw_thread_loop_start(pw->loop) < 0) { + pw_thread_loop_unlock(pw->loop); + pw_properties_free(props); + pw_thread_loop_destroy(pw->loop); + bfree(pw); + return false; + } + pw->stream = pw_stream_new_simple(pw_thread_loop_get_loop(pw->loop), name, props, &vmic_pw_events, pw); + bool ok = pw->stream != NULL; + if (ok) { + uint8_t buf[512]; + struct spa_pod_builder bld = SPA_POD_BUILDER_INIT(buf, sizeof(buf)); + struct spa_audio_info_raw info = {.format = SPA_AUDIO_FORMAT_F32, + .rate = rate, + .channels = VMIC_CHANNELS}; + info.position[0] = SPA_AUDIO_CHANNEL_FL; + info.position[1] = SPA_AUDIO_CHANNEL_FR; + const struct spa_pod *params[1] = {spa_format_audio_raw_build(&bld, SPA_PARAM_EnumFormat, &info)}; + /* No AUTOCONNECT: it is a device apps link to, not a stream to + * play on the speakers. */ + ok = pw_stream_connect(pw->stream, PW_DIRECTION_OUTPUT, PW_ID_ANY, + PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS, params, 1) == 0; + } + /* Wait until the daemon took the node, or gave up on it. */ + uint64_t deadline = os_gettime_ns() + 3000000000ULL; + while (ok) { + const char *error = NULL; + enum pw_stream_state state = pw_stream_get_state(pw->stream, &error); + if (state == PW_STREAM_STATE_ERROR || state == PW_STREAM_STATE_UNCONNECTED) { + blog(LOG_INFO, "Virtual microphone: PipeWire node failed (%s)", error ? error : "unconnected"); + ok = false; + break; + } + if (state == PW_STREAM_STATE_PAUSED || state == PW_STREAM_STATE_STREAMING) + break; + if (os_gettime_ns() > deadline) { + ok = false; + break; + } + pw_thread_loop_timed_wait(pw->loop, 1); + } + pw_thread_loop_unlock(pw->loop); + if (!ok) { + pw_thread_loop_stop(pw->loop); + if (pw->stream) + pw_stream_destroy(pw->stream); + pw_thread_loop_destroy(pw->loop); + bfree(pw); + return false; + } + vcam->mic_pw = pw; + vcam->mic_rate = rate; + /* The audio waits in the jitter buffer; so does the picture. */ + vcam->mic_lead_ns = util_mul_div64(VMIC_PW_KEEP_FRAMES, 1000000000ULL, rate); + return true; +} + +static void vmic_pw_stop(struct virtualcam_data *vcam) +{ + struct vmic_pw *pw = vcam->mic_pw; + if (!pw) + return; + pthread_mutex_lock(&vcam->sync.mutex); + vcam->mic_pw = NULL; + pthread_mutex_unlock(&vcam->sync.mutex); + pw_thread_loop_stop(pw->loop); + pw_stream_destroy(pw->stream); + pw_thread_loop_destroy(pw->loop); + bfree(pw); +} + +/* Drops the packet when the ring is full, which only happens while no app + * reads the node; the reader then starts from the newest audio. */ +static void vmic_pw_write(struct vmic_pw *pw, const uint8_t *data, size_t size) +{ + uint64_t now = os_gettime_ns(); + if (now >= pw->next_report) { + long underruns = os_atomic_exchange_long(&pw->underruns, 0); + long skipped = os_atomic_exchange_long(&pw->skipped, 0); + if (pw->next_report && (underruns || skipped)) + blog(LOG_INFO, "Virtual microphone: %ld underruns, %ld stale frames dropped in the last minute", + underruns, skipped); + pw->next_report = now + 60000000000ULL; + } + uint32_t index; + int32_t filled = spa_ringbuffer_get_write_index(&pw->ring, &index); + if (filled < 0 || (size_t)filled + size > VMIC_PW_RING) + return; + spa_ringbuffer_write_data(&pw->ring, pw->data, VMIC_PW_RING, index % VMIC_PW_RING, data, (uint32_t)size); + spa_ringbuffer_write_update(&pw->ring, (int32_t)(index + (uint32_t)size)); +} +#else +static bool vmic_pw_start(struct virtualcam_data *vcam, const char *name, const char *description, uint32_t rate) +{ + UNUSED_PARAMETER(vcam); + UNUSED_PARAMETER(name); + UNUSED_PARAMETER(description); + UNUSED_PARAMETER(rate); + return false; +} + +static void vmic_pw_stop(struct virtualcam_data *vcam) +{ + UNUSED_PARAMETER(vcam); +} + +static void vmic_pw_write(struct vmic_pw *pw, const uint8_t *data, size_t size) +{ + UNUSED_PARAMETER(pw); + UNUSED_PARAMETER(data); + UNUSED_PARAMETER(size); +} +#endif + static bool vmic_pactl_runs(void) { char *version = run_pactl("--version"); @@ -591,6 +833,7 @@ static bool vmic_pactl_runs(void) static void vmic_stop(struct virtualcam_data *vcam) { + vmic_pw_stop(vcam); pthread_mutex_lock(&vcam->sync.mutex); if (vcam->mic_fifo >= 0) { close(vcam->mic_fifo); @@ -797,6 +1040,18 @@ static void vmic_start(struct virtualcam_data *vcam) snprintf(description, sizeof(description), "OBS Audio (%d)", k); uint32_t rate = audio_output_get_sample_rate(obs_get_audio()); + /* A native node first: no FIFO, no tunnel buffer (#4119). */ + if (vmic_pw_start(vcam, source, description, rate)) { + struct audio_convert_info pw_aci = {0}; + pw_aci.format = AUDIO_FORMAT_FLOAT; + pw_aci.speakers = SPEAKERS_STEREO; + pw_aci.samples_per_sec = rate; + obs_output_set_audio_conversion(vcam->output, &pw_aci); + obs_output_set_mixer(vcam->output, vcam->audio_mixer); + blog(LOG_INFO, "Virtual microphone '%s' started (PipeWire node, %u Hz, track %zu)", source, rate, + vcam->audio_mixer + 1); + return; + } struct dstr args; dstr_init(&args); dstr_printf(&args, @@ -939,6 +1194,13 @@ static void vmic_stop(struct virtualcam_data *vcam) { UNUSED_PARAMETER(vcam); } + +static void vmic_pw_write(struct vmic_pw *pw, const uint8_t *data, size_t size) +{ + UNUSED_PARAMETER(pw); + UNUSED_PARAMETER(data); + UNUSED_PARAMETER(size); +} #endif static void virtualcam_audio_proc(void *data, calldata_t *cd) @@ -1233,7 +1495,7 @@ static void virtual_video(void *param, struct video_data *frame) pthread_mutex_lock(&sync->mutex); /* No running microphone (mic_rate is set only by vmic_start): nothing to wait for. */ - if (vcam->mic_fifo < 0 || vcam->mic_rate == 0 || + if ((vcam->mic_fifo < 0 && !vcam->mic_pw) || vcam->mic_rate == 0 || (sync->len == 0 && frame->timestamp + vcam->mic_lead_ns <= sync->audio_end)) { vcam_write_frame(vcam, frame->data[0], frame->timestamp); pthread_mutex_unlock(&sync->mutex); @@ -1257,7 +1519,7 @@ static void virtual_video(void *param, struct video_data *frame) static void virtual_audio(void *param, struct audio_data *frames) { struct virtualcam_data *vcam = (struct virtualcam_data *)param; - if (vcam->mic_fifo < 0 || vcam->mic_rate == 0) + if ((vcam->mic_fifo < 0 && !vcam->mic_pw) || vcam->mic_rate == 0) return; size_t size = (size_t)frames->frames * VMIC_CHANNELS * sizeof(float); /* Keep at most one packet unread, so a reader hears the newest audio. */ @@ -1266,6 +1528,9 @@ static void virtual_audio(void *param, struct audio_data *frames) uint64_t end = frames->timestamp + util_mul_div64(frames->frames, 1000000000ULL, vcam->mic_rate); pthread_mutex_lock(&vcam->sync.mutex); + /* Under the mutex: vmic_pw_stop clears mic_pw under it before freeing. */ + if (vcam->mic_pw) + vmic_pw_write(vcam->mic_pw, frames->data[0], size); vcam->stats_audio_frames += frames->frames; vcam->stats_audio_dropped += discarded / (VMIC_CHANNELS * sizeof(float)); if (!accepted) @@ -1307,3 +1572,7 @@ struct obs_output_info virtualcam_info = { #undef VMIC_PA_TIMEOUT_NS #undef VCAM_SYNC_FRAMES #undef VMIC_PIPEWIRE_TUNNEL_FRAMES +#undef VMIC_PW_KEEP_FRAMES +#undef VMIC_PW_HIGH_FRAMES +#undef VMIC_PW_RING +#undef VMIC_PW_STRIDE diff --git a/rust/obs-build/tests/native/registration/support/headless_helpers_runtime.rs b/rust/obs-build/tests/native/registration/support/headless_helpers_runtime.rs index 577e5e9fee..cddd0efec4 100644 --- a/rust/obs-build/tests/native/registration/support/headless_helpers_runtime.rs +++ b/rust/obs-build/tests/native/registration/support/headless_helpers_runtime.rs @@ -25,7 +25,7 @@ fn assert_cases(output: &std::process::Output, name: &str) { let count = match name { "test_text_file" => 11, "test_v4l2_vcam_write" => 3, - "test_v4l2_vcam_audio" => 20, + "test_v4l2_vcam_audio" => 21, "test_v4l2_fd_cloexec" => 4, "test_hotkey_background_ui" => 27, "test_hotkey_background_use_key" => 5, diff --git a/test/cmocka/build/test-graph.d/test_v4l2_vmic_pipewire.json b/test/cmocka/build/test-graph.d/test_v4l2_vmic_pipewire.json new file mode 100644 index 0000000000..3cc75b4129 --- /dev/null +++ b/test/cmocka/build/test-graph.d/test_v4l2_vmic_pipewire.json @@ -0,0 +1,63 @@ +{ + "schema": 1, + "targets": { + "test_v4l2_vmic_pipewire": { + "sources": [ + "test/cmocka/test_v4l2_vcam_audio.c", + "plugins/linux-v4l2/vcam-format.c.h" + ], + "libraries": [ + "OBS::libobs", + "PulseAudio::PulseAudio", + "PipeWire::PipeWire", + "OBS::native-test-cmocka" + ], + "requires": { + "all": [ + "OS_LINUX", + "HAVE_OBS_V4L2", + "HAVE_OBS_PULSEAUDIO", + "HAVE_OBS_PIPEWIRE" + ] + }, + "includes": [ + ".", + "plugins/linux-v4l2" + ], + "watch_inputs": [ + "plugins/linux-v4l2/v4l2-output.c.h", + "plugins/linux-v4l2/build/linux-v4l2-nix.pch.h", + "plugins/linux-v4l2/build/linux-v4l2-nix-output.pch.h" + ], + "header_libraries": [ + "Libv4l2::Libv4l2" + ], + "definitions": [ + "HAVE_LIBPULSE", + "HAVE_PIPEWIRE" + ] + } + }, + "tests": { + "test_v4l2_vmic_pipewire": { + "target": "test_v4l2_vmic_pipewire", + "requires": { + "all": [ + "OS_LINUX", + "HAVE_OBS_V4L2", + "HAVE_OBS_PULSEAUDIO", + "HAVE_OBS_PIPEWIRE" + ] + }, + "command": [ + "uv", + "run", + "--script", + "${source}/test/cmocka/test_pulse_monitor_device.py", + "${target}" + ], + "timeout_seconds": 120, + "skip_return_code": 77 + } + } +} diff --git a/test/cmocka/parallel-environment.cmake b/test/cmocka/parallel-environment.cmake index 9b45da77b9..83d689794b 100644 --- a/test/cmocka/parallel-environment.cmake +++ b/test/cmocka/parallel-environment.cmake @@ -29,6 +29,7 @@ if(OS_LINUX) test_pipewire_screencast_shm test_pipewire_wrapper test_v4l2_vmic_libpulse + test_v4l2_vmic_pipewire test_v4l2_vmic_server ) if(TEST ${_audio_daemon_test}) diff --git a/test/cmocka/test_v4l2_vcam_audio.c b/test/cmocka/test_v4l2_vcam_audio.c index ecba04e281..4cbd625653 100644 --- a/test/cmocka/test_v4l2_vcam_audio.c +++ b/test/cmocka/test_v4l2_vcam_audio.c @@ -18,6 +18,7 @@ #include #include #include +#include #include "plugins/linux-v4l2/v4l2-output.c.h" @@ -705,6 +706,157 @@ static void video_waits_for_the_tunnel(void **state) sync_done(vcam, dev, mic); } +/* #4119: the PipeWire node's reader is a jitter buffer. It waits for + * 2048 frames beyond a cycle's request before it plays (and again after it + * ran dry), and drops audio only past 4096, back down to 2048. */ +static void pipewire_reader_is_a_jitter_buffer(void **state) +{ + (void)state; + bool primed = false; + struct vmic_pw_read r = vmic_pw_plan(0, 256, &primed); + assert_int_equal(r.skip, 0); + assert_int_equal(r.take, 0); + r = vmic_pw_plan(256 + 2047, 256, &primed); + assert_int_equal(r.take, 0); + assert_false(primed); + r = vmic_pw_plan(256 + 2048, 256, &primed); + assert_int_equal(r.take, 256); + assert_true(primed); + + /* Primed: a backlog up to the high mark stays. */ + r = vmic_pw_plan(256 + 4096, 256, &primed); + assert_int_equal(r.skip, 0); + assert_int_equal(r.take, 256); + r = vmic_pw_plan(256 + 4097, 256, &primed); + assert_int_equal(r.skip, 4097 - 2048); + assert_int_equal(r.take, 256); + + /* Running dry plays what is left, then waits for the keep level. */ + r = vmic_pw_plan(100, 256, &primed); + assert_int_equal(r.take, 100); + assert_false(primed); + r = vmic_pw_plan(1024, 256, &primed); + assert_int_equal(r.take, 0); +} + +/* A frame waits for its audio when the microphone is the PipeWire node too. */ +static void video_waits_for_pipewire_audio(void **state) +{ + (void)state; +#ifdef HAVE_PIPEWIRE + int dev[2], mic[2]; + struct virtualcam_data *vcam = sync_vcam(dev, mic); + close(vcam->mic_fifo); + vcam->mic_fifo = -1; + struct vmic_pw *pw = bzalloc(sizeof(*pw)); + spa_ringbuffer_init(&pw->ring); + vcam->mic_pw = pw; + + send_frame(vcam, MS(1000)); + assert_int_equal(queued_bytes(dev[0]), 0); + send_audio(vcam, MS(1000), 1024); + assert_int_equal(queued_bytes(dev[0]), SYNC_FRAME); + uint32_t idx; + assert_int_equal(spa_ringbuffer_get_read_index(&pw->ring, &idx), 1024 * 2 * (int)sizeof(float)); + + vcam->mic_pw = NULL; + bfree(pw); + sync_done(vcam, dev, mic); +#else + skip(); +#endif +} + +#ifdef HAVE_PIPEWIRE +struct pw_capture { + struct pw_stream *stream; + struct spa_hook listener; + volatile float peak; +}; + +static void pw_capture_process(void *arg) +{ + struct pw_capture *cap = arg; + struct pw_buffer *b = pw_stream_dequeue_buffer(cap->stream); + if (!b) + return; + struct spa_data *d = &b->buffer->datas[0]; + if (d->data && d->chunk) { + const float *f = (const float *)((const uint8_t *)d->data + d->chunk->offset); + for (uint32_t i = 0; i < d->chunk->size / sizeof(float); i++) + if (fabsf(f[i]) > cap->peak) + cap->peak = fabsf(f[i]); + } + pw_stream_queue_buffer(cap->stream, b); +} + +static const struct pw_stream_events pw_capture_events = { + PW_VERSION_STREAM_EVENTS, + .process = pw_capture_process, +}; +#endif + +/* Against the private PipeWire: the node is listed under its name, and a + * tone written through virtual_audio reaches a capture stream linked to it. */ +static void pipewire_node_carries_audio(void **state) +{ + (void)state; +#ifdef HAVE_PIPEWIRE + if (!getenv("PULSE_SERVER")) + skip(); + + struct virtualcam_data *vcam = virtualcam_create(NULL, NULL); + bool started = vmic_pw_start(vcam, "obs_vmic_pw_test", "OBS Audio", 48000); + /* Frames also wait out the jitter buffer: 2048 frames at 48 kHz. */ + uint64_t lead = vcam->mic_lead_ns; + char *sources = started ? vmic_pa_list(false) : NULL; + bool listed = sources && vmic_source_listed(sources, "obs_vmic_pw_test"); + bfree(sources); + + struct pw_capture cap = {0}; + struct pw_thread_loop *loop = pw_thread_loop_new("vmic-test-capture", NULL); + pw_thread_loop_lock(loop); + cap.stream = pw_stream_new_simple(pw_thread_loop_get_loop(loop), "vmic-test-capture", + pw_properties_new(PW_KEY_MEDIA_TYPE, "Audio", PW_KEY_MEDIA_CATEGORY, + "Capture", PW_KEY_TARGET_OBJECT, "obs_vmic_pw_test", NULL), + &pw_capture_events, &cap); + uint8_t buf[512]; + struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buf, sizeof(buf)); + struct spa_audio_info_raw info = {.format = SPA_AUDIO_FORMAT_F32, .rate = 48000, .channels = 2}; + const struct spa_pod *params[1] = {spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &info)}; + pw_stream_connect(cap.stream, PW_DIRECTION_INPUT, PW_ID_ANY, + PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS, params, + 1); + pw_thread_loop_unlock(loop); + pw_thread_loop_start(loop); + + static float tone[1024 * 2]; + for (size_t i = 0; i < 1024 * 2; i++) + tone[i] = 0.5f; + struct audio_data audio = {0}; + audio.data[0] = (uint8_t *)tone; + audio.frames = 1024; + for (int n = 0; started && n < 150 && cap.peak < 0.25f; n++) { + audio.timestamp = MS(1000) + util_mul_div64((uint64_t)n * 1024, 1000000000ULL, 48000); + virtual_audio(vcam, &audio); + usleep(21333); + } + float peak = cap.peak; + + pw_thread_loop_stop(loop); + pw_stream_destroy(cap.stream); + pw_thread_loop_destroy(loop); + virtualcam_destroy(vcam); /* stops the node */ + + assert_true(started); + assert_true(listed); + assert_true(peak > 0.25f); + assert_int_equal(lead, 42666666ULL); +#else + skip(); +#endif +} + int main(void) { const struct CMUnitTest tests[] = { @@ -729,6 +881,9 @@ int main(void) cmocka_unit_test(stale_audio_is_dropped), cmocka_unit_test(pipewire_tunnel_lead_is_8192_frames), cmocka_unit_test(video_waits_for_the_tunnel), + cmocka_unit_test(pipewire_reader_is_a_jitter_buffer), + cmocka_unit_test(video_waits_for_pipewire_audio), + cmocka_unit_test(pipewire_node_carries_audio), }; return cmocka_run_group_tests(tests, NULL, NULL); }