Skip to content

Fix casting from GNOME Wayland: SIGKILL mid-cast, no frames, idle stalls, reconnects, window sharing - #6

Merged
vindeckyy merged 14 commits into
vindeckyy:masterfrom
JoshGalland:fix/ubuntu-26.04
Dec 5, 2026
Merged

vindeckyy merged 14 commits into
vindeckyy:masterfrom
JoshGalland:fix/ubuntu-26.04

Conversation

@JoshGalland

Copy link
Copy Markdown
Contributor

Summary

Fixes for casting from a GNOME Wayland desktop (Ubuntu 26.04, 2880x1920 3:2 laptop) to a Chromecast. Each commit is one fix; all are listed under Unreleased in CHANGELOG.md. Rebased onto master (1.0.4).

Crashes and cast failures

  • App killed mid-cast with no log or crash report. The screen-cast stream used PW_STREAM_FLAG_RT_PROCESS, so each frame was copied on PipeWire's realtime thread. rtkit caps that thread at 200 ms of CPU without sleeping (RLIMIT_RTTIME). Copying a 2880x1920 BGRx frame at 60 fps went over the cap, and the kernel SIGKILLed the process: no log line, no core dump, no kernel message. Confirmed with bpftrace on signal:signal_generate: data-loop.0 sends SIGKILL to itself from posix_cpu_timers_work. The flag is removed, so the callback runs on the stream's own pw_main_loop thread, and finalize_sw_frame copies with assign() instead of zero-filling then copying.
  • Wayland cast never started. The stream asked for a fixed 60/1 frame rate, but Mutter offers a variable 0/1 rate, so the formats never matched and no frame arrived ("Screen share permission denied or timed out"). It now asks for a size range and a frame-rate range that includes 0/1, and logs stream state changes and errors.
  • A still screen ended the cast after ~5 s. Mutter only sends a frame when the screen changes, so the stall detector tore the session down. The Wayland capture now re-sends the last frame every 100 ms while idle, as FramePacer does for X11 and Windows. Re-sent frames advance the same monotonic timeline as fresh frames, so RTP time never goes backwards. Empty or corrupted buffers are skipped, and capture fps, skips and re-sends are logged every 10 s.
  • Every reconnect ended the cast ("The cast was ended on the TV"). The reconnect path STOPs the mirroring app itself, and the receiver's resulting CLOSE was read as the user pressing Back. It is now ignored while recovery is in progress. This path is shared with Windows.
  • Frozen picture after a dead stream. GNOME sometimes fails a format renegotiation ("no more input formats") a few seconds in, and the idle re-send then repeated the last frame forever. A stream error now stops the re-send, so the stall detector reconnects with a fresh stream.

Window sharing

  • Window toggle hidden on every Wayland desktop. The probe called GetAvailableSourceTypes as a D-Bus method, but AvailableSourceTypes is a property. It is now read through org.freedesktop.DBus.Properties.Get.
  • Window cast could share the whole screen. The restore token was offered whenever the UI's current choice matched, not the kind the token was issued for. The token's kind is now saved with it (portal_restore_token_kind). GNOME's "Remember this selection" switch now decides whether the picker shows. A reconnect reuses the capture object's own token, so the picker never interrupts a running cast.

Picture

  • Light stripe beside the picture on non-16:9 sources. libswscale writes rows in 8-pixel SIMD blocks, so when the fit width is not a multiple of 8 (1620 for a 3:2 screen) a few columns spill into the right letterbox bar. The bar is repainted after every scale in all three conversion paths (BGRA to YUV420p, BGRA to NV12, NV12 to NV12). Shared with Windows. New test: GpuProcessorTest.RightBarStaysBlackWhenFitWidthIsNotABlockMultiple.
  • docs/improvements.md notes why a 3:2 screen cannot fill a 16:9 TV, and that there is no way back to the portal picker once a selection is remembered, each with a proposed fix.

