Skip to content

Commit 3980061

Browse files
authored
fix: wide planar audio, audio timestamp gaps and vanished audio devices (#428)
* fix: fail a device switch when the device is gone A descriptor the module no longer lists selected device 0, so an unplugged microphone was silently replaced by another one. Modules that name no devices (Linux) keep using their default. * fix: read wide planar audio from extended_data and keep audio gaps swr_convert got frame->data, which holds eight planes, so planar audio of more channels read past it and crashed. Audio timestamps now drive the output: gaps are filled with silence and overlaps skipped, so audio no longer drifts ahead of video after missing audio.
1 parent 81a3337 commit 3980061

10 files changed

Lines changed: 618 additions & 61 deletions

File tree

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ devices.useMicrophone(devices.microphones().get(1));
416416
devices.useSpeaker(devices.speakers().get(0));
417417
```
418418

419-
`useMicrophone` and `useSpeaker` switch devices also for tracks that are sent or played now.
419+
`useMicrophone` and `useSpeaker` switch devices also for tracks that are sent or played now. A device that was disconnected since the list was read fails the returned future, and the device in use stays as it was. On Linux, where WebRTC's audio device module cannot tell devices apart, the default device is used whichever is given.
420420

421421
## Receiving Media
422422

‎webrtc-java-media/src/main/cpp/include/media/AudioDecoder.h‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,18 @@ namespace ffmpeg
4646
// WebRTC takes 10 ms of audio at a time and nothing else.
4747
static constexpr int kFramesPerChunk = kSampleRate / 100;
4848

49+
// How far a frame's timestamp may stray from where the audio
50+
// before it ends. Containers round their timestamps, so a frame
51+
// is followed by its sample count as long as it stays this close,
52+
// which is also below the point where audio running ahead of
53+
// video starts to show.
54+
static constexpr int64_t kTimestampToleranceUs = 40000;
55+
56+
// The longest stretch of missing audio filled with silence, or of
57+
// repeated audio skipped. Beyond it the source's clock is taken
58+
// to have jumped, as ffplay does past the same ten seconds.
59+
static constexpr int64_t kMaxGapUs = 10000000;
60+
4961
AudioDecoder() = default;
5062
~AudioDecoder();
5163

@@ -82,6 +94,17 @@ namespace ffmpeg
8294
// Resamples one decoded frame into the pending buffer.
8395
int Resample(const AVFrame * frame);
8496

97+
// Holds the audio to the frame's timestamp where it strays from
98+
// where the audio before it ends: missing audio becomes silence,
99+
// and a frame that repeats audio already given out skips what it
100+
// repeats, which it reports as the number of input samples to
101+
// skip.
102+
int FollowTimestamp(int64_t timestamp_us, int * skip);
103+
104+
// Where the audio taken in so far ends, in microseconds on the
105+
// source's timeline.
106+
int64_t GetEndTimestampUs() const;
107+
85108
// Moves whatever swresample still holds into the pending buffer,
86109
// which it only hands out when told that no more input follows.
87110
int DrainResampler();
@@ -113,7 +136,9 @@ namespace ffmpeg
113136
// When the next chunk starts, in microseconds on the source's own
114137
// timeline. Chunks advance it in exact 10 ms steps, so the audio
115138
// this produces is perfectly regular whatever the container's
116-
// packet timing looks like.
139+
// packet timing looks like. Gaps in the source's timestamps are
140+
// filled with silence rather than closed up, so audio stays where
141+
// video, which follows its own timestamps, expects it.
117142
int64_t next_timestamp_us_ = 0;
118143
bool have_timestamp_ = false;
119144

‎webrtc-java-media/src/main/cpp/src/media/AudioDecoder.cpp‎

Lines changed: 102 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616

1717
#include "media/AudioDecoder.h"
1818

19+
#include <algorithm>
20+
#include <climits>
21+
#include <cstdlib>
22+
1923
extern "C" {
2024
#include <libavutil/channel_layout.h>
2125
#include <libavutil/opt.h>
@@ -205,15 +209,6 @@ namespace ffmpeg
205209

206210
int AudioDecoder::Resample(const AVFrame * frame)
207211
{
208-
if (!have_timestamp_) {
209-
int64_t pts = frame->best_effort_timestamp != AV_NOPTS_VALUE
210-
? frame->best_effort_timestamp : frame->pts;
211-
212-
next_timestamp_us_ = pts != AV_NOPTS_VALUE
213-
? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) : 0;
214-
have_timestamp_ = true;
215-
}
216-
217212
if (frame->format != in_format_ || frame->sample_rate != in_rate_
218213
|| av_channel_layout_compare(&frame->ch_layout, &in_layout_) != 0) {
219214
// The stream changed its format. What swresample still holds of
@@ -232,24 +227,63 @@ namespace ffmpeg
232227
}
233228
}
234229

230+
int64_t pts = frame->best_effort_timestamp != AV_NOPTS_VALUE
231+
? frame->best_effort_timestamp : frame->pts;
232+
int skip = 0;
233+
234+
if (!have_timestamp_) {
235+
next_timestamp_us_ = pts != AV_NOPTS_VALUE
236+
? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) : 0;
237+
have_timestamp_ = true;
238+
}
239+
else if (pts != AV_NOPTS_VALUE) {
240+
int result = FollowTimestamp(av_rescale_q(pts, time_base_, AV_TIME_BASE_Q),
241+
&skip);
242+
243+
if (result < 0) {
244+
return result;
245+
}
246+
}
247+
248+
const int samples = frame->nb_samples - skip;
249+
250+
if (samples <= 0) {
251+
return 0;
252+
}
253+
235254
// swresample holds samples back when rates differ, and those come out
236255
// of a later call, so the room needed is the delay plus this frame.
237256
int64_t delay = swr_get_delay(swr_context_, in_rate_);
238-
int64_t capacity = av_rescale_rnd(delay + frame->nb_samples, kSampleRate,
257+
int64_t capacity = av_rescale_rnd(delay + samples, kSampleRate,
239258
in_rate_, AV_ROUND_UP);
240259

241260
if (capacity <= 0) {
242261
return 0;
243262
}
244263

264+
// swresample reads a plane for every input channel, and data has room
265+
// for eight: planar audio of more channels has the rest only in
266+
// extended_data.
267+
const AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
268+
const bool planar = av_sample_fmt_is_planar(format) != 0;
269+
const int planes = planar ? frame->ch_layout.nb_channels : 1;
270+
const int stride = av_get_bytes_per_sample(format)
271+
* (planar ? 1 : frame->ch_layout.nb_channels);
272+
273+
std::vector<const uint8_t *> input(static_cast<size_t>(planes));
274+
275+
for (int i = 0; i < planes; ++i) {
276+
input[i] = frame->extended_data[i] + static_cast<size_t>(skip) * stride;
277+
}
278+
245279
const size_t offset = pending_.size();
246280

247281
pending_.resize(offset + static_cast<size_t>(capacity) * channels_);
248282

249283
uint8_t * output = reinterpret_cast<uint8_t *>(pending_.data() + offset);
250284

251285
int converted = swr_convert(swr_context_, &output, static_cast<int>(capacity),
252-
const_cast<const uint8_t **>(frame->data), frame->nb_samples);
286+
input.data(), samples);
253287

254288
if (converted < 0) {
255289
pending_.resize(offset);
@@ -263,6 +297,63 @@ namespace ffmpeg
263297
return 0;
264298
}
265299

300+
int AudioDecoder::FollowTimestamp(int64_t timestamp_us, int * skip)
301+
{
302+
const int64_t drift = timestamp_us - GetEndTimestampUs();
303+
304+
if (std::abs(drift) <= kTimestampToleranceUs) {
305+
return 0;
306+
}
307+
308+
if (std::abs(drift) > kMaxGapUs) {
309+
// Too far to be audio that went missing: the source's clock
310+
// jumped, as a live stream's does when it restarts it. The audio
311+
// goes on without a break, on the new timeline. What is pending
312+
// is less than a chunk, so it lands just before the jump.
313+
next_timestamp_us_ += drift;
314+
315+
return 0;
316+
}
317+
318+
if (drift < 0) {
319+
// The frame starts where audio already given out has been, so
320+
// that much of its start goes.
321+
*skip = static_cast<int>(std::min<int64_t>(
322+
av_rescale(-drift, in_rate_, AV_TIME_BASE), INT_MAX));
323+
324+
return 0;
325+
}
326+
327+
// Audio is missing before this frame, and silence takes its place, so
328+
// that what follows plays at its own time and not early. What
329+
// swresample holds back belongs before the gap.
330+
int result = DrainResampler();
331+
332+
if (result < 0) {
333+
return result;
334+
}
335+
336+
result = swr_init(swr_context_);
337+
338+
if (result < 0) {
339+
return result;
340+
}
341+
342+
const int64_t silence = av_rescale(drift, kSampleRate, AV_TIME_BASE);
343+
344+
pending_.resize(pending_.size() + static_cast<size_t>(silence) * channels_, 0);
345+
346+
return 0;
347+
}
348+
349+
int64_t AudioDecoder::GetEndTimestampUs() const
350+
{
351+
const int64_t frames = static_cast<int64_t>(pending_.size() / channels_)
352+
+ swr_get_delay(swr_context_, kSampleRate);
353+
354+
return next_timestamp_us_ + av_rescale(frames, AV_TIME_BASE, kSampleRate);
355+
}
356+
266357
int AudioDecoder::DrainResampler()
267358
{
268359
if (swr_context_ == nullptr) {

‎webrtc-java-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java‎

Lines changed: 80 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434
import java.util.concurrent.atomic.AtomicInteger;
3535
import java.util.concurrent.atomic.AtomicLong;
3636
import java.util.concurrent.atomic.AtomicReference;
37+
import java.util.stream.Collectors;
38+
import java.util.stream.IntStream;
39+
import java.util.stream.LongStream;
3740

3841
import dev.onvoid.webrtc.PeerConnectionFactory;
3942
import dev.onvoid.webrtc.media.audio.AudioDeviceModule;
@@ -534,6 +537,74 @@ void deliversResamplerTail() throws Exception {
534537
}
535538
}
536539

540+
@Test
541+
void downmixesMoreThanEightChannels() throws Exception {
542+
// One second of 14 planar channels. A frame has the planes from the
543+
// ninth on only in its extended data, and reading them from its data
544+
// pointers instead crashes the process.
545+
Path file = TestMedia.wideOpusMatroska(tempDir, 14, 50);
546+
547+
try (Playback playback = new Playback(new MediaReader(file))) {
548+
playback.player.play();
549+
550+
assertTrue(playback.ended.await(10, TimeUnit.SECONDS), "no end of stream");
551+
552+
assertEquals(2, playback.channels.get());
553+
assertTrue(Math.abs(playback.chunks.get() - 100) <= 2,
554+
"audio chunks: " + playback.chunks.get());
555+
}
556+
}
557+
558+
@Test
559+
void fillsAudioGapWithSilence() throws Exception {
560+
// A second of audio, a second missing, and a second more. Closing the
561+
// gap up would play the last second a second early, ahead of any
562+
// video that follows its own timestamps.
563+
Path file = TestMedia.pcmMatroska(tempDir, (short) 1000,
564+
blockTimes(0, 10, 2000, 10));
565+
566+
try (Playback playback = new Playback(new MediaReader(file))) {
567+
playback.player.play();
568+
569+
assertTrue(playback.ended.await(10, TimeUnit.SECONDS), "no end of stream");
570+
571+
assertEquals(300, playback.chunks.get());
572+
assertEquals(96000, playback.nonZeroSamples.get());
573+
assertEquals(IntStream.range(100, 200).boxed().collect(Collectors.toList()),
574+
playback.silentChunks);
575+
}
576+
}
577+
578+
@Test
579+
void skipsRepeatedAudio() throws Exception {
580+
// The second second starts 50 ms before the first one ends, so 50 ms
581+
// of it repeat what has played already.
582+
Path file = TestMedia.pcmMatroska(tempDir, (short) 1000,
583+
blockTimes(0, 10, 950, 10));
584+
585+
try (Playback playback = new Playback(new MediaReader(file))) {
586+
playback.player.play();
587+
588+
assertTrue(playback.ended.await(10, TimeUnit.SECONDS), "no end of stream");
589+
590+
assertEquals(195, playback.chunks.get());
591+
assertEquals(195 * 480, playback.nonZeroSamples.get());
592+
assertTrue(playback.silentChunks.isEmpty(),
593+
"silent chunks: " + playback.silentChunks);
594+
}
595+
}
596+
597+
/**
598+
* The times of two runs of 100 ms blocks, in milliseconds.
599+
*/
600+
private static long[] blockTimes(long firstStart, int firstBlocks,
601+
long secondStart, int secondBlocks) {
602+
return LongStream.concat(
603+
LongStream.range(0, firstBlocks).map(i -> firstStart + i * 100),
604+
LongStream.range(0, secondBlocks).map(i -> secondStart + i * 100))
605+
.toArray();
606+
}
607+
537608
private static int countNonZero(byte[] data) {
538609
int count = 0;
539610

@@ -608,6 +679,7 @@ private final class Playback implements AutoCloseable {
608679
final AtomicLong firstChunkNs = new AtomicLong();
609680
final AtomicInteger unevenChunks = new AtomicInteger();
610681
final AtomicLong nonZeroSamples = new AtomicLong();
682+
final List<Integer> silentChunks = Collections.synchronizedList(new ArrayList<>());
611683

612684
private final VideoTrackSink videoSink = frame -> {
613685
frameTimes.add(System.nanoTime());
@@ -618,7 +690,7 @@ private final class Playback implements AutoCloseable {
618690

619691
private final AudioTrackSink audioSink = (data, bits, rate, ch, count) -> {
620692
firstChunkNs.compareAndSet(0, System.nanoTime());
621-
chunks.incrementAndGet();
693+
int index = chunks.getAndIncrement();
622694
sampleRate.set(rate);
623695
channels.set(ch);
624696
framesPerChunk.set(count);
@@ -627,7 +699,13 @@ private final class Playback implements AutoCloseable {
627699
unevenChunks.incrementAndGet();
628700
}
629701

630-
nonZeroSamples.addAndGet(countNonZero(data));
702+
int nonZero = countNonZero(data);
703+
704+
if (nonZero == 0) {
705+
silentChunks.add(index);
706+
}
707+
708+
nonZeroSamples.addAndGet(nonZero);
631709
};
632710

633711
private boolean closed;

0 commit comments

Comments
 (0)