diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 5038d01c3..e48944eae 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 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 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 +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: ```xml @@ -639,6 +651,13 @@ 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. - `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..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 @@ -45,6 +45,9 @@ * 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 { @@ -58,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 buffers: the converting thread fills back, 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 Pixels back; + private final Pixels[] buffers = new Pixels[2]; private Pixels ready; @@ -71,9 +74,10 @@ 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. + // Reserved under lock only while JavaFX copies pixels into the image. + private Pixels reading; - private Pixels shown; + // Confined to the JavaFX Application Thread. private WritableImage image; @@ -96,12 +100,15 @@ 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 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(); + int byteCount = frameBytes(width, height); long started; // Before the wait for convertLock, as the frame came before any clear() @@ -111,15 +118,31 @@ 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. 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] == reading) { + slot++; + } + if (buffers[slot] == ready) { + ready = null; + } + } + Pixels target = buffers[slot]; + 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; + 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 +157,6 @@ public void accept(VideoFrame frame) { return; } - back = ready; ready = target; if (scheduled) { @@ -148,6 +170,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. @@ -156,10 +187,8 @@ public void clear() { synchronized (lock) { generation++; ready = null; - back = null; } - shown = null; image = null; draw(); } @@ -224,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(); } @@ -270,23 +306,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..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 @@ -20,8 +20,15 @@ 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; +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 +107,7 @@ void needsToolkit() { @Test void showsFrame() throws Exception { - VideoView view = onFx(VideoView::new); + VideoView view = onFx(() -> new VideoView()); assertNull(onFx(view::snapshot)); view.accept(frame(64, 48, 128, 128)); @@ -119,7 +126,7 @@ void showsFrame() throws Exception { @Test void clearDropsFrameInConversion() throws Exception { - VideoView view = onFx(VideoView::new); + VideoView view = onFx(() -> new VideoView()); CountDownLatch converting = new CountDownLatch(1); CountDownLatch cleared = new CountDownLatch(1); VideoFrame held = frame(64, 48, 128, 128); @@ -183,6 +190,181 @@ public void release() { assertEquals(32, (int) presented(view).getWidth()); } + @Test + void rejectsInvalidSizes() throws Exception { + 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 }, + (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 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()); + 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 < 3 || 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() <= 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); @@ -234,7 +416,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()); callee.onTrack(track -> track.asVideo().onFrame(view)); caller.addTrack(video); 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..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,12 +44,18 @@ * 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; - /** 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 +66,8 @@ public class VideoView extends JComponent implements Consumer { private transient ByteBuffer pixels; + private long generation; + private int rotation; private volatile boolean mirrored; @@ -80,25 +88,36 @@ 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 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(); + int byteCount = frameBytes(width, height); + 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); } - if (pixels == null || pixels.capacity() != width * height * 4) { - pixels = ByteBuffer.allocateDirect(width * height * 4).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 { // 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()); @@ -107,23 +126,37 @@ 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(); } + /** 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. + * 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..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,10 +21,22 @@ 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; 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 +53,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; @@ -91,6 +104,129 @@ 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); + CountDownLatch converting = new CountDownLatch(1); + CountDownLatch resume = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + view.accept(initial); + VideoFrameBuffer blocked = + (VideoFrameBuffer) Proxy.newProxyInstance( + getClass().getClassLoader(), + new Class[] { 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); + }); + Future delivery = executor.submit(() -> view.accept(new VideoFrame(blocked, 0))); + assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + FutureTask painting = new FutureTask<>(() -> { + assertGray(new Color(paint(view).getRGB(32, 24))); + view.clear(); + assertNull(view.snapshot()); + return null; + }); + 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 rejectsInvalidSizes() throws Exception { + 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 }, + (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 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(); + 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 < 3 || 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(); 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); + } +}