Test plan

  • cmake --build build succeeds
  • ctest --output-on-failure in build/: 255/256 pass with WAYLAND_DISPLAY unset (no xvfb here). The one failure, CastE2ETest.AvSkewStaysBoundedOnLinux, also fails on unmodified master on this machine
  • Windows UI change verified with scripts\smoke_winui.ps1: N/A, no Windows UI change
  • Linux GUI change verified with ./build/app/castmirror-gui: Window toggle and GNOME window picker on Wayland
  • Real Cast device tested: Ubuntu 26.04, GNOME Wayland, 2880x1920, to a Chromecast. Before the rebase: a 9-minute cast with no crash, a steady 24 fps from the compositor, and idle re-sends while the screen was still. After the rebase: repeated start/stop casts, clean shutdown, no warnings
  • clang-format 22.1.8 --dry-run -Werror over core app tools tests passes

Notes

  • Rebase onto 1.0.4. This branch was cut before 1.0.3. Two of its original fixes were already in 1.0.4 in a more general form, so I kept upstream's versions and dropped mine: the first-frame probe lifetime fix (ProbeState in a shared_ptr) and the libayatana-appindicator-glib 2.x tray build. The idle re-send was ported onto 1.0.4's finalize_sw_frame path. NV12 CPU copies own their pixels, so they are kept for re-send; only frames borrowing a DMA-BUF fd are not.
  • Threading. Removing PW_STREAM_FLAG_RT_PROCESS puts the process callback on the same thread as the idle re-send timer. The shared timeline fields (last_emit_ts_, last_emit_now_) are still guarded by last_frame_mutex_, so earlier commits in the series are safe on their own.
  • Not yet known: why GNOME's format renegotiation fails mid-cast. The reconnect recovers from it, but the cause is open.

🤖 Generated with Claude Code

JoshGalland and others added 11 commits December 4, 2026 13:21
The portal stream offered a fixed 60/1 framerate. GNOME (Mutter) offers
a variable framerate of 0/1 with the real cap in maxFramerate, so the
formats never intersected, the stream never got a format or buffers,
and the session sat on "Connecting" until the 60 s first-frame wait
gave up with "Screen share permission denied or timed out".

The EnumFormat pods now carry a size range and a framerate range that
includes 0/1, which matches Mutter, KDE and wlroots. I also log stream
state changes and errors, which were invisible before.

Verified on Ubuntu 26.04 (GNOME, Wayland, 2880x1920) casting to a
Chromecast: format negotiated as BGRx 2880x1920 and the session
reached Streaming.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit used to also build the tray against
libayatana-appindicator-glib 2.x. Upstream 1.0.4 fixed that more
generally (both AppIndicator API generations), so on rebase I kept
upstream's tray.cc and app/CMakeLists.txt and dropped the matching
changelog lines, along with the first-frame probe entry that 1.0.4
also covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mutter only produces a buffer when the screen changes, so a still
screen (or a paused video) starved the encoder, tripped the session's
video-stall detector, and tore the cast down after 5 s. The Wayland
backend now re-sends the last frame every 100 ms while idle, the job
FramePacer already does for Windows desktop duplication. DMA-BUF frames
only borrow the PipeWire buffer's fd, so they are not kept for re-send.

I also skip buffers with no picture (size 0 or SPA_CHUNK_FLAG_CORRUPTED)
instead of encoding them or keeping them as the re-send frame, and log
compositor fps, skipped buffers and idle re-sends every 10 s so a choppy
picture can be traced to the compositor or to us.

Verified on Ubuntu 26.04 (GNOME, Wayland) casting to a Chromecast:
stretches at 6-8 fps from the compositor no longer raise a stall.

Rebased onto 1.0.4: the SW copy path is now finalize_sw_frame, which
emits through EmitFrame. NV12 CPU copies own their pixels, so they are
kept for re-send; only frames borrowing a DMA-BUF fd are not. Re-sent
frames advance the 1.0.3 monotonic timeline (last_emit_ts_ + elapsed,
as FramePacer does) under last_frame_mutex_, so a fresh frame after an
idle stretch never goes backwards in RTP time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reconnect path STOPs the mirroring app before it relaunches. The
receiver then sends CLOSE from the app's transport, which
OnChannelMessage took to mean the user pressed Back on the TV, so it
called FailSession and every stall-triggered reconnect ended the cast
for good ("The cast was ended on the TV"). A CLOSE that arrives while
recovery is in progress is now expected and ignored.

