Skip to content

fix(linux/pipewire): support explicit sync for DMA-BUF capture - #6228

Open
Sunssshine wants to merge 5 commits into
SunshineStream:masterfrom
Sunssshine:fix/pipewire-explicit-sync
Open

Sunssshine wants to merge 5 commits into
SunshineStream:masterfrom
Sunssshine:fix/pipewire-explicit-sync

Conversation

@Sunssshine

@Sunssshine Sunssshine commented Dec 5, 2026 •

Copy link
Copy Markdown

Description

With portal capture on the NVIDIA proprietary driver the stream sometimes shows the previous frame again:
the picture jumps back by one frame and then forward. It happens now and then rather than constantly,
and shows on anything that moves, such as a dragged window.

The cause is missing synchronisation on the DMA-BUF. The compositor queues a buffer as soon as it has
submitted the rendering, not when the rendering has finished. Drivers with implicit sync make the reader
wait, the NVIDIA driver does not, so the GL conversion can sample the buffer too early and gets whatever
it held before. The same gap exists on the way back: the buffer is returned to the compositor when the
next frame arrives, whether or not the encoder is still reading it.

PipeWire has explicit sync for this (SPA_META_SyncTimeline): every buffer carries a DRM syncobj timeline
with an acquire point, which signals when the producer is done, and a release point, which the consumer
signals when it is done. Mutter offers it for DMA-BUF streams since 47, Sunshine did not ask for it. This
change negotiates it and uses both points:

  • snapshot() waits for the acquire point before it hands a frame out. The wait is capped at 100 ms. A
    frame whose point has not signalled by then is dropped and the capture retries, and so is a frame whose
    syncobjs cannot be imported.
  • The dequeued buffer is owned by a buffer_hold_t. The image returned by snapshot() shares ownership of
    it, so the buffer goes back to PipeWire when the last encoder drops the image. That owner also keeps the
    display alive, since the buffer has to be returned to its stream.
  • The release point is not signalled by waiting on the CPU. After the GL conversion that samples the buffer,
    egl::finish_reads() exports a native fence (EGL_ANDROID_native_fence_sync) and the hold attaches it to
    the release point, so the compositor waits for the read on its side. Several consumers of one image have
    their fences merged. Whenever a fence cannot be handed over (no extension, failed merge) the consumer
    finishes its reads with glFinish() before the image is released. If the release point cannot be
    scheduled (failed import, failed signal, or a fence that can neither be attached nor waited for), the
    buffer is not returned and the stream is restarted.

Scope and fallbacks:

  • Explicit sync is only requested when the stream uses DMA-BUFs and the frames go to the GL to CUDA
    converter. That is the path where the problem shows and the one I could test. VAAPI uses the same EGL
    conversion, so it would only need the finish_reads() call and the condition in ensure_stream(), but I
    have no setup to verify it and left it out. The Vulkan path is unchanged as well.
  • The timeline layout is sent as the preferred Buffers param, with metaType mandatory, followed by the
    existing one. A producer without explicit sync picks the old layout and nothing changes. The same happens
    when no DRM device with timeline syncobjs can be opened.
  • Buffers that PipeWire removes while a hold is still outstanding are not queued again (remove_buffer
    bumps a generation counter).
  • The metadata exists since PipeWire 1.2. For builds against older headers the few definitions are provided
    locally, next to the existing SPA_VIDEO_TRANSFER_SMPTE2084 one, and the timeline is only requested when
    the library at runtime is 1.2 or newer. The UNSCHEDULED_RELEASE flag only appeared in 1.4.x and is
    defined separately when it is missing.
  • linux/sync_file.h is optional. Without it (FreeBSD) the fences of several consumers are waited for
    instead of merged.
  • libdrm is now linked for KWin and portal builds too. So far only its headers were needed there, the
    syncobj calls need the library.

EGL_ANDROID_native_fence_sync is added to the glad EGL extension list for eglDupNativeFenceFDANDROID.

Screenshot

Issues Fixed or Closed

Roadmap Issues

Testing

Unit tests, in tests/unit/platform/linux/test_pipewire.cpp:

  • PipeWireExplicitSyncTest.* run the buffer life cycle against a fake syncobj layer and a recording
    queue_buffer: finding the timeline in a buffer, waiting for the acquire point, release by signal, by
    fence and by merged fences, the fallbacks when a fence cannot be attached or merged, buffers removed
    while held, the pending frame on pause and on renegotiation, the params sent with and without explicit
    sync, and the lifetime of the buffer behind the image returned by snapshot().
  • SyncobjOperationsWorkOnARealDevice calls the real syncobj and sync_file wrappers. It is skipped on
    machines without a DRM device that supports timeline syncobjs.
  • PipeWireReadSyncTest covers egl::finish_reads().

