Skip to content

Commit 8b675ca

Browse files
authored
fix: keep retained desktop frames intact and end sources without a backend (#546)
Unscaled frames shared one I420 buffer that the next capture overwrote, so a pool now reuses only buffers nothing references. A missing capture backend crashed the capture thread; the source now ends instead.
1 parent 62a5f7c commit 8b675ca

4 files changed

Lines changed: 181 additions & 5 deletions

File tree

‎docs/guide/video/desktop-capture.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,16 @@ videoSource.stop();
148148
videoSource.dispose();
149149
```
150150

151+
### Handling Capture Failures
152+
153+
`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:
154+
155+
```java
156+
videoTrack.addTrackEndedListener(track -> {
157+
// No frames will arrive from this source.
158+
});
159+
```
160+
151161
### Processing Frames
152162

153163
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).

‎webrtc-jni/src/main/cpp/include/media/video/VideoTrackDesktopSource.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
#ifndef JNI_WEBRTC_MEDIA_VIDEO_TRACK_DESKTOP_SOURCE_H_
1818
#define JNI_WEBRTC_MEDIA_VIDEO_TRACK_DESKTOP_SOURCE_H_
1919

20-
#include "api/video/i420_buffer.h"
2120
#include "api/video/adapted_video_track_source.h"
21+
#include "common_video/include/video_frame_buffer_pool.h"
2222
#include "modules/desktop_capture/desktop_capturer.h"
2323
#include "rtc_base/platform_thread.h"
2424

@@ -75,7 +75,7 @@ namespace jni
7575

7676
webrtc::PlatformThread captureThread;
7777

78-
webrtc::scoped_refptr<webrtc::I420Buffer> buffer;
78+
webrtc::VideoFrameBufferPool bufferPool;
7979
};
8080
}
8181

‎webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,10 @@ namespace jni
179179
}
180180
#endif
181181

182-
if (!buffer || buffer->width() != crop_w || buffer->height() != crop_h) {
183-
buffer = webrtc::I420Buffer::Create(crop_w, crop_h);
184-
}
182+
// Sinks and video processors may keep a frame beyond this call. The pool
183+
// writes only to buffers nothing else references, so that a kept frame
184+
// keeps its pixels. It has no size limit and never returns null.
185+
webrtc::scoped_refptr<webrtc::I420Buffer> buffer = bufferPool.CreateI420Buffer(crop_w, crop_h);
185186

186187
const int conversionResult = libyuv::ConvertToI420(
187188
frame->data(),
@@ -297,6 +298,15 @@ namespace jni
297298
: webrtc::DesktopCapturer::CreateScreenCapturer(options);
298299
}
299300

301+
if (!inner) {
302+
RTC_LOG(LS_ERROR) << "VideoTrackDesktopSource: No desktop capture backend available. "
303+
"Possible causes: no display, missing X11 extensions, a Wayland session "
304+
"without PipeWire support, or snap confinement.";
305+
306+
terminate();
307+
return;
308+
}
309+
300310
std::unique_ptr<webrtc::DesktopCapturer> capturer;
301311
capturer.reset(new webrtc::DesktopAndCursorComposer(std::move(inner), options));
302312

@@ -340,5 +350,9 @@ namespace jni
340350
}
341351

342352
capturer.reset();
353+
354+
// Frees what a burst of kept frames left behind. Buffers still in use
355+
// stay with their frames.
356+
bufferPool.Release();
343357
}
344358
}

‎webrtc/src/test/java/dev/onvoid/webrtc/media/video/VideoDesktopSourceTests.java‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import static org.junit.jupiter.api.Assumptions.assumeTrue;
2525

2626
import dev.onvoid.webrtc.TestBase;
27+
import dev.onvoid.webrtc.media.MediaStreamTrackState;
2728
import dev.onvoid.webrtc.media.video.desktop.DesktopSource;
2829
import dev.onvoid.webrtc.media.video.desktop.ScreenCapturer;
2930

@@ -37,7 +38,10 @@
3738
import java.util.List;
3839
import java.util.Locale;
3940
import java.util.concurrent.CompletableFuture;
41+
import java.util.concurrent.CountDownLatch;
4042
import java.util.concurrent.TimeUnit;
43+
import java.util.concurrent.atomic.AtomicInteger;
44+
import java.util.concurrent.atomic.AtomicReference;
4145

4246
import org.junit.jupiter.api.Test;
4347
import org.junit.jupiter.api.parallel.Execution;
@@ -199,6 +203,154 @@ void screenFramesFollowScreen() throws Exception {
199203
+ String.format(Locale.ROOT, "%.1f to %.1f", min, max));
200204
}
201205

