Skip to content

Commit 65c65db

Browse files
committed
fix: Bound video view dimensions and reuse direct pixel buffers
1 parent 6318d44 commit 65c65db

5 files changed

Lines changed: 246 additions & 42 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,18 @@ frame.add(remoteView, BorderLayout.CENTER);
318318

319319
`snapshot()` returns a copy of the picture shown, for saving a still or for tests.
320320

321+
Both views reject nonpositive dimensions and frames above `VideoView.MAX_PIXELS`
322+
(3840 × 2160 pixels) with `IllegalArgumentException`. Use `new VideoView(maxPixels)`
323+
to choose a smaller limit, for example `new VideoView(1280 * 720)` for a preview.
324+
Conversion buffers reserve their configured maximum capacity on first use and stay
325+
available across resolution changes and `clear()`. They are freed when the view
326+
becomes unreachable. Swing uses one direct buffer; JavaFX uses up to three.
327+
Including displayed images and a replacement image during a resize, live pixel
328+
storage is at most `maxPixels * 16L` bytes for Swing and `maxPixels * 20L` for
329+
JavaFX (about 127 MiB and 159 MiB at the default limit). Input frames, snapshots,
330+
toolkit rendering resources, and discarded heap images awaiting collection are
331+
additional. Set a smaller limit when displaying several videos.
332+
321333
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:
322334

323335
```xml
@@ -639,6 +651,7 @@ peer.onChannel(channel -> { // channels the remote peer opens
639651
});
640652
```
641653

654+
642655
- A channel may be used right away: messages sent before it opens are held until it does.
643656
- 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.
644657
- `send` takes a `String`, a `byte[]` or a `ByteBuffer`, and copies the data before it returns.

‎webrtc-javafx/src/main/java/dev/onvoid/webrtc/client/javafx/VideoView.java‎