The race itself needs a compositor and a GPU, so there is no unit test that fails without the fix. That
part was checked by hand.

Commands:

  • ./test_sunshine --gtest_filter='PipeWire*': 45 passed.
  • ./test_sunshine --gtest_filter='-SystemTray*': 1152 passed, 6 skipped (NVENC encoder validation, mouse
    HID, the Windows-only UTF test). The tray tests were left out because the shell I build in has no session
    bus.
  • The touched sources and their tests compile with -Werror on GCC and parse with clang.
  • pipewire.cpp and test_pipewire.cpp also compile with -fsyntax-only -Werror against the PipeWire 0.3.48,
    1.0.5, 1.2.0, 1.2.7, 1.4.0 and 1.4.9 headers, and with the linux/sync_file.h include disabled.
  • clang-format 23.1.0 on the touched files.

Manual:

The stale frames need three things together:

  • a compositor that hands out screencast DMA-BUFs before their rendering has finished, as Mutter does;
  • that compositor rendering on the NVIDIA proprietary driver, which has no implicit sync;
  • Sunshine capturing through PipeWire with DMA-BUFs and encoding with NVENC (capture = portal).

For the fix to take effect the compositor also has to offer SPA_META_SyncTimeline. Nothing else about
the setup should matter.

Tested with GNOME 50.5 (Mutter), PipeWire 1.6.9 and an RTX 4060 on driver 620.70.10, capturing a 2752x2064
monitor at 120 Hz:

  • Before: the picture jumped back and forward from time to time. After: not seen again with this change.
  • With temporary counters (not part of this PR) every frame was released through an attached fence, there
    were no acquire timeouts, and the wait for the acquire point averaged about 0.5 ms with a maximum below
    2 ms.
  • The glFinish() fallback was exercised with a build that treats the EGL extension as missing. Every
    frame was then released by signalling the point directly, again without timeouts or visible jumps.

Not tested: producers other than Mutter, more than one client on the same display (the fence merge is only
covered by the unit test), and a FreeBSD build.

Type of Change

  • feat: New feature (non-breaking change which adds functionality)
  • fix: Bug fix (non-breaking change which fixes an issue)
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semicolons, etc.)
  • refactor: Code change that neither fixes a bug nor adds a feature
  • perf: Code change that improves performance
  • test: Adding missing tests or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit
  • BREAKING CHANGE: Introduces a breaking change (can be combined with any type above)

Checklist

  • Code follows the style guidelines of this project
  • Code has been self-reviewed
  • Code has been commented, particularly in hard-to-understand areas
  • Code docstring/documentation-blocks for new or existing methods/components have been added or updated
  • Tests have been added or updated for new or modified functionality, including regression tests for bug fixes

AI Usage

See our AI usage policy.

  • AI tools were used while preparing this PR

Used for assistance with matching this PR to your guidelines and re-checking my code.

Compositors hand out DMA-BUF frames whose rendering may still be in
flight. Drivers with implicit sync make readers wait for it. The NVIDIA
driver has none, so the converter could sample a buffer before the
compositor had finished drawing into it and encode what the buffer held
before. In the stream this shows as the picture jumping back by a frame
and forward again.

Negotiate SPA_META_SyncTimeline for DMA-BUF streams when the producer
offers it:

- Wait for the acquire point of a frame before handing the frame out.
- Keep the PipeWire buffer dequeued until the last consumer of the
  image has dropped it, instead of returning it when the next frame
  arrives.
- Export a native fence for the GL conversion that samples the buffer
  and attach it to the release point. The producer then waits for the
  read on its side and nothing blocks on the CPU. Without
  EGL_ANDROID_native_fence_sync the conversion is finished with
  glFinish() before the buffer is released.

Explicit sync is requested for the GL to CUDA converter, which now
reports its reads. The other converters and producers without the
metadata keep the previous buffer layout.

The metadata exists since PipeWire 1.2. Builds against older headers
get the few definitions locally, and the timeline is only requested
from a library of 1.2 or newer. libdrm is now linked for PipeWire
capture as well, because the syncobj calls come from it.
- Group the explicit sync state of a stream in stream_sync_t, which
  brings stream_data_t back under the field limit.
- Move the timeline params out of apply_format() and the acquire wait
  out of the snapshot() loop, for complexity and nesting depth.
- Use class template argument deduction, std::format and direct
  make_shared arguments where the analyzer asks for them, and capture
  explicitly in the read sync test.
- Drop the sv suffix that the analyzer misreads as an integer suffix.
- Keep the timeout state private. The protected members finding on
  pipewire_display_t predates this change and is only reported again
  because the class declaration changed.

@ReenigneArcher ReenigneArcher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for a PipeWire header compatibility break and two paths that bypass explicit synchronization when a wait fails.

