From 6318d44df3a4605702da58e97b325582c5392392 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Fri, 6 Nov 2026 21:02:57 +0100 Subject: [PATCH 1/5] fix: Keep Swing painting responsive during frame conversion --- .../onvoid/webrtc/client/swing/VideoView.java | 31 ++++++++---- .../webrtc/client/swing/VideoViewTests.java | 47 +++++++++++++++++++ 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java index 1aaa4821f..de37bad25 100644 --- a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java +++ b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java @@ -49,7 +49,10 @@ public class VideoView extends JComponent implements Consumer { private static final long serialVersionUID = 1L; - /** Guards the images and the pixel buffer. */ + /** Serializes conversion; never acquired by the event dispatch thread. */ + private final Object convertLock = new Object(); + + /** Guards the displayed image and its hand-over. */ private final Object lock = new Object(); /** The picture shown. */ @@ -60,6 +63,8 @@ public class VideoView extends JComponent implements Consumer { private transient ByteBuffer pixels; + private long generation; + private int rotation; private volatile boolean mirrored; @@ -87,7 +92,12 @@ public void accept(VideoFrame frame) { int width = buffer.getWidth(); int height = buffer.getHeight(); + long started; synchronized (lock) { + started = generation; + } + + synchronized (convertLock) { if (back == null || back.getWidth() != width || back.getHeight() != height) { back = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } @@ -107,23 +117,28 @@ public void accept(VideoFrame frame) { throw new IllegalStateException("The frame could not be converted", e); } - BufferedImage shown = front; - front = back; - back = shown; - rotation = frame.rotation; + synchronized (lock) { + if (started != generation) { + return; + } + BufferedImage shown = front; + front = back; + back = shown; + rotation = frame.rotation; + } } repaint(); } /** - * Removes the picture, leaving the background. + * Removes the picture, leaving the background, and drops frames already + * waiting for or undergoing conversion. */ public void clear() { synchronized (lock) { + generation++; front = null; - back = null; - pixels = null; } repaint(); diff --git a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java index 0f2ac89e7..54e8f1859 100644 --- a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java +++ b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java @@ -91,6 +91,53 @@ void showsFrame() { assertNull(view.snapshot()); } + @Test + void conversionLeavesEdtFree() throws Exception { + VideoView view = new VideoView(); + view.setSize(64, 48); + VideoFrame initial = frame(64, 48, 128, 128); + VideoFrame held = frame(64, 48, 16, 235); + java.util.concurrent.CountDownLatch converting = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.CountDownLatch resume = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + view.accept(initial); + dev.onvoid.webrtc.media.video.VideoFrameBuffer blocked = + (dev.onvoid.webrtc.media.video.VideoFrameBuffer) java.lang.reflect.Proxy.newProxyInstance( + getClass().getClassLoader(), + new Class[] { dev.onvoid.webrtc.media.video.VideoFrameBuffer.class }, + (proxy, method, args) -> { + if (method.getName().equals("toI420")) { + converting.countDown(); + assertTrue(resume.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } + return method.invoke(held.buffer, args); + }); + java.util.concurrent.Future delivery = executor.submit(() -> view.accept(new VideoFrame(blocked, 0))); + assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + java.util.concurrent.FutureTask painting = new java.util.concurrent.FutureTask<>(() -> { + assertGray(new Color(paint(view).getRGB(32, 24))); + view.clear(); + assertNull(view.snapshot()); + return null; + }); + javax.swing.SwingUtilities.invokeLater(painting); + painting.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + resume.countDown(); + delivery.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertNull(view.snapshot()); + view.accept(initial); + assertNotNull(view.snapshot()); + } + finally { + resume.countDown(); + executor.shutdownNow(); + executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); + initial.release(); + held.release(); + } + } + @Test void keepsAspectRatio() { VideoView view = new VideoView(); From 65c65db78fb4ae052d32f710fed58a7b4600613d Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Fri, 6 Nov 2026 21:07:22 +0100 Subject: [PATCH 2/5] fix: Bound video view dimensions and reuse direct pixel buffers --- docs/guide/client-api.md | 13 +++ .../webrtc/client/javafx/VideoView.java | 78 ++++++++++++---- .../webrtc/client/javafx/VideoViewTest.java | 68 +++++++++++++- .../onvoid/webrtc/client/swing/VideoView.java | 38 +++++++- .../webrtc/client/swing/VideoViewTests.java | 91 +++++++++++++++---- 5 files changed, 246 insertions(+), 42 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 5038d01c3..02f276039 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -318,6 +318,18 @@ frame.add(remoteView, BorderLayout.CENTER); `snapshot()` returns a copy of the picture shown, for saving a still or for tests. +Both views reject nonpositive dimensions and frames above `VideoView.MAX_PIXELS` +(3840 × 2160 pixels) with `IllegalArgumentException`. Use `new VideoView(maxPixels)` +to choose a smaller limit, for example `new VideoView(1280 * 720)` for a preview. +Conversion buffers reserve their configured maximum capacity on first use and stay +available across resolution changes and `clear()`. They are freed when the view +becomes unreachable. Swing uses one direct buffer; JavaFX uses up to three. +Including displayed images and a replacement image during a resize, live pixel +storage is at most `maxPixels * 16L` bytes for Swing and `maxPixels * 20L` for +JavaFX (about 127 MiB and 159 MiB at the default limit). Input frames, snapshots, +toolkit rendering resources, and discarded heap images awaiting collection are +additional. Set a smaller limit when displaying several videos. + For JavaFX, the `webrtc-java-javafx` module has a `VideoView` node in `dev.onvoid.webrtc.client.javafx` that works the same way. It needs Java 11 and the JavaFX your application already uses: ```xml @@ -639,6 +651,7 @@ peer.onChannel(channel -> { // channels the remote peer opens }); ``` + - A channel may be used right away: messages sent before it opens are held until it does. - Messages that arrive while a channel has no `onMessage` handler are kept for the next one, so none are lost while a handler is being set up. - `send` takes a `String`, a `byte[]` or a `ByteBuffer`, and copies the data before it returns. diff --git a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java index 1de71a375..f774b956c 100644 --- a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java +++ b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java @@ -50,6 +50,11 @@ public class VideoView extends Region implements Consumer { private final Canvas canvas = new Canvas(); + /** Default and maximum permitted number of pixels per frame (3840 by 2160). */ + public static final int MAX_PIXELS = 3840 * 2160; + + private final int maxPixels; + private final BooleanProperty mirrored = new SimpleBooleanProperty(this, "mirrored"); /** Serializes conversions, for frames of more than one subscription. */ @@ -58,11 +63,11 @@ public class VideoView extends Region implements Consumer { /** Guards the hand-over between the converting thread and the JavaFX thread. */ private final Object lock = new Object(); - // Three buffers: the converting thread fills back, hands it over as + // Three reusable buffers: the converting thread fills a free slot, hands it over as // ready, and the JavaFX thread paints from shown. None is written while // another thread reads it. - private Pixels back; + private final Pixels[] buffers = new Pixels[3]; private Pixels ready; @@ -71,10 +76,11 @@ public class VideoView extends Region implements Consumer { /** Counts the calls of clear(), to tell the frames that came before one. */ private long generation; - // Confined to the JavaFX Application Thread. - + // Set under lock; its pixels are read only on the JavaFX Application Thread. private Pixels shown; + // Confined to the JavaFX Application Thread. + private WritableImage image; private int rotation; @@ -84,6 +90,27 @@ public class VideoView extends Region implements Consumer { * Creates a view with a preferred size of 640 by 360 pixels. */ public VideoView() { + this(MAX_PIXELS); + } + + /** + * Creates a view with a limit on frame size. Conversion buffers reserve + * {@code maxPixels * 4} bytes each on first use and are reused across size + * changes and clear(). They are released with the view, not by clear(). + * At most three direct buffers and two live JavaFX images (including a + * replacement during a resize) require at most {@code maxPixels * 20L} + * bytes of pixel storage. + * This excludes input frames, snapshots, toolkit rendering resources and + * unreachable images awaiting garbage collection. + * + * @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}. + * @throws IllegalArgumentException if the limit is outside this range. + */ + public VideoView(int maxPixels) { + if (maxPixels <= 0 || maxPixels > MAX_PIXELS) { + throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels); + } + this.maxPixels = maxPixels; getChildren().add(canvas); setPrefSize(640, 360); setMinSize(0, 0); @@ -96,12 +123,19 @@ public VideoView() { * frame is not released, which its subscription does. * * @param frame the frame to show. + * @throws IllegalArgumentException if dimensions are nonpositive or the + * frame exceeds this view's pixel limit. */ @Override public void accept(VideoFrame frame) { VideoFrameBuffer buffer = frame.buffer; int width = buffer.getWidth(); int height = buffer.getHeight(); + long pixelCount = (long) width * height; + if (width <= 0 || height <= 0 || pixelCount > maxPixels) { + throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height); + } + int byteCount = (int) (pixelCount * 4L); long started; // Before the wait for convertLock, as the frame came before any clear() @@ -111,15 +145,26 @@ public void accept(VideoFrame frame) { } synchronized (convertLock) { - Pixels target = back; - - if (target == null || !target.fits(width, height)) { - target = new Pixels(width, height); + // Only this thread chooses/writes a slot; presentation may read the + // other two. Allocate outside the hand-over lock. + int slot = 0; + synchronized (lock) { + while (buffers[slot] != null && (buffers[slot] == ready || buffers[slot] == shown)) { + slot++; + } } + Pixels target = buffers[slot]; + if (target == null) { + target = new Pixels((int) (maxPixels * 4L)); + buffers[slot] = target; + } + target.width = width; + target.height = height; try { // libyuv's ARGB is B, G, R, A in memory, which is JavaFX's BGRA. target.data.clear(); + target.data.limit(byteCount); VideoBufferConverter.convertFromI420(buffer, target.data, FourCC.ARGB); target.data.rewind(); } @@ -134,7 +179,6 @@ public void accept(VideoFrame frame) { return; } - back = ready; ready = target; if (scheduled) { @@ -156,10 +200,9 @@ public void clear() { synchronized (lock) { generation++; ready = null; - back = null; + shown = null; } - shown = null; image = null; draw(); } @@ -270,23 +313,18 @@ private void draw() { private static final class Pixels { - final int width; + int width; - final int height; + int height; final ByteBuffer data; int rotation; - Pixels(int width, int height) { - this.width = width; - this.height = height; - this.data = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.LITTLE_ENDIAN); + Pixels(int capacity) { + this.data = ByteBuffer.allocateDirect(capacity).order(ByteOrder.LITTLE_ENDIAN); } - boolean fits(int otherWidth, int otherHeight) { - return width == otherWidth && height == otherHeight; - } } } diff --git a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java index 41831bbdb..551f1e1ab 100644 --- a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java +++ b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java @@ -20,8 +20,14 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; import java.nio.ByteBuffer; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; @@ -100,7 +106,7 @@ void needsToolkit() { @Test void showsFrame() throws Exception { - VideoView view = onFx(VideoView::new); + VideoView view = onFx(() -> new VideoView(320 * 240)); assertNull(onFx(view::snapshot)); view.accept(frame(64, 48, 128, 128)); @@ -119,7 +125,7 @@ void showsFrame() throws Exception { @Test void clearDropsFrameInConversion() throws Exception { - VideoView view = onFx(VideoView::new); + VideoView view = onFx(() -> new VideoView(320 * 240)); CountDownLatch converting = new CountDownLatch(1); CountDownLatch cleared = new CountDownLatch(1); VideoFrame held = frame(64, 48, 128, 128); @@ -183,6 +189,60 @@ public void release() { assertEquals(32, (int) presented(view).getWidth()); } + @Test + void rejectsInvalidSizes() throws Exception { + assertThrows(IllegalArgumentException.class, () -> new VideoView(0)); + assertThrows(IllegalArgumentException.class, + () -> new VideoView(VideoView.MAX_PIXELS + 1)); + VideoView view = onFx(() -> new VideoView(64 * 48)); + for (int[] size : new int[][] { { 0, 1 }, { -1, -1 }, { 65, 48 }, + { 65536, 65536 }, { Integer.MAX_VALUE, Integer.MAX_VALUE } }) { + VideoFrameBuffer invalid = (VideoFrameBuffer) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] { VideoFrameBuffer.class }, + (proxy, method, args) -> { + if (method.getName().equals("getWidth")) return size[0]; + if (method.getName().equals("getHeight")) return size[1]; + throw new AssertionError("Invalid frame reached conversion"); + }); + assertThrows(IllegalArgumentException.class, + () -> view.accept(new VideoFrame(invalid, 0))); + } + } + + @Test + void reusesBuffersAcrossSizes() throws Exception { + VideoView view = onFx(() -> new VideoView(64 * 48)); + Set storage = Collections.newSetFromMap(new IdentityHashMap<>()); + Field field = VideoView.class.getDeclaredField("buffers"); + field.setAccessible(true); + for (int i = 0; i < 12; i++) { + int width = i % 2 == 0 ? 64 : 32; + VideoFrame frame = frame(width, 48, 128, 128); + try { + view.accept(frame); + Image snapshot = onFx(view::snapshot); + assertEquals(width, (int) snapshot.getWidth()); + assertGray(snapshot.getPixelReader().getColor(0, 0)); + for (Object slot : (Object[]) field.get(view)) { + if (slot != null) { + Field data = slot.getClass().getDeclaredField("data"); + data.setAccessible(true); + storage.add((ByteBuffer) data.get(slot)); + } + } + if (i >= 6) onFx(() -> { view.clear(); return null; }); + } + finally { + frame.release(); + } + } + assertTrue(storage.size() <= 3); + for (ByteBuffer data : storage) { + assertTrue(data.isDirect()); + assertEquals(64 * 48 * 4, data.capacity()); + } + } + @Test void keepsAspectRatio() throws Exception { VideoView view = sized(200, 100); @@ -234,7 +294,7 @@ void showsRemoteVideo() throws Exception { Peer caller = rtc.createPeer(PeerOptions.builder().signaling(link.first()).build()); Peer callee = rtc.createPeer(PeerOptions.builder().signaling(link.second()).polite(true).build()); CustomVideo video = rtc.media().customVideo("video"); - VideoView view = onFx(VideoView::new); + VideoView view = onFx(() -> new VideoView(320 * 240)); callee.onTrack(track -> track.asVideo().onFrame(view)); caller.addTrack(video); @@ -260,7 +320,7 @@ void showsRemoteVideo() throws Exception { private VideoView sized(int width, int height) throws Exception { return onFx(() -> { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); new Scene(view, width, height); view.resize(width, height); view.layout(); diff --git a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java index de37bad25..55d86f598 100644 --- a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java +++ b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java @@ -49,6 +49,11 @@ public class VideoView extends JComponent implements Consumer { private static final long serialVersionUID = 1L; + /** Default and maximum permitted number of pixels per frame (3840 by 2160). */ + public static final int MAX_PIXELS = 3840 * 2160; + + private final int maxPixels; + /** Serializes conversion; never acquired by the event dispatch thread. */ private final Object convertLock = new Object(); @@ -75,6 +80,27 @@ public class VideoView extends JComponent implements Consumer { * 360 pixels. */ public VideoView() { + this(MAX_PIXELS); + } + + /** + * Creates a view with a limit on frame size. Conversion buffers reserve + * {@code maxPixels * 4} bytes each on first use and are reused across size + * changes and clear(). They are released with the view, not by clear(). + * One direct buffer and at most three live image arrays (including a + * replacement during a resize) require at most {@code maxPixels * 16L} + * bytes of pixel storage. + * This excludes input frames, snapshots, toolkit rendering resources and + * unreachable images awaiting garbage collection. + * + * @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}. + * @throws IllegalArgumentException if the limit is outside this range. + */ + public VideoView(int maxPixels) { + if (maxPixels <= 0 || maxPixels > MAX_PIXELS) { + throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels); + } + this.maxPixels = maxPixels; setBackground(Color.BLACK); setOpaque(true); setPreferredSize(new Dimension(640, 360)); @@ -85,12 +111,19 @@ public VideoView() { * frame is not released, which its subscription does. * * @param frame the frame to show. + * @throws IllegalArgumentException if dimensions are nonpositive or the + * frame exceeds this view's pixel limit. */ @Override public void accept(VideoFrame frame) { VideoFrameBuffer buffer = frame.buffer; int width = buffer.getWidth(); int height = buffer.getHeight(); + long pixelCount = (long) width * height; + if (width <= 0 || height <= 0 || pixelCount > maxPixels) { + throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height); + } + int byteCount = (int) (pixelCount * 4L); long started; synchronized (lock) { @@ -101,14 +134,15 @@ public void accept(VideoFrame frame) { if (back == null || back.getWidth() != width || back.getHeight() != height) { back = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } - if (pixels == null || pixels.capacity() != width * height * 4) { - pixels = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.LITTLE_ENDIAN); + if (pixels == null) { + pixels = ByteBuffer.allocateDirect((int) (maxPixels * 4L)).order(ByteOrder.LITTLE_ENDIAN); } try { // libyuv's ARGB is B, G, R, A in memory, which read as // little-endian ints is what TYPE_INT_RGB holds. pixels.clear(); + pixels.limit(byteCount); VideoBufferConverter.convertFromI420(buffer, pixels, FourCC.ARGB); pixels.rewind(); pixels.asIntBuffer().get(((DataBufferInt) back.getRaster().getDataBuffer()).getData()); diff --git a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java index 54e8f1859..cbd498248 100644 --- a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java +++ b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java @@ -21,10 +21,21 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import javax.swing.SwingUtilities; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -41,6 +52,7 @@ import dev.onvoid.webrtc.client.WebRtc; import dev.onvoid.webrtc.media.video.NativeI420Buffer; import dev.onvoid.webrtc.media.video.VideoFrame; +import dev.onvoid.webrtc.media.video.VideoFrameBuffer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -76,7 +88,7 @@ void closeRuntime() { @Test void showsFrame() { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); assertNull(view.snapshot()); view.accept(frame(64, 48, 128, 128)); @@ -93,19 +105,19 @@ void showsFrame() { @Test void conversionLeavesEdtFree() throws Exception { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); view.setSize(64, 48); VideoFrame initial = frame(64, 48, 128, 128); VideoFrame held = frame(64, 48, 16, 235); - java.util.concurrent.CountDownLatch converting = new java.util.concurrent.CountDownLatch(1); - java.util.concurrent.CountDownLatch resume = new java.util.concurrent.CountDownLatch(1); - java.util.concurrent.ExecutorService executor = Executors.newSingleThreadExecutor(); + CountDownLatch converting = new CountDownLatch(1); + CountDownLatch resume = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); try { view.accept(initial); - dev.onvoid.webrtc.media.video.VideoFrameBuffer blocked = - (dev.onvoid.webrtc.media.video.VideoFrameBuffer) java.lang.reflect.Proxy.newProxyInstance( + VideoFrameBuffer blocked = + (VideoFrameBuffer) Proxy.newProxyInstance( getClass().getClassLoader(), - new Class[] { dev.onvoid.webrtc.media.video.VideoFrameBuffer.class }, + new Class[] { VideoFrameBuffer.class }, (proxy, method, args) -> { if (method.getName().equals("toI420")) { converting.countDown(); @@ -113,15 +125,15 @@ void conversionLeavesEdtFree() throws Exception { } return method.invoke(held.buffer, args); }); - java.util.concurrent.Future delivery = executor.submit(() -> view.accept(new VideoFrame(blocked, 0))); + Future delivery = executor.submit(() -> view.accept(new VideoFrame(blocked, 0))); assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); - java.util.concurrent.FutureTask painting = new java.util.concurrent.FutureTask<>(() -> { + FutureTask painting = new FutureTask<>(() -> { assertGray(new Color(paint(view).getRGB(32, 24))); view.clear(); assertNull(view.snapshot()); return null; }); - javax.swing.SwingUtilities.invokeLater(painting); + SwingUtilities.invokeLater(painting); painting.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); resume.countDown(); delivery.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -138,9 +150,56 @@ void conversionLeavesEdtFree() throws Exception { } } + @Test + void rejectsInvalidSizes() throws Exception { + assertThrows(IllegalArgumentException.class, () -> new VideoView(0)); + assertThrows(IllegalArgumentException.class, + () -> new VideoView(VideoView.MAX_PIXELS + 1)); + VideoView view = new VideoView(64 * 48); + for (int[] size : new int[][] { { 0, 1 }, { -1, -1 }, { 65, 48 }, + { 65536, 65536 }, { Integer.MAX_VALUE, Integer.MAX_VALUE } }) { + VideoFrameBuffer invalid = (VideoFrameBuffer) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] { VideoFrameBuffer.class }, + (proxy, method, args) -> { + if (method.getName().equals("getWidth")) return size[0]; + if (method.getName().equals("getHeight")) return size[1]; + throw new AssertionError("Invalid frame reached conversion"); + }); + assertThrows(IllegalArgumentException.class, + () -> view.accept(new VideoFrame(invalid, 0))); + } + } + + @Test + void reusesBuffersAcrossSizes() throws Exception { + VideoView view = new VideoView(64 * 48); + Set storage = Collections.newSetFromMap(new IdentityHashMap<>()); + Field field = VideoView.class.getDeclaredField("pixels"); + field.setAccessible(true); + for (int i = 0; i < 12; i++) { + int width = i % 2 == 0 ? 64 : 32; + VideoFrame frame = frame(width, 48, 128, 128); + try { + view.accept(frame); + assertEquals(width, view.snapshot().getWidth()); + assertGray(new Color(view.snapshot().getRGB(0, 0))); + storage.add((ByteBuffer) field.get(view)); + if (i >= 6) view.clear(); + } + finally { + frame.release(); + } + } + assertTrue(storage.size() <= 1); + for (ByteBuffer data : storage) { + assertTrue(data.isDirect()); + assertEquals(64 * 48 * 4, data.capacity()); + } + } + @Test void keepsAspectRatio() { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); view.setSize(200, 100); view.accept(frame(64, 48, 128, 128)); @@ -152,7 +211,7 @@ void keepsAspectRatio() { @Test void mirrors() { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); view.setSize(64, 48); view.accept(frame(64, 48, 16, 235)); @@ -171,7 +230,7 @@ void anyRotationMultiple() { assertArrayEquals(rotated(90), rotated(450)); // Sideways, a 4:3 picture in a 4:3 view leaves bars on the sides. - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); view.setSize(64, 48); view.accept(frame(64, 48, 128, 128, -90)); @@ -184,7 +243,7 @@ void anyRotationMultiple() { void showsRemoteVideo() throws Exception { Peer[] peers = pair(); CustomVideo video = rtc.media().customVideo("video"); - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); peers[1].onTrack(track -> track.asVideo().onFrame(view)); peers[0].addTrack(video); @@ -230,7 +289,7 @@ private Peer[] pair() { /** The pixels a 64x48 view paints of a 64x48 two-tone frame with the given rotation. */ private static int[] rotated(int rotation) { - VideoView view = new VideoView(); + VideoView view = new VideoView(320 * 240); view.setSize(64, 48); view.accept(frame(64, 48, 16, 235, rotation)); From 97d22d65406ff2a2991563ed7cab068358e2caff Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Fri, 6 Nov 2026 21:08:00 +0100 Subject: [PATCH 3/5] fix: Keep message payloads out of default log output --- docs/guide/client-api.md | 6 ++ .../dev/onvoid/webrtc/client/Message.java | 92 ++++++++++++++++++- .../onvoid/webrtc/client/MessageTests.java | 89 ++++++++++++++++++ 3 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/client/MessageTests.java diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 02f276039..4c6cfaf89 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -651,6 +651,12 @@ peer.onChannel(channel -> { // channels the remote peer opens }); ``` +`Message.toString()` reports only the message type and byte length. Access content +explicitly with `text()` or `bytes()`. For diagnostics, `message.preview(64)` inspects +at most 64 payload bytes and escapes control characters. Binary previews use hex. +Use `message.preview(64, prefix -> redact(prefix))` to apply your own masking before +escaping; the masking function must handle secrets truncated at the prefix boundary. +The preview marks truncated content and also limits the masking function's output. - A channel may be used right away: messages sent before it opens are held until it does. - Messages that arrive while a channel has no `onMessage` handler are kept for the next one, so none are lost while a handler is being set up. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Message.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Message.java index 81a382fdc..871686a95 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Message.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Message.java @@ -16,7 +16,12 @@ package dev.onvoid.webrtc.client; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.function.UnaryOperator; /** * A message received on a {@link DataChannel}. It holds a copy of the data and @@ -62,8 +67,93 @@ public int size() { return data.length; } + /** + * Returns message type and byte length, without exposing payload data. + * Use {@link #text()}, {@link #bytes()} or {@link #preview(int)} explicitly + * when content is needed. + */ @Override public String toString() { - return binary ? "Message[" + data.length + " bytes]" : "Message[" + text() + "]"; + return "Message[type=" + (binary ? "binary" : "text") + ", length=" + data.length + " bytes]"; + } + + /** + * Returns metadata with an escaped, bounded payload preview. Text uses + * UTF-8; binary data uses hexadecimal. An incomplete trailing UTF-8 + * character is omitted. Control characters are escaped for single-line logs. + * + * @param maxBytes maximum input bytes to inspect; must be nonnegative. + * @return the diagnostic representation. + */ + public String preview(int maxBytes) { + return preview(maxBytes, UnaryOperator.identity()); + } + + /** + * Returns a bounded preview with application-defined masking, applied before + * escaping. The mask receives only the bounded prefix, so masking rules must + * also handle secrets cut off at its end. Its result is limited to twice + * {@code maxBytes} UTF-16 units (enough for hexadecimal), then escaped. + * At most six output characters are used per UTF-16 unit. + * + * @param maxBytes maximum input bytes to inspect; must be nonnegative. + * @param mask transforms the prefix to remove sensitive values; must return + * a non-null string. + * @return metadata and the masked preview, with a truncation indicator. + * @throws IllegalArgumentException if maxBytes is negative. + * @throws NullPointerException if mask or its result is null. + */ + public String preview(int maxBytes, UnaryOperator mask) { + if (maxBytes < 0) { + throw new IllegalArgumentException("Negative preview limit"); + } + Objects.requireNonNull(mask, "mask"); + int count = Math.min(data.length, maxBytes); + String prefix; + boolean truncated = count < data.length; + if (binary) { + StringBuilder hex = new StringBuilder(); + for (int i = 0; i < count; i++) { + int value = data[i] & 0xff; + hex.append(Character.forDigit(value >>> 4, 16)); + hex.append(Character.forDigit(value & 15, 16)); + } + prefix = hex.toString(); + } + else { + ByteBuffer input = ByteBuffer.wrap(data, 0, count); + CharBuffer output = CharBuffer.allocate(count); + StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .decode(input, output, count == data.length); + truncated |= input.hasRemaining(); + output.flip(); + prefix = output.toString(); + } + String masked = Objects.requireNonNull(mask.apply(prefix), "mask result"); + int end = (int) Math.min(masked.length(), 2L * maxBytes); + if (end > 0 && end < masked.length() && Character.isHighSurrogate(masked.charAt(end - 1))) { + end--; + } + truncated |= end < masked.length(); + StringBuilder escaped = new StringBuilder(); + for (int i = 0; i < end; i++) { + char ch = masked.charAt(i); + if (ch == '\\' || ch == '"') { + escaped.append('\\').append(ch); + } + else if (Character.isISOControl(ch) || Character.getType(ch) == Character.FORMAT + || ch == '\u2028' || ch == '\u2029') { + escaped.append("\\u"); + for (int shift = 12; shift >= 0; shift -= 4) { + escaped.append(Character.forDigit((ch >>> shift) & 15, 16)); + } + } + else { + escaped.append(ch); + } + } + return toString() + " preview=\"" + escaped + "\"" + (truncated ? " (truncated)" : ""); } } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/MessageTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/MessageTests.java new file mode 100644 index 000000000..81ce5cf7f --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MessageTests.java @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.Test; + +class MessageTests { + + @Test + void metadataOmitsContent() { + assertEquals("Message[type=text, length=6 bytes]", text("secret").toString()); + assertEquals("Message[type=binary, length=3 bytes]", + new Message(new byte[] { 1, 2, 3 }, true).toString()); + assertTrue(new Message(new byte[1_000_000], false).toString().length() < 64); + assertEquals("secret", text("secret").text()); + } + + @Test + void boundedPreview() { + assertEquals("Message[type=text, length=6 bytes] preview=\"sec\" (truncated)", + text("secret").preview(3)); + assertTrue(text("secret").preview(0).endsWith("preview=\"\" (truncated)")); + assertTrue(text("").preview(0).endsWith("preview=\"\"")); + assertTrue(text("é😀!").preview(4).endsWith("preview=\"é\" (truncated)")); + assertTrue(text("é😀!").preview(6).endsWith("preview=\"é😀\" (truncated)")); + assertTrue(text("é😀!").preview(7).endsWith("preview=\"é😀!\"")); + } + + @Test + void escapesLogControls() { + String preview = text("a\n\r\t\u001b\u2028\u202e\"\\").preview(100); + assertTrue(preview.endsWith("preview=\"a\\u000a\\u000d\\u0009\\u001b\\u2028\\u202e\\\"\\\\\"")); + assertFalse(preview.contains("\n")); + } + + @Test + void masksBeforeEscaping() { + AtomicReference inspected = new AtomicReference<>(); + String preview = text("token=secret and more").preview(12, prefix -> { + inspected.set(prefix); + return prefix.replace("secret", "[hidden]"); + }); + assertEquals("token=secret", inspected.get()); + assertFalse(preview.contains("secret")); + assertTrue(preview.contains("token=[hidden]")); + assertTrue(text("abc").preview(2, prefix -> "123456789").endsWith("preview=\"1234\" (truncated)")); + } + + @Test + void binaryPreview() { + Message message = new Message(new byte[] { 0, (byte) 0xff, 42 }, true); + assertTrue(message.preview(2).endsWith("preview=\"00ff\" (truncated)")); + assertTrue(message.preview(3).endsWith("preview=\"00ff2a\"")); + assertTrue(message.preview(3, prefix -> "hidden").endsWith("preview=\"hidden\"")); + } + + @Test + void rejectsInvalidPreview() { + assertThrows(IllegalArgumentException.class, () -> text("x").preview(-1)); + assertThrows(NullPointerException.class, () -> text("x").preview(1, null)); + assertThrows(NullPointerException.class, () -> text("x").preview(1, prefix -> null)); + } + + private static Message text(String value) { + return new Message(value.getBytes(StandardCharsets.UTF_8), false); + } +} From 1ad811dd691d5744d90a4f56fa80be6193aaca2a Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 10:33:23 +0100 Subject: [PATCH 4/5] fix: remove the fixed video view pixel limit --- docs/guide/client-api.md | 20 +++---- .../webrtc/client/javafx/VideoView.java | 52 ++++++----------- .../webrtc/client/javafx/VideoViewTest.java | 55 ++++++++++++++---- .../onvoid/webrtc/client/swing/VideoView.java | 52 ++++++----------- .../webrtc/client/swing/VideoViewTests.java | 58 ++++++++++++++----- 5 files changed, 133 insertions(+), 104 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 4c6cfaf89..3bee0a64c 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -318,17 +318,15 @@ frame.add(remoteView, BorderLayout.CENTER); `snapshot()` returns a copy of the picture shown, for saving a still or for tests. -Both views reject nonpositive dimensions and frames above `VideoView.MAX_PIXELS` -(3840 × 2160 pixels) with `IllegalArgumentException`. Use `new VideoView(maxPixels)` -to choose a smaller limit, for example `new VideoView(1280 * 720)` for a preview. -Conversion buffers reserve their configured maximum capacity on first use and stay -available across resolution changes and `clear()`. They are freed when the view -becomes unreachable. Swing uses one direct buffer; JavaFX uses up to three. -Including displayed images and a replacement image during a resize, live pixel -storage is at most `maxPixels * 16L` bytes for Swing and `maxPixels * 20L` for -JavaFX (about 127 MiB and 159 MiB at the default limit). Input frames, snapshots, -toolkit rendering resources, and discarded heap images awaiting collection are -additional. Set a smaller limit when displaying several videos. +Both views support resolutions such as 8K without a fixed pixel limit. They reject +nonpositive dimensions and frames whose four-byte pixel data cannot fit in a Java +buffer, using overflow-safe arithmetic. Conversion buffers allocate on demand, +grow geometrically when necessary, and retain their capacity across smaller frames +and `clear()`. Swing reuses one direct buffer; JavaFX reuses up to three. Buffer +memory is released when the view becomes unreachable. Memory usage follows the +largest frames received and includes displayed images, conversion buffers, and +replacement allocations awaiting garbage collection. Snapshots, input frames and +toolkit rendering resources use additional memory. For JavaFX, the `webrtc-java-javafx` module has a `VideoView` node in `dev.onvoid.webrtc.client.javafx` that works the same way. It needs Java 11 and the JavaFX your application already uses: diff --git a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java index f774b956c..a476322cb 100644 --- a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java +++ b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java @@ -45,16 +45,14 @@ * Application Thread only paints, at most once per pulse however many frames * arrive. The picture keeps its aspect ratio and its rotation, on a black * background, and can be mirrored for a local camera preview. + * Conversion buffers grow on demand and are reused across resolution changes + * and clear(). Their retained capacity follows the largest frames received; + * buffer memory is released when the view becomes unreachable. */ public class VideoView extends Region implements Consumer { private final Canvas canvas = new Canvas(); - /** Default and maximum permitted number of pixels per frame (3840 by 2160). */ - public static final int MAX_PIXELS = 3840 * 2160; - - private final int maxPixels; - private final BooleanProperty mirrored = new SimpleBooleanProperty(this, "mirrored"); /** Serializes conversions, for frames of more than one subscription. */ @@ -90,27 +88,6 @@ public class VideoView extends Region implements Consumer { * Creates a view with a preferred size of 640 by 360 pixels. */ public VideoView() { - this(MAX_PIXELS); - } - - /** - * Creates a view with a limit on frame size. Conversion buffers reserve - * {@code maxPixels * 4} bytes each on first use and are reused across size - * changes and clear(). They are released with the view, not by clear(). - * At most three direct buffers and two live JavaFX images (including a - * replacement during a resize) require at most {@code maxPixels * 20L} - * bytes of pixel storage. - * This excludes input frames, snapshots, toolkit rendering resources and - * unreachable images awaiting garbage collection. - * - * @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}. - * @throws IllegalArgumentException if the limit is outside this range. - */ - public VideoView(int maxPixels) { - if (maxPixels <= 0 || maxPixels > MAX_PIXELS) { - throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels); - } - this.maxPixels = maxPixels; getChildren().add(canvas); setPrefSize(640, 360); setMinSize(0, 0); @@ -124,18 +101,14 @@ public VideoView(int maxPixels) { * * @param frame the frame to show. * @throws IllegalArgumentException if dimensions are nonpositive or the - * frame exceeds this view's pixel limit. + * frame cannot be represented by a Java pixel buffer. */ @Override public void accept(VideoFrame frame) { VideoFrameBuffer buffer = frame.buffer; int width = buffer.getWidth(); int height = buffer.getHeight(); - long pixelCount = (long) width * height; - if (width <= 0 || height <= 0 || pixelCount > maxPixels) { - throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height); - } - int byteCount = (int) (pixelCount * 4L); + int byteCount = frameBytes(width, height); long started; // Before the wait for convertLock, as the frame came before any clear() @@ -154,8 +127,10 @@ public void accept(VideoFrame frame) { } } Pixels target = buffers[slot]; - if (target == null) { - target = new Pixels((int) (maxPixels * 4L)); + if (target == null || target.data.capacity() < byteCount) { + long previous = target == null ? 0 : target.data.capacity(); + int capacity = (int) Math.min(Integer.MAX_VALUE, Math.max(byteCount, previous * 2L)); + target = new Pixels(capacity); buffers[slot] = target; } target.width = width; @@ -192,6 +167,15 @@ public void accept(VideoFrame frame) { Platform.runLater(this::present); } + /** ByteBuffer capacities and image array lengths must fit in an int. */ + static int frameBytes(int width, int height) { + long pixels = (long) width * height; + if (width <= 0 || height <= 0 || pixels > Integer.MAX_VALUE / 4) { + throw new IllegalArgumentException("Invalid or unrepresentable frame dimensions: " + width + "x" + height); + } + return (int) (pixels * 4L); + } + /** * Removes the picture, leaving the background, and drops the frames still * being converted. Called on the JavaFX Application Thread. diff --git a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java index 551f1e1ab..c203e7833 100644 --- a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java +++ b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -106,7 +107,7 @@ void needsToolkit() { @Test void showsFrame() throws Exception { - VideoView view = onFx(() -> new VideoView(320 * 240)); + VideoView view = onFx(() -> new VideoView()); assertNull(onFx(view::snapshot)); view.accept(frame(64, 48, 128, 128)); @@ -125,7 +126,7 @@ void showsFrame() throws Exception { @Test void clearDropsFrameInConversion() throws Exception { - VideoView view = onFx(() -> new VideoView(320 * 240)); + VideoView view = onFx(() -> new VideoView()); CountDownLatch converting = new CountDownLatch(1); CountDownLatch cleared = new CountDownLatch(1); VideoFrame held = frame(64, 48, 128, 128); @@ -191,11 +192,9 @@ public void release() { @Test void rejectsInvalidSizes() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new VideoView(0)); - assertThrows(IllegalArgumentException.class, - () -> new VideoView(VideoView.MAX_PIXELS + 1)); - VideoView view = onFx(() -> new VideoView(64 * 48)); - for (int[] size : new int[][] { { 0, 1 }, { -1, -1 }, { 65, 48 }, + VideoView view = onFx(() -> new VideoView()); + for (int[] size : new int[][] { { 0, 1 }, { 1, 0 }, { -1, -1 }, { 1, -1 }, { -1, 1 }, + { Integer.MAX_VALUE / 4 + 1, 1 }, { 65536, 65536 }, { Integer.MAX_VALUE, Integer.MAX_VALUE } }) { VideoFrameBuffer invalid = (VideoFrameBuffer) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] { VideoFrameBuffer.class }, @@ -209,14 +208,48 @@ void rejectsInvalidSizes() throws Exception { } } + @Test + void supports8kDimensions() { + assertEquals(7680 * 4320 * 4, VideoView.frameBytes(7680, 4320)); + assertEquals((Integer.MAX_VALUE / 4) * 4, VideoView.frameBytes(Integer.MAX_VALUE / 4, 1)); + } + + @Test + void growsBuffersOnDemand() throws Exception { + VideoView view = onFx(VideoView::new); + Field field = VideoView.class.getDeclaredField("buffers"); + field.setAccessible(true); + ByteBuffer previous = null; + for (int width : new int[] { 32, 64, 32, 64 }) { + VideoFrame frame = frame(width, 48, 128, 128); + try { + view.accept(frame); + assertEquals(width, (int) onFx(view::snapshot).getWidth()); + Object slot = ((Object[]) field.get(view))[0]; + Field data = slot.getClass().getDeclaredField("data"); + data.setAccessible(true); + ByteBuffer current = (ByteBuffer) data.get(slot); + onFx(() -> { view.clear(); return null; }); + if (previous != null && previous.capacity() >= width * 48 * 4) { + assertSame(previous, current); + } + assertEquals(previous == null ? 32 * 48 * 4 : 64 * 48 * 4, current.capacity()); + previous = current; + } + finally { + frame.release(); + } + } + } + @Test void reusesBuffersAcrossSizes() throws Exception { - VideoView view = onFx(() -> new VideoView(64 * 48)); + VideoView view = onFx(() -> new VideoView()); Set storage = Collections.newSetFromMap(new IdentityHashMap<>()); Field field = VideoView.class.getDeclaredField("buffers"); field.setAccessible(true); for (int i = 0; i < 12; i++) { - int width = i % 2 == 0 ? 64 : 32; + int width = i < 3 || i % 2 == 0 ? 64 : 32; VideoFrame frame = frame(width, 48, 128, 128); try { view.accept(frame); @@ -294,7 +327,7 @@ void showsRemoteVideo() throws Exception { Peer caller = rtc.createPeer(PeerOptions.builder().signaling(link.first()).build()); Peer callee = rtc.createPeer(PeerOptions.builder().signaling(link.second()).polite(true).build()); CustomVideo video = rtc.media().customVideo("video"); - VideoView view = onFx(() -> new VideoView(320 * 240)); + VideoView view = onFx(() -> new VideoView()); callee.onTrack(track -> track.asVideo().onFrame(view)); caller.addTrack(video); @@ -320,7 +353,7 @@ void showsRemoteVideo() throws Exception { private VideoView sized(int width, int height) throws Exception { return onFx(() -> { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); new Scene(view, width, height); view.resize(width, height); view.layout(); diff --git a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java index 55d86f598..feb7ab798 100644 --- a/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java +++ b/webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java @@ -44,16 +44,14 @@ * Frames are converted on the thread that delivers them, so the event dispatch * thread only paints. The picture keeps its aspect ratio and its rotation, with * the component's background around it. + * Conversion buffers grow on demand and are reused across resolution changes + * and clear(). Their retained capacity follows the largest frames received; + * buffer memory is released when the view becomes unreachable. */ public class VideoView extends JComponent implements Consumer { private static final long serialVersionUID = 1L; - /** Default and maximum permitted number of pixels per frame (3840 by 2160). */ - public static final int MAX_PIXELS = 3840 * 2160; - - private final int maxPixels; - /** Serializes conversion; never acquired by the event dispatch thread. */ private final Object convertLock = new Object(); @@ -80,27 +78,6 @@ public class VideoView extends JComponent implements Consumer { * 360 pixels. */ public VideoView() { - this(MAX_PIXELS); - } - - /** - * Creates a view with a limit on frame size. Conversion buffers reserve - * {@code maxPixels * 4} bytes each on first use and are reused across size - * changes and clear(). They are released with the view, not by clear(). - * One direct buffer and at most three live image arrays (including a - * replacement during a resize) require at most {@code maxPixels * 16L} - * bytes of pixel storage. - * This excludes input frames, snapshots, toolkit rendering resources and - * unreachable images awaiting garbage collection. - * - * @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}. - * @throws IllegalArgumentException if the limit is outside this range. - */ - public VideoView(int maxPixels) { - if (maxPixels <= 0 || maxPixels > MAX_PIXELS) { - throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels); - } - this.maxPixels = maxPixels; setBackground(Color.BLACK); setOpaque(true); setPreferredSize(new Dimension(640, 360)); @@ -112,18 +89,14 @@ public VideoView(int maxPixels) { * * @param frame the frame to show. * @throws IllegalArgumentException if dimensions are nonpositive or the - * frame exceeds this view's pixel limit. + * frame cannot be represented by a Java pixel buffer. */ @Override public void accept(VideoFrame frame) { VideoFrameBuffer buffer = frame.buffer; int width = buffer.getWidth(); int height = buffer.getHeight(); - long pixelCount = (long) width * height; - if (width <= 0 || height <= 0 || pixelCount > maxPixels) { - throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height); - } - int byteCount = (int) (pixelCount * 4L); + int byteCount = frameBytes(width, height); long started; synchronized (lock) { @@ -134,8 +107,10 @@ public void accept(VideoFrame frame) { if (back == null || back.getWidth() != width || back.getHeight() != height) { back = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } - if (pixels == null) { - pixels = ByteBuffer.allocateDirect((int) (maxPixels * 4L)).order(ByteOrder.LITTLE_ENDIAN); + if (pixels == null || pixels.capacity() < byteCount) { + long previous = pixels == null ? 0 : pixels.capacity(); + int capacity = (int) Math.min(Integer.MAX_VALUE, Math.max(byteCount, previous * 2L)); + pixels = ByteBuffer.allocateDirect(capacity).order(ByteOrder.LITTLE_ENDIAN); } try { @@ -165,6 +140,15 @@ public void accept(VideoFrame frame) { repaint(); } + /** ByteBuffer capacities and image array lengths must fit in an int. */ + static int frameBytes(int width, int height) { + long pixels = (long) width * height; + if (width <= 0 || height <= 0 || pixels > Integer.MAX_VALUE / 4) { + throw new IllegalArgumentException("Invalid or unrepresentable frame dimensions: " + width + "x" + height); + } + return (int) (pixels * 4L); + } + /** * Removes the picture, leaving the background, and drops frames already * waiting for or undergoing conversion. diff --git a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java index cbd498248..a6a041f7c 100644 --- a/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java +++ b/webrtc-swing/src/test/java/dev/onvoid/webrtc/client/swing/VideoViewTests.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import java.awt.Color; @@ -88,7 +89,7 @@ void closeRuntime() { @Test void showsFrame() { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); assertNull(view.snapshot()); view.accept(frame(64, 48, 128, 128)); @@ -105,7 +106,7 @@ void showsFrame() { @Test void conversionLeavesEdtFree() throws Exception { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); view.setSize(64, 48); VideoFrame initial = frame(64, 48, 128, 128); VideoFrame held = frame(64, 48, 16, 235); @@ -152,11 +153,9 @@ void conversionLeavesEdtFree() throws Exception { @Test void rejectsInvalidSizes() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new VideoView(0)); - assertThrows(IllegalArgumentException.class, - () -> new VideoView(VideoView.MAX_PIXELS + 1)); - VideoView view = new VideoView(64 * 48); - for (int[] size : new int[][] { { 0, 1 }, { -1, -1 }, { 65, 48 }, + VideoView view = new VideoView(); + for (int[] size : new int[][] { { 0, 1 }, { 1, 0 }, { -1, -1 }, { 1, -1 }, { -1, 1 }, + { Integer.MAX_VALUE / 4 + 1, 1 }, { 65536, 65536 }, { Integer.MAX_VALUE, Integer.MAX_VALUE } }) { VideoFrameBuffer invalid = (VideoFrameBuffer) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] { VideoFrameBuffer.class }, @@ -170,14 +169,45 @@ void rejectsInvalidSizes() throws Exception { } } + @Test + void supports8kDimensions() { + assertEquals(7680 * 4320 * 4, VideoView.frameBytes(7680, 4320)); + assertEquals((Integer.MAX_VALUE / 4) * 4, VideoView.frameBytes(Integer.MAX_VALUE / 4, 1)); + } + + @Test + void growsBuffersOnDemand() throws Exception { + VideoView view = new VideoView(); + Field field = VideoView.class.getDeclaredField("pixels"); + field.setAccessible(true); + ByteBuffer previous = null; + for (int width : new int[] { 32, 64, 32, 64 }) { + VideoFrame frame = frame(width, 48, 128, 128); + try { + view.accept(frame); + assertEquals(width, view.snapshot().getWidth()); + ByteBuffer current = (ByteBuffer) field.get(view); + view.clear(); + if (previous != null && previous.capacity() >= width * 48 * 4) { + assertSame(previous, current); + } + assertEquals(previous == null ? 32 * 48 * 4 : 64 * 48 * 4, current.capacity()); + previous = current; + } + finally { + frame.release(); + } + } + } + @Test void reusesBuffersAcrossSizes() throws Exception { - VideoView view = new VideoView(64 * 48); + VideoView view = new VideoView(); Set storage = Collections.newSetFromMap(new IdentityHashMap<>()); Field field = VideoView.class.getDeclaredField("pixels"); field.setAccessible(true); for (int i = 0; i < 12; i++) { - int width = i % 2 == 0 ? 64 : 32; + int width = i < 3 || i % 2 == 0 ? 64 : 32; VideoFrame frame = frame(width, 48, 128, 128); try { view.accept(frame); @@ -199,7 +229,7 @@ void reusesBuffersAcrossSizes() throws Exception { @Test void keepsAspectRatio() { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); view.setSize(200, 100); view.accept(frame(64, 48, 128, 128)); @@ -211,7 +241,7 @@ void keepsAspectRatio() { @Test void mirrors() { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); view.setSize(64, 48); view.accept(frame(64, 48, 16, 235)); @@ -230,7 +260,7 @@ void anyRotationMultiple() { assertArrayEquals(rotated(90), rotated(450)); // Sideways, a 4:3 picture in a 4:3 view leaves bars on the sides. - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); view.setSize(64, 48); view.accept(frame(64, 48, 128, 128, -90)); @@ -243,7 +273,7 @@ void anyRotationMultiple() { void showsRemoteVideo() throws Exception { Peer[] peers = pair(); CustomVideo video = rtc.media().customVideo("video"); - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); peers[1].onTrack(track -> track.asVideo().onFrame(view)); peers[0].addTrack(video); @@ -289,7 +319,7 @@ private Peer[] pair() { /** The pixels a 64x48 view paints of a 64x48 two-tone frame with the given rotation. */ private static int[] rotated(int rotation) { - VideoView view = new VideoView(320 * 240); + VideoView view = new VideoView(); view.setSize(64, 48); view.accept(frame(64, 48, 16, 235, rotation)); From 1b3a14c20c9c2597139e43367b4ac095b1183693 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 14:19:38 +0100 Subject: [PATCH 5/5] fix: reduce JavaFX video conversion buffers --- docs/guide/client-api.md | 4 +- .../webrtc/client/javafx/VideoView.java | 45 +++++---- .../webrtc/client/javafx/VideoViewTest.java | 91 ++++++++++++++++++- 3 files changed, 120 insertions(+), 20 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 3bee0a64c..e48944eae 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -322,7 +322,9 @@ Both views support resolutions such as 8K without a fixed pixel limit. They reje nonpositive dimensions and frames whose four-byte pixel data cannot fit in a Java buffer, using overflow-safe arithmetic. Conversion buffers allocate on demand, grow geometrically when necessary, and retain their capacity across smaller frames -and `clear()`. Swing reuses one direct buffer; JavaFX reuses up to three. Buffer +and `clear()`. Swing reuses one direct buffer; JavaFX reuses up to two. +JavaFX reserves a buffer only while copying it into the displayed image; a waiting +frame may be replaced by a newer frame to avoid building a queue. Buffer memory is released when the view becomes unreachable. Memory usage follows the largest frames received and includes displayed images, conversion buffers, and replacement allocations awaiting garbage collection. Snapshots, input frames and diff --git a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java index a476322cb..7c3a6ab3f 100644 --- a/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java +++ b/webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java @@ -61,11 +61,11 @@ public class VideoView extends Region implements Consumer { /** Guards the hand-over between the converting thread and the JavaFX thread. */ private final Object lock = new Object(); - // Three reusable buffers: the converting thread fills a free slot, hands it over as - // ready, and the JavaFX thread paints from shown. None is written while - // another thread reads it. + // Two reusable buffers: only the one JavaFX is copying is reserved. A waiting + // frame may be reclaimed for conversion, so the newest frame wins without + // blocking either thread during conversion or copying. - private final Pixels[] buffers = new Pixels[3]; + private final Pixels[] buffers = new Pixels[2]; private Pixels ready; @@ -74,8 +74,8 @@ public class VideoView extends Region implements Consumer { /** Counts the calls of clear(), to tell the frames that came before one. */ private long generation; - // Set under lock; its pixels are read only on the JavaFX Application Thread. - private Pixels shown; + // Reserved under lock only while JavaFX copies pixels into the image. + private Pixels reading; // Confined to the JavaFX Application Thread. @@ -118,13 +118,16 @@ public void accept(VideoFrame frame) { } synchronized (convertLock) { - // Only this thread chooses/writes a slot; presentation may read the - // other two. Allocate outside the hand-over lock. + // Only this thread chooses/writes a slot. Never overwrite a buffer + // JavaFX is copying; withdraw a waiting frame before reusing it. int slot = 0; synchronized (lock) { - while (buffers[slot] != null && (buffers[slot] == ready || buffers[slot] == shown)) { + while (buffers[slot] != null && buffers[slot] == reading) { slot++; } + if (buffers[slot] == ready) { + ready = null; + } } Pixels target = buffers[slot]; if (target == null || target.data.capacity() < byteCount) { @@ -184,7 +187,6 @@ public void clear() { synchronized (lock) { generation++; ready = null; - shown = null; } image = null; @@ -251,17 +253,24 @@ private void present() { return; } - ready = shown; - shown = next; + ready = null; + reading = next; } - if (image == null || image.getWidth() != next.width || image.getHeight() != next.height) { - image = new WritableImage(next.width, next.height); - } + try { + if (image == null || image.getWidth() != next.width || image.getHeight() != next.height) { + image = new WritableImage(next.width, next.height); + } - image.getPixelWriter().setPixels(0, 0, next.width, next.height, - PixelFormat.getByteBgraPreInstance(), next.data, next.width * 4); - rotation = next.rotation; + image.getPixelWriter().setPixels(0, 0, next.width, next.height, + PixelFormat.getByteBgraPreInstance(), next.data, next.width * 4); + rotation = next.rotation; + } + finally { + synchronized (lock) { + reading = null; + } + } draw(); } diff --git a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java index c203e7833..275e847e6 100644 --- a/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java +++ b/webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java @@ -269,13 +269,102 @@ void reusesBuffersAcrossSizes() throws Exception { frame.release(); } } - assertTrue(storage.size() <= 3); + assertTrue(storage.size() <= 2); for (ByteBuffer data : storage) { assertTrue(data.isDirect()); assertEquals(64 * 48 * 4, data.capacity()); } } + @Test + void replacesWaitingFrame() throws Exception { + VideoView view = onFx(VideoView::new); + CountDownLatch blocked = new CountDownLatch(1); + CountDownLatch unblock = new CountDownLatch(1); + CompletableFuture ui = new CompletableFuture<>(); + Platform.runLater(() -> { + blocked.countDown(); + try { + assertTrue(unblock.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + ui.complete(null); + } + catch (Throwable e) { + ui.completeExceptionally(e); + } + }); + try { + assertTrue(blocked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + for (int width : new int[] { 64, 32, 64, 32 }) { + VideoFrame frame = frame(width, 48, 128, 128); + try { + view.accept(frame); + } + finally { + frame.release(); + } + } + } + finally { + unblock.countDown(); + } + ui.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertEquals(32, (int) onFx(view::snapshot).getWidth()); + Field reading = VideoView.class.getDeclaredField("reading"); + reading.setAccessible(true); + assertNull(reading.get(view), "The copied buffer must be released"); + Field buffers = VideoView.class.getDeclaredField("buffers"); + buffers.setAccessible(true); + assertEquals(2, ((Object[]) buffers.get(view)).length); + } + + @Test + void withdrawsFrameBeforeConversion() throws Exception { + VideoView view = onFx(VideoView::new); + VideoFrame first = frame(64, 48, 128, 128); + VideoFrame latest = frame(32, 24, 16, 16); + CountDownLatch converting = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + VideoFrameBuffer buffer = (VideoFrameBuffer) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] { VideoFrameBuffer.class }, + (proxy, method, args) -> { + if (method.getName().equals("toI420")) { + converting.countDown(); + assertTrue(finish.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } + return method.invoke(latest.buffer, args); + }); + CompletableFuture delivered = new CompletableFuture<>(); + Thread delivery = new Thread(() -> { + try { + view.accept(new VideoFrame(buffer, 0)); + delivered.complete(null); + } + catch (Throwable e) { + delivered.completeExceptionally(e); + } + }); + try { + // Queue presentation, then reclaim its buffer before JavaFX can read it. + onFx(() -> { + view.accept(first); + delivery.start(); + assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + return null; + }); + assertNull(onFx(view::snapshot), "No partially converted frame may be copied"); + } + finally { + finish.countDown(); + delivery.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + first.release(); + latest.release(); + } + delivered.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + Image snapshot = onFx(view::snapshot); + assertEquals(32, (int) snapshot.getWidth()); + assertTrue(snapshot.getPixelReader().getColor(0, 0).getBrightness() < 0.1); + } + @Test void keepsAspectRatio() throws Exception { VideoView view = sized(200, 100);