Lines changed: 58 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ public class VideoView extends Region implements Consumer<VideoFrame> {
5050

5151
private final Canvas canvas = new Canvas();
5252

53+
/** Default and maximum permitted number of pixels per frame (3840 by 2160). */
54+
public static final int MAX_PIXELS = 3840 * 2160;
55+
56+
private final int maxPixels;
57+
5358
private final BooleanProperty mirrored = new SimpleBooleanProperty(this, "mirrored");
5459

5560
/** Serializes conversions, for frames of more than one subscription. */
@@ -58,11 +63,11 @@ public class VideoView extends Region implements Consumer<VideoFrame> {
5863
/** Guards the hand-over between the converting thread and the JavaFX thread. */
5964
private final Object lock = new Object();
6065

61-
// Three buffers: the converting thread fills back, hands it over as
66+
// Three reusable buffers: the converting thread fills a free slot, hands it over as
6267
// ready, and the JavaFX thread paints from shown. None is written while
6368
// another thread reads it.
6469

65-
private Pixels back;
70+
private final Pixels[] buffers = new Pixels[3];
6671

6772
private Pixels ready;
6873

@@ -71,10 +76,11 @@ public class VideoView extends Region implements Consumer<VideoFrame> {
7176
/** Counts the calls of clear(), to tell the frames that came before one. */
7277
private long generation;
7378

74-
// Confined to the JavaFX Application Thread.
75-
79+
// Set under lock; its pixels are read only on the JavaFX Application Thread.
7680
private Pixels shown;
7781

82+
// Confined to the JavaFX Application Thread.
83+
7884
private WritableImage image;
7985

8086
private int rotation;
@@ -84,6 +90,27 @@ public class VideoView extends Region implements Consumer<VideoFrame> {
8490
* Creates a view with a preferred size of 640 by 360 pixels.
8591
*/
8692
public VideoView() {
93+
this(MAX_PIXELS);
94+
}
95+
96+
/**
97+
* Creates a view with a limit on frame size. Conversion buffers reserve
98+
* {@code maxPixels * 4} bytes each on first use and are reused across size
99+
* changes and clear(). They are released with the view, not by clear().
100+
* At most three direct buffers and two live JavaFX images (including a
101+
* replacement during a resize) require at most {@code maxPixels * 20L}
102+
* bytes of pixel storage.
103+
* This excludes input frames, snapshots, toolkit rendering resources and
104+
* unreachable images awaiting garbage collection.
105+
*
106+
* @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}.
107+
* @throws IllegalArgumentException if the limit is outside this range.
108+
*/
109+
public VideoView(int maxPixels) {
110+
if (maxPixels <= 0 || maxPixels > MAX_PIXELS) {
111+
throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels);
112+
}
113+
this.maxPixels = maxPixels;
87114
getChildren().add(canvas);
88115
setPrefSize(640, 360);
89116
setMinSize(0, 0);
@@ -96,12 +123,19 @@ public VideoView() {
96123
* frame is not released, which its subscription does.
97124
*
98125
* @param frame the frame to show.
126+
* @throws IllegalArgumentException if dimensions are nonpositive or the
127+
* frame exceeds this view's pixel limit.
99128
*/
100129
@Override
101130
public void accept(VideoFrame frame) {
102131
VideoFrameBuffer buffer = frame.buffer;
103132
int width = buffer.getWidth();
104133
int height = buffer.getHeight();
134+
long pixelCount = (long) width * height;
135+
if (width <= 0 || height <= 0 || pixelCount > maxPixels) {
136+
throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height);
137+
}
138+
int byteCount = (int) (pixelCount * 4L);
105139
long started;
106140

107141
// Before the wait for convertLock, as the frame came before any clear()
@@ -111,15 +145,26 @@ public void accept(VideoFrame frame) {
111145
}
112146

113147
synchronized (convertLock) {
114-
Pixels target = back;
115-
116-
if (target == null || !target.fits(width, height)) {
117-
target = new Pixels(width, height);
148+
// Only this thread chooses/writes a slot; presentation may read the
149+
// other two. Allocate outside the hand-over lock.
150+
int slot = 0;
151+
synchronized (lock) {
152+
while (buffers[slot] != null && (buffers[slot] == ready || buffers[slot] == shown)) {
153+
slot++;
154+
}
118155
}
156+
Pixels target = buffers[slot];
157+
if (target == null) {
158+
target = new Pixels((int) (maxPixels * 4L));
159+
buffers[slot] = target;
160+
}
161+
target.width = width;
162+
target.height = height;
119163

120164
try {
121165
// libyuv's ARGB is B, G, R, A in memory, which is JavaFX's BGRA.
122166
target.data.clear();
167+
target.data.limit(byteCount);
123168
VideoBufferConverter.convertFromI420(buffer, target.data, FourCC.ARGB);
124169
target.data.rewind();
125170
}
@@ -134,7 +179,6 @@ public void accept(VideoFrame frame) {
134179
return;
135180
}
136181

137-
back = ready;
138182
ready = target;
139183

140184
if (scheduled) {
@@ -156,10 +200,9 @@ public void clear() {
156200
synchronized (lock) {
157201
generation++;
158202
ready = null;
159-
back = null;
203+
shown = null;
160204
}
161205

162-
shown = null;
163206
image = null;
164207
draw();
165208
}
@@ -270,23 +313,18 @@ private void draw() {
270313

271314
private static final class Pixels {
272315

273-
final int width;
316+
int width;
274317

275-
final int height;
318+
int height;
276319

277320
final ByteBuffer data;
278321

279322
int rotation;
280323

281324

282-
Pixels(int width, int height) {
283-
this.width = width;
284-
this.height = height;
285-
this.data = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.LITTLE_ENDIAN);
325+
Pixels(int capacity) {
326+
this.data = ByteBuffer.allocateDirect(capacity).order(ByteOrder.LITTLE_ENDIAN);
286327
}
287328

288-
boolean fits(int otherWidth, int otherHeight) {
289-
return width == otherWidth && height == otherHeight;
290-
}
291329
}
292330
}

‎webrtc-javafx/src/test/java/dev/onvoid/webrtc/client/javafx/VideoViewTest.java‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,14 @@
2020
import static org.junit.jupiter.api.Assertions.assertNotNull;
2121
import static org.junit.jupiter.api.Assertions.assertNull;
2222
import static org.junit.jupiter.api.Assertions.assertTrue;
23+
import static org.junit.jupiter.api.Assertions.assertThrows;
2324
import static org.junit.jupiter.api.Assumptions.assumeTrue;
2425

26+
import java.lang.reflect.Field;
27+
import java.lang.reflect.Proxy;
28+
import java.util.Collections;
29+
import java.util.IdentityHashMap;
30+
import java.util.Set;
2531
import java.nio.ByteBuffer;
2632
import java.util.concurrent.Callable;
2733
import java.util.concurrent.CompletableFuture;
@@ -100,7 +106,7 @@ void needsToolkit() {
100106

101107
@Test
102108
void showsFrame() throws Exception {
103-
VideoView view = onFx(VideoView::new);
109+
VideoView view = onFx(() -> new VideoView(320 * 240));
104110
assertNull(onFx(view::snapshot));
105111

106112
view.accept(frame(64, 48, 128, 128));
@@ -119,7 +125,7 @@ void showsFrame() throws Exception {
119125

120126
@Test
121127
void clearDropsFrameInConversion() throws Exception {
122-
VideoView view = onFx(VideoView::new);
128+
VideoView view = onFx(() -> new VideoView(320 * 240));
123129
CountDownLatch converting = new CountDownLatch(1);
124130
CountDownLatch cleared = new CountDownLatch(1);
125131
VideoFrame held = frame(64, 48, 128, 128);
@@ -183,6 +189,60 @@ public void release() {
183189
assertEquals(32, (int) presented(view).getWidth());
184190
}
185191

192+
@Test
193+
void rejectsInvalidSizes() throws Exception {
194+
assertThrows(IllegalArgumentException.class, () -> new VideoView(0));
195+
assertThrows(IllegalArgumentException.class,
196+
() -> new VideoView(VideoView.MAX_PIXELS + 1));
197+
VideoView view = onFx(() -> new VideoView(64 * 48));
198+
for (int[] size : new int[][] { { 0, 1 }, { -1, -1 }, { 65, 48 },
199+
{ 65536, 65536 }, { Integer.MAX_VALUE, Integer.MAX_VALUE } }) {
200+
VideoFrameBuffer invalid = (VideoFrameBuffer) Proxy.newProxyInstance(
201+
getClass().getClassLoader(), new Class<?>[] { VideoFrameBuffer.class },
202+
(proxy, method, args) -> {
203+
if (method.getName().equals("getWidth")) return size[0];
204+
if (method.getName().equals("getHeight")) return size[1];
205+
throw new AssertionError("Invalid frame reached conversion");
206+
});
207+
assertThrows(IllegalArgumentException.class,
208+
() -> view.accept(new VideoFrame(invalid, 0)));
209+
}
210+
}
211+
212+
@Test
213+
void reusesBuffersAcrossSizes() throws Exception {
214+
VideoView view = onFx(() -> new VideoView(64 * 48));
215+
Set<ByteBuffer> storage = Collections.newSetFromMap(new IdentityHashMap<>());
216+
Field field = VideoView.class.getDeclaredField("buffers");
217+
field.setAccessible(true);
218+
for (int i = 0; i < 12; i++) {
219+
int width = i % 2 == 0 ? 64 : 32;
220+
VideoFrame frame = frame(width, 48, 128, 128);
221+
try {
222+
view.accept(frame);
223+
Image snapshot = onFx(view::snapshot);
224+
assertEquals(width, (int) snapshot.getWidth());
225+
assertGray(snapshot.getPixelReader().getColor(0, 0));
226+
for (Object slot : (Object[]) field.get(view)) {
227+
if (slot != null) {
228+
Field data = slot.getClass().getDeclaredField("data");
229+
data.setAccessible(true);
230+
storage.add((ByteBuffer) data.get(slot));
231+
}
232+
}
233+
if (i >= 6) onFx(() -> { view.clear(); return null; });
234+
}
235+
finally {
236+
frame.release();
237+
}
238+
}
239+
assertTrue(storage.size() <= 3);
240+
for (ByteBuffer data : storage) {
241+
assertTrue(data.isDirect());
242+
assertEquals(64 * 48 * 4, data.capacity());
243+
}
244+
}
245+
186246
@Test
187247
void keepsAspectRatio() throws Exception {
188248
VideoView view = sized(200, 100);
@@ -234,7 +294,7 @@ void showsRemoteVideo() throws Exception {
234294
Peer caller = rtc.createPeer(PeerOptions.builder().signaling(link.first()).build());
235295
Peer callee = rtc.createPeer(PeerOptions.builder().signaling(link.second()).polite(true).build());
236296
CustomVideo video = rtc.media().customVideo("video");
237-
VideoView view = onFx(VideoView::new);
297+
VideoView view = onFx(() -> new VideoView(320 * 240));
238298

239299
callee.onTrack(track -> track.asVideo().onFrame(view));
240300
caller.addTrack(video);
@@ -260,7 +320,7 @@ void showsRemoteVideo() throws Exception {
260320

261321
private VideoView sized(int width, int height) throws Exception {
262322
return onFx(() -> {
263-
VideoView view = new VideoView();
323+
VideoView view = new VideoView(320 * 240);
264324
new Scene(view, width, height);
265325
view.resize(width, height);
266326
view.layout();

‎webrtc-swing/src/main/java/dev/onvoid/webrtc/client/swing/VideoView.java‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ public class VideoView extends JComponent implements Consumer<VideoFrame> {
4949

5050
private static final long serialVersionUID = 1L;
5151

52+
/** Default and maximum permitted number of pixels per frame (3840 by 2160). */
53+
public static final int MAX_PIXELS = 3840 * 2160;
54+
55+
private final int maxPixels;
56+
5257
/** Serializes conversion; never acquired by the event dispatch thread. */
5358
private final Object convertLock = new Object();
5459

@@ -75,6 +80,27 @@ public class VideoView extends JComponent implements Consumer<VideoFrame> {
7580
* 360 pixels.
7681
*/
7782
public VideoView() {
83+
this(MAX_PIXELS);
84+
}
85+
86+
/**
87+
* Creates a view with a limit on frame size. Conversion buffers reserve
88+
* {@code maxPixels * 4} bytes each on first use and are reused across size
89+
* changes and clear(). They are released with the view, not by clear().
90+
* One direct buffer and at most three live image arrays (including a
91+
* replacement during a resize) require at most {@code maxPixels * 16L}
92+
* bytes of pixel storage.
93+
* This excludes input frames, snapshots, toolkit rendering resources and
94+
* unreachable images awaiting garbage collection.
95+
*
96+
* @param maxPixels maximum frame pixel count, from 1 to {@link #MAX_PIXELS}.
97+
* @throws IllegalArgumentException if the limit is outside this range.
98+
*/
99+
public VideoView(int maxPixels) {
100+
if (maxPixels <= 0 || maxPixels > MAX_PIXELS) {
101+
throw new IllegalArgumentException("Invalid pixel limit: " + maxPixels);
102+
}
103+
this.maxPixels = maxPixels;
78104
setBackground(Color.BLACK);
79105
setOpaque(true);
80106
setPreferredSize(new Dimension(640, 360));
@@ -85,12 +111,19 @@ public VideoView() {
85111
* frame is not released, which its subscription does.
86112
*
87113
* @param frame the frame to show.
114+
* @throws IllegalArgumentException if dimensions are nonpositive or the
115+
* frame exceeds this view's pixel limit.
88116
*/
89117
@Override
90118
public void accept(VideoFrame frame) {
91119
VideoFrameBuffer buffer = frame.buffer;
92120
int width = buffer.getWidth();
93121
int height = buffer.getHeight();
122+
long pixelCount = (long) width * height;
123+
if (width <= 0 || height <= 0 || pixelCount > maxPixels) {
124+
throw new IllegalArgumentException("Frame dimensions exceed the pixel limit: " + width + "x" + height);
125+
}
126+
int byteCount = (int) (pixelCount * 4L);
94127

95128
long started;
96129
synchronized (lock) {
@@ -101,14 +134,15 @@ public void accept(VideoFrame frame) {
101134
if (back == null || back.getWidth() != width || back.getHeight() != height) {
102135
back = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
103136
}
104-
if (pixels == null || pixels.capacity() != width * height * 4) {
105-
pixels = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.LITTLE_ENDIAN);
137+
if (pixels == null) {
138+
pixels = ByteBuffer.allocateDirect((int) (maxPixels * 4L)).order(ByteOrder.LITTLE_ENDIAN);
106139
}
107140

108141
try {
109142
// libyuv's ARGB is B, G, R, A in memory, which read as
110143
// little-endian ints is what TYPE_INT_RGB holds.
111144
pixels.clear();
145+
pixels.limit(byteCount);
112146
VideoBufferConverter.convertFromI420(buffer, pixels, FourCC.ARGB);
113147
pixels.rewind();
114148
pixels.asIntBuffer().get(((DataBufferInt) back.getRaster().getDataBuffer()).getData());

0 commit comments

Comments
 (0)