This overlaps with #5498 on retaining CUDA/NVENC capture buffers during GPU reads. #5498 keeps KWin buffers dequeued without requiring timeline metadata. This PR adds acquire and release synchronization for producers that negotiate a timeline, and uses the existing buffer return behavior for producers without it. I found no exact duplicate.

git diff --check and clang-format 23.1.0 passed. A focused syntax check reproduced the header failure and verified the suggested guard. GitHub Actions returned no jobs for this head, and I could not run the Linux tests or reproduce the compositor issue on this host.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Comment thread src/platform/linux/pipewire.cpp Outdated
Comment on lines +50 to +61
constexpr uint32_t SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE = 1U << 0; ///< Flag cleared by a consumer that signals the release point.

/**
* @brief Timeline points of a buffer that uses explicit sync.
*/
struct spa_meta_sync_timeline {
uint32_t flags; ///< SPA_META_SYNC_TIMELINE_* flags.
uint32_t padding; ///< Unused.
uint64_t acquire_point; ///< Point that signals once the buffer may be read.
uint64_t release_point; ///< Point to signal once the buffer is no longer read.
};
#endif

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Build with PipeWire 1.2 and 1.4 headers

The version guard skips this fallback with PipeWire 1.2.0 and 1.4.0. Both versions define spa_meta_sync_timeline and omit SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE, so compiling the flag clear in buffer_hold_t fails. Guard the release flag independently of the timeline types. PipeWire 1.2.0 header · PipeWire 1.4.0 header

Suggested change
constexpr uint32_t SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE = 1U << 0; ///< Flag cleared by a consumer that signals the release point.
/**
* @brief Timeline points of a buffer that uses explicit sync.
*/
struct spa_meta_sync_timeline {
uint32_t flags; ///< SPA_META_SYNC_TIMELINE_* flags.
uint32_t padding; ///< Unused.
uint64_t acquire_point; ///< Point that signals once the buffer may be read.
uint64_t release_point; ///< Point to signal once the buffer is no longer read.
};
#endif
/**
* @brief Timeline points of a buffer that uses explicit sync.
*/
struct spa_meta_sync_timeline {
uint32_t flags; ///< SPA_META_SYNC_TIMELINE_* flags.
uint32_t padding; ///< Unused.
uint64_t acquire_point; ///< Point that signals once the buffer may be read.
uint64_t release_point; ///< Point to signal once the buffer is no longer read.
};
#endif
#ifndef SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE
constexpr uint32_t SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE = 1U << 0; ///< Flag cleared by a consumer that signals the release point.
#endif

The extracted code fails a syntax check with 1.2.0 and 1.4.0 headers. The suggested guard passes the same check with 1.2.0, 1.4.0, and 1.6.9.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5a89147. Applied the suggested guard, the flag is now defined separately from the timeline types. Builds with the 1.2 and 1.4 headers.