This path is shared with Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The window-support probe called GetAvailableSourceTypes as a method on
org.freedesktop.portal.ScreenCast. AvailableSourceTypes is a property,
so the call always failed with UnknownMethod and the GUI hid the
Screen | Window toggle on every Wayland desktop. I read it through
org.freedesktop.DBus.Properties.Get instead (GNOME reports 7: monitor,
window and virtual).

The portal restore token was offered when last_source_kind matched the
requested kind, but last_source_kind is the UI's current choice, saved
as soon as the toggle moves. A screen token was therefore offered for a
Window request and the portal silently restored the whole screen. I now
save the kind the token was issued for (portal_restore_token_kind, an
internal key like portal_restore_token) and only offer a token for the
same kind. An existing token has no kind, so the picker shows once.

Verified on Ubuntu 26.04 (GNOME, Wayland): the Window toggle appears,
GNOME's window picker is shown, and the chosen window casts to a
Chromecast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/improvements.md explains the letterboxing GpuProcessor does, the
workarounds (a 16:9 desktop resolution, or sharing a 16:9 window), and
a proposed Fit / Fill / Stretch setting with the files it would touch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion"

A few seconds into some casts GNOME failed a format renegotiation ("no
more input formats") and the PipeWire stream died. The idle re-send kept
repeating the last frame, so the TV showed a frozen picture for the rest
of the cast. On a stream error I now stop the re-send, so the session's
stall detector reconnects and starts a fresh stream. Why the
renegotiation fails is not known yet.

The per-10 s frame stats line was only written from the process
callback, so a compositor that stopped sending frames went unlogged. It
is now also written from the idle timer.

Restore tokens: a new cast offers the stored token only if it was issued
for the same kind. GNOME issues one only when "Remember this selection"
is on, so that switch decides whether the picker shows, for windows and
screens alike. When no token comes back, a stale stored token of that
kind is cleared. A reconnect reuses the capture object's own token, so
the picker never interrupts a running cast.

docs/improvements.md now notes that there is no way back to the picker
once a selection is remembered, with a proposed fix.

Verified on Ubuntu 26.04 (GNOME, Wayland) with a window cast to a
Chromecast: a steady 24 fps from the compositor during video playback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libswscale writes each output row in whole SIMD blocks (8 pixels on
x86). GpuProcessor scales into a fit rect in the middle of the frame, so
when the fit width is not a multiple of the block the last block spills
past the picture into the right-hand letterbox bar. A 3:2 screen
(2880x1920, fit width 1620) got 4 columns of Y=128 there, a light stripe
along the right edge of the picture on the TV; some window sizes did the
same. I repaint the right bar (luma and chroma) after every scale in all
three conversion paths.

GpuProcessorTest.RightBarStaysBlackWhenFitWidthIsNotABlockMultiple fails
without the fix and passes with it. The code is shared with Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The PipeWire screen-cast stream was connected with PW_STREAM_FLAG_RT_PROCESS,
so the process callback ran on PipeWire's realtime data-loop thread. rtkit
grants that thread realtime priority with RLIMIT_RTTIME at 200 ms soft/hard.
On the SW fallback path (BGRx 2880x1920) each callback allocates, zero-fills
and copies a ~22 MB frame, then the session copies it again; at 60 fps the
thread never sleeps long enough, passes 200 ms of RT CPU, and the kernel
SIGKILLs the whole app. No log line, no core dump, no kernel message: the
log just stops, anywhere from the LAUNCH reply to ~30 s into streaming.

Confirmed with bpftrace on signal:signal_generate: data-loop.0 sends SIGKILL
to itself from posix_cpu_timers_work.

- Drop PW_STREAM_FLAG_RT_PROCESS so the callback runs on the stream's own
  pw_main_loop thread, which has no RT time limit. The idle re-send timer
  runs on that thread too.
- Copy frames in finalize_sw_frame with vector::assign instead of
  resize + memcpy, so each frame is no longer zero-filled first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
clang-format 22.1.8 (the version CI pins) with the repo's .clang-format,
so the style job's --dry-run -Werror passes. Whitespace only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b8814676-84c1-4a23-b706-66ada9063de8
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@vindeckyy vindeckyy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Good work tracking all of this down. The Wayland fixes are real bugs and the writeup is thorough. Not merging yet, two things to fix first.

  1. CI is red on Ubuntu Release. scripts/count_tests.py --check fails because the new test bumps the count to 272 and the markers are stale in README.md, docs/ARCHITECTURE.md, docs/TEST_REPORT.md and docs/index.html. Run python3 scripts/count_tests.py and commit the refreshed markers. Master is green on the same base, so this is from your change.

  2. ResendIdleFrame() in core/src/display_capture_wayland.cc:1055 calls the frame callback while holding last_frame_mutex_. Copy the frame under the lock, release it, then call the callback. A slow or re-entrant callback under that lock stalls fresh frames and risks deadlock with Stop().

  3. FillBar() in core/src/gpu_processor.cc:22 does raw memsets with no bounds clamping. Clamp the row and x ranges to the plane before writing. The callers pass in-range geometry today, but a heap OOB write is one bad fit rect away.

Smaller stuff, fix or push back:

  • StreamLoop() at display_capture_wayland.cc:994 overwrites resend_timer_ without destroying a previous timer, and Stop() never clears the session restore token. Destroy any existing timer before creating one and clear the token in Stop().
  • The empty-buffer check at display_capture_wayland.cc:620 dereferences sbuf->datas[0] with no null check on sbuf->datas.
  • build_format() return value is never checked before use at display_capture_wayland.cc:968. A null param on builder overflow would break the connect call.

Local verification is blocked on my side (no PipeWire or FFmpeg dev headers on this host), so I am leaning on CI here. Fix the count markers and the callback lock and I will re-review.

JoshGalland and others added 3 commits December 5, 2026 12:34
scripts/count_tests.py --check failed in CI: the right-bar test brought the count to 272.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FillBar() now clamps its rows and columns to the plane's size and stride, so a bad fit rectangle cannot write outside the buffer. Today's callers pass in-range geometry; this is a guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ResendIdleFrame() called the frame callback while holding last_frame_mutex_. The kept frame is now a shared_ptr: the re-send takes a reference and stamps the timestamp under the lock, then calls the callback after releasing it, without copying ~22 MB of pixels each time.

Also from review: StreamLoop() destroys any earlier re-send timer before creating one, the empty-buffer check tests sbuf->datas for null, and a failed build_format() (pod buffer overflow) stops the connect with an error instead of passing a null param.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@vindeckyy vindeckyy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

All three fixes check out.

  • Test count markers refreshed to 272 in all four places. That was the CI failure, fixed.
  • ResendIdleFrame now copies the frame under the lock and calls the callback with no lock held. The shared_ptr handoff is sound: EmitFrame swaps the pointer instead of mutating the frame, and Stop drops it only after joining the loop thread.
  • FillBar clamps to the plane before writing, callers pass real plane sizes. Same for the chroma and NV12 UV planes.
  • The smaller items are in too: sbuf->datas null check, build_format return check, timer destroyed before recreate.

One thing I am leaving alone: Stop() still does not clear the session restore token. The comment at the declaration says the token is per capture object and CastSession makes a new object per cast, so clearing it in Stop() would just fight the reconnect path. Fine as is.

CI was stuck waiting on approval since this is a fork PR. I approved the run, it is executing now. Merging once it goes green.

@vindeckyy
vindeckyy merged commit 7b0376e into vindeckyy:master Dec 5, 2026
12 checks passed
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