206+
@Test
207+
void retainedFrameKeepsPixels() throws Exception {
208+
assumeFalse(isWaylandSession(), "Starting a capture asks the user what to share");
209+
assumeFalse(GraphicsEnvironment.isHeadless(), "No display");
210+
211+
DesktopSource screen = firstScreen();
212+
213+
// A window of our own, to change the screen while a frame is retained.
214+
Frame window = new Frame();
215+
Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment()
216+
.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
217+
218+
EventQueue.invokeAndWait(() -> {
219+
window.setUndecorated(true);
220+
window.setAlwaysOnTop(true);
221+
window.setBackground(Color.BLACK);
222+
window.setBounds(bounds.x + bounds.width / 10, bounds.y + bounds.height / 10,
223+
bounds.width * 8 / 10, bounds.height * 8 / 10);
224+
window.setVisible(true);
225+
window.toFront();
226+
});
227+
228+
// No maximum size: only frames that are not scaled were shared.
229+
VideoDesktopSource source = new VideoDesktopSource();
230+
source.setSourceId(screen.id, false);
231+
source.setFrameRate(10);
232+
233+
VideoTrack track = factory.createVideoTrack("screen", source);
234+
235+
AtomicReference<VideoFrame> retained = new AtomicReference<>();
236+
AtomicReference<ByteBuffer> original = new AtomicReference<>();
237+
CountDownLatch firstFrame = new CountDownLatch(1);
238+
CountDownLatch changedFrame = new CountDownLatch(1);
239+
240+
VideoProcessor processor = new VideoProcessor() {
241+
@Override
242+
public void setSink(VideoTrackSink sink) {
243+
}
244+
245+
@Override
246+
public void onFrameCaptured(VideoFrame frame) {
247+
ByteBuffer pixels = ((NativeI420Buffer) frame.buffer).getDataY();
248+
249+
if (retained.get() == null) {
250+
frame.retain();
251+
252+
original.set(copyOf(pixels));
253+
retained.set(frame);
254+
firstFrame.countDown();
255+
}
256+
else if (!original.get().equals(pixels)) {
257+
changedFrame.countDown();
258+
}
259+
}
260+
};
261+
262+
// Without a sink the source drops its frames.
263+
VideoTrackSink sink = VideoFrame::release;
264+
265+
try {
266+
source.setVideoProcessor(processor);
267+
track.addSink(sink);
268+
source.start();
269+
270+
assumeTrue(firstFrame.await(10, TimeUnit.SECONDS), "The screen delivered no frames");
271+
272+
EventQueue.invokeAndWait(() -> {
273+
window.setBackground(Color.WHITE);
274+
window.repaint();
275+
});
276+
277+
assumeTrue(changedFrame.await(10, TimeUnit.SECONDS), "The screen did not change");
278+
279+
source.stop();
280+
281+
assertEquals(original.get(), ((NativeI420Buffer) retained.get().buffer).getDataY(),
282+
"The next capture changed the pixels of a retained frame");
283+
}
284+
finally {
285+
source.stop();
286+
track.removeSink(sink);
287+
track.dispose();
288+
source.dispose();
289+
290+
if (retained.get() != null) {
291+
retained.get().release();
292+
}
293+
294+
EventQueue.invokeAndWait(window::dispose);
295+
}
296+
}
297+
298+
@Test
299+
void missingBackendEndsTrack() {
300+
assumeFalse(isWaylandSession(), "Starting a capture asks the user what to share");
301+
assumeTrue(hasNoBackend(), "A capture backend is available");
302+
303+
VideoDesktopSource source = new VideoDesktopSource();
304+
VideoTrack track = factory.createVideoTrack("screen", source);
305+
306+
AtomicInteger ended = new AtomicInteger();
307+
308+
track.addTrackEndedListener(t -> ended.incrementAndGet());
309+
310+
try {
311+
source.start();
312+
// Waits for the capture thread, which has given up by then.
313+
source.stop();
314+
315+
assertEquals(MediaStreamTrackState.ENDED, track.getState());
316+
assertEquals(1, ended.get());
317+
}
318+
finally {
319+
track.dispose();
320+
source.dispose();
321+
}
322+
}
323+
324+
private static ByteBuffer copyOf(ByteBuffer buffer) {
325+
ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
326+
327+
copy.put(buffer.duplicate());
328+
copy.flip();
329+
330+
return copy;
331+
}
332+
333+
private static boolean isWaylandSession() {
334+
return "wayland".equals(System.getenv("XDG_SESSION_TYPE"));
335+
}
336+
337+
private static boolean hasNoBackend() {
338+
ScreenCapturer capturer = new ScreenCapturer();
339+
340+
try {
341+
capturer.getDesktopSources();
342+
343+
return false;
344+
}
345+
catch (Error | RuntimeException e) {
346+
// Without a display, as on headless Linux, listing fails.
347+
return true;
348+
}
349+
finally {
350+
capturer.dispose();
351+
}
352+
}
353+
202354
private static double meanLuma(NativeI420Buffer buffer) {
203355
ByteBuffer data = buffer.getDataY();
204356
int stride = buffer.getStrideY();

0 commit comments

Comments
 (0)