Comment thread src/platform/linux/pipewire.cpp Outdated
if (status == platf::capture_e::ok && (img_egl->sd.fds[0] >= 0 || img_egl->data != nullptr) && !is_buffer_redundant(img_egl)) {
// Explicit sync: the DMA-BUF must not be read before the producer has finished rendering into it
if (hold) {
wait_for_producer(*hold);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Drop frames whose acquire point has not signalled

After the acquire wait times out or fails, this path still returns capture_e::ok. A failed acquire syncobj import also passes wait_acquire() outright. With explicit sync negotiated, the GL converter can then sample a DMA-BUF the compositor is still writing and encode stale or partially rendered pixels. The 100 ms limit should bound how long Sunshine waits for the frame. PipeWire defines the acquire point as the point at which the data can be accessed. PipeWire timeline metadata

Have buffer_hold_t::wait_acquire() return false when the handle is missing, and have wait_for_producer() return the readiness result after logging. Then use this guard before updating frame metadata in snapshot():

if (hold && !wait_for_producer(*hold)) {
  ++retries;
  continue;
}

This releases the unread frame and lets capture retry within its deadline. Update SnapshotUsesAFrameWhoseAcquirePointDoesNotSignal to expect no captured frame, and cover a failed acquire import as well. The control flow was reviewed from source.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

@Sunssshine Sunssshine Dec 5, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5a89147. A frame is dropped when its acquire point has not signalled within the timeout or when a syncobj import failed, and capture retries. I had it this way at first, then switched because a frozen picture seemed worse. I see now that dropping is the better choice. Test updated, import failure is covered too.

Comment thread src/platform/linux/pipewire.cpp Outdated
},
.wait_fence = [](int fence_fd) {
struct pollfd pfd {fence_fd, POLLIN, 0};
poll(&pfd, 1, FENCE_WAIT_TIMEOUT_MS);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve pending read fences when the fallback wait fails

If fence merge or attachment fails, poll() can time out or be interrupted while a GPU read is still pending. add_read_fence() then drops the extra fence, and release() can signal the timeline after the same unsuccessful wait. Either path permits the compositor to reuse a buffer that Sunshine is still sampling. With a failed release syncobj import, release() also closes any recorded fence without waiting. PipeWire timeline metadata

Change syncobj_ops_t::wait_fence to return a completion result and check it in both callers. The polling operation can report readiness with:

return poll(&pfd, 1, FENCE_WAIT_TIMEOUT_MS) > 0 && (pfd.revents & POLLIN) != 0;

If merge fails, keep the extra fence or finish the read on the reporting GL context. If attachment and the wait both fail, defer release until completion or fail the stream while the buffer is still withheld. Skip the frame or finish its reads synchronously when the release syncobj cannot be imported. Extend the existing fallback tests to have the wait report a pending fence and assert that the buffer remains unavailable for reuse. The failure paths were reviewed from source.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5a89147. wait_fence returns a result now, and a fence that cannot be recorded is refused so the reads are finished with glFinish(). If a read is still pending at release, the buffer is withheld and the stream restarts. Tests extended.

- Define SPA_META_SYNC_TIMELINE_UNSCHEDULED_RELEASE on its own. The
  PipeWire 1.2.0 to 1.4.0 headers have the timeline but not the flag.
- Do not hand out a frame whose acquire point has not signalled within
  the timeout, or whose syncobjs could not be imported. The frame is
  dropped and the capture retries.
- Do not let a bounded wait stand in for a pending read. A fence that
  cannot be recorded is refused, so its consumer finishes the read on
  its own context. A fence that can neither be attached to the release
  point nor waited for keeps the buffer withheld and restarts the
  stream.
Restarting the stream logs and takes the frame lock, either of which
may throw. Catch that in the destructor, the way ~dbus_t does.
@Sunssshine

Copy link
Copy Markdown
Author

Re #5498: no conflict in behaviour as far as I can tell. This PR only changes buffer handling when the producer negotiates the timeline, and KWin does not. They touch the same code though, I can rebase if #5498 lands first. The hold added here could also keep buffers for producers without a timeline, if one mechanism for both is preferred. I would do that as a separate PR.

@ReenigneArcher ReenigneArcher left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The revised header guard, dropped-frame behavior, and read-fence fallbacks address the earlier findings. One release path still returns buffers to Mutter without scheduling their release point. Please route failed release imports and failed signal calls through the existing stream recovery.

The overlap with #5498 remains limited to DMA-BUF ownership during NVENC reads. This PR still requires timeline metadata for its new ownership path. I found no exact duplicate.

git diff --check, clang-format 23.1.0, and focused syntax checks of the current header guard with PipeWire 1.2.0, 1.4.0, and 1.6.9 passed. GitHub Actions exposed no jobs for this head. Linux unit tests and NVIDIA reproduction remain unverified.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Comment thread src/platform/linux/pipewire.cpp Outdated
if (has_fence) {
close(read_fence);
}
return finished;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Recover when the release point cannot be signalled

release() reports success when there is no read fence even if the release syncobj failed to import. It also discards errors from drmSyncobjTimelineSignal(), which can fail while allocating the fence chain. Either path requeues a buffer with an unsignalled release point. Mutter 47 and 50.5 check that point before reusing every DMA-BUF with timeline metadata, regardless of the UNSCHEDULED_RELEASE flag. Each such failure removes a buffer from the usable pool, and repeated failures can freeze capture. The new import-failure regression currently expects this requeue. Mutter 50.5 buffer reuse · Linux timeline signal implementation

Change syncobj_ops_t::signal to return bool and have its libdrm wrapper return drmSyncobjTimelineSignal(drm_fd, &handle, &point, 1) == 0. In release(), replace the signal block with the result below and return released after the existing cleanup. This lets the destructor use its existing withhold-and-restart path. Update the restart log to cover a failed release signal as well as a pending read.

const bool released = attached || (release_handle && finished && d.sync.ops->signal(release_handle, release_point));

In test_pipewire.cpp, expect the buffer to be withheld and the stream marked dead when the release import fails, and cover a false result from the fake signal operation. Keep the case where only acquire import fails and release succeeds. An isolated check with the current hold and fake operations reproduced both unsignalled requeues and verified that this change takes the restart path while still requeueing on success.

Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in aaa3d8d. signal returns a result now, and a buffer whose release point cannot be signalled, or whose release syncobj failed to import, is withheld and the stream restarts. Tests updated.

A buffer went back to the producer even when its release syncobj could
not be imported or signalling the point failed. Mutter only reuses a
buffer whose release point has signalled, so every such buffer was lost
to it. Report the result of the signal and take the existing path that
withholds the buffer and restarts the stream.
@sonarqubecloud

sonarqubecloud Bot commented Dec 5, 2026

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants