Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/guide/video/desktop-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -75,7 +75,7 @@ namespace jni

webrtc::PlatformThread captureThread;

webrtc::scoped_refptr<webrtc::I420Buffer> buffer;
webrtc::VideoFrameBufferPool bufferPool;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<webrtc::I420Buffer> buffer = bufferPool.CreateI420Buffer(crop_w, crop_h);

const int conversionResult = libyuv::ConvertToI420(
frame->data(),
Expand Down Expand Up @@ -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<webrtc::DesktopCapturer> capturer;
capturer.reset(new webrtc::DesktopAndCursorComposer(std::move(inner), options));

Expand Down Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -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<VideoFrame> retained = new AtomicReference<>();
AtomicReference<ByteBuffer> 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();
Expand Down
Loading