Skip to content

Commit 0111d0d

Browse files
authored
fix: send pushed audio from a thread apart from the timeouts (#452)
The ticks of CustomAudio ran on the runtime's single timer thread, so a slow push into WebRTC delayed operation timeouts, HTTP deadlines and stats. They now run on an audio pacer of their own, and after a stall only ticks at most 50 ms late send, so the missed ticks no longer burst out.
1 parent c01723c commit 0111d0d

5 files changed

Lines changed: 167 additions & 26 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ CustomAudio voice = media.customAudio("voice");
407407
voice.push(pcm, PcmFormat.of(48000, 1));
408408
```
409409

410-
`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms from a thread of its own, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it.
410+
`CustomAudio` takes PCM in pieces of any length and from any thread. It cuts the audio into the 10 ms chunks WebRTC works with and sends one every 10 ms from a thread of its own, so pushing a whole second at once is as fine as pushing every 10 ms. `queuedMillis()` tells how much is still waiting, and `clear()` drops it. That thread does nothing else, so a slow push into WebRTC delays only the audio, not the timeouts of the runtime. Should it stall, as in a long garbage collection pause, it makes up for at most the last 50 ms instead of sending the whole pause at once; the queued audio then stays behind by the rest, until `clear()` drops it.
411411

412412
### Controlling Senders and Tracks
413413

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@
2323
* Audio may be pushed in pieces of any length, from any thread. The track
2424
* cuts it into 10 ms chunks and sends one every 10 ms from a thread of its
2525
* own, so pushing a whole second at once is as fine as pushing every 10 ms.
26+
* <p>
27+
* Should that thread stall, such as in a long garbage collection pause, it
28+
* makes up for at most the last 50 ms of the stall. The audio of the rest is
29+
* not sent faster but later, so what is queued then stays that much behind,
30+
* unless {@link #clear()} drops it.
2631
*/
2732
public interface CustomAudio extends LocalAudio {
2833

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,34 @@
2828

2929
/**
3030
* An audio track fed with audio the application pushes. Pushed audio is cut
31-
* into 10 ms chunks, which the runtime's timer thread hands to the source one
32-
* every 10 ms. That thread is the only one that pushes into the source, as
33-
* {@link CustomAudioSource} requires.
31+
* into 10 ms chunks, which the runtime's audio pacer hands to the source one
32+
* every 10 ms. Its thread is the only one that pushes into the source, as
33+
* {@link CustomAudioSource} requires, and it runs no timeouts, which a slow
34+
* push would hold up.
3435
*/
3536
final class CustomAudioImpl extends LocalAudioImpl implements CustomAudio {
3637

38+
private static final long TICK_NANOS = TimeUnit.MILLISECONDS.toNanos(10);
39+
40+
/**
41+
* How late a tick may run and still send. The pacer runs at a fixed rate,
42+
* so after a stall it runs the missed ticks back to back: those up to this
43+
* late are made up for, so that a short stall keeps the pace, and the
44+
* earlier ones are skipped, so that a long one does not burst out all the
45+
* audio of the pause at once. Skipped ticks leave the queue as it is.
46+
*/
47+
private static final long MAX_LATE_NANOS = TimeUnit.MILLISECONDS.toNanos(50);
48+
3749
private final CustomAudioSource source;
3850

51+
// Confined to the pacer, once the ticker is scheduled.
52+
53+
/** When the first tick was due. */
54+
private long start;
55+
56+
/** The ticks run so far. */
57+
private long ticks;
58+
3959
// Guarded by queue.
4060

4161
private final ArrayDeque<Chunk> queue = new ArrayDeque<>();
@@ -98,7 +118,8 @@ public void push(byte[] pcm, PcmFormat pcmFormat) {
98118
}
99119

100120
if (ticker == null) {
101-
ticker = rtc.timer.scheduleAtFixedRate(this::tick, 0, 10, TimeUnit.MILLISECONDS);
121+
start = rtc.clock.getAsLong();
122+
ticker = rtc.audioPacer.scheduleAtFixedRate(this::tick, 0, TICK_NANOS, TimeUnit.NANOSECONDS);
102123
}
103124
}
104125
}
@@ -144,6 +165,12 @@ private void flushPartial() {
144165
}
145166

146167
private void tick() {
168+
long late = rtc.clock.getAsLong() - (start + ticks++ * TICK_NANOS);
169+
170+
if (late > MAX_LATE_NANOS) {
171+
return;
172+
}
173+
147174
Chunk chunk;
148175

149176
synchronized (queue) {

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

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,15 @@ public final class WebRtc implements AutoCloseable {
102102

103103
final ScheduledExecutorService timer;
104104

105+
/**
106+
* The one thread that sends pushed audio, apart from the timer: a slow
107+
* push must not delay the timeouts.
108+
*/
109+
final ScheduledExecutorService audioPacer;
110+
111+
/** The time in nanoseconds, as {@link System#nanoTime()}. */
112+
final LongSupplier clock;
113+
105114
final Duration operationTimeout;
106115

107116
/** How much audio an {@code onAudio} subscription buffers by default. */
@@ -166,6 +175,9 @@ private WebRtc(Builder builder) {
166175
this.framePool = pool(builder.frameThreads, "webrtc-client-frames-" + runtime + "-");
167176
this.timer = builder.timer != null ? builder.timer
168177
: Executors.newSingleThreadScheduledExecutor(threads("webrtc-client-timer-" + runtime + "-"));
178+
this.audioPacer = builder.audioPacer != null ? builder.audioPacer
179+
: Executors.newSingleThreadScheduledExecutor(threads("webrtc-client-audio-" + runtime + "-"));
180+
this.clock = builder.clock;
169181

170182
if (builder.eventExecutor != null) {
171183
this.eventExecutor = builder.eventExecutor;
@@ -570,6 +582,7 @@ private void shutdownPools() {
570582
controlPool.shutdown();
571583
framePool.shutdown();
572584
timer.shutdownNow();
585+
audioPacer.shutdownNow();
573586

574587
if (ownsEventExecutor) {
575588
((ExecutorService) eventExecutor).shutdown();
@@ -648,6 +661,8 @@ public static final class Builder {
648661

649662
private ScheduledExecutorService timer;
650663

664+
private ScheduledExecutorService audioPacer;
665+
651666
private LongSupplier clock = System::nanoTime;
652667

653668

@@ -850,8 +865,18 @@ Builder timer(ScheduledExecutorService timer) {
850865
}
851866

852867
/**
853-
* Replaces the clock of the load statistics and of the turns of the
854-
* executors, so that tests decide how much time passes.
868+
* Replaces the thread that sends pushed audio, so that tests decide
869+
* when each chunk is due. The runtime shuts it down when it closes.
870+
*/
871+
Builder audioPacer(ScheduledExecutorService pacer) {
872+
this.audioPacer = requireNonNull(pacer, "pacer");
873+
return this;
874+
}
875+
876+
/**
877+
* Replaces the clock of the load statistics, of the turns of the
878+
* executors and of the audio pacing, so that tests decide how much
879+
* time passes.
855880
*
856881
* @param nanos the time in nanoseconds, as {@link System#nanoTime()}.
857882
*/

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

Lines changed: 103 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
import java.util.concurrent.ScheduledExecutorService;
4040
import java.util.concurrent.TimeUnit;
4141
import java.util.concurrent.atomic.AtomicInteger;
42+
import java.util.concurrent.atomic.AtomicLong;
43+
import java.util.function.Consumer;
4244

4345
import dev.onvoid.webrtc.RTCStats;
4446
import dev.onvoid.webrtc.RTCStatsType;
@@ -90,31 +92,17 @@ void pushedAudioArrives() throws Exception {
9092
void clearedAudioNotResent() throws Exception {
9193
// A format change sends the chunk begun before it, filled with
9294
// silence, not with the audio that clear() dropped from it.
93-
ManualTimer timer = new ManualTimer();
95+
ManualTimer pacer = new ManualTimer();
9496
WebRtc runtime = WebRtc.builder()
9597
.audio(AudioMode.HEADLESS)
9698
.errorHandler(errors::add)
97-
.timer(timer)
99+
.audioPacer(pacer)
98100
.build();
99-
LocalMediaImpl media = (LocalMediaImpl) runtime.media();
100101
List<byte[]> sent = new ArrayList<>();
101-
CustomAudioImpl voice;
102-
103-
try (LocalMediaImpl.Creation creation = media.begin()) {
104-
CustomAudioSource source = new CustomAudioSource() {
105-
106-
@Override
107-
public void pushAudio(byte[] audioData, int bitsPerSample, int sampleRate, int channels,
108-
int frameCount) {
109-
sent.add(audioData.clone());
110-
}
111-
};
112-
113-
voice = media.register(new CustomAudioImpl(media, runtime.factory.createAudioTrack("voice", source),
114-
source));
115-
}
116102

117103
try {
104+
CustomAudioImpl voice = recordingAudio(runtime, sent::add);
105+
118106
// 160 bytes in 10 ms.
119107
PcmFormat format = PcmFormat.of(8000, 1);
120108
byte[] dropped = new byte[120];
@@ -127,7 +115,7 @@ public void pushAudio(byte[] audioData, int bitsPerSample, int sampleRate, int c
127115
voice.push(kept, format);
128116
voice.push(new byte[2], PcmFormat.of(16000, 1));
129117

130-
timer.fire(Duration.ofMillis(10));
118+
pacer.fire(Duration.ofMillis(10));
131119

132120
assertEquals(1, sent.size());
133121
assertEquals(160, sent.get(0).length);
@@ -141,6 +129,83 @@ public void pushAudio(byte[] audioData, int bitsPerSample, int sampleRate, int c
141129
}
142130
}
143131

132+
@Test
133+
void stalledAudioNotBurst() throws Exception {
134+
// After a stall the pacer runs the missed ticks back to back. Those
135+
// at most 50 ms late send, the earlier ones leave the audio queued.
136+
ManualTimer pacer = new ManualTimer();
137+
AtomicLong now = new AtomicLong();
138+
WebRtc runtime = WebRtc.builder()
139+
.audio(AudioMode.HEADLESS)
140+
.errorHandler(errors::add)
141+
.audioPacer(pacer)
142+
.clock(now::get)
143+
.build();
144+
List<byte[]> sent = new ArrayList<>();
145+
146+
try {
147+
CustomAudioImpl voice = recordingAudio(runtime, sent::add);
148+
Duration tick = Duration.ofMillis(10);
149+
150+
// One second, 100 chunks of 160 bytes.
151+
voice.push(new byte[16000], PcmFormat.of(8000, 1));
152+
pacer.fire(tick);
153+
154+
assertEquals(1, sent.size());
155+
156+
// Stalled for a second: ticks 1 to 100 are due.
157+
now.set(TimeUnit.SECONDS.toNanos(1));
158+
159+
for (int i = 0; i < 100; i++) {
160+
pacer.fire(tick);
161+
}
162+
163+
// Ticks 95 to 100, due from 950 ms on.
164+
assertEquals(7, sent.size());
165+
assertEquals(930, voice.queuedMillis());
166+
167+
// Back on pace.
168+
now.addAndGet(tick.toNanos());
169+
pacer.fire(tick);
170+
171+
assertEquals(8, sent.size());
172+
}
173+
finally {
174+
runtime.close();
175+
}
176+
}
177+
178+
@Test
179+
void slowPushLeavesTimerFree() throws Exception {
180+
// Pushed audio is sent on a thread of its own: a push that hangs in
181+
// WebRTC holds up the audio, not the timeouts on the timer.
182+
CountDownLatch pushing = new CountDownLatch(1);
183+
CountDownLatch unblock = new CountDownLatch(1);
184+
CustomAudioImpl voice = recordingAudio(rtc, data -> {
185+
pushing.countDown();
186+
187+
try {
188+
unblock.await();
189+
}
190+
catch (InterruptedException e) {
191+
Thread.currentThread().interrupt();
192+
}
193+
});
194+
195+
try {
196+
voice.push(new byte[160], PcmFormat.of(8000, 1));
197+
assertTrue(pushing.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
198+
199+
CompletableFuture<Void> fired = new CompletableFuture<>();
200+
rtc.timer.schedule(() -> fired.complete(null), 1, TimeUnit.MILLISECONDS);
201+
202+
await(fired);
203+
}
204+
finally {
205+
unblock.countDown();
206+
}
207+
}
208+
144209
@Test
145210
void oversizedFormatRejected() {
146211
// 10 ms of these hold 30720 samples, more than WebRTC takes at once.
@@ -470,4 +535,23 @@ private static byte[] tone(int sampleRate, int channels, int millis) {
470535
return pcm;
471536
}
472537

538+
/** A pushed-audio track whose source hands each chunk to the consumer. */
539+
private static CustomAudioImpl recordingAudio(WebRtc runtime, Consumer<byte[]> chunks) {
540+
LocalMediaImpl media = (LocalMediaImpl) runtime.media();
541+
542+
try (LocalMediaImpl.Creation creation = media.begin()) {
543+
CustomAudioSource source = new CustomAudioSource() {
544+
545+
@Override
546+
public void pushAudio(byte[] audioData, int bitsPerSample, int sampleRate, int channels,
547+
int frameCount) {
548+
chunks.accept(audioData.clone());
549+
}
550+
};
551+
552+
return media.register(new CustomAudioImpl(media, runtime.factory.createAudioTrack("voice", source),
553+
source));
554+
}
555+
}
556+
473557
}

0 commit comments

Comments
 (0)