diff --git a/docs/guide/video/desktop-capture.md b/docs/guide/video/desktop-capture.md index 3c127c7f..4207121b 100644 --- a/docs/guide/video/desktop-capture.md +++ b/docs/guide/video/desktop-capture.md @@ -148,6 +148,16 @@ videoSource.stop(); videoSource.dispose(); ``` +### Handling Capture Failures + +`start()` returns before capturing begins. If capturing cannot begin, because no capture backend is available or the selected source does not exist, the source ends and its tracks with it. Create the track and add the listener before calling `start()`, as a listener added later misses this: + +```java +videoTrack.addTrackEndedListener(track -> { + // No frames will arrive from this source. +}); +``` + ### Processing Frames A `VideoDesktopSource` can pass its frames through a `VideoProcessor` before they reach its tracks, for example to blank out a part of the screen. It works as for a camera; see [Changing Frames Before They Are Sent](/guide/video/camera-capture#changing-frames-before-they-are-sent). diff --git a/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h b/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h index 300bed40..bc8dc48d 100644 --- a/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h +++ b/webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h @@ -17,8 +17,8 @@ #ifndef JNI_WEBRTC_MEDIA_VIDEO_TRACK_DESKTOP_SOURCE_H_ #define JNI_WEBRTC_MEDIA_VIDEO_TRACK_DESKTOP_SOURCE_H_ -#include "api/video/i420_buffer.h" #include "api/video/adapted_video_track_source.h" +#include "common_video/include/video_frame_buffer_pool.h" #include "modules/desktop_capture/desktop_capturer.h" #include "rtc_base/platform_thread.h" @@ -75,7 +75,7 @@ namespace jni webrtc::PlatformThread captureThread; - webrtc::scoped_refptr buffer; + webrtc::VideoFrameBufferPool bufferPool; }; } diff --git a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp index 96f8c34e..f13a2dc8 100644 --- a/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp +++ b/webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp @@ -179,9 +179,10 @@ namespace jni } #endif - if (!buffer || buffer->width() != crop_w || buffer->height() != crop_h) { - buffer = webrtc::I420Buffer::Create(crop_w, crop_h); - } + // Sinks and video processors may keep a frame beyond this call. The pool + // writes only to buffers nothing else references, so that a kept frame + // keeps its pixels. It has no size limit and never returns null. + webrtc::scoped_refptr buffer = bufferPool.CreateI420Buffer(crop_w, crop_h); const int conversionResult = libyuv::ConvertToI420( frame->data(), @@ -297,6 +298,15 @@ namespace jni : webrtc::DesktopCapturer::CreateScreenCapturer(options); } + if (!inner) { + RTC_LOG(LS_ERROR) << "VideoTrackDesktopSource: No desktop capture backend available. " + "Possible causes: no display, missing X11 extensions, a Wayland session " + "without PipeWire support, or snap confinement."; + + terminate(); + return; + } + std::unique_ptr capturer; capturer.reset(new webrtc::DesktopAndCursorComposer(std::move(inner), options)); @@ -340,5 +350,9 @@ namespace jni } capturer.reset(); + + // Frees what a burst of kept frames left behind. Buffers still in use + // stay with their frames. + bufferPool.Release(); } } \ No newline at end of file diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java index 4ca3cc49..eab0f05c 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java @@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import dev.onvoid.webrtc.TestBase; +import dev.onvoid.webrtc.media.MediaStreamTrackState; import dev.onvoid.webrtc.media.video.desktop.DesktopSource; import dev.onvoid.webrtc.media.video.desktop.ScreenCapturer; @@ -37,7 +38,10 @@ import java.util.List; import java.util.Locale; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -199,6 +203,154 @@ void screenFramesFollowScreen() throws Exception { + String.format(Locale.ROOT, "%.1f to %.1f", min, max)); } + @Test + void retainedFrameKeepsPixels() throws Exception { + assumeFalse(isWaylandSession(), "Starting a capture asks the user what to share"); + assumeFalse(GraphicsEnvironment.isHeadless(), "No display"); + + DesktopSource screen = firstScreen(); + + // A window of our own, to change the screen while a frame is retained. + Frame window = new Frame(); + Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice().getDefaultConfiguration().getBounds(); + + EventQueue.invokeAndWait(() -> { + window.setUndecorated(true); + window.setAlwaysOnTop(true); + window.setBackground(Color.BLACK); + window.setBounds(bounds.x + bounds.width / 10, bounds.y + bounds.height / 10, + bounds.width * 8 / 10, bounds.height * 8 / 10); + window.setVisible(true); + window.toFront(); + }); + + // No maximum size: only frames that are not scaled were shared. + VideoDesktopSource source = new VideoDesktopSource(); + source.setSourceId(screen.id, false); + source.setFrameRate(10); + + VideoTrack track = factory.createVideoTrack("screen", source); + + AtomicReference retained = new AtomicReference<>(); + AtomicReference original = new AtomicReference<>(); + CountDownLatch firstFrame = new CountDownLatch(1); + CountDownLatch changedFrame = new CountDownLatch(1); + + VideoProcessor processor = new VideoProcessor() { + @Override + public void setSink(VideoTrackSink sink) { + } + + @Override + public void onFrameCaptured(VideoFrame frame) { + ByteBuffer pixels = ((NativeI420Buffer) frame.buffer).getDataY(); + + if (retained.get() == null) { + frame.retain(); + + original.set(copyOf(pixels)); + retained.set(frame); + firstFrame.countDown(); + } + else if (!original.get().equals(pixels)) { + changedFrame.countDown(); + } + } + }; + + // Without a sink the source drops its frames. + VideoTrackSink sink = VideoFrame::release; + + try { + source.setVideoProcessor(processor); + track.addSink(sink); + source.start(); + + assumeTrue(firstFrame.await(10, TimeUnit.SECONDS), "The screen delivered no frames"); + + EventQueue.invokeAndWait(() -> { + window.setBackground(Color.WHITE); + window.repaint(); + }); + + assumeTrue(changedFrame.await(10, TimeUnit.SECONDS), "The screen did not change"); + + source.stop(); + + assertEquals(original.get(), ((NativeI420Buffer) retained.get().buffer).getDataY(), + "The next capture changed the pixels of a retained frame"); + } + finally { + source.stop(); + track.removeSink(sink); + track.dispose(); + source.dispose(); + + if (retained.get() != null) { + retained.get().release(); + } + + EventQueue.invokeAndWait(window::dispose); + } + } + + @Test + void missingBackendEndsTrack() { + assumeFalse(isWaylandSession(), "Starting a capture asks the user what to share"); + assumeTrue(hasNoBackend(), "A capture backend is available"); + + VideoDesktopSource source = new VideoDesktopSource(); + VideoTrack track = factory.createVideoTrack("screen", source); + + AtomicInteger ended = new AtomicInteger(); + + track.addTrackEndedListener(t -> ended.incrementAndGet()); + + try { + source.start(); + // Waits for the capture thread, which has given up by then. + source.stop(); + + assertEquals(MediaStreamTrackState.ENDED, track.getState()); + assertEquals(1, ended.get()); + } + finally { + track.dispose(); + source.dispose(); + } + } + + private static ByteBuffer copyOf(ByteBuffer buffer) { + ByteBuffer copy = ByteBuffer.allocate(buffer.remaining()); + + copy.put(buffer.duplicate()); + copy.flip(); + + return copy; + } + + private static boolean isWaylandSession() { + return "wayland".equals(System.getenv("XDG_SESSION_TYPE")); + } + + private static boolean hasNoBackend() { + ScreenCapturer capturer = new ScreenCapturer(); + + try { + capturer.getDesktopSources(); + + return false; + } + catch (Error | RuntimeException e) { + // Without a display, as on headless Linux, listing fails. + return true; + } + finally { + capturer.dispose(); + } + } + private static double meanLuma(NativeI420Buffer buffer) { ByteBuffer data = buffer.getDataY(); int stride = buffer.getStrideY();