Skip to content

Commit 61799cf

Browse files
authored
fix: close races in stats sampling and the JavaFX view (#539)
* fix: stop a stats timer whose first sample found the peer closing The first sample is due at once and may run before its task is known, so it could not cancel it. Check again once the task is set. * fix: keep a slow custom audio track from delaying the others The pacer now only counts the ticks due. Pushing into the source moves to a pool of its own, with at most one hand-over per track at a time, and missed ticks are made up for as before. * fix: drop frames in conversion when the JavaFX view is cleared A conversion runs outside the lock of clear() and could put the old picture back. A generation counter now tells the frames that came before the clear. * fix: end the voice activity of a custom audio track on close CustomAudioImpl.beforeRelease() skipped the one of LocalAudioImpl, so a change still queued reached its handler after the track closed. * revert: keep the custom audio pacing out of this change This reverts commit 7df9590.
1 parent 45b41bc commit 61799cf

7 files changed

Lines changed: 176 additions & 4 deletions

File tree

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ public class VideoView extends Region implements Consumer<VideoFrame> {
6868

6969
private boolean scheduled;
7070

71+
/** Counts the calls of clear(), to tell the frames that came before one. */
72+
private long generation;
73+
7174
// Confined to the JavaFX Application Thread.
7275

7376
private Pixels shown;
@@ -99,6 +102,13 @@ public void accept(VideoFrame frame) {
99102
VideoFrameBuffer buffer = frame.buffer;
100103
int width = buffer.getWidth();
101104
int height = buffer.getHeight();
105+
long started;
106+
107+
// Before the wait for convertLock, as the frame came before any clear()
108+
// that happens during it.
109+
synchronized (lock) {
110+
started = generation;
111+
}
102112

103113
synchronized (convertLock) {
104114
Pixels target = back;
@@ -120,6 +130,10 @@ public void accept(VideoFrame frame) {
120130
target.rotation = frame.rotation;
121131

122132
synchronized (lock) {
133+
if (started != generation) {
134+
return;
135+
}
136+
123137
back = ready;
124138
ready = target;
125139

@@ -135,11 +149,12 @@ public void accept(VideoFrame frame) {
135149
}
136150

137151
/**
138-
* Removes the picture, leaving the background. Called on the JavaFX
139-
* Application Thread.
152+
* Removes the picture, leaving the background, and drops the frames still
153+
* being converted. Called on the JavaFX Application Thread.
140154
*/
141155
public void clear() {
142156
synchronized (lock) {
157+
generation++;
143158
ready = null;
144159
back = null;
145160
}

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

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.nio.ByteBuffer;
2626
import java.util.concurrent.Callable;
2727
import java.util.concurrent.CompletableFuture;
28+
import java.util.concurrent.CountDownLatch;
2829
import java.util.concurrent.Executors;
2930
import java.util.concurrent.ScheduledExecutorService;
3031
import java.util.concurrent.TimeUnit;
@@ -41,8 +42,10 @@
4142
import dev.onvoid.webrtc.client.Signaling;
4243
import dev.onvoid.webrtc.client.SignalingPair;
4344
import dev.onvoid.webrtc.client.WebRtc;
45+
import dev.onvoid.webrtc.media.video.I420Buffer;
4446
import dev.onvoid.webrtc.media.video.NativeI420Buffer;
4547
import dev.onvoid.webrtc.media.video.VideoFrame;
48+
import dev.onvoid.webrtc.media.video.VideoFrameBuffer;
4649

4750
import org.junit.jupiter.api.AfterAll;
4851
import org.junit.jupiter.api.BeforeAll;
@@ -114,6 +117,72 @@ void showsFrame() throws Exception {
114117
assertNull(onFx(view::snapshot));
115118
}
116119

120+
@Test
121+
void clearDropsFrameInConversion() throws Exception {
122+
VideoView view = onFx(VideoView::new);
123+
CountDownLatch converting = new CountDownLatch(1);
124+
CountDownLatch cleared = new CountDownLatch(1);
125+
VideoFrame held = frame(64, 48, 128, 128);
126+
VideoFrameBuffer buffer = new VideoFrameBuffer() {
127+
128+
@Override
129+
public int getWidth() {
130+
return held.buffer.getWidth();
131+
}
132+
133+
@Override
134+
public int getHeight() {
135+
return held.buffer.getHeight();
136+
}
137+
138+
@Override
139+
public I420Buffer toI420() {
140+
converting.countDown();
141+
142+
try {
143+
cleared.await();
144+
}
145+
catch (InterruptedException e) {
146+
Thread.currentThread().interrupt();
147+
}
148+
149+
return held.buffer.toI420();
150+
}
151+
152+
@Override
153+
public VideoFrameBuffer cropAndScale(int cropX, int cropY, int cropWidth, int cropHeight,
154+
int scaleWidth, int scaleHeight) {
155+
throw new UnsupportedOperationException();
156+
}
157+
158+
@Override
159+
public void retain() {
160+
}
161+
162+
@Override
163+
public void release() {
164+
}
165+
};
166+
Thread delivery = new Thread(() -> view.accept(new VideoFrame(buffer, 0)));
167+
168+
delivery.start();
169+
assertTrue(converting.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
170+
171+
onFx(() -> {
172+
view.clear();
173+
return null;
174+
});
175+
cleared.countDown();
176+
delivery.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS));
177+
178+
// Runs after whatever the conversion handed to the JavaFX thread.
179+
assertNull(onFx(view::snapshot));
180+
181+
// The next frame shows as usual.
182+
view.accept(frame(32, 24, 128, 128));
183+
assertEquals(32, (int) presented(view).getWidth());
184+
}
185+
117186
@Test
118187
void keepsAspectRatio() throws Exception {
119188
VideoView view = sized(200, 100);

‎webrtc/src/main/java/dev/onvoid/webrtc/client/CustomAudioImpl.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ void beforeRelease() {
192192
ticker = null;
193193
}
194194
}
195+
196+
super.beforeRelease();
195197
}
196198

197199
/** Queues what is left of the previous format, filled with silence. */

‎webrtc/src/main/java/dev/onvoid/webrtc/client/StatsSampler.java‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,15 @@ else if (!(PeerImpl.unwrap(error) instanceof PeerClosedException)) {
136136
}));
137137
};
138138

139-
task.set(peer.rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS));
139+
ScheduledFuture<?> scheduled = peer.rtc.timer.scheduleAtFixedRate(sample, 0, millis, TimeUnit.MILLISECONDS);
140+
141+
task.set(scheduled);
142+
143+
// The first sample is due at once, and may have found the peer closing
144+
// before it could see the task.
145+
if (!active.get()) {
146+
scheduled.cancel(false);
147+
}
140148

141149
return () -> {
142150
active.set(false);

‎webrtc/src/test/java/dev/onvoid/webrtc/client/LocalAudioTests.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,38 @@ void closingTrackEndsSubscriptions() throws Exception {
138138
assertTrue(changes.isEmpty());
139139
}
140140

141+
@Test
142+
void closingTrackDropsQueuedChange() throws Exception {
143+
// A change still waiting for its event thread when the track closes
144+
// stays unheard, as after closing the subscription.
145+
ManualExecutor control = new ManualExecutor();
146+
ManualExecutor events = new ManualExecutor();
147+
WebRtc runtime = WebRtc.builder()
148+
.audio(AudioMode.HEADLESS)
149+
.errorHandler(errors::add)
150+
.controlPool(control)
151+
.eventExecutor(events)
152+
.build();
153+
BlockingQueue<Boolean> changes = new LinkedBlockingQueue<>();
154+
155+
try {
156+
CustomAudio audio = runtime.media().customAudio("audio");
157+
158+
audio.onVoiceActivity(ONE_SEGMENT, changes::add);
159+
audio.push(speech(48000, 1), PcmFormat.of(48000, 1));
160+
events.awaitQueued(10);
161+
162+
audio.close();
163+
control.runAll();
164+
events.runAll();
165+
166+
assertTrue(changes.isEmpty());
167+
}
168+
finally {
169+
HttpSessionTests.closeStepping(runtime, control);
170+
}
171+
}
172+
141173
@Test
142174
void rejectsNull() {
143175
CustomAudio audio = rtc.media().customAudio("audio");

‎webrtc/src/test/java/dev/onvoid/webrtc/client/ManualTimer.java‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,17 @@ final class ManualTimer extends AbstractExecutorService implements ScheduledExec
4444

4545
private boolean shutdown;
4646

47+
private boolean eagerPeriodic;
48+
49+
50+
/**
51+
* Has every periodic task scheduled from now on run once before its
52+
* schedule call returns, as a timer thread may, when its first run is due
53+
* at once.
54+
*/
55+
synchronized void eagerPeriodic() {
56+
eagerPeriodic = true;
57+
}
4758

4859
/**
4960
* Fires every task scheduled with the delay that has not been cancelled.
@@ -101,7 +112,17 @@ public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUni
101112

102113
@Override
103114
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
104-
return add(new Task<>(Executors.callable(command, null), unit.toMillis(period), true));
115+
Task<?> task = add(new Task<>(Executors.callable(command, null), unit.toMillis(period), true));
116+
117+
synchronized (this) {
118+
if (!eagerPeriodic) {
119+
return task;
120+
}
121+
}
122+
123+
task.fire();
124+
125+
return task;
105126
}
106127

107128
@Override

‎webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,31 @@ void statsStopOnClose() throws Exception {
771771
}
772772
}
773773

774+
@Test
775+
void statsStopBeforeTaskKnown() throws Exception {
776+
// The first sample is due at once, so it may find the peer closed
777+
// before the task it has to cancel is known.
778+
ManualTimer timer = new ManualTimer();
779+
Duration interval = Duration.ofSeconds(7);
780+
781+
try (WebRtc runtime = WebRtc.builder()
782+
.audio(AudioMode.HEADLESS)
783+
.errorHandler(errors::add)
784+
.timer(timer)
785+
.build()) {
786+
Peer peer = runtime.createPeer(manualOptions());
787+
AtomicInteger calls = new AtomicInteger();
788+
789+
await(peer.closeAsync());
790+
791+
timer.eagerPeriodic();
792+
peer.onStats(interval, stats -> calls.incrementAndGet());
793+
794+
assertEquals(0, timer.scheduled(interval));
795+
assertEquals(0, calls.get());
796+
}
797+
}
798+
774799
@Test
775800
void statsOfClosedPeerFail() throws Exception {
776801
Peer peer = rtc.createPeer(manualOptions());

0 commit comments

Comments